Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Preview the redesigned participant page at /invite/[urlId]/vote (#3411)

Luke Velladc2010d71482
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 86815d41f..43bd32083 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -1,6 +1,8 @@
{
"12h": "12-hour",
+ "12hShort": "12h",
"24h": "24-hour",
+ "24hShort": "24h",
"acceptInvite": "Accept invite",
"acceptInviteMetadataTitle": "Join {spaceName}",
"acceptInviteNotEnoughSeats": "There are not enough seats available to join this space",
@@ -49,9 +51,12 @@
"adminSetupDescription": "Click the button below to make yourself an admin user.",
"adminSetupTitle": "Are you the admin?",
"advisorySeverity": "{severity, select, critical {critical} high {high} medium {medium} low {low} other {unrated}}",
+ "allDatesPast": "Every date has passed",
"allDay": "All day",
"allMembers": "All",
+ "allOptionsPastDescription": "Turn off the filter to see them.",
"allParticipants": "All participants",
+ "allTimesPast": "Every time has passed",
"alreadyLoggedInContinue": "Continue",
"alreadyLoggedInDescription": "Continue to your dashboard or sign out to use a different account.",
"alreadyLoggedInTitle": "You're already signed in",
@@ -330,6 +335,7 @@
"emailInvitesDescription": "Track who opened and responded with personal invite links",
"emailMismatch": "Email does not match the account email",
"emailPlaceholder": "[email protected]",
+ "emptyDaysHidden": "{count, plural, one {# day hidden} other {# days hidden}}",
"enabled": "Enabled",
"errorBackToHome": "Back to home",
"errorDescription": "An unexpected error occurred. Please try again or visit one of the pages below.",
@@ -405,9 +411,12 @@
"hexColor": "Hex color",
"hiddenParticipantName": "Participant #{number}",
"hideAttribution": "Hide attribution",
+ "hideEmptyDays": "Hide empty days",
"hideParticipantsDescription": "Participants will not be able to see the names of other respondents.",
"hideParticipantsTitle": "Hide participant names",
"hidePassword": "Hide password",
+ "hidePastDates": "Hide past dates",
+ "hidePastTimes": "Hide past times",
"hideScoresDescription": "Hide everyone's votes from a participant until they cast their own.",
"hideScoresTitle": "Hide votes",
"home": "Home",
@@ -606,6 +615,7 @@
"noCalendars": "No calendars found",
"noCalendarsDescription": "No calendars found",
"noChanges": "No changes",
+ "noDates": "No dates to vote on",
"noDatesSelected": "No dates selected",
"noDatesSelectedDescription": "Click on a date to add a time slot",
"noDeliveriesYet": "No deliveries yet",
@@ -614,6 +624,7 @@
"noLicenseKeyDescription": "This instance doesn’t have a license key yet.",
"noOpenPolls": "No open polls",
"noOpenPollsDescription": "Polls close automatically once all of their dates have passed. You have {count, plural, one {1 closed poll} other {# closed polls}}.",
+ "noOptionsDescription": "The organizer hasn't added any options yet.",
"noParticipants": "No participants",
"noParticipantsDescription": "Click <b>Share</b> to invite participants",
"noPolls": "No polls",
@@ -633,6 +644,8 @@
"notifyNewCommentDescription": "Receive an email when someone comments on your poll.",
"notifyNewResponse": "New response",
"notifyNewResponseDescription": "Receive an email when a participant submits a response.",
+ "noTimes": "No times to vote on",
+ "noTimesShort": "None",
"noUsers": "No users found",
"noUsersDescription": "Try adjusting your search",
"noVotes": "No one has voted for this option",
@@ -646,6 +659,8 @@
"optionCount": "{count, plural, one {# option} other {# options}}",
"optionsSelected": "{count, plural, =0 {None selected} one {# option selected} other {# options selected}}",
"optionVoteBreakdown": "{yesScore} yes, {ifNeedBeScore} if need be",
+ "optionVoteBreakdownOfTotal": "{yesScore} yes, {ifNeedBeScore} if need be, of {total} responses",
+ "optionVoteBreakdownYesOfTotal": "{yesScore} yes of {total} responses",
"optionVoteBreakdownYesOnly": "{yesScore} yes",
"organizationName": "Organization name",
"organizationNamePlaceholder": "e.g. Acme Corp",
@@ -934,8 +949,11 @@
"shareDialogRemoveInvite": "Remove invite",
"shareDialogSendFailed": "Couldn't send to {email}. Try again.",
"shareDialogSendInvite": "Send invite",
+ "showEmptyDays": "Show empty days",
"showParticipantVotes": "Show participant votes",
"showPassword": "Show password",
+ "showPastDates": "Show past dates",
+ "showPastTimes": "Show past times",
"shrink": "Shrink",
"signedInAs": "You're signed in as:",
"signIn": "Sign in",
@@ -1008,7 +1026,6 @@
"unconfirmedEventsEmptyStateDescription": "Unconfirmed events will show up here.",
"unconfirmedEventsEmptyStateTitle": "No unconfirmed events",
"undo": "Undo",
- "unexpectedError": "Unexpected error",
"unlicensed": "Unlicensed",
"unmuteNotifications": "Unmute notifications",
"unsubscribeInvalidLinkDescription": "The item it pointed to may have been deleted. You can manage all your email notifications from your <a>notification settings</a>.",
@@ -1057,6 +1074,10 @@
"voteSummaryAvailable": "{availableCount} of {total} available",
"voteSummaryIfNeedBe": "{count} if need be",
"voteSummaryNotAvailable": "You're not available",
+ "voteView": "View",
+ "voteViewCalendar": "Calendar",
+ "voteViewList": "List",
+ "voteViewWeek": "Week",
"webhookAdded": "Webhook added",
"webhookAddedDescription": "Copy your signing secret now. You won't be able to see it again.",
"webhookDeleted": "Webhook deleted",
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
index 0790f2f7b..8049df9d1 100644
--- a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
+++ b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx
@@ -1,73 +1,13 @@
"use client";
-import { buttonVariants, cn } from "@rallly/ui";
-import { Alert, AlertAction, AlertDescription } from "@rallly/ui/alert";
-import { ArrowUpRightIcon, CrownIcon } from "lucide-react";
-import { Link } from "@/components/link";
import { Spinner } from "@/components/spinner";
-import { usePoll } from "@/features/poll/client";
-import { CommentsSheet } from "@/features/poll/components/comments-sheet";
import { EventCard } from "@/features/poll/components/event-card";
import { PollFooter } from "@/features/poll/components/poll-footer";
import { ResponsiveResults } from "@/features/poll/components/responsive-results";
-import {
- useVotingForm,
- VotingForm,
-} from "@/features/poll/components/voting-form";
-import { useUser } from "@/features/user/client";
-import { Trans } from "@/i18n/client";
+import { VotingForm } from "@/features/poll/components/voting-form";
+import { CreatorBanner } from "@/features/poll/invite/components/creator-banner";
+import { FloatingComments } from "@/features/poll/invite/components/floating-comments";
import { useHydrated } from "@/lib/datetime/use-hydrated";
-const FloatingComments = () => {
- const votingForm = useVotingForm();
- const isVoting = votingForm.watch("mode") !== "view";
-
- return (
- <div
- className={cn(
- "fixed right-4 z-40 m-0 transition-[bottom] duration-300 ease-out lg:right-6 lg:bottom-6",
- // The mobile poll (below sm) shows a sticky voting footer while a
- // response is being edited; lift the button clear of it.
- isVoting ? "bottom-20 sm:bottom-4" : "bottom-4",
- )}
- >
- <CommentsSheet className="rounded-full shadow-lg" />
- </div>
- );
-};
-
-const GoToApp = () => {
- const poll = usePoll();
- const { user } = useUser();
-
- if (!user || user.id !== poll.userId) {
- return null;
- }
-
- return (
- <Alert variant="primary">
- <CrownIcon />
- <AlertDescription>
- <p>
- <Trans
- i18nKey="eventHostDescription"
- defaults="You are the creator of this poll"
- />
- </p>
- </AlertDescription>
- <AlertAction>
- <Link
- className={buttonVariants({ variant: "primary", size: "sm" })}
- href={`/poll/${poll.id}`}
- prefetch={false}
- >
- <Trans i18nKey="manage" defaults="Manage" />
- <ArrowUpRightIcon className="size-4" />
- </Link>
- </AlertAction>
- </Alert>
- );
-};
-
/**
* The voting grid depends on two things the server cannot know: the
* viewer's zone and Intl output for the option dates, and the viewport
@@ -96,7 +36,7 @@ export function InvitePage({
tabIndex={-1}
className="mx-auto w-full max-w-4xl space-y-3"
>
- <GoToApp />
+ <CreatorBanner />
<EventCard />
<VotingForm>
<ResponsiveResults />
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/vote/page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/vote/page.tsx
new file mode 100644
index 000000000..5f64ebcc0
--- /dev/null
+++ b/apps/web/src/app/[locale]/invite/[urlId]/vote/page.tsx
@@ -0,0 +1,165 @@
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { Suspense } from "react";
+import { SessionRefresher } from "@/components/session-refresher";
+import { loadInstanceBranding } from "@/features/branding/loaders";
+import { loadInstancePolicy } from "@/features/instance-policy/loaders";
+import { loadFooterLinks } from "@/features/instance-settings/loaders";
+import { InviteOpenRecorder } from "@/features/poll/invite/components/invite-open-recorder";
+import { PollUnavailable } from "@/features/poll/invite/components/poll-unavailable";
+import { loadPollAvailability } from "@/features/poll/loaders";
+import { PollBranding } from "@/features/poll/vote/components/poll-branding";
+import { loadCanManagePoll, loadVotePage } from "@/features/poll/vote/loaders";
+import { getLocale } from "@/i18n/server/get-locale";
+import { getSession } from "@/lib/auth";
+import { DeviceDateTimeProvider } from "@/lib/datetime/device";
+import { getDeviceDateTimeConfig } from "@/lib/datetime/server";
+import { VotePage, VotePageLoading } from "./vote-page";
+
+type PageProps = {
+ params: Promise<{ urlId: string }>;
+ searchParams: Promise<{
+ token?: string | string[];
+ invite?: string | string[];
+ }>;
+};
+
+/**
+ * Preview of the merged participant layout at `/invite/[urlId]/vote`. It
+ * serves the same poll as the invite page and will replace it once the
+ * layout is adopted, so it is kept out of search indexes meanwhile.
+ */
+async function VotePageContent({ params, searchParams }: PageProps) {
+ const { urlId } = await params;
+
+ const [availability, { token: tokenParam, invite: inviteParam }] =
+ await Promise.all([loadPollAvailability(urlId), searchParams]);
+
+ if (!availability) {
+ notFound();
+ }
+
+ if (availability.unavailable) {
+ const footerLinks = await loadFooterLinks();
+ return (
+ <PollUnavailable
+ reason={availability.unavailable}
+ footerLinks={footerLinks}
+ />
+ );
+ }
+
+ // `invite` is the param older invite emails carry; both name the same
+ // token and the client reads them the same way. A repeated param arrives
+ // as an array; only a single value is a token.
+ const token = [tokenParam, inviteParam].find(
+ (value): value is string => typeof value === "string",
+ );
+
+ const [
+ view,
+ session,
+ locale,
+ deviceDateTimeConfig,
+ footerLinks,
+ instancePolicy,
+ instanceBranding,
+ canManage,
+ ] = await Promise.all([
+ loadVotePage({ pollId: urlId, token }),
+ getSession(),
+ getLocale(),
+ getDeviceDateTimeConfig(),
+ loadFooterLinks(),
+ loadInstancePolicy(),
+ loadInstanceBranding(),
+ loadCanManagePoll(urlId),
+ ]);
+
+ const { poll } = view;
+ const spaceBranding =
+ poll.space?.showBranding && instancePolicy.spaceBrandingAllowed
+ ? poll.space
+ : null;
+
+ return (
+ <>
+ <SessionRefresher />
+ {token ? <InviteOpenRecorder pollId={urlId} token={token} /> : null}
+ <DeviceDateTimeProvider
+ locale={locale}
+ timeZone={deviceDateTimeConfig.timeZone}
+ timeFormat={deviceDateTimeConfig.timeFormat}
+ >
+ <PollBranding primaryColor={spaceBranding?.primaryColor ?? null} />
+ <VotePage
+ view={view}
+ footerLinks={footerLinks}
+ hideAttribution={
+ instanceBranding.hideAttribution ||
+ (poll.space?.hideAttribution ?? false)
+ }
+ canManage={canManage}
+ requireParticipantEmail={poll.requireParticipantEmail}
+ user={session?.user ?? null}
+ spaceBrandingAllowed={instancePolicy.spaceBrandingAllowed}
+ instanceBranding={instanceBranding}
+ />
+ </DeviceDateTimeProvider>
+ </>
+ );
+}
+
+export default function Page(props: PageProps) {
+ return (
+ <Suspense fallback={<VotePageLoading />}>
+ <VotePageContent {...props} />
+ </Suspense>
+ );
+}
+
+export async function generateMetadata(props: {
+ params: Promise<{ urlId: string; locale: string }>;
+}): Promise<Metadata> {
+ const { urlId } = await props.params;
+
+ const availability = await loadPollAvailability(urlId);
+
+ if (!availability) {
+ notFound();
+ }
+
+ if (availability.unavailable) {
+ return {
+ title: "Poll unavailable",
+ robots: { index: false, follow: false },
+ };
+ }
+
+ const { title, id, authorName } = availability;
+
+ const ogImageUrl = absoluteUrl("/api/og-image-poll", {
+ title,
+ author: authorName,
+ });
+
+ return {
+ title,
+ robots: { index: false, follow: false },
+ metadataBase: new URL(absoluteUrl()),
+ openGraph: {
+ title,
+ description: `By ${authorName}`,
+ url: `/invite/${id}`,
+ images: [
+ {
+ url: ogImageUrl,
+ width: 1200,
+ height: 630,
+ alt: title,
+ },
+ ],
+ },
+ };
+}
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/vote/vote-page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/vote/vote-page.tsx
new file mode 100644
index 000000000..c94132912
--- /dev/null
+++ b/apps/web/src/app/[locale]/invite/[urlId]/vote/vote-page.tsx
@@ -0,0 +1,91 @@
+import { Card } from "@rallly/ui/card";
+import { Spinner } from "@/components/spinner";
+import { ThemeSwitcher } from "@/components/theme-switcher";
+import { EventSidebar } from "@/features/poll/invite/components/event-sidebar";
+import { ManagePollButton } from "@/features/poll/vote/components/manage-poll-button";
+import { VotePageFooter } from "@/features/poll/vote/components/vote-page-footer";
+import { VotePanel } from "@/features/poll/vote/components/vote-panel";
+import type { VotePageView } from "@/features/poll/vote/types";
+import type { UserDTO } from "@/features/user/schema";
+
+/**
+ * Participant view as one card centered on a page that never scrolls: the
+ * event details sit in a sidebar beside the voting panel on large screens
+ * and stack above it below that.
+ *
+ * Everything but the panel renders on the server.
+ */
+export function VotePage({
+ view,
+ footerLinks,
+ hideAttribution,
+ canManage,
+ requireParticipantEmail,
+ user,
+ spaceBrandingAllowed,
+ instanceBranding,
+}: {
+ view: VotePageView;
+ footerLinks: { label: string; href: string }[];
+ hideAttribution: boolean;
+ /** Owner, or a member of the poll's space when that space is shared. */
+ canManage: boolean;
+ requireParticipantEmail: boolean;
+ user: UserDTO | null;
+ spaceBrandingAllowed: boolean;
+ instanceBranding: { appName: string; logoIcon?: string };
+}) {
+ return (
+ // Below lg the page itself scrolls and the card gives up its frame,
+ // so a phone spends every pixel on the options. From lg up the card is
+ // a fixed size centred in a page that never scrolls.
+ <div className="page-bg-gray-100 flex min-h-dvh flex-col lg:h-dvh lg:min-h-0 lg:items-center lg:justify-center lg:gap-3 lg:overflow-hidden lg:p-6 dark:bg-gray-900">
+ <main
+ id="main-content"
+ tabIndex={-1}
+ className="flex w-full flex-1 flex-col lg:min-h-0 lg:max-w-5xl lg:flex-initial lg:gap-3"
+ >
+ {/* In the flow rather than pinned to the page corner, which lands
+ on the card whenever the gutter beside it is narrower than
+ these controls. */}
+ <div className="flex items-center justify-end gap-2 p-3 lg:p-0">
+ <ThemeSwitcher />
+ {canManage ? <ManagePollButton pollId={view.poll.id} /> : null}
+ </div>
+ {/* max-lg:overflow-visible: the card clips its rounded corners, which
+ would also stop the panel footer sticking to the viewport while
+ the page scrolls. There are no corners to clip at that width. */}
+ <Card className="flex flex-1 flex-col max-lg:overflow-visible max-lg:rounded-none max-lg:border-x-0 max-lg:border-t-0 max-lg:shadow-none lg:h-176 lg:min-h-0 lg:flex-initial">
+ <div className="flex flex-1 flex-col lg:grid lg:min-h-0 lg:grid-cols-[20rem_1fr] lg:grid-rows-[minmax(0,1fr)]">
+ <aside className="shrink-0 border-b p-4 lg:min-h-0 lg:overflow-y-auto lg:border-b-0">
+ <EventSidebar
+ poll={view.poll}
+ spaceBrandingAllowed={spaceBrandingAllowed}
+ instanceBranding={instanceBranding}
+ hideAttribution={hideAttribution}
+ />
+ </aside>
+ <section className="flex flex-1 flex-col lg:min-h-0 lg:border-l">
+ <VotePanel
+ {...view}
+ requireParticipantEmail={requireParticipantEmail}
+ user={user}
+ />
+ </section>
+ </div>
+ </Card>
+ </main>
+ <div className="shrink-0">
+ <VotePageFooter footerLinks={footerLinks} />
+ </div>
+ </div>
+ );
+}
+
+export function VotePageLoading() {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <Spinner />
+ </div>
+ );
+}
diff --git a/apps/web/src/components/data-list.tsx b/apps/web/src/components/data-list.tsx
index dfbd14c4f..4b4a83a2f 100644
--- a/apps/web/src/components/data-list.tsx
+++ b/apps/web/src/components/data-list.tsx
@@ -14,9 +14,20 @@ declare module "@tanstack/react-table" {
type DataListGroup = { id: string; label: React.ReactNode };
-function DataListRow<TData>({ row }: { row: Row<TData> }) {
+function DataListRow<TData>({
+ row,
+ className,
+}: {
+ row: Row<TData>;
+ className?: string;
+}) {
return (
- <li className="relative col-span-full grid h-12 grid-cols-subgrid items-center rounded-lg pr-3 pl-4 hover:bg-accent/60 has-[a:focus-visible]:bg-accent/60 has-[a[aria-current=page]]:bg-accent">
+ <li
+ className={cn(
+ "relative col-span-full grid h-12 grid-cols-subgrid items-center rounded-lg pr-3 pl-4 hover:bg-accent/60 has-[a:focus-visible]:bg-accent/60 has-[a[aria-current=page]]:bg-accent",
+ className,
+ )}
+ >
{row.getVisibleCells().map((cell) => (
<div
key={cell.id}
@@ -45,23 +56,34 @@ function DataListRow<TData>({ row }: { row: Row<TData> }) {
* To make a whole row clickable, render a link in one cell with an
* `after:absolute after:inset-0` overlay and give other interactive cells
* `relative z-10` so they sit above it.
+ *
+ * `getRowClassName` styles a row from its data, e.g. to tint it by state.
*/
export function DataList<TData>({
table,
getGroup,
+ getRowClassName,
+ rowGapClassName,
className,
}: {
table: Table<TData>;
getGroup?: (row: TData) => DataListGroup;
+ getRowClassName?: (row: TData) => string | undefined;
+ /** Space between rows, e.g. when rows carry their own background. */
+ rowGapClassName?: string;
className?: string;
}) {
const rows = table.getRowModel().rows;
if (!getGroup) {
return (
- <ul className={cn("grid gap-x-5 px-4 py-2", className)}>
+ <ul className={cn("grid gap-x-5 px-4 py-2", rowGapClassName, className)}>
{rows.map((row) => (
- <DataListRow key={row.id} row={row} />
+ <DataListRow
+ key={row.id}
+ row={row}
+ className={getRowClassName?.(row.original)}
+ />
))}
</ul>
);
@@ -88,9 +110,18 @@ export function DataList<TData>({
<h2 className="col-span-full mb-1 flex h-12 items-center gap-2 rounded-lg bg-muted/60 px-4 text-sm">
{group.label}
</h2>
- <ul className="col-span-full grid grid-cols-subgrid">
+ <ul
+ className={cn(
+ "col-span-full grid grid-cols-subgrid",
+ rowGapClassName,
+ )}
+ >
{rows.map((row) => (
- <DataListRow key={row.id} row={row} />
+ <DataListRow
+ key={row.id}
+ row={row}
+ className={getRowClassName?.(row.original)}
+ />
))}
</ul>
</li>
diff --git a/apps/web/src/features/branding/loaders.ts b/apps/web/src/features/branding/loaders.ts
index 02288443f..03e8fe06c 100644
--- a/apps/web/src/features/branding/loaders.ts
+++ b/apps/web/src/features/branding/loaders.ts
@@ -5,9 +5,12 @@ import { env } from "@/env";
import { getInstanceSettings } from "@/features/instance-settings/data";
import { loadInstanceLicense } from "@/features/licensing/data";
import { DEFAULT_PRIMARY_COLOR } from "./constants";
-import { getCustomBrandingConfig } from "./data";
+import { getCustomBrandingConfig, getInstanceBrandingConfig } from "./data";
import { getPrimaryColorVars } from "./utils";
+/** The instance's effective branding, for pages that render its identity. */
+export const loadInstanceBranding = cache(() => getInstanceBrandingConfig());
+
/**
* Raw branding values for the control panel branding page. Editable fields
* expose the stored value (db, then env, then default) rather than the
diff --git a/apps/web/src/features/poll/client.tsx b/apps/web/src/features/poll/client.tsx
index 2d33cfbc3..e3c6acd31 100644
--- a/apps/web/src/features/poll/client.tsx
+++ b/apps/web/src/features/poll/client.tsx
@@ -52,6 +52,10 @@ export function PollProvider({
export const usePoll = () => useRequiredContext(PollContext).poll;
+/** The poll when a provider is mounted, for components shared with pages
+ * that pass their data as props instead. */
+export const usePollOrNull = () => React.useContext(PollContext)?.poll ?? null;
+
export const useRole = () => useRequiredContext(PollContext).viewerRole;
export const useComments = () => useRequiredContext(PollContext).comments;
diff --git a/apps/web/src/features/poll/components/event-card.tsx b/apps/web/src/features/poll/components/event-card.tsx
index f52aaaf71..d80a3fd5a 100644
--- a/apps/web/src/features/poll/components/event-card.tsx
+++ b/apps/web/src/features/poll/components/event-card.tsx
@@ -1,4 +1,5 @@
"use client";
+import { cn } from "@rallly/ui";
import { Card, CardContent } from "@rallly/ui/card";
import { MapPinIcon, User2Icon } from "lucide-react";
import { RandomGradientBar } from "@/components/random-gradient-bar";
@@ -18,12 +19,13 @@ import { SpaceIcon } from "@/features/space/components/space-icon";
import { Trans } from "@/i18n/client";
function IconDescriptionList({
+ className,
children,
...props
}: React.HTMLAttributes<HTMLDListElement>) {
return (
<dl
- className="flex flex-wrap items-center gap-4 text-muted-foreground text-sm"
+ className={cn("flex flex-wrap items-center gap-4 text-xs", className)}
{...props}
>
{children}
@@ -46,70 +48,78 @@ function IconDescription({
);
}
-export function EventCard() {
+/**
+ * The event's identity: branding chip, title, description, organizer and
+ * location. `EventCard` frames it as a standalone card with the response
+ * legend; the vote page places it in the sidebar of the merged card.
+ */
+export function EventDetails() {
const poll = usePoll();
const branding = useBranding();
const { spaceBrandingAllowed } = useInstancePolicy();
return (
- <Card>
- <RandomGradientBar />
- <CardContent>
- {poll.space?.showBranding && poll.space.image ? (
- <div className="mb-2">
- <SpaceIcon
- name={poll.space.name}
- src={poll.space.image}
- size="xl"
+ <>
+ {poll.space?.showBranding && poll.space.image ? (
+ <div className="mb-2">
+ <SpaceIcon name={poll.space.name} src={poll.space.image} size="xl" />
+ <p className="mt-2 font-medium text-muted-foreground text-sm">
+ {poll.space.name}
+ </p>
+ </div>
+ ) : !spaceBrandingAllowed ? (
+ // Instance branding is enforced: the space chip is suppressed, so
+ // the slot carries the instance's logo icon and name instead
+ <div className="mb-2">
+ <SpaceIcon
+ name={branding.appName}
+ src={branding.logoIcon}
+ size="xl"
+ />
+ <p className="mt-2 font-medium text-muted-foreground text-sm">
+ {branding.appName}
+ </p>
+ </div>
+ ) : null}
+ <EventMetaTitle>{poll.title}</EventMetaTitle>
+ <EventMetaDescription className="mt-4" content={poll.description} />
+ <EventMetaList className="mt-4">
+ {poll.user ? (
+ <EventMetaItem>
+ <User2Icon />
+ <Trans
+ i18nKey="organizedBy"
+ defaults="Organized by {name}"
+ values={{ name: poll.user.name }}
/>
- <p className="mt-2 font-medium text-muted-foreground text-sm">
- {poll.space.name}
- </p>
- </div>
- ) : !spaceBrandingAllowed ? (
- // Instance branding is enforced: the space chip is suppressed, so
- // the slot carries the instance's logo icon and name instead
- <div className="mb-2">
- <SpaceIcon
- name={branding.appName}
- src={branding.logoIcon}
- size="xl"
+ </EventMetaItem>
+ ) : null}
+ {poll.location ? (
+ <EventMetaItem>
+ <MapPinIcon />
+ <TruncatedLinkify>{poll.location}</TruncatedLinkify>
+ </EventMetaItem>
+ ) : null}
+ {poll.conferencing ? (
+ <EventMetaItem>
+ <PollConferencingSummary
+ conferencing={poll.conferencing}
+ meetingUri={poll.event?.conferencingUri}
/>
- <p className="mt-2 font-medium text-muted-foreground text-sm">
- {branding.appName}
- </p>
- </div>
+ </EventMetaItem>
) : null}
- <div>
- <EventMetaTitle>{poll.title}</EventMetaTitle>
- <EventMetaDescription className="mt-2" content={poll.description} />
- </div>
- <EventMetaList className="mt-4">
- {poll.user ? (
- <EventMetaItem>
- <User2Icon />
- <Trans
- i18nKey="organizedBy"
- defaults="Organized by {name}"
- values={{ name: poll.user.name }}
- />
- </EventMetaItem>
- ) : null}
- {poll.location ? (
- <EventMetaItem>
- <MapPinIcon />
- <TruncatedLinkify>{poll.location}</TruncatedLinkify>
- </EventMetaItem>
- ) : null}
- {poll.conferencing ? (
- <EventMetaItem>
- <PollConferencingSummary
- conferencing={poll.conferencing}
- meetingUri={poll.event?.conferencingUri}
- />
- </EventMetaItem>
- ) : null}
- </EventMetaList>
- <h2 className="mt-4 mb-1.5 font-medium text-sm">
+ </EventMetaList>
+ </>
+ );
+}
+
+export function EventCard() {
+ const poll = usePoll();
+ return (
+ <Card>
+ <RandomGradientBar />
+ <CardContent>
+ <EventDetails />
+ <h2 className="mt-4 mb-1.5 text-muted-foreground text-xs">
<Trans i18nKey="responseOptions" defaults="Response options" />
</h2>
<IconDescriptionList aria-label="Response options">
diff --git a/apps/web/src/features/poll/components/event-meta.tsx b/apps/web/src/features/poll/components/event-meta.tsx
index 5c520419f..985e09d1d 100644
--- a/apps/web/src/features/poll/components/event-meta.tsx
+++ b/apps/web/src/features/poll/components/event-meta.tsx
@@ -55,7 +55,9 @@ export function EventMetaItem({
<li
className={cn(
className,
- "flex flex-wrap items-center gap-1.5 text-sm [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground",
+ // The icon holds its column and the text wraps beside it rather
+ // than under it, so a long location stays legible.
+ "flex items-start gap-1.5 text-sm [&>*:not(svg)]:min-w-0 [&_svg]:mt-0.5 [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground",
)}
>
{children}
diff --git a/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx b/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx
index 9c9885469..bff1d8da2 100644
--- a/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx
+++ b/apps/web/src/features/poll/components/mobile-poll/poll-option.tsx
@@ -12,11 +12,8 @@ import {
} from "@rallly/ui/dialog";
import * as m from "motion/react-m";
import type * as React from "react";
-
-import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
-import { useParticipants } from "@/features/poll/client";
import { IfScoresVisible } from "@/features/poll/components/visibility";
-import { filterParticipantsByVote } from "@/features/poll/utils";
+import { PollOptionVoteSummary } from "@/features/poll/components/vote-breakdown-dialog";
import { Trans, useTranslation } from "@/i18n/client";
import { ConnectedScoreSummary } from "../score-summary";
import VoteIcon from "../vote-icon";
@@ -36,48 +33,6 @@ export interface PollOptionProps {
allowTentativeVotes?: boolean;
}
-const PollOptionVoteSummary: React.FunctionComponent<{ optionId: string }> = ({
- optionId,
-}) => {
- const { t } = useTranslation();
- const { participants } = useParticipants();
- const participantsWithVotes = (["yes", "ifNeedBe", "no"] as const).flatMap(
- (voteType) =>
- filterParticipantsByVote(participants, optionId, voteType).map(
- (participant) => ({ participant, voteType }),
- ),
- );
-
- if (participantsWithVotes.length === 0) {
- return (
- <p className="rounded-lg bg-muted p-2 text-center text-muted-foreground text-sm">
- {t("noVotes", {
- defaultValue: "No one has voted for this option",
- })}
- </p>
- );
- }
-
- return (
- <ul className="max-h-[min(20rem,40dvh)] space-y-2.5 overflow-y-auto">
- {participantsWithVotes.map(({ participant, voteType }) => (
- <li key={participant.id} className="flex items-center gap-x-2.5">
- <OptimizedAvatarImage
- size="sm"
- name={participant.name}
- src={participant.image ?? undefined}
- className="shrink-0"
- />
- <div className="min-w-0 flex-1 truncate text-sm">
- {participant.name}
- </div>
- <VoteIcon type={voteType} className="shrink-0" />
- </li>
- ))}
- </ul>
- );
-};
-
const PollOption: React.FunctionComponent<PollOptionProps> = ({
children,
selectedParticipantId,
diff --git a/apps/web/src/features/poll/components/new-participant-modal.tsx b/apps/web/src/features/poll/components/new-participant-modal.tsx
index 4003259cd..c1fde4954 100644
--- a/apps/web/src/features/poll/components/new-participant-modal.tsx
+++ b/apps/web/src/features/poll/components/new-participant-modal.tsx
@@ -29,7 +29,7 @@ import { useForm } from "react-hook-form";
import * as z from "zod";
import { IfCloudHosted } from "@/components/environment";
import { Link } from "@/components/link";
-import { usePoll } from "@/features/poll/client";
+import { usePollOrNull } from "@/features/poll/client";
import {
useAddParticipant,
useEditToken,
@@ -58,6 +58,9 @@ const schema = z.union([requiredEmailSchema, optionalEmailSchema]);
interface NewParticipantModalProps {
votes: { optionId: string; type: VoteType }[];
+ /** These fall back to the poll in context on the legacy surfaces. */
+ pollId?: string;
+ requireParticipantEmail?: boolean;
onSubmit?: (data: { id: string }) => void;
onCancel?: () => void;
}
@@ -127,9 +130,11 @@ const VoteSummary = ({
export const NewParticipantForm = (props: NewParticipantModalProps) => {
const { t } = useTranslation();
- const poll = usePoll();
+ const poll = usePollOrNull();
- const isEmailRequired = poll.requireParticipantEmail;
+ const isEmailRequired =
+ props.requireParticipantEmail ?? poll?.requireParticipantEmail ?? false;
+ const pollId = props.pollId ?? poll?.id;
const { timeZone } = useDateTimeConfig();
const { user, createGuestIfNeeded } = useUser();
const isLoggedIn = user && !user.isGuest;
@@ -224,12 +229,12 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
posthog?.capture(
"new_participant_dialog:create_poll_button_click",
{
- pollId: poll.id,
- spaceId: poll.spaceId,
- tier: poll.space?.tier,
+ pollId,
+ spaceId: poll?.spaceId,
+ tier: poll?.space?.tier,
$groups: {
- poll: poll.id,
- ...(poll.spaceId ? { space: poll.spaceId } : {}),
+ poll: pollId,
+ ...(poll?.spaceId ? { space: poll.spaceId } : {}),
},
},
);
@@ -263,13 +268,16 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
<form
id="new-participant-form"
onSubmit={handleSubmit(async (data) => {
+ if (!pollId) {
+ throw new Error("NewParticipantForm needs a pollId");
+ }
await createGuestIfNeeded();
const result = await addParticipant.execute({
name: data.name,
votes: props.votes,
email: data.email,
note: data.note,
- pollId: poll.id,
+ pollId,
timeZone,
token,
});
@@ -399,12 +407,12 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
posthog?.capture(
"new_participant_dialog:add_note_button_click",
{
- pollId: poll.id,
- spaceId: poll.spaceId,
- tier: poll.space?.tier,
+ pollId,
+ spaceId: poll?.spaceId,
+ tier: poll?.space?.tier,
$groups: {
- poll: poll.id,
- ...(poll.spaceId ? { space: poll.spaceId } : {}),
+ poll: pollId,
+ ...(poll?.spaceId ? { space: poll.spaceId } : {}),
},
},
);
diff --git a/apps/web/src/features/poll/components/participant-dropdown.tsx b/apps/web/src/features/poll/components/participant-dropdown.tsx
index 572bc0cb5..46a6fdf63 100644
--- a/apps/web/src/features/poll/components/participant-dropdown.tsx
+++ b/apps/web/src/features/poll/components/participant-dropdown.tsx
@@ -182,7 +182,7 @@ const CopyEditLinkMenuItem = ({
);
};
-const DeleteParticipantModal = ({
+export const DeleteParticipantModal = ({
open,
onOpenChange,
participantId,
@@ -264,7 +264,7 @@ const changeNameSchema = z.object({
name: z.string().trim().min(1),
});
-const ChangeNameModal = (props: {
+export const ChangeNameModal = (props: {
oldName: string;
participantId: string;
open: boolean;
diff --git a/apps/web/src/features/poll/components/poll-outcome.tsx b/apps/web/src/features/poll/components/poll-outcome.tsx
new file mode 100644
index 000000000..877b28b04
--- /dev/null
+++ b/apps/web/src/features/poll/components/poll-outcome.tsx
@@ -0,0 +1,130 @@
+"use client";
+
+import { Button } from "@rallly/ui/button";
+import { CalendarIcon, LockIcon } from "lucide-react";
+import * as React from "react";
+import {
+ EmptyState,
+ EmptyStateDescription,
+ EmptyStateFooter,
+ EmptyStateIcon,
+ EmptyStateTitle,
+} from "@/components/empty-state";
+import { AddToCalendarButton } from "@/features/calendars/components/add-to-calendar-button";
+import { usePoll } from "@/features/poll/client";
+import {
+ EventDate,
+ EventTimeRange,
+} from "@/features/scheduled-event/components/event-date-time";
+import { Trans } from "@/i18n/client";
+
+function ScheduledDateTime({
+ start,
+ duration,
+ timeZone,
+}: {
+ start: Date;
+ duration: number;
+ timeZone: string | null;
+}) {
+ const allDay = duration === 0;
+
+ return (
+ <span className="flex flex-col items-center gap-0.5">
+ <EventDate
+ value={start}
+ allDay={allDay}
+ timeZone={timeZone}
+ preset="dateFull"
+ className={allDay ? undefined : "text-foreground"}
+ />
+ <EventTimeRange
+ start={start}
+ end={new Date(start.getTime() + duration * 60_000)}
+ allDay={allDay}
+ timeZone={timeZone}
+ showTimeZone
+ />
+ </span>
+ );
+}
+
+/**
+ * Stands in for the voting interface while a poll is scheduled or closed,
+ * until the viewer asks to see the results. Renders its children otherwise.
+ * `frame` wraps the notice when the surrounding layout gives the children
+ * their own container (the legacy stacked pages wrap it in a card).
+ */
+export function PollOutcome({
+ children,
+ frame: Frame = React.Fragment,
+}: {
+ children: React.ReactNode;
+ frame?: React.ElementType;
+}) {
+ const poll = usePoll();
+ const [dismissed, setDismissed] = React.useState(false);
+
+ if (!dismissed && poll.status === "scheduled" && poll.event) {
+ return (
+ <Frame>
+ <EmptyState>
+ <EmptyStateIcon>
+ <CalendarIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans i18nKey="pollStatusScheduled" defaults="Scheduled" />
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ <ScheduledDateTime
+ start={poll.event.start}
+ duration={poll.event.duration}
+ timeZone={poll.timeZone}
+ />
+ </EmptyStateDescription>
+ <EmptyStateFooter className="flex flex-wrap items-center justify-center gap-2">
+ <AddToCalendarButton eventId={poll.event.id} />
+ <Button onClick={() => setDismissed(true)}>
+ <Trans i18nKey="viewResults" defaults="View results" />
+ </Button>
+ </EmptyStateFooter>
+ </EmptyState>
+ </Frame>
+ );
+ }
+
+ if (!dismissed && poll.status === "closed") {
+ return (
+ <Frame>
+ <EmptyState>
+ <EmptyStateIcon>
+ <LockIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans i18nKey="pollStatusClosed" defaults="Closed" />
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ {poll.closedReason === "auto" ? (
+ <Trans
+ i18nKey="pollAutoClosedDescription"
+ defaults="This poll was closed automatically because all of its dates have passed. No more responses are being accepted."
+ />
+ ) : (
+ <Trans
+ i18nKey="pollClosedDescription"
+ defaults="No more responses are being accepted."
+ />
+ )}
+ </EmptyStateDescription>
+ <EmptyStateFooter>
+ <Button onClick={() => setDismissed(true)}>
+ <Trans i18nKey="viewResults" defaults="View results" />
+ </Button>
+ </EmptyStateFooter>
+ </EmptyState>
+ </Frame>
+ );
+ }
+
+ return children;
+}
diff --git a/apps/web/src/features/poll/components/responsive-results.tsx b/apps/web/src/features/poll/components/responsive-results.tsx
index 4a7457840..0198f9eba 100644
--- a/apps/web/src/features/poll/components/responsive-results.tsx
+++ b/apps/web/src/features/poll/components/responsive-results.tsx
@@ -1,126 +1,20 @@
"use client";
-import { Button } from "@rallly/ui/button";
import { Card } from "@rallly/ui/card";
-import { CalendarIcon, LockIcon } from "lucide-react";
-import * as React from "react";
import { createBreakpoint } from "react-use";
-import {
- EmptyState,
- EmptyStateDescription,
- EmptyStateFooter,
- EmptyStateIcon,
- EmptyStateTitle,
-} from "@/components/empty-state";
-import { AddToCalendarButton } from "@/features/calendars/components/add-to-calendar-button";
-import { usePoll } from "@/features/poll/client";
import DesktopPoll from "@/features/poll/components/desktop-poll";
import MobilePoll from "@/features/poll/components/mobile-poll";
-import {
- EventDate,
- EventTimeRange,
-} from "@/features/scheduled-event/components/event-date-time";
-import { Trans } from "@/i18n/client";
+import { PollOutcome } from "@/features/poll/components/poll-outcome";
const useBreakpoint = createBreakpoint({ list: 320, table: 640 });
-function ScheduledDateTime({
- start,
- duration,
- timeZone,
-}: {
- start: Date;
- duration: number;
- timeZone: string | null;
-}) {
- const allDay = duration === 0;
-
- return (
- <span className="flex flex-col items-center gap-0.5">
- <EventDate
- value={start}
- allDay={allDay}
- timeZone={timeZone}
- preset="dateFull"
- className={allDay ? undefined : "text-foreground"}
- />
- <EventTimeRange
- start={start}
- end={new Date(start.getTime() + duration * 60_000)}
- allDay={allDay}
- timeZone={timeZone}
- showTimeZone
- />
- </span>
- );
-}
-
export function ResponsiveResults() {
- const poll = usePoll();
const breakpoint = useBreakpoint();
- const [dismissed, setDismissed] = React.useState(false);
const PollComponent = breakpoint === "table" ? DesktopPoll : MobilePoll;
- if (!dismissed && poll.status === "scheduled" && poll.event) {
- return (
- <Card>
- <EmptyState>
- <EmptyStateIcon>
- <CalendarIcon />
- </EmptyStateIcon>
- <EmptyStateTitle>
- <Trans i18nKey="pollStatusScheduled" defaults="Scheduled" />
- </EmptyStateTitle>
- <EmptyStateDescription>
- <ScheduledDateTime
- start={poll.event.start}
- duration={poll.event.duration}
- timeZone={poll.timeZone}
- />
- </EmptyStateDescription>
- <EmptyStateFooter className="flex flex-wrap items-center justify-center gap-2">
- <AddToCalendarButton eventId={poll.event.id} />
- <Button onClick={() => setDismissed(true)}>
- <Trans i18nKey="viewResults" defaults="View results" />
- </Button>
- </EmptyStateFooter>
- </EmptyState>
- </Card>
- );
- }
-
- if (!dismissed && poll.status === "closed") {
- return (
- <Card>
- <EmptyState>
- <EmptyStateIcon>
- <LockIcon />
- </EmptyStateIcon>
- <EmptyStateTitle>
- <Trans i18nKey="pollStatusClosed" defaults="Closed" />
- </EmptyStateTitle>
- <EmptyStateDescription>
- {poll.closedReason === "auto" ? (
- <Trans
- i18nKey="pollAutoClosedDescription"
- defaults="This poll was closed automatically because all of its dates have passed. No more responses are being accepted."
- />
- ) : (
- <Trans
- i18nKey="pollClosedDescription"
- defaults="No more responses are being accepted."
- />
- )}
- </EmptyStateDescription>
- <EmptyStateFooter>
- <Button onClick={() => setDismissed(true)}>
- <Trans i18nKey="viewResults" defaults="View results" />
- </Button>
- </EmptyStateFooter>
- </EmptyState>
- </Card>
- );
- }
-
- return <PollComponent />;
+ return (
+ <PollOutcome frame={Card}>
+ <PollComponent />
+ </PollOutcome>
+ );
}
diff --git a/apps/web/src/features/poll/components/score-summary.tsx b/apps/web/src/features/poll/components/score-summary.tsx
index 0db3d6248..6cd5279a3 100644
--- a/apps/web/src/features/poll/components/score-summary.tsx
+++ b/apps/web/src/features/poll/components/score-summary.tsx
@@ -1,10 +1,11 @@
+"use client";
import { cn } from "@rallly/ui";
import { User2Icon } from "lucide-react";
import { AnimatePresence } from "motion/react";
import * as m from "motion/react-m";
import * as React from "react";
import { usePrevious } from "react-use";
-import { usePoll } from "@/features/poll/components/poll-context";
+import { usePollScores } from "@/features/poll/components/use-poll-scores";
import { IfScoresVisible } from "@/features/poll/components/visibility";
export interface PopularityScoreProps {
@@ -22,7 +23,7 @@ export interface PopularityScoreProps {
export const ConnectedScoreSummary: React.FunctionComponent<{
optionId: string;
}> = ({ optionId }) => {
- const { getScore, highScore, poll } = usePoll();
+ const { getScore, highScore, poll } = usePollScores();
const { yes, ifNeedBe } = getScore(optionId);
const score = yes + ifNeedBe;
const highlight = score === highScore && score > 1;
diff --git a/apps/web/src/features/poll/components/use-poll-scores.ts b/apps/web/src/features/poll/components/use-poll-scores.ts
new file mode 100644
index 000000000..69f1ad00f
--- /dev/null
+++ b/apps/web/src/features/poll/components/use-poll-scores.ts
@@ -0,0 +1,65 @@
+"use client";
+import * as React from "react";
+import { useParticipants, usePoll } from "@/features/poll/client";
+import type { VoteType } from "@/features/poll/constants";
+
+/**
+ * Vote tallies derived from the poll and its participants. These are pure
+ * derivations of what `PollProvider` already holds, so they need no
+ * provider of their own.
+ */
+export function usePollScores() {
+ const poll = usePoll();
+ const { participants } = useParticipants();
+
+ return React.useMemo(() => {
+ const scores = new Map<
+ string,
+ { yes: number; ifNeedBe: number; no: number; skip: number }
+ >();
+ for (const option of poll.options) {
+ scores.set(option.id, { yes: 0, ifNeedBe: 0, no: 0, skip: 0 });
+ }
+ for (const participant of participants) {
+ for (const vote of participant.votes) {
+ const score = scores.get(vote.optionId);
+ if (!score) {
+ continue;
+ }
+ if (vote.type === "yes") {
+ score.yes += 1;
+ } else if (vote.type === "ifNeedBe") {
+ score.ifNeedBe += 1;
+ } else if (vote.type === "no") {
+ score.no += 1;
+ } else {
+ score.skip += 1;
+ }
+ }
+ }
+
+ const empty = { yes: 0, ifNeedBe: 0, no: 0, skip: 0 };
+ const getScore = (optionId: string) => scores.get(optionId) ?? empty;
+
+ // Starts at 1 so a single yes never counts as the high score.
+ let highScore = 1;
+ for (const option of poll.options) {
+ const { yes, ifNeedBe } = getScore(option.id);
+ highScore = Math.max(highScore, yes + ifNeedBe);
+ }
+
+ return {
+ poll,
+ highScore,
+ optionIds: poll.options.map((option) => option.id),
+ getScore,
+ getVote: (
+ participantId: string,
+ optionId: string,
+ ): VoteType | undefined =>
+ participants
+ .find((participant) => participant.id === participantId)
+ ?.votes.find((vote) => vote.optionId === optionId)?.type,
+ };
+ }, [poll, participants]);
+}
diff --git a/apps/web/src/features/poll/components/vote-breakdown-dialog.tsx b/apps/web/src/features/poll/components/vote-breakdown-dialog.tsx
new file mode 100644
index 000000000..f79516884
--- /dev/null
+++ b/apps/web/src/features/poll/components/vote-breakdown-dialog.tsx
@@ -0,0 +1,78 @@
+"use client";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@rallly/ui/dialog";
+import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
+import { useParticipants } from "@/features/poll/client";
+import VoteIcon from "@/features/poll/components/vote-icon";
+import { filterParticipantsByVote } from "@/features/poll/utils";
+import { Trans, useTranslation } from "@/i18n/client";
+
+/** Who voted what on one option, yes first. */
+export function PollOptionVoteSummary({ optionId }: { optionId: string }) {
+ const { t } = useTranslation();
+ const { participants } = useParticipants();
+ const participantsWithVotes = (["yes", "ifNeedBe", "no"] as const).flatMap(
+ (voteType) =>
+ filterParticipantsByVote(participants, optionId, voteType).map(
+ (participant) => ({ participant, voteType }),
+ ),
+ );
+
+ if (participantsWithVotes.length === 0) {
+ return (
+ <p className="rounded-lg bg-muted p-2 text-center text-muted-foreground text-sm">
+ {t("noVotes", {
+ defaultValue: "No one has voted for this option",
+ })}
+ </p>
+ );
+ }
+
+ return (
+ <ul className="max-h-[min(20rem,40dvh)] space-y-2.5 overflow-y-auto">
+ {participantsWithVotes.map(({ participant, voteType }) => (
+ <li key={participant.id} className="flex items-center gap-x-2.5">
+ <OptimizedAvatarImage
+ size="sm"
+ name={participant.name}
+ src={participant.image ?? undefined}
+ className="shrink-0"
+ />
+ <div className="min-w-0 flex-1 truncate text-sm">
+ {participant.name}
+ </div>
+ <VoteIcon type={voteType} className="shrink-0" />
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+/** Dialog listing who voted on an option. Spread `useDialog().dialogProps`. */
+export function VoteBreakdownDialog({
+ optionId,
+ optionLabel,
+ ...dialogProps
+}: React.ComponentProps<typeof Dialog> & {
+ optionId: string;
+ optionLabel: string;
+}) {
+ return (
+ <Dialog {...dialogProps}>
+ <DialogContent size="sm">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="participants" defaults="Participants" />
+ </DialogTitle>
+ <DialogDescription>{optionLabel}</DialogDescription>
+ </DialogHeader>
+ <PollOptionVoteSummary optionId={optionId} />
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/poll/components/vote-options.tsx b/apps/web/src/features/poll/components/vote-options.tsx
new file mode 100644
index 000000000..71bea9261
--- /dev/null
+++ b/apps/web/src/features/poll/components/vote-options.tsx
@@ -0,0 +1,50 @@
+"use client";
+import * as React from "react";
+import { usePoll } from "@/features/poll/client";
+import VoteIcon from "@/features/poll/components/vote-icon";
+import { Trans } from "@/i18n/client";
+
+function VoteOption({
+ icon,
+ label,
+}: {
+ icon: React.ReactNode;
+ label: React.ReactNode;
+}) {
+ return (
+ <div className="flex items-center gap-1.5">
+ <dt>{icon}</dt>
+ <dd>{label}</dd>
+ </div>
+ );
+}
+
+/** The available vote types as a stacked legend, for a narrow sidebar. */
+export function VoteOptions() {
+ const poll = usePoll();
+ const headingId = React.useId();
+
+ return (
+ <div>
+ <h2 id={headingId} className="mb-1.5 text-muted-foreground text-xs">
+ <Trans i18nKey="responseOptions" defaults="Response options" />
+ </h2>
+ <dl aria-labelledby={headingId} className="flex flex-col gap-2 text-xs">
+ <VoteOption
+ icon={<VoteIcon type="yes" />}
+ label={<Trans i18nKey="yes" defaults="Yes" />}
+ />
+ {poll.allowTentativeVotes ? (
+ <VoteOption
+ icon={<VoteIcon type="ifNeedBe" />}
+ label={<Trans i18nKey="ifNeedBe" defaults="If need be" />}
+ />
+ ) : null}
+ <VoteOption
+ icon={<VoteIcon type="no" />}
+ label={<Trans i18nKey="no" defaults="No" />}
+ />
+ </dl>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/components/vote-segmented-control.tsx b/apps/web/src/features/poll/components/vote-segmented-control.tsx
index 1f14d0059..0245ee704 100644
--- a/apps/web/src/features/poll/components/vote-segmented-control.tsx
+++ b/apps/web/src/features/poll/components/vote-segmented-control.tsx
@@ -44,7 +44,8 @@ export const VoteSegmentedControl = ({
<SegmentedControl
data-testid="vote-selector"
aria-label={optionLabel}
- className={cn("h-11", className)}
+ // Touch-sized below sm; from there it matches a default button.
+ className={cn("h-11 sm:h-9", className)}
value={value ?? null}
onValueChange={(newValue) => {
if (newValue) {
@@ -57,7 +58,7 @@ export const VoteSegmentedControl = ({
key={type}
value={type}
aria-label={voteLabels[type]}
- className="w-11 data-unchecked:[&_svg]:text-gray-400"
+ className="w-11 sm:w-9 data-unchecked:[&_svg]:text-gray-400 dark:data-unchecked:[&_svg]:text-gray-600"
>
<VoteIcon type={type} />
</SegmentedControlItem>
diff --git a/apps/web/src/features/poll/components/voting-footer.tsx b/apps/web/src/features/poll/components/voting-footer.tsx
index 295242c85..52ace1807 100644
--- a/apps/web/src/features/poll/components/voting-footer.tsx
+++ b/apps/web/src/features/poll/components/voting-footer.tsx
@@ -11,29 +11,48 @@ import {
useDialog,
} from "@rallly/ui/dialog";
import { toast } from "@rallly/ui/sonner";
+import type * as React from "react";
import { useVotingForm } from "@/features/poll/components/voting-form";
import { Trans, useTranslation } from "@/i18n/client";
-/**
- * Shared footer for the desktop and mobile voting forms. Announces the
- * selection count to screen readers, offers an explicit decline path for an
- * all-no response (confirming first if it would discard selections), and the
- * Continue/Save submit which is gated until a new participant selects at
- * least one option.
- */
-export const VotingFooter = ({ className }: { className?: string }) => {
- const { t } = useTranslation();
+function useSelection() {
const votingForm = useVotingForm();
- const confirmDialog = useDialog();
-
const selectedParticipantId = votingForm.watch("participantId");
const votes = votingForm.watch("votes");
- const selectedCount = votes.filter(
- (vote) => vote?.type === "yes" || vote?.type === "ifNeedBe",
+ const yesCount = votes.filter((vote) => vote?.type === "yes").length;
+ const ifNeedBeCount = votes.filter(
+ (vote) => vote?.type === "ifNeedBe",
).length;
- const isNewResponse = !selectedParticipantId;
- const isBlocked = isNewResponse && selectedCount === 0;
+ return {
+ votingForm,
+ votes,
+ yesCount,
+ ifNeedBeCount,
+ selectedCount: yesCount + ifNeedBeCount,
+ isNewResponse: !selectedParticipantId,
+ };
+}
+
+/** Yes and if need be counts of the response being edited. */
+export function useSelectionCount() {
+ const { yesCount, ifNeedBeCount, selectedCount } = useSelection();
+ return { yesCount, ifNeedBeCount, selectedCount };
+}
+
+/**
+ * Submits an all-no response, confirming first when it would discard
+ * selections.
+ */
+export function DeclineButton({
+ className,
+ size = "lg",
+}: {
+ className?: string;
+ size?: React.ComponentProps<typeof Button>["size"];
+}) {
+ const { votingForm, votes, selectedCount } = useSelection();
+ const confirmDialog = useDialog();
const submitAllNo = () => {
votingForm.setValue(
@@ -44,26 +63,11 @@ export const VotingFooter = ({ className }: { className?: string }) => {
};
return (
- <div
- className={cn(
- "relative flex items-center gap-x-2.5 md:justify-end",
- className,
- )}
- >
- {/* Invisible, but keeps vote taps audible for screen readers. The
- wrapper is positioned so this absolutely positioned node resolves
- against it instead of the body, which would extend the document. */}
- <p aria-live="polite" className="sr-only">
- <Trans
- i18nKey="optionsSelected"
- defaults="{count, plural, =0 {None selected} one {# option selected} other {# options selected}}"
- values={{ count: selectedCount }}
- />
- </p>
+ <>
<Button
type="button"
- size="lg"
- className="flex-1 md:flex-none"
+ size={size}
+ className={className}
disabled={votingForm.formState.isSubmitting}
onClick={() => {
if (selectedCount > 0) {
@@ -75,31 +79,6 @@ export const VotingFooter = ({ className }: { className?: string }) => {
>
<Trans i18nKey="decline" defaults="Decline" />
</Button>
- <Button
- form="voting-form"
- type="submit"
- size="lg"
- variant="primary"
- className="flex-2 bg-primary/80 backdrop-blur-lg aria-disabled:opacity-50 md:flex-none"
- aria-disabled={isBlocked}
- loading={votingForm.formState.isSubmitting}
- onClick={(event) => {
- if (isBlocked) {
- event.preventDefault();
- toast(
- t("selectAtLeastOneOptionOrDecline", {
- defaultValue: "Select at least one option, or decline",
- }),
- );
- }
- }}
- >
- {isNewResponse ? (
- <Trans i18nKey="continue" defaults="Continue" />
- ) : (
- <Trans i18nKey="save" defaults="Save" />
- )}
- </Button>
<Dialog {...confirmDialog.dialogProps}>
<DialogContent size="sm">
<DialogHeader>
@@ -135,6 +114,82 @@ export const VotingFooter = ({ className }: { className?: string }) => {
</DialogFooter>
</DialogContent>
</Dialog>
+ </>
+ );
+}
+
+/**
+ * Continue (new response) or Save (existing one). A new response is gated
+ * until at least one option is selected; the gate explains itself in a toast
+ * rather than disabling the button, so it stays reachable.
+ */
+export function SubmitResponseButton({
+ className,
+ size = "lg",
+}: {
+ className?: string;
+ size?: React.ComponentProps<typeof Button>["size"];
+}) {
+ const { t } = useTranslation();
+ const { votingForm, selectedCount, isNewResponse } = useSelection();
+ const isBlocked = isNewResponse && selectedCount === 0;
+
+ return (
+ <Button
+ form="voting-form"
+ type="submit"
+ size={size}
+ variant="primary"
+ className={className}
+ aria-disabled={isBlocked}
+ loading={votingForm.formState.isSubmitting}
+ onClick={(event) => {
+ if (isBlocked) {
+ event.preventDefault();
+ toast(
+ t("selectAtLeastOneOptionOrDecline", {
+ defaultValue: "Select at least one option, or decline",
+ }),
+ );
+ }
+ }}
+ >
+ {isNewResponse ? (
+ <Trans i18nKey="continue" defaults="Continue" />
+ ) : (
+ <Trans i18nKey="save" defaults="Save" />
+ )}
+ </Button>
+ );
+}
+
+/**
+ * Shared footer for the desktop and mobile voting forms. Announces the
+ * selection count to screen readers, offers an explicit decline path for an
+ * all-no response, and the Continue/Save submit.
+ */
+export const VotingFooter = ({ className }: { className?: string }) => {
+ const { selectedCount } = useSelection();
+
+ return (
+ <div
+ className={cn(
+ "relative flex items-center gap-x-2.5 md:justify-end",
+ className,
+ )}
+ >
+ {/* Invisible, but keeps vote taps audible for screen readers. The
+ wrapper is positioned so this absolutely positioned node resolves
+ against it instead of the body, which would extend the document. */}
+ <p aria-live="polite" className="sr-only">
+ <Trans
+ i18nKey="optionsSelected"
+ defaults="{count, plural, =0 {None selected} one {# option selected} other {# options selected}}"
+ values={{ count: selectedCount }}
+ />
+ </p>
+ <DeclineButton className="flex-1 md:flex-none" />
+ <SubmitResponseButton className="flex-2 bg-primary/80 backdrop-blur-lg aria-disabled:opacity-50 md:flex-none" />
</div>
);
};
diff --git a/apps/web/src/features/poll/invite/components/creator-banner.tsx b/apps/web/src/features/poll/invite/components/creator-banner.tsx
new file mode 100644
index 000000000..d16f6e6d4
--- /dev/null
+++ b/apps/web/src/features/poll/invite/components/creator-banner.tsx
@@ -0,0 +1,42 @@
+"use client";
+import { buttonVariants } from "@rallly/ui";
+import { Alert, AlertAction, AlertDescription } from "@rallly/ui/alert";
+import { ArrowUpRightIcon, CrownIcon } from "lucide-react";
+import { Link } from "@/components/link";
+import { usePoll } from "@/features/poll/client";
+import { useUser } from "@/features/user/client";
+import { Trans } from "@/i18n/client";
+
+/** Points the poll's creator from the participant view to the admin page. */
+export function CreatorBanner() {
+ const poll = usePoll();
+ const { user } = useUser();
+
+ if (!user || user.id !== poll.userId) {
+ return null;
+ }
+
+ return (
+ <Alert variant="primary">
+ <CrownIcon />
+ <AlertDescription>
+ <p>
+ <Trans
+ i18nKey="eventHostDescription"
+ defaults="You are the creator of this poll"
+ />
+ </p>
+ </AlertDescription>
+ <AlertAction>
+ <Link
+ className={buttonVariants({ variant: "primary", size: "sm" })}
+ href={`/poll/${poll.id}`}
+ prefetch={false}
+ >
+ <Trans i18nKey="manage" defaults="Manage" />
+ <ArrowUpRightIcon className="size-4" />
+ </Link>
+ </AlertAction>
+ </Alert>
+ );
+}
diff --git a/apps/web/src/features/poll/invite/components/event-sidebar.tsx b/apps/web/src/features/poll/invite/components/event-sidebar.tsx
new file mode 100644
index 000000000..a4a0ed4f1
--- /dev/null
+++ b/apps/web/src/features/poll/invite/components/event-sidebar.tsx
@@ -0,0 +1,123 @@
+import { MapPinIcon, User2Icon } from "lucide-react";
+import { Trans } from "react-i18next/TransWithoutContext";
+import { PollConferencingSummary } from "@/features/conferencing/components/poll-conferencing-summary";
+import type { PollConferencing } from "@/features/conferencing/schema";
+import {
+ EventMetaDescription,
+ EventMetaItem,
+ EventMetaList,
+ EventMetaTitle,
+} from "@/features/poll/components/event-meta";
+import TruncatedLinkify from "@/features/poll/components/truncated-linkify";
+import { PoweredByLink } from "@/features/poll/vote/components/powered-by-link";
+import { SpaceIcon } from "@/features/space/components/space-icon";
+import { getTranslation } from "@/i18n/server";
+import { VoteLegend } from "./vote-legend";
+
+type SidebarPoll = {
+ id: string;
+ title: string;
+ description: string | null;
+ location: string | null;
+ conferencing: PollConferencing | null;
+ event: { conferencingUri: string | null } | null;
+ allowTentativeVotes: boolean;
+ spaceId: string | null;
+ user: { name: string } | null;
+ space: { name: string; image: string | null; showBranding: boolean } | null;
+};
+
+/**
+ * The event's identity in the vote page sidebar: branding chip, title,
+ * description, organizer, location, video call and the vote legend, with attribution
+ * and the theme switcher in a footer beneath them. Rendered on the server;
+ * nothing here depends on the viewer's clock.
+ */
+export async function EventSidebar({
+ poll,
+ spaceBrandingAllowed,
+ instanceBranding,
+ hideAttribution,
+}: {
+ poll: SidebarPoll;
+ spaceBrandingAllowed: boolean;
+ instanceBranding: { appName: string; logoIcon?: string };
+ hideAttribution: boolean;
+}) {
+ const { t, i18n } = await getTranslation();
+
+ const brand =
+ poll.space?.showBranding && poll.space.image
+ ? { name: poll.space.name, image: poll.space.image }
+ : // Instance branding is enforced: the space chip is suppressed, so
+ // the slot carries the instance's logo icon and name instead.
+ !spaceBrandingAllowed
+ ? {
+ name: instanceBranding.appName,
+ image: instanceBranding.logoIcon ?? null,
+ }
+ : null;
+
+ return (
+ // The footer sits at the bottom of the sidebar, so the content above it
+ // takes the leftover height.
+ <div className="flex min-h-full flex-col">
+ <div className="flex-1">
+ {brand ? (
+ <div className="mb-2">
+ <SpaceIcon
+ name={brand.name}
+ src={brand.image ?? undefined}
+ size="xl"
+ />
+ <p className="mt-2 font-medium text-muted-foreground text-sm">
+ {brand.name}
+ </p>
+ </div>
+ ) : null}
+ <EventMetaTitle>{poll.title}</EventMetaTitle>
+ <EventMetaDescription className="mt-4" content={poll.description} />
+ <EventMetaList className="mt-4">
+ {poll.user ? (
+ <EventMetaItem>
+ <User2Icon />
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="organizedBy"
+ defaults="Organized by {name}"
+ values={{ name: poll.user.name }}
+ />
+ </EventMetaItem>
+ ) : null}
+ {poll.location ? (
+ <EventMetaItem>
+ <MapPinIcon />
+ <TruncatedLinkify>{poll.location}</TruncatedLinkify>
+ </EventMetaItem>
+ ) : null}
+ {poll.conferencing ? (
+ <EventMetaItem>
+ <PollConferencingSummary
+ conferencing={poll.conferencing}
+ meetingUri={poll.event?.conferencingUri}
+ />
+ </EventMetaItem>
+ ) : null}
+ </EventMetaList>
+ <div className="mt-4">
+ <VoteLegend allowTentativeVotes={poll.allowTentativeVotes} />
+ </div>
+ </div>
+ {/* Attribution can be turned off per instance or per space, and then
+ the footer goes with it. The theme switcher lives on the page, not
+ in the card. */}
+ {hideAttribution ? null : (
+ <div className="mt-6 flex justify-center">
+ <PoweredByLink pollId={poll.id} spaceId={poll.spaceId} />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/invite/components/floating-comments.tsx b/apps/web/src/features/poll/invite/components/floating-comments.tsx
new file mode 100644
index 000000000..7ebe925a9
--- /dev/null
+++ b/apps/web/src/features/poll/invite/components/floating-comments.tsx
@@ -0,0 +1,35 @@
+"use client";
+import { cn } from "@rallly/ui";
+import { CommentsSheet } from "@/features/poll/components/comments-sheet";
+import { useVotingForm } from "@/features/poll/components/voting-form";
+
+/**
+ * Comments pill pinned to the viewport corner. Must render inside
+ * `VotingForm`. While a response is being edited the list's sticky footer
+ * occupies the bottom edge, so the pill lifts clear of it: below `sm` on the
+ * legacy page, where the grid takes over above that, and at every width on
+ * the vote page, where the list is the only interface.
+ */
+export function FloatingComments({
+ liftAtAllWidths = false,
+}: {
+ liftAtAllWidths?: boolean;
+}) {
+ const votingForm = useVotingForm();
+ const isVoting = votingForm.watch("mode") !== "view";
+
+ return (
+ <div
+ className={cn(
+ "fixed right-4 z-40 m-0 transition-[bottom] duration-300 ease-out lg:right-6",
+ isVoting
+ ? liftAtAllWidths
+ ? "bottom-20"
+ : "bottom-20 sm:bottom-4 lg:bottom-6"
+ : "bottom-4 lg:bottom-6",
+ )}
+ >
+ <CommentsSheet className="rounded-full shadow-lg" />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/invite/components/vote-legend.tsx b/apps/web/src/features/poll/invite/components/vote-legend.tsx
new file mode 100644
index 000000000..d4285f2db
--- /dev/null
+++ b/apps/web/src/features/poll/invite/components/vote-legend.tsx
@@ -0,0 +1,45 @@
+import { VoteIcon } from "@rallly/ui/vote-icon";
+import { Trans } from "react-i18next/TransWithoutContext";
+import { getTranslation } from "@/i18n/server";
+
+/** The available vote types as a stacked legend, for a narrow sidebar. */
+export async function VoteLegend({
+ allowTentativeVotes,
+}: {
+ allowTentativeVotes: boolean;
+}) {
+ const { t, i18n } = await getTranslation();
+ const headingId = "vote-legend-heading";
+
+ const types = [
+ { type: "yes" as const, key: "yes", label: "Yes" },
+ ...(allowTentativeVotes
+ ? [{ type: "ifNeedBe" as const, key: "ifNeedBe", label: "If need be" }]
+ : []),
+ { type: "no" as const, key: "no", label: "No" },
+ ];
+
+ return (
+ <div>
+ <h2 id={headingId} className="mb-1.5 text-muted-foreground text-xs">
+ <Trans
+ t={t}
+ i18n={i18n}
+ ns="app"
+ i18nKey="responseOptions"
+ defaults="Response options"
+ />
+ </h2>
+ <dl aria-labelledby={headingId} className="flex flex-col gap-2 text-xs">
+ {types.map(({ type, key, label }) => (
+ <div key={key} className="flex items-center gap-1.5">
+ <dt>
+ <VoteIcon type={type} title={t(key, { defaultValue: label })} />
+ </dt>
+ <dd>{t(key, { defaultValue: label })}</dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/mutations.ts b/apps/web/src/features/poll/mutations.ts
index cb253a455..124f61e1f 100644
--- a/apps/web/src/features/poll/mutations.ts
+++ b/apps/web/src/features/poll/mutations.ts
@@ -429,6 +429,8 @@ export async function removeDeletedPolls() {
* render of the page that called it and drops the router's copy of both.
*/
export function revalidatePollPages() {
- revalidatePath("/[locale]/invite/[urlId]", "page");
+ // "layout" so the nested /vote route is covered too; as a "page" it
+ // would keep serving a response the viewer has just deleted.
+ revalidatePath("/[locale]/invite/[urlId]", "layout");
revalidatePath("/[locale]/(optional-space)/poll/[urlId]", "layout");
}
diff --git a/apps/web/src/features/poll/vote/components/hide-past-toggle.tsx b/apps/web/src/features/poll/vote/components/hide-past-toggle.tsx
new file mode 100644
index 000000000..fdab02759
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/hide-past-toggle.tsx
@@ -0,0 +1,42 @@
+"use client";
+import { buttonVariants, cn } from "@rallly/ui";
+import { Checkbox } from "@rallly/ui/checkbox";
+import * as React from "react";
+import { Trans } from "@/i18n/client";
+
+/**
+ * Hides options that have already passed.
+ *
+ * A checkbox inside a button shell: `Checkbox` renders a native button of
+ * its own, so it cannot be nested in another one. A label wraps it instead
+ * and carries the button styling, which keeps the primitive's own box and
+ * check mark and leaves the whole control clickable.
+ */
+export function HidePastToggle({
+ checked,
+ onCheckedChange,
+ isTimeSlot,
+}: {
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ isTimeSlot: boolean;
+}) {
+ const id = React.useId();
+
+ return (
+ <label
+ htmlFor={id}
+ className={cn(
+ buttonVariants({ variant: "ghost" }),
+ "cursor-pointer gap-2 font-normal",
+ )}
+ >
+ <Checkbox id={id} checked={checked} onCheckedChange={onCheckedChange} />
+ {isTimeSlot ? (
+ <Trans i18nKey="hidePastTimes" defaults="Hide past times" />
+ ) : (
+ <Trans i18nKey="hidePastDates" defaults="Hide past dates" />
+ )}
+ </label>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/manage-poll-button.tsx b/apps/web/src/features/poll/vote/components/manage-poll-button.tsx
new file mode 100644
index 000000000..1f23c7ae7
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/manage-poll-button.tsx
@@ -0,0 +1,25 @@
+import { buttonVariants } from "@rallly/ui";
+import { SettingsIcon } from "lucide-react";
+import { Trans } from "react-i18next/TransWithoutContext";
+import { Link } from "@/components/link";
+import { getTranslation } from "@/i18n/server";
+
+/**
+ * Takes the host from the participant view through to the admin page.
+ * Shown only to someone who can actually manage the poll, so it never
+ * leads to a redirect back here.
+ */
+export async function ManagePollButton({ pollId }: { pollId: string }) {
+ const { t, i18n } = await getTranslation();
+
+ return (
+ <Link
+ className={buttonVariants()}
+ href={`/poll/${pollId}`}
+ prefetch={false}
+ >
+ <SettingsIcon data-icon="inline-start" />
+ <Trans t={t} i18n={i18n} ns="app" i18nKey="manage" defaults="Manage" />
+ </Link>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/option-date.tsx b/apps/web/src/features/poll/vote/components/option-date.tsx
new file mode 100644
index 000000000..faab0176d
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/option-date.tsx
@@ -0,0 +1,29 @@
+"use client";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import { formatDateTime } from "@/lib/datetime/format";
+import type { DateInput } from "@/lib/datetime/types";
+import { useHydrated } from "@/lib/datetime/use-hydrated";
+import { toISODate } from "@/lib/datetime/utils";
+
+/** A date option's label: the full date, in the locale's own order. */
+export function OptionDate({ value }: { value: DateInput }) {
+ const hydrated = useHydrated();
+ const { locale } = useDateTimeConfig();
+
+ // Intl output isn't stable across engines, so it can't be rendered on the
+ // server; hold the row's height until hydration.
+ if (!hydrated) {
+ return <time dateTime={toISODate(value)}> </time>;
+ }
+
+ return (
+ <time dateTime={toISODate(value)} className="truncate">
+ {/* All-day dates are stored as UTC wall time and read back in UTC. */}
+ {formatDateTime(value, {
+ preset: "dateFull",
+ locale,
+ timeZone: "UTC",
+ })}
+ </time>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/poll-branding.tsx b/apps/web/src/features/poll/vote/components/poll-branding.tsx
new file mode 100644
index 000000000..62dc5493c
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/poll-branding.tsx
@@ -0,0 +1,13 @@
+import { BrandStyle } from "@/features/branding/components/brand-style";
+
+/** Applies a space's brand color to the page when it has one. */
+export function PollBranding({
+ primaryColor,
+}: {
+ primaryColor: string | null;
+}) {
+ if (!primaryColor) {
+ return null;
+ }
+ return <BrandStyle primaryColor={primaryColor} />;
+}
diff --git a/apps/web/src/features/poll/vote/components/powered-by-link.tsx b/apps/web/src/features/poll/vote/components/powered-by-link.tsx
new file mode 100644
index 000000000..d70396a88
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/powered-by-link.tsx
@@ -0,0 +1,39 @@
+"use client";
+import { posthog } from "@rallly/posthog/client";
+import { Link } from "@/components/link";
+import { DEFAULT_APP_NAME } from "@/features/branding/constants";
+import { Trans } from "@/i18n/client";
+
+/** The attribution pill. Client only because the click is tracked. */
+export function PoweredByLink({
+ pollId,
+ spaceId,
+}: {
+ pollId: string;
+ spaceId: string | null;
+}) {
+ return (
+ <Link
+ className="inline-flex h-9 shrink-0 items-center gap-2 whitespace-nowrap rounded-full border border-border bg-background px-4 font-normal text-foreground text-xs shadow-xs transition-[background-color,transform] ease-out hover:bg-gray-50 active:scale-[.98] motion-reduce:active:scale-100 dark:bg-muted dark:hover:bg-[color-mix(in_oklab,var(--color-gray-800),var(--color-gray-700)_25%)]"
+ href="https://rallly.co?utm_source=rallly&utm_medium=poll&utm_campaign=powered_by"
+ onClick={() => {
+ posthog?.capture("poll_footer:powered_by_link_click", {
+ pollId,
+ spaceId,
+ $groups: {
+ poll: pollId,
+ ...(spaceId ? { space: spaceId } : {}),
+ },
+ });
+ }}
+ >
+ <Trans i18nKey="poweredBy" defaults="Powered by" />
+ {/* The wordmark is masked so it inherits the pill's text color in both themes */}
+ <span
+ aria-hidden="true"
+ className="h-3.5 w-[75px] bg-foreground [mask:url(/static/logo.svg)_no-repeat_center/contain]"
+ />
+ <span className="sr-only"> {DEFAULT_APP_NAME}</span>
+ </Link>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/time-format-switcher.tsx b/apps/web/src/features/poll/vote/components/time-format-switcher.tsx
new file mode 100644
index 000000000..518218df0
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/time-format-switcher.tsx
@@ -0,0 +1,54 @@
+"use client";
+import {
+ SegmentedControl,
+ SegmentedControlItem,
+} from "@rallly/ui/segmented-control";
+import { Trans, useTranslation } from "@/i18n/client";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import { useDeviceDateTime } from "@/lib/datetime/device";
+import { getLocaleDefaults } from "@/lib/datetime/locales";
+
+/**
+ * The viewer's clock format, beside the time zone rather than inside its
+ * dialog. Only time polls render it: a date has no time to format.
+ */
+export function TimeFormatSwitcher() {
+ const { t } = useTranslation();
+ const { locale, timeFormat } = useDateTimeConfig();
+ const { setTimeFormat } = useDeviceDateTime();
+
+ // With no explicit preference the locale's own default is what renders.
+ const value = timeFormat ?? getLocaleDefaults(locale).timeFormat;
+
+ return (
+ <SegmentedControl
+ aria-label={t("timeFormat", { defaultValue: "Time format" })}
+ value={value}
+ onValueChange={(next) => {
+ if (next) {
+ setTimeFormat(next as "hours12" | "hours24");
+ }
+ }}
+ >
+ {/* The visible label is compact to fit the header; the accessible
+ name stays the long form, which is what a screen reader should
+ read out. The shared `12h`/`24h` keys hold that long form and
+ are already translated, so they are reused here rather than
+ redefined. */}
+ <SegmentedControlItem
+ value="hours12"
+ aria-label={t("12h")}
+ className="px-2.5 text-xs"
+ >
+ <Trans i18nKey="12hShort" defaults="12h" />
+ </SegmentedControlItem>
+ <SegmentedControlItem
+ value="hours24"
+ aria-label={t("24h")}
+ className="px-2.5 text-xs"
+ >
+ <Trans i18nKey="24hShort" defaults="24h" />
+ </SegmentedControlItem>
+ </SegmentedControl>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/time-zone-switcher.tsx b/apps/web/src/features/poll/vote/components/time-zone-switcher.tsx
new file mode 100644
index 000000000..b2612dad1
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/time-zone-switcher.tsx
@@ -0,0 +1,31 @@
+"use client";
+import { TimeZoneSelect } from "@/components/time-zone-picker/time-zone-select";
+import { useTranslation } from "@/i18n/client";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import { useDeviceDateTime } from "@/lib/datetime/device";
+
+/**
+ * The viewer's time zone, inline in the header rather than behind a dialog,
+ * so changing it is one interaction. `TimeZoneSelect` is already a combobox
+ * with search, a curated shortlist and the current time per zone.
+ */
+export function TimeZoneSwitcher() {
+ const { t } = useTranslation();
+ const { timeZone } = useDateTimeConfig();
+ const { setTimeZone } = useDeviceDateTime();
+
+ if (!timeZone) {
+ return null;
+ }
+
+ return (
+ <TimeZoneSelect
+ value={timeZone}
+ onValueChange={setTimeZone}
+ aria-label={t("timeZone")}
+ // Narrower than the select's own default, which is sized for a form
+ // field rather than a row of header controls.
+ className="min-w-0 sm:w-48"
+ />
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-empty-state.tsx b/apps/web/src/features/poll/vote/components/vote-empty-state.tsx
new file mode 100644
index 000000000..46f391091
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-empty-state.tsx
@@ -0,0 +1,72 @@
+"use client";
+import { Button } from "@rallly/ui/button";
+import { CalendarXIcon } from "lucide-react";
+import {
+ EmptyState,
+ EmptyStateDescription,
+ EmptyStateFooter,
+ EmptyStateIcon,
+ EmptyStateTitle,
+} from "@/components/empty-state";
+import { Trans } from "@/i18n/client";
+
+/**
+ * Shown when the options list has nothing in it. The filtered case offers a
+ * way back, since the viewer hid the options themselves and would otherwise
+ * be looking at an empty panel with no obvious cause.
+ */
+export function VoteEmptyState({
+ isTimeSlot,
+ hiddenByFilter,
+ onShowAll,
+}: {
+ isTimeSlot: boolean;
+ /** True when options exist but the past filter is hiding all of them. */
+ hiddenByFilter: boolean;
+ onShowAll: () => void;
+}) {
+ return (
+ <EmptyState className="flex-1 p-8">
+ <EmptyStateIcon>
+ <CalendarXIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ {hiddenByFilter ? (
+ isTimeSlot ? (
+ <Trans i18nKey="allTimesPast" defaults="Every time has passed" />
+ ) : (
+ <Trans i18nKey="allDatesPast" defaults="Every date has passed" />
+ )
+ ) : isTimeSlot ? (
+ <Trans i18nKey="noTimes" defaults="No times to vote on" />
+ ) : (
+ <Trans i18nKey="noDates" defaults="No dates to vote on" />
+ )}
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ {hiddenByFilter ? (
+ <Trans
+ i18nKey="allOptionsPastDescription"
+ defaults="Turn off the filter to see them."
+ />
+ ) : (
+ <Trans
+ i18nKey="noOptionsDescription"
+ defaults="The organizer hasn't added any options yet."
+ />
+ )}
+ </EmptyStateDescription>
+ {hiddenByFilter ? (
+ <EmptyStateFooter>
+ <Button type="button" onClick={onShowAll}>
+ {isTimeSlot ? (
+ <Trans i18nKey="showPastTimes" defaults="Show past times" />
+ ) : (
+ <Trans i18nKey="showPastDates" defaults="Show past dates" />
+ )}
+ </Button>
+ </EmptyStateFooter>
+ ) : null}
+ </EmptyState>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-form.tsx b/apps/web/src/features/poll/vote/components/vote-form.tsx
new file mode 100644
index 000000000..ccd35826c
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-form.tsx
@@ -0,0 +1,304 @@
+"use client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Dialog, DialogContent } from "@rallly/ui/dialog";
+import { toast } from "@rallly/ui/sonner";
+import * as React from "react";
+import { FormProvider, useForm, useFormContext } from "react-hook-form";
+import * as z from "zod";
+import {
+ normalizeVotes,
+ useEditToken,
+ useUpdateParticipantVotes,
+} from "@/features/poll/components/mutations";
+import { NewParticipantForm } from "@/features/poll/components/new-participant-modal";
+import type { VoteType } from "@/features/poll/constants";
+import { getVoteTypes } from "@/features/poll/constants";
+import type { VotePageView, VoteResult } from "@/features/poll/vote/types";
+import { useTranslation } from "@/i18n/client";
+
+const schema = z.object({
+ mode: z.enum(["new", "edit", "view"]),
+ votes: z.array(
+ z
+ .object({
+ optionId: z.string(),
+ type: z.enum(["yes", "no", "ifNeedBe"]).optional(),
+ })
+ .optional(),
+ ),
+});
+
+type VoteFormValues = z.infer<typeof schema>;
+
+export const useVoteForm = () => useFormContext<VoteFormValues>();
+
+/**
+ * Writes one option's vote. Separate from `useVote` so a view that handles
+ * clicks above its cells can set a vote without subscribing to one option.
+ *
+ * `type` may be a function of the current vote, so a caller that cycles does
+ * not have to close over the votes: a stale closure would freeze the cycle
+ * after one step.
+ */
+export function useSetVote() {
+ const form = useVoteForm();
+
+ return React.useCallback(
+ (
+ optionId: string,
+ type: VoteType | ((current: VoteType | undefined) => VoteType),
+ ) => {
+ const next = [...form.getValues("votes")];
+ const at = next.findIndex((vote) => vote?.optionId === optionId);
+ const resolved =
+ typeof type === "function"
+ ? type(at === -1 ? undefined : next[at]?.type)
+ : type;
+ const entry = { optionId, type: resolved };
+ if (at === -1) {
+ next.push(entry);
+ } else {
+ next[at] = entry;
+ }
+ form.setValue("votes", next, { shouldDirty: true });
+ },
+ [form],
+ );
+}
+
+/**
+ * Read and write one option's vote. Every view goes through this, so the
+ * selection survives switching between them and no view needs to know how
+ * the votes array is laid out.
+ */
+export function useVote(optionId: string) {
+ const form = useVoteForm();
+ const votes = form.watch("votes");
+ const mode = form.watch("mode");
+ const index = votes.findIndex((vote) => vote?.optionId === optionId);
+ const set = useSetVote();
+
+ const setVote = React.useCallback(
+ (type: VoteType) => set(optionId, type),
+ [set, optionId],
+ );
+
+ return {
+ value: index === -1 ? undefined : votes[index]?.type,
+ setVote,
+ /** True while the viewer is composing, false when reviewing a saved one. */
+ isEditing: mode !== "view",
+ };
+}
+
+/**
+ * Every option's current vote, for views that style all their cells at once
+ * rather than one at a time. Returns the saved response once it is no longer
+ * being edited, so a view shows what is stored rather than a stale draft.
+ */
+export function useVotesByOption(savedVotes: Map<string, VoteType>) {
+ const form = useVoteForm();
+ const votes = form.watch("votes");
+ const mode = form.watch("mode");
+ const isEditing = mode !== "view";
+
+ const byOption = React.useMemo(() => {
+ if (!isEditing) {
+ return savedVotes;
+ }
+ const map = new Map<string, VoteType>();
+ for (const vote of votes) {
+ if (vote?.optionId && vote.type) {
+ map.set(vote.optionId, vote.type);
+ }
+ }
+ return map;
+ }, [votes, isEditing, savedVotes]);
+
+ return { byOption, isEditing };
+}
+
+/**
+ * An option's tally with the viewer's pending vote folded in, so the bar
+ * moves as they vote. The server score already counts their saved vote, so
+ * that one is taken back out first; a new response has none to remove.
+ *
+ * Returns null when the poll hides scores, matching the stored score.
+ */
+export function useLiveScore({
+ optionId,
+ score,
+ savedVote,
+ participantCount,
+ hasSavedResponse,
+}: {
+ score: VoteResult["score"];
+ optionId: string;
+ /** The viewer's stored vote on this option, already inside `score`. */
+ savedVote: VoteType | undefined;
+ participantCount: number | null;
+ /** Whether the viewer already counts towards `participantCount`. */
+ hasSavedResponse: boolean;
+}) {
+ const { value, isEditing } = useVote(optionId);
+
+ if (score === null || participantCount === null) {
+ return null;
+ }
+ if (!isEditing) {
+ return { score, participantCount };
+ }
+
+ const next = { ...score };
+ if (savedVote === "yes") {
+ next.yes -= 1;
+ } else if (savedVote === "ifNeedBe") {
+ next.ifNeedBe -= 1;
+ }
+ if (value === "yes") {
+ next.yes += 1;
+ } else if (value === "ifNeedBe") {
+ next.ifNeedBe += 1;
+ }
+
+ // A response in progress is not in the denominator yet. It counts once
+ // for the whole poll, not once per option with a vote on it.
+ return {
+ score: next,
+ participantCount: hasSavedResponse
+ ? participantCount
+ : participantCount + 1,
+ };
+}
+
+/**
+ * The next vote in the cycle, for views where one control advances through
+ * the types rather than offering all of them at once. The order is the
+ * shared display order, so a cycling cell and the list's control agree.
+ */
+export function nextVoteType(
+ current: VoteType | undefined,
+ allowTentativeVotes: boolean,
+): VoteType {
+ const types = getVoteTypes(allowTentativeVotes);
+ const at = current ? types.indexOf(current) : -1;
+ return types[(at + 1) % types.length];
+}
+
+/**
+ * A new response starts as a no on every option, which is what an
+ * untouched form submits anyway; showing it makes that explicit.
+ */
+const emptyVotes = (results: VotePageView["results"]) =>
+ results.map((result) => ({
+ optionId: result.optionId,
+ type: "no" as const,
+ }));
+
+/**
+ * Owns the response being composed. Writes go through a server action and
+ * the page then re-renders from the loader, so nothing is patched here.
+ */
+export function VoteForm({
+ pollId,
+ requireParticipantEmail,
+ results,
+ response,
+ canVote,
+ children,
+}: {
+ pollId: string;
+ requireParticipantEmail: boolean;
+ results: VotePageView["results"];
+ response: VotePageView["response"];
+ canVote: boolean;
+ children: React.ReactNode;
+}) {
+ const { t } = useTranslation();
+ const updateVotes = useUpdateParticipantVotes();
+ const token = useEditToken();
+ const [isNewParticipantOpen, setIsNewParticipantOpen] = React.useState(false);
+
+ const optionIds = results.map((result) => result.optionId);
+ const mode: VoteFormValues["mode"] = canVote && !response ? "new" : "view";
+ const form = useForm<VoteFormValues>({
+ defaultValues: { mode, votes: emptyVotes(results) },
+ resolver: zodResolver(schema),
+ });
+
+ // The page re-renders from the loader after every write, so the form
+ // follows the response appearing or disappearing: deleting one puts the
+ // viewer straight back into composing a new response. Only the response
+ // identity is a dependency; `results` and `mode` are recomputed on every
+ // server render and would fire this on any refresh.
+ const responseId = response?.participantId ?? null;
+ const lastResponseId = React.useRef(responseId);
+ const latest = React.useRef<{
+ mode: VoteFormValues["mode"];
+ results: VotePageView["results"];
+ }>({ mode, results });
+ latest.current = { mode, results };
+ React.useEffect(() => {
+ if (lastResponseId.current === responseId) {
+ return;
+ }
+ lastResponseId.current = responseId;
+ form.reset({
+ mode: latest.current.mode,
+ votes: emptyVotes(latest.current.results),
+ });
+ }, [responseId, form]);
+
+ return (
+ <FormProvider {...form}>
+ <form
+ id="vote-form"
+ onSubmit={form.handleSubmit(async (data) => {
+ if (!response) {
+ setIsNewParticipantOpen(true);
+ return;
+ }
+
+ const result = await updateVotes.execute({
+ participantId: response.participantId,
+ votes: normalizeVotes(optionIds, data.votes),
+ token,
+ });
+
+ if (!result.ok) {
+ // Stay in edit mode so the selection is not lost.
+ toast.error(
+ result.reason === "closed"
+ ? t("pollClosedDescription", {
+ defaultValue: "No more responses are being accepted.",
+ })
+ : t("actionErrorInternalServerError", {
+ defaultValue: "An internal server error occurred",
+ }),
+ );
+ return;
+ }
+
+ form.reset({ mode: "view", votes: emptyVotes(results) });
+ })}
+ />
+ <Dialog
+ open={isNewParticipantOpen}
+ onOpenChange={setIsNewParticipantOpen}
+ >
+ <DialogContent size="sm">
+ <NewParticipantForm
+ pollId={pollId}
+ requireParticipantEmail={requireParticipantEmail}
+ votes={normalizeVotes(optionIds, form.watch("votes"))}
+ onSubmit={() => {
+ form.reset({ mode: "view", votes: emptyVotes(results) });
+ }}
+ onCancel={() => setIsNewParticipantOpen(false)}
+ />
+ </DialogContent>
+ </Dialog>
+ {children}
+ </FormProvider>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-outcome.tsx b/apps/web/src/features/poll/vote/components/vote-outcome.tsx
new file mode 100644
index 000000000..a51741509
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-outcome.tsx
@@ -0,0 +1,107 @@
+"use client";
+import { Button } from "@rallly/ui/button";
+import { CalendarIcon, LockIcon } from "lucide-react";
+import * as React from "react";
+import {
+ EmptyState,
+ EmptyStateDescription,
+ EmptyStateFooter,
+ EmptyStateIcon,
+ EmptyStateTitle,
+} from "@/components/empty-state";
+import { AddToCalendarButton } from "@/features/calendars/components/add-to-calendar-button";
+import type { VotePageView } from "@/features/poll/vote/types";
+import {
+ EventDate,
+ EventTimeRange,
+} from "@/features/scheduled-event/components/event-date-time";
+import { Trans } from "@/i18n/client";
+
+/**
+ * Stands in for the panel while a poll is scheduled or closed, until the
+ * viewer asks to see the results.
+ */
+export function VoteOutcome({
+ poll,
+ children,
+}: {
+ poll: VotePageView["poll"];
+ children: React.ReactNode;
+}) {
+ const [dismissed, setDismissed] = React.useState(false);
+
+ if (!dismissed && poll.status === "scheduled" && poll.event) {
+ const allDay = poll.event.duration === 0;
+ return (
+ <EmptyState className="flex-1">
+ <EmptyStateIcon>
+ <CalendarIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans i18nKey="pollStatusScheduled" defaults="Scheduled" />
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ <span className="flex flex-col items-center gap-0.5">
+ <EventDate
+ value={poll.event.start}
+ allDay={allDay}
+ timeZone={poll.timeZone}
+ preset="dateFull"
+ className={allDay ? undefined : "text-foreground"}
+ />
+ <EventTimeRange
+ start={poll.event.start}
+ end={
+ new Date(
+ poll.event.start.getTime() + poll.event.duration * 60_000,
+ )
+ }
+ allDay={allDay}
+ timeZone={poll.timeZone}
+ showTimeZone
+ />
+ </span>
+ </EmptyStateDescription>
+ <EmptyStateFooter className="flex flex-wrap items-center justify-center gap-2">
+ <AddToCalendarButton eventId={poll.event.id} />
+ <Button onClick={() => setDismissed(true)}>
+ <Trans i18nKey="viewResults" defaults="View results" />
+ </Button>
+ </EmptyStateFooter>
+ </EmptyState>
+ );
+ }
+
+ if (!dismissed && poll.status === "closed") {
+ return (
+ <EmptyState className="flex-1">
+ <EmptyStateIcon>
+ <LockIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans i18nKey="pollStatusClosed" defaults="Closed" />
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ {poll.closedReason === "auto" ? (
+ <Trans
+ i18nKey="pollAutoClosedDescription"
+ defaults="This poll was closed automatically because all of its dates have passed. No more responses are being accepted."
+ />
+ ) : (
+ <Trans
+ i18nKey="pollClosedDescription"
+ defaults="No more responses are being accepted."
+ />
+ )}
+ </EmptyStateDescription>
+ <EmptyStateFooter>
+ <Button onClick={() => setDismissed(true)}>
+ <Trans i18nKey="viewResults" defaults="View results" />
+ </Button>
+ </EmptyStateFooter>
+ </EmptyState>
+ );
+ }
+
+ return children;
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-page-footer.tsx b/apps/web/src/features/poll/vote/components/vote-page-footer.tsx
new file mode 100644
index 000000000..52cd8d949
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-page-footer.tsx
@@ -0,0 +1,22 @@
+import { InstanceFooterLinks } from "@/components/instance-footer-links";
+
+/**
+ * The instance's footer links, which carry legal disclosures and are shown
+ * regardless of the space's settings. Attribution and the theme switcher
+ * live in the card's sidebar footer instead.
+ */
+export function VotePageFooter({
+ footerLinks,
+}: {
+ footerLinks: { label: string; href: string }[];
+}) {
+ if (footerLinks.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-col items-center gap-4 py-3 text-center text-muted-foreground text-sm">
+ <InstanceFooterLinks links={footerLinks} />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-panel-footer.tsx b/apps/web/src/features/poll/vote/components/vote-panel-footer.tsx
new file mode 100644
index 000000000..2dd484b1f
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-panel-footer.tsx
@@ -0,0 +1,300 @@
+"use client";
+import { Button } from "@rallly/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ useDialog,
+} from "@rallly/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@rallly/ui/dropdown-menu";
+import { toast } from "@rallly/ui/sonner";
+import { MoreHorizontalIcon, TagIcon, TrashIcon } from "lucide-react";
+import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
+import {
+ ChangeNameModal,
+ DeleteParticipantModal,
+} from "@/features/poll/components/participant-dropdown";
+import VoteIcon from "@/features/poll/components/vote-icon";
+import { useVoteForm } from "@/features/poll/vote/components/vote-form";
+import type { VotePageView } from "@/features/poll/vote/types";
+import { Trans, useTranslation } from "@/i18n/client";
+
+function SelectionCount({
+ yesCount,
+ ifNeedBeCount,
+ allowTentativeVotes,
+}: {
+ yesCount: number;
+ ifNeedBeCount: number;
+ allowTentativeVotes: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <p aria-live="polite" className="flex items-center gap-4 text-sm">
+ <span className="sr-only">
+ {allowTentativeVotes
+ ? t("optionVoteBreakdown", {
+ defaultValue: "{yesScore} yes, {ifNeedBeScore} if need be",
+ yesScore: yesCount,
+ ifNeedBeScore: ifNeedBeCount,
+ })
+ : t("optionVoteBreakdownYesOnly", {
+ defaultValue: "{yesScore} yes",
+ yesScore: yesCount,
+ })}
+ </span>
+ {/* A zero says nothing the empty footer does not already say. */}
+ {yesCount > 0 ? (
+ <span aria-hidden="true" className="inline-flex items-center gap-1.5">
+ <VoteIcon type="yes" />
+ <span className="tabular-nums">{yesCount}</span>
+ </span>
+ ) : null}
+ {allowTentativeVotes && ifNeedBeCount > 0 ? (
+ <span aria-hidden="true" className="inline-flex items-center gap-1.5">
+ <VoteIcon type="ifNeedBe" />
+ <span className="tabular-nums">{ifNeedBeCount}</span>
+ </span>
+ ) : null}
+ </p>
+ );
+}
+
+/**
+ * The response and its actions. While composing, that is the live selection
+ * count with Decline and Continue, or Cancel and Save when editing. Once a
+ * response is saved it becomes the participant's name with Edit and an
+ * overflow menu, so the panel header is left to display settings alone.
+ */
+export function VotePanelFooter({
+ poll,
+ results,
+ response,
+ canVote,
+}: {
+ poll: VotePageView["poll"];
+ results: VotePageView["results"];
+ response: VotePageView["response"];
+ canVote: boolean;
+}) {
+ const { t } = useTranslation();
+ const form = useVoteForm();
+ const confirmDialog = useDialog();
+ const changeNameDialog = useDialog();
+ const deleteDialog = useDialog();
+ const mode = form.watch("mode");
+ const votes = form.watch("votes");
+
+ if (response && mode === "view") {
+ return (
+ // Keyed so React remounts rather than reusing the composing footer's
+ // DOM nodes. Both branches render the same shape, so without this the
+ // button under the pointer is reused: a click on Edit finishes on the
+ // Save button that takes its place and submits the response.
+ <footer
+ key="saved"
+ className="sticky bottom-0 z-10 flex min-h-16 shrink-0 items-center justify-between gap-4 bg-card px-4 py-3 lg:static lg:bg-transparent"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <OptimizedAvatarImage
+ size="sm"
+ name={response.name}
+ src={response.image ?? undefined}
+ className="shrink-0"
+ />
+ <p className="truncate font-medium text-sm">{response.name}</p>
+ </div>
+ {canVote ? (
+ <div className="flex shrink-0 items-center gap-2">
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ data-testid="participant-menu"
+ render={
+ <Button
+ aria-label={t("moreOptions", {
+ defaultValue: "More options",
+ })}
+ variant="ghost"
+ size="icon"
+ >
+ <MoreHorizontalIcon />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => changeNameDialog.trigger()}>
+ <TagIcon />
+ <Trans i18nKey="changeName" defaults="Change name" />
+ </DropdownMenuItem>
+ {/* Removing the response entirely is rarer than changing it
+ to a no, so it sits in the menu rather than beside Edit. */}
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => deleteDialog.trigger()}
+ >
+ <TrashIcon />
+ <Trans i18nKey="delete" defaults="Delete" />
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Button
+ onClick={() => {
+ form.reset({
+ mode: "edit",
+ votes: results.map((result) => ({
+ optionId: result.optionId,
+ type: response.votes.find(
+ (vote) => vote.optionId === result.optionId,
+ )?.type,
+ })),
+ });
+ }}
+ >
+ <Trans i18nKey="edit" defaults="Edit" />
+ </Button>
+ <ChangeNameModal
+ {...changeNameDialog.dialogProps}
+ oldName={response.name}
+ participantId={response.participantId}
+ />
+ <DeleteParticipantModal
+ {...deleteDialog.dialogProps}
+ participantId={response.participantId}
+ participantName={response.name}
+ />
+ </div>
+ ) : null}
+ </footer>
+ );
+ }
+
+ if (!canVote || mode === "view") {
+ return null;
+ }
+
+ const yesCount = votes.filter((vote) => vote?.type === "yes").length;
+ const ifNeedBeCount = votes.filter(
+ (vote) => vote?.type === "ifNeedBe",
+ ).length;
+ const selectedCount = yesCount + ifNeedBeCount;
+ const isBlocked = !response && selectedCount === 0;
+
+ const submitAllNo = () => {
+ form.setValue(
+ "votes",
+ results.map((result) => ({
+ optionId: result.optionId,
+ type: "no" as const,
+ })),
+ );
+ document.querySelector<HTMLFormElement>("#vote-form")?.requestSubmit();
+ };
+
+ return (
+ // Below lg the page scrolls, so the footer pins to the viewport rather
+ // than scrolling away from the options it acts on. Keyed to match the
+ // saved footer above, so the two never share DOM nodes.
+ <footer
+ key="composing"
+ className="sticky bottom-0 z-10 flex min-h-16 shrink-0 items-center justify-between gap-4 bg-card px-4 py-3 lg:static lg:bg-transparent"
+ >
+ <SelectionCount
+ yesCount={yesCount}
+ ifNeedBeCount={ifNeedBeCount}
+ allowTentativeVotes={poll.allowTentativeVotes}
+ />
+ <div className="flex items-center gap-2">
+ {response ? (
+ <Button
+ onClick={() => {
+ form.reset({
+ mode: "view",
+ votes: results.map((result) => ({
+ optionId: result.optionId,
+ })),
+ });
+ }}
+ >
+ <Trans i18nKey="cancel" defaults="Cancel" />
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ disabled={form.formState.isSubmitting}
+ onClick={() => {
+ if (selectedCount > 0) {
+ confirmDialog.trigger();
+ } else {
+ submitAllNo();
+ }
+ }}
+ >
+ <Trans i18nKey="decline" defaults="Decline" />
+ </Button>
+ )}
+ <Button
+ form="vote-form"
+ type="submit"
+ variant="primary"
+ aria-disabled={isBlocked}
+ loading={form.formState.isSubmitting}
+ onClick={(event) => {
+ if (isBlocked) {
+ event.preventDefault();
+ toast(
+ t("selectAtLeastOneOptionOrDecline", {
+ defaultValue: "Select at least one option, or decline",
+ }),
+ );
+ }
+ }}
+ >
+ {response ? (
+ <Trans i18nKey="save" defaults="Save" />
+ ) : (
+ <Trans i18nKey="continue" defaults="Continue" />
+ )}
+ </Button>
+ </div>
+ <Dialog {...confirmDialog.dialogProps}>
+ <DialogContent size="sm">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="declineConfirmTitle" defaults="Decline?" />
+ </DialogTitle>
+ <DialogDescription>
+ <Trans
+ i18nKey="declineConfirmDescription"
+ defaults="{count, plural, one {This will discard your selected option and respond no to everything.} other {This will discard your # selected options and respond no to everything.}}"
+ values={{ count: selectedCount }}
+ />
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button onClick={() => confirmDialog.dismiss()}>
+ <Trans i18nKey="cancel" defaults="Cancel" />
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={form.formState.isSubmitting}
+ onClick={() => {
+ confirmDialog.dismiss();
+ submitAllNo();
+ }}
+ >
+ <Trans i18nKey="decline" defaults="Decline" />
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </footer>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-panel-header.tsx b/apps/web/src/features/poll/vote/components/vote-panel-header.tsx
new file mode 100644
index 000000000..3999d81f2
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-panel-header.tsx
@@ -0,0 +1,92 @@
+"use client";
+import { HidePastToggle } from "@/features/poll/vote/components/hide-past-toggle";
+import { TimeFormatSwitcher } from "@/features/poll/vote/components/time-format-switcher";
+import { TimeZoneSwitcher } from "@/features/poll/vote/components/time-zone-switcher";
+import { VoteViewSwitcher } from "@/features/poll/vote/components/vote-view-switcher";
+import type { VotePageView, VoteViewId } from "@/features/poll/vote/types";
+
+/**
+ * The panel's controls: what is shown on the left, how it is shown on the
+ * right. Filtering lives on the left, display settings on the right; the
+ * response itself belongs to the footer.
+ */
+export function VotePanelHeader({
+ poll,
+ results,
+ views,
+ view,
+ onViewChange,
+ pastCount,
+ hidePast,
+ onHidePastChange,
+}: {
+ poll: VotePageView["poll"];
+ results: VotePageView["results"];
+ /** The views this poll offers; the switcher is hidden below two. */
+ views: VoteViewId[];
+ view: VoteViewId;
+ onViewChange: (view: VoteViewId) => void;
+ /** How many options have already passed; the filter hides itself at zero. */
+ pastCount: number;
+ hidePast: boolean;
+ onHidePastChange: (hidePast: boolean) => void;
+}) {
+ const isTimeSlot = (results[0]?.duration ?? 0) > 0;
+ // Floating-time polls have no zone to switch, so the zone picker only
+ // appears on zoned time polls. Only a time poll has a format to set.
+ const showClock = isTimeSlot && poll.timeZone !== null;
+ const showTimeFormat = isTimeSlot;
+ const showViewSwitcher = views.length > 1;
+ // Nothing to hide on a poll whose options are all still ahead.
+ const showHidePast = pastCount > 0;
+
+ const hasFilters = showHidePast;
+ const hasDisplaySettings = showClock || showTimeFormat || showViewSwitcher;
+
+ if (!hasFilters && !hasDisplaySettings) {
+ return null;
+ }
+
+ return (
+ <header // Below lg the page scrolls, so the header pins to the viewport; from
+ // lg up the panel's own layout places it. Below sm the two groups take
+ // a line each rather than squeezing onto one.
+ // px-4 to match the rows and the footer. The segmented controls paint
+ // their own background, so their box edge is the edge you see; a
+ // smaller pad would leave them overhanging everything below.
+ className="sticky top-0 z-20 flex min-h-14 shrink-0 flex-col items-stretch gap-2 bg-card px-4 py-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4 lg:static lg:bg-transparent"
+ >
+ <div
+ data-testid="filters"
+ className="flex min-w-0 items-center gap-2 empty:hidden"
+ >
+ {showHidePast ? (
+ <HidePastToggle
+ checked={hidePast}
+ onCheckedChange={onHidePastChange}
+ isTimeSlot={isTimeSlot}
+ />
+ ) : null}
+ </div>
+ {hasDisplaySettings ? (
+ <div
+ data-testid="display-settings"
+ // ms-auto rather than relying on justify-between: the filters
+ // group hides itself when empty, and with one child left
+ // justify-between puts it at the start.
+ className="flex shrink-0 items-center justify-end gap-2 sm:ms-auto"
+ >
+ {showViewSwitcher ? (
+ <VoteViewSwitcher
+ views={views}
+ value={view}
+ onChange={onViewChange}
+ />
+ ) : null}
+ {showClock ? <TimeZoneSwitcher /> : null}
+ {showTimeFormat ? <TimeFormatSwitcher /> : null}
+ </div>
+ ) : null}
+ </header>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-panel.tsx b/apps/web/src/features/poll/vote/components/vote-panel.tsx
new file mode 100644
index 000000000..1605d7ef3
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-panel.tsx
@@ -0,0 +1,141 @@
+"use client";
+import * as React from "react";
+import { VoteEmptyState } from "@/features/poll/vote/components/vote-empty-state";
+import { VoteForm } from "@/features/poll/vote/components/vote-form";
+import { VoteOutcome } from "@/features/poll/vote/components/vote-outcome";
+import { VotePanelFooter } from "@/features/poll/vote/components/vote-panel-footer";
+import { VotePanelHeader } from "@/features/poll/vote/components/vote-panel-header";
+import { VoteViewCalendar } from "@/features/poll/vote/components/vote-view-calendar";
+import { VoteViewList } from "@/features/poll/vote/components/vote-view-list";
+import { VoteViewWeek } from "@/features/poll/vote/components/vote-view-week";
+import type {
+ VotePageView,
+ VoteResult,
+ VoteViewId,
+} from "@/features/poll/vote/types";
+import { UserProvider } from "@/features/user/client";
+import type { UserDTO } from "@/features/user/schema";
+import { useHydrated } from "@/lib/datetime/use-hydrated";
+import { getCalendarDate, toISODate } from "@/lib/datetime/utils";
+import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
+
+/**
+ * Whether an option has already been and gone, from the viewer's clock.
+ *
+ * A time slot is past once it has ended. An all-day date is a floating
+ * calendar date stored as UTC midnight (RFC 5545), so it is past only once
+ * the viewer's own calendar date has moved on — comparing its instant to
+ * now would retire today's date for everyone west of UTC.
+ */
+function pastPredicate(isTimeSlot: boolean) {
+ if (isTimeSlot) {
+ const now = Date.now();
+ return (result: VoteResult) =>
+ result.startTime.getTime() + result.duration * 60_000 < now;
+ }
+ const today = getCalendarDate(new Date(), getBrowserTimeZone());
+ return (result: VoteResult) => toISODate(result.startTime) < today;
+}
+
+/**
+ * The voting panel: a header, the results table as the scroll area, and a
+ * footer. Client only, and it renders nothing until hydration: option times
+ * are formatted in the viewer's zone, which the server cannot know, so
+ * server rendering them would show a time the browser then corrects.
+ */
+export function VotePanel({
+ poll,
+ results,
+ participantCount,
+ response,
+ canVote,
+ requireParticipantEmail,
+ user,
+}: VotePageView & {
+ requireParticipantEmail: boolean;
+ /** Signing in as a guest happens here, so the viewer is client state. */
+ user: UserDTO | null;
+}) {
+ const hydrated = useHydrated();
+ const [view, setView] = React.useState<VoteViewId>("list");
+ const [hidePast, setHidePast] = React.useState(false);
+
+ if (!hydrated) {
+ return null;
+ }
+
+ // A month cell is a day, so only all-day polls can offer a calendar; a
+ // time poll would have several options on one cell and gets the week
+ // view instead, which has room to stack them.
+ const isTimeSlot = (results[0]?.duration ?? 0) > 0;
+ const views: VoteViewId[] = isTimeSlot
+ ? ["list", "week"]
+ : ["list", "calendar"];
+ const activeView = views.includes(view) ? view : "list";
+
+ // Safe to read the clock here: the panel renders only after hydration, so
+ // this never runs during a server render.
+ const isPast = pastPredicate(isTimeSlot);
+ const pastCount = results.filter(isPast).length;
+ // Only the displayed options are filtered. The form still holds a vote for
+ // every option, so hiding one never drops it from the saved response.
+ const visibleResults =
+ hidePast && pastCount > 0
+ ? results.filter((result) => !isPast(result))
+ : results;
+
+ // Every view takes these, so switching is a swap with nothing rewired.
+ const viewProps = {
+ poll,
+ results: visibleResults,
+ participantCount,
+ response,
+ canVote,
+ };
+
+ return (
+ <UserProvider user={user}>
+ <VoteForm
+ pollId={poll.id}
+ requireParticipantEmail={requireParticipantEmail}
+ results={results}
+ response={response}
+ canVote={canVote}
+ >
+ <VoteOutcome poll={poll}>
+ <div className="flex min-h-0 flex-1 flex-col">
+ <VotePanelHeader
+ poll={poll}
+ results={results}
+ views={views}
+ view={activeView}
+ onViewChange={setView}
+ pastCount={pastCount}
+ hidePast={hidePast}
+ onHidePastChange={setHidePast}
+ />
+ {visibleResults.length === 0 ? (
+ <VoteEmptyState
+ isTimeSlot={isTimeSlot}
+ hiddenByFilter={results.length > 0}
+ onShowAll={() => setHidePast(false)}
+ />
+ ) : activeView === "calendar" ? (
+ <VoteViewCalendar {...viewProps} />
+ ) : activeView === "week" ? (
+ <VoteViewWeek {...viewProps} />
+ ) : (
+ <VoteViewList {...viewProps} />
+ )}
+ <VotePanelFooter
+ poll={poll}
+ results={results}
+ response={response}
+ canVote={canVote}
+ />
+ </div>
+ </VoteOutcome>
+ </VoteForm>
+ </UserProvider>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-progress.tsx b/apps/web/src/features/poll/vote/components/vote-progress.tsx
new file mode 100644
index 000000000..51c305771
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-progress.tsx
@@ -0,0 +1,82 @@
+"use client";
+import { cn } from "@rallly/ui";
+import type { VoteResult } from "@/features/poll/vote/types";
+import { useTranslation } from "@/i18n/client";
+
+/**
+ * An option's tally as a share of everyone who responded: a yes segment, a
+ * tentative one, and the rest left empty. The counts are also given as text
+ * for screen readers, which cannot read a bar.
+ */
+export function VoteProgress({
+ score,
+ participantCount,
+ allowTentativeVotes,
+ className,
+}: {
+ score: NonNullable<VoteResult["score"]>;
+ participantCount: number;
+ allowTentativeVotes: boolean;
+ /** Sizes the track; a calendar cell gives it the full cell width. */
+ className?: string;
+}) {
+ const { t } = useTranslation();
+ const total = Math.max(participantCount, score.yes + score.ifNeedBe);
+ const pct = (n: number) => (total > 0 ? (n / total) * 100 : 0);
+ // A poll that turned tentative votes off after some were cast still has
+ // them, so the segment appears whenever there are any.
+ const showTentative = allowTentativeVotes || score.ifNeedBe > 0;
+
+ const label = showTentative
+ ? t("optionVoteBreakdownOfTotal", {
+ defaultValue:
+ "{yesScore} yes, {ifNeedBeScore} if need be, of {total} responses",
+ yesScore: score.yes,
+ ifNeedBeScore: score.ifNeedBe,
+ total: participantCount,
+ })
+ : t("optionVoteBreakdownYesOfTotal", {
+ defaultValue: "{yesScore} yes of {total} responses",
+ yesScore: score.yes,
+ total: participantCount,
+ });
+
+ const yesPct = pct(score.yes);
+ const tentativePct = pct(score.ifNeedBe);
+
+ return (
+ <span className="flex items-center">
+ <span
+ aria-hidden="true"
+ // The track needs to read as an empty share, so it sits a step away
+ // from the surface in both themes rather than using one muted token.
+ className={cn(
+ "relative block h-1.5 w-16 overflow-hidden rounded-sm bg-gray-200 dark:bg-gray-700",
+ className,
+ )}
+ >
+ {/* Each segment fills the track and is scaled down to its share, so
+ the size change is a transform rather than a width: width would
+ lay out and paint every frame, and two flex siblings animating
+ their widths would fight over the leftover space.
+ motion-reduce keeps the colour and drops the travel. */}
+ <span
+ className="absolute inset-0 origin-left bg-green-500 transition-transform duration-200 ease-out-ui motion-reduce:transition-none"
+ style={{ transform: `scaleX(${yesPct / 100})` }}
+ />
+ {showTentative ? (
+ <span
+ className="absolute inset-0 origin-left bg-amber-400 transition-transform duration-200 ease-out-ui motion-reduce:transition-none"
+ style={{
+ // Sits after the yes segment, then takes its own share.
+ transform: `translateX(${yesPct}%) scaleX(${tentativePct / 100})`,
+ }}
+ />
+ ) : null}
+ </span>
+ {/* The bar carries no number, so the counts are the only thing a
+ screen reader gets. */}
+ <span className="sr-only">{label}</span>
+ </span>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-score.tsx b/apps/web/src/features/poll/vote/components/vote-score.tsx
new file mode 100644
index 000000000..0ff6bc130
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-score.tsx
@@ -0,0 +1,48 @@
+"use client";
+import type { VoteType } from "@/features/poll/constants";
+import { useLiveScore } from "@/features/poll/vote/components/vote-form";
+import { VoteProgress } from "@/features/poll/vote/components/vote-progress";
+import type { VoteResult } from "@/features/poll/vote/types";
+
+/**
+ * An option's tally, following the viewer's pending vote so the bar moves
+ * as they vote. Shared by every view so they agree on the arithmetic.
+ */
+export function VoteScore({
+ optionId,
+ score,
+ savedVote,
+ participantCount,
+ hasSavedResponse,
+ allowTentativeVotes,
+ className,
+}: {
+ optionId: string;
+ score: VoteResult["score"];
+ savedVote: VoteType | undefined;
+ participantCount: number | null;
+ hasSavedResponse: boolean;
+ allowTentativeVotes: boolean;
+ className?: string;
+}) {
+ const live = useLiveScore({
+ optionId,
+ score,
+ savedVote,
+ participantCount,
+ hasSavedResponse,
+ });
+
+ if (!live) {
+ return null;
+ }
+
+ return (
+ <VoteProgress
+ score={live.score}
+ participantCount={live.participantCount}
+ allowTentativeVotes={allowTentativeVotes}
+ className={className}
+ />
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-view-calendar.tsx b/apps/web/src/features/poll/vote/components/vote-view-calendar.tsx
new file mode 100644
index 000000000..b93c271d8
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-view-calendar.tsx
@@ -0,0 +1,273 @@
+"use client";
+import { cn } from "@rallly/ui";
+import type { MonthGridDayProps } from "@rallly/ui/month-grid";
+import { MonthGrid } from "@rallly/ui/month-grid";
+import * as React from "react";
+import VoteIcon from "@/features/poll/components/vote-icon";
+import type { VoteType } from "@/features/poll/constants";
+import {
+ nextVoteType,
+ useSetVote,
+ useVote,
+ useVoteForm,
+ useVotesByOption,
+} from "@/features/poll/vote/components/vote-form";
+import { VoteScore } from "@/features/poll/vote/components/vote-score";
+import type { VoteResult, VoteViewProps } from "@/features/poll/vote/types";
+import { useTranslation } from "@/i18n/client";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import { getLocaleDefaults } from "@/lib/datetime/locales";
+import { useHydrated } from "@/lib/datetime/use-hydrated";
+import { toISODate } from "@/lib/datetime/utils";
+
+/**
+ * The tint each vote gives its day, applied through DayPicker's modifiers.
+ * No keeps the plain surface: a new response is a no on every option, so
+ * tinting it would make a fresh month a wall of red. The icon in the corner
+ * is what states the vote, so colour is never alone.
+ */
+const modifiersClassNames: Record<string, string> = {
+ // A day the poll does not offer is recessed, so the month reads as a
+ // calendar and the votable days stand out as the surface.
+ notOption: "bg-muted/40",
+ voteYes: "bg-green-100 dark:bg-green-500/20",
+ voteIfNeedBe: "bg-amber-100 dark:bg-amber-500/20",
+};
+
+/** Months the options fall in, so the calendar opens on the first one. */
+function getMonthRange(results: VoteResult[]) {
+ let first: Date | undefined;
+ let last: Date | undefined;
+ for (const result of results) {
+ const month = new Date(
+ Date.UTC(
+ result.startTime.getUTCFullYear(),
+ result.startTime.getUTCMonth(),
+ 1,
+ ),
+ );
+ if (!first || month < first) {
+ first = month;
+ }
+ if (!last || month > last) {
+ last = month;
+ }
+ }
+ return { first, last };
+}
+
+type DayContext = {
+ byDate: Map<string, VoteResult>;
+ savedVotes: Map<string, VoteType>;
+ participantCount: number | null;
+ hasSavedResponse: boolean;
+ allowTentativeVotes: boolean;
+ canVote: boolean;
+};
+
+const DayContextValue = React.createContext<DayContext | null>(null);
+
+/** The contents of a day the poll offers: its number, vote and tally. */
+function OptionDayContent({
+ result,
+ dayNumber,
+}: {
+ result: VoteResult;
+ dayNumber: React.ReactNode;
+}) {
+ const ctx = React.useContext(DayContextValue);
+ const { value, isEditing } = useVote(result.optionId);
+ const savedVote = ctx?.savedVotes.get(result.optionId);
+ const shown = isEditing ? value : savedVote;
+
+ return (
+ <>
+ <span className="flex w-full items-start justify-between gap-1">
+ <span aria-hidden="true" className="tabular-nums">
+ {dayNumber}
+ </span>
+ {/* VoteIcon carries its own title, so the vote is announced
+ without the cell repeating it. */}
+ {shown ? <VoteIcon type={shown} size="sm" /> : null}
+ </span>
+ <VoteScore
+ optionId={result.optionId}
+ score={result.score}
+ savedVote={savedVote}
+ participantCount={ctx?.participantCount ?? null}
+ hasSavedResponse={ctx?.hasSavedResponse ?? false}
+ allowTentativeVotes={ctx?.allowTentativeVotes ?? true}
+ className="w-full"
+ />
+ </>
+ );
+}
+
+/**
+ * One day. DayPicker owns the button and its click, so this fills it: the
+ * poll's own days carry a vote, the rest are inert numbers.
+ */
+function DayCell({ day, modifiers, className, ...props }: MonthGridDayProps) {
+ const ctx = React.useContext(DayContextValue);
+ const result = ctx?.byDate.get(toISODate(day.date));
+ const interactive = result !== undefined && (ctx?.canVote ?? false);
+
+ return (
+ <button
+ type="button"
+ // The tint comes from the cell's modifier class, so the button is
+ // transparent and only owns its layout and focus ring.
+ className={cn(
+ "flex h-full w-full flex-col justify-between gap-1 rounded-lg p-2 text-left text-sm transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
+ interactive
+ ? "cursor-pointer hover:brightness-[0.97] dark:hover:brightness-125"
+ : "cursor-default text-muted-foreground",
+ className,
+ )}
+ {...props}
+ >
+ {result ? (
+ <OptionDayContent result={result} dayNumber={props.children} />
+ ) : (
+ <span aria-hidden="true" className="tabular-nums">
+ {props.children}
+ </span>
+ )}
+ </button>
+ );
+}
+
+/**
+ * The options as a month calendar, one cell per day. Days the poll does not
+ * offer are inert, so the month reads as a calendar rather than a list.
+ */
+export function VoteViewCalendar({
+ poll,
+ results,
+ participantCount,
+ response,
+ canVote,
+}: VoteViewProps) {
+ const hydrated = useHydrated();
+ const { locale } = useDateTimeConfig();
+ const { t } = useTranslation();
+
+ const savedVotes = React.useMemo(() => {
+ const map = new Map<string, VoteType>();
+ for (const vote of response?.votes ?? []) {
+ map.set(vote.optionId, vote.type);
+ }
+ return map;
+ }, [response]);
+
+ // Keyed by calendar date, so a day cell finds its option in one lookup.
+ const byDate = React.useMemo(() => {
+ const map = new Map<string, VoteResult>();
+ for (const result of results) {
+ map.set(toISODate(result.startTime), result);
+ }
+ return map;
+ }, [results]);
+
+ const { first, last } = React.useMemo(
+ () => getMonthRange(results),
+ [results],
+ );
+
+ // The votes drive the day tints through DayPicker's modifiers, so a click
+ // restyles its cell the same way a prop-driven modifier would.
+ const { byOption: currentVotes } = useVotesByOption(savedVotes);
+ const modifiers = React.useMemo(() => {
+ const yes: Date[] = [];
+ const ifNeedBe: Date[] = [];
+ for (const result of results) {
+ const vote = currentVotes.get(result.optionId);
+ if (vote === "yes") {
+ yes.push(result.startTime);
+ } else if (vote === "ifNeedBe") {
+ ifNeedBe.push(result.startTime);
+ }
+ }
+ return { voteYes: yes, voteIfNeedBe: ifNeedBe };
+ }, [results, currentVotes]);
+
+ // DayPicker owns the day buttons, so the click is handled here rather
+ // than in the cell: it maps the date back to its option and advances it.
+ const setVote = useSetVote();
+ const form = useVoteForm();
+ const handleDayClick = React.useCallback(
+ (date: Date) => {
+ const result = byDate.get(toISODate(date));
+ // Read the mode at click time: DayPicker holds on to this handler, so
+ // a captured value would go stale the moment the response is saved.
+ if (!result || !canVote || form.getValues("mode") === "view") {
+ return;
+ }
+ setVote(result.optionId, (current) =>
+ nextVoteType(current, poll.allowTentativeVotes),
+ );
+ },
+ [byDate, canVote, form, setVote, poll.allowTentativeVotes],
+ );
+
+ const ctx = React.useMemo(
+ () => ({
+ byDate,
+ savedVotes,
+ participantCount,
+ hasSavedResponse: response !== null,
+ allowTentativeVotes: poll.allowTentativeVotes,
+ canVote,
+ }),
+ [
+ byDate,
+ savedVotes,
+ participantCount,
+ response,
+ poll.allowTentativeVotes,
+ canVote,
+ ],
+ );
+
+ // Intl output is not stable across engines, so the calendar waits for the
+ // client, exactly as the list's dates do.
+ if (!hydrated) {
+ return null;
+ }
+
+ const { weekStart } = getLocaleDefaults(locale);
+
+ return (
+ // A month is a fixed number of weeks, so from lg the grid fills the
+ // panel rather than scrolling inside it. Below lg the page scrolls and
+ // the weeks keep their natural height.
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ <DayContextValue.Provider value={ctx}>
+ <MonthGrid
+ // All-day options are stored as UTC wall time, so the calendar
+ // does its month maths in UTC; anything else shifts a day across
+ // the boundary.
+ timeZone="UTC"
+ weekStartsOn={weekStart as 0 | 1 | 2 | 3 | 4 | 5 | 6}
+ defaultMonth={first}
+ startMonth={first}
+ endMonth={last}
+ onDayClick={handleDayClick}
+ modifiers={{
+ notOption: (date: Date) => !byDate.has(toISODate(date)),
+ ...modifiers,
+ }}
+ modifiersClassNames={modifiersClassNames}
+ labels={{
+ labelNext: () =>
+ t("nextMonth", { defaultValue: "Go to the next month" }),
+ labelPrevious: () =>
+ t("previousMonth", { defaultValue: "Go to the previous month" }),
+ }}
+ renderDay={(dayProps) => <DayCell {...dayProps} />}
+ className="min-h-0 flex-1 p-4"
+ />
+ </DayContextValue.Provider>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-view-list.tsx b/apps/web/src/features/poll/vote/components/vote-view-list.tsx
new file mode 100644
index 000000000..47e352422
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-view-list.tsx
@@ -0,0 +1,254 @@
+"use client";
+import {
+ createColumnHelper,
+ getCoreRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import * as React from "react";
+import { DataList } from "@/components/data-list";
+import VoteIcon from "@/features/poll/components/vote-icon";
+import { VoteSegmentedControl } from "@/features/poll/components/vote-segmented-control";
+import type { VoteType } from "@/features/poll/constants";
+import { OptionDate } from "@/features/poll/vote/components/option-date";
+import {
+ useVote,
+ useVotesByOption,
+} from "@/features/poll/vote/components/vote-form";
+import { VoteScore } from "@/features/poll/vote/components/vote-score";
+import type { VoteResult, VoteViewProps } from "@/features/poll/vote/types";
+import { EventTimeRange } from "@/features/scheduled-event/components/event-date-time";
+import { Trans } from "@/i18n/client";
+import { CalendarDate } from "@/lib/datetime/calendar-date";
+import { useDateTime } from "@/lib/datetime/client";
+import {
+ calendarDateToUTCMidnight,
+ getCalendarDate,
+} from "@/lib/datetime/utils";
+
+/** A recorded vote: icon only, with the vote type for screen readers. */
+function VoteLabel({ type }: { type?: VoteType }) {
+ return (
+ // flex rather than inline-flex: an inline box sits on the text
+ // baseline, which leaves the icon a few pixels above the row's centre.
+ <span className="flex items-center justify-center">
+ <VoteIcon type={type} />
+ <span className="sr-only">
+ {type === "yes" ? (
+ <Trans i18nKey="yes" defaults="Yes" />
+ ) : type === "ifNeedBe" ? (
+ <Trans i18nKey="ifNeedBe" defaults="If need be" />
+ ) : type === "no" ? (
+ <Trans i18nKey="no" defaults="No" />
+ ) : (
+ <Trans i18nKey="pending" defaults="Pending" />
+ )}
+ </span>
+ </span>
+ );
+}
+
+const columnHelper = createColumnHelper<VoteResult>();
+
+const endOf = (result: VoteResult) =>
+ new Date(result.startTime.getTime() + result.duration * 60_000);
+
+function VoteCell({
+ optionId,
+ optionLabel,
+ allowTentativeVotes,
+ savedVote,
+ canVote,
+}: {
+ optionId: string;
+ optionLabel: string;
+ allowTentativeVotes: boolean;
+ savedVote?: VoteType;
+ canVote: boolean;
+}) {
+ const { value, setVote, isEditing } = useVote(optionId);
+
+ if (!canVote || !isEditing) {
+ return savedVote !== undefined ? <VoteLabel type={savedVote} /> : null;
+ }
+ return (
+ <VoteSegmentedControl
+ value={value}
+ onChange={setVote}
+ optionLabel={optionLabel}
+ allowTentativeVotes={allowTentativeVotes}
+ />
+ );
+}
+
+/**
+ * The options as a list. A time poll groups them by day under the same
+ * headings the events page uses; a date poll's rows each carry their own
+ * full date, so they run flat.
+ */
+export function VoteViewList({
+ poll,
+ results,
+ participantCount,
+ response,
+ canVote,
+}: VoteViewProps) {
+ const { formatDateTime, formatDateTimeRange } = useDateTime();
+
+ const isTimeSlot = (results[0]?.duration ?? 0) > 0;
+ // All-day dates and floating times are stored as UTC wall time and read
+ // back in UTC; a zoned time poll is read in the viewer's zone.
+ const readZone = isTimeSlot && poll.timeZone ? undefined : "UTC";
+
+ const savedVotes = React.useMemo(() => {
+ const map = new Map<string, VoteType>();
+ for (const vote of response?.votes ?? []) {
+ map.set(vote.optionId, vote.type);
+ }
+ return map;
+ }, [response]);
+
+ const columns = React.useMemo(
+ () => [
+ columnHelper.display({
+ id: "option",
+ meta: { className: "text-sm" },
+ cell: ({ row }) => (
+ // DataList owns the row element, so the option cell carries the
+ // handle tests use to find an option.
+ <span data-testid="poll-option" className="truncate">
+ {isTimeSlot ? (
+ <EventTimeRange
+ start={row.original.startTime}
+ end={endOf(row.original)}
+ allDay={false}
+ timeZone={poll.timeZone}
+ />
+ ) : (
+ <OptionDate value={row.original.startTime} />
+ )}
+ </span>
+ ),
+ }),
+ columnHelper.display({
+ id: "votes",
+ // The vote control needs the width on a narrow screen, and the bar
+ // is what can go.
+ meta: { className: "hidden justify-end sm:flex" },
+ cell: ({ row }) => (
+ <VoteScore
+ optionId={row.original.optionId}
+ score={row.original.score}
+ savedVote={savedVotes.get(row.original.optionId)}
+ participantCount={participantCount}
+ hasSavedResponse={response !== null}
+ allowTentativeVotes={poll.allowTentativeVotes}
+ />
+ ),
+ }),
+ columnHelper.display({
+ id: "vote",
+ meta: { className: "justify-end" },
+ cell: ({ row }) => {
+ const result = row.original;
+ const optionLabel = isTimeSlot
+ ? `${formatDateTime(result.startTime, "dateFull", {
+ timeZone: readZone,
+ })}, ${formatDateTimeRange(
+ result.startTime,
+ endOf(result),
+ "time",
+ {
+ timeZone: readZone,
+ },
+ )}`
+ : formatDateTime(result.startTime, "dateFull", { timeZone: "UTC" });
+ return (
+ <VoteCell
+ optionId={result.optionId}
+ optionLabel={optionLabel}
+ allowTentativeVotes={poll.allowTentativeVotes}
+ savedVote={savedVotes.get(result.optionId)}
+ canVote={canVote}
+ />
+ );
+ },
+ }),
+ ],
+ [
+ canVote,
+ participantCount,
+ formatDateTime,
+ formatDateTimeRange,
+ isTimeSlot,
+ poll.allowTentativeVotes,
+ poll.timeZone,
+ readZone,
+ response,
+ savedVotes,
+ ],
+ );
+
+ const table = useReactTable({
+ data: results,
+ columns,
+ getRowId: (result) => result.optionId,
+ getCoreRowModel: getCoreRowModel(),
+ });
+
+ // The tint follows the vote being composed, not just the saved one, so
+ // the row responds as the viewer picks. Same colours as the calendar.
+ // The gradient is a background image, so the row's hover colour would
+ // show through its transparent end; hover is cleared to keep it clean.
+ const { byOption: currentVotes } = useVotesByOption(savedVotes);
+ const getRowClassName = (result: VoteResult) => {
+ const vote = currentVotes.get(result.optionId);
+ if (vote === "yes") {
+ return "bg-linear-to-r from-green-50 to-transparent text-green-700 hover:bg-transparent dark:from-green-500/10 dark:text-green-400";
+ }
+ if (vote === "ifNeedBe") {
+ return "bg-linear-to-r from-amber-50 to-transparent text-amber-700 hover:bg-transparent dark:from-amber-500/10 dark:text-amber-400";
+ }
+ return undefined;
+ };
+
+ // DataList groups adjacent rows, and the loader returns options in time
+ // order, so each day's slots already sit together.
+ const getGroup = isTimeSlot
+ ? (result: VoteResult) => {
+ const key = getCalendarDate(result.startTime, readZone ?? "UTC");
+ return {
+ id: key,
+ label: (
+ <>
+ <CalendarDate
+ value={calendarDateToUTCMidnight(key)}
+ preset="weekday"
+ className="font-medium text-foreground"
+ />
+ <CalendarDate
+ value={calendarDateToUTCMidnight(key)}
+ preset="dateLong"
+ className="text-muted-foreground"
+ />
+ </>
+ ),
+ };
+ }
+ : undefined;
+
+ return (
+ // The scroll area. Only the results scroll, and only from lg: below
+ // that the page scrolls, so the list grows to its natural height.
+ <div className="lg:scrollbar-thin dark:lg:scrollbar-thumb-gray-600 dark:lg:scrollbar-track-gray-800 hover:lg:scrollbar-thumb-gray-400 dark:hover:lg:scrollbar-thumb-gray-500 lg:scrollbar-thumb-gray-300 lg:scrollbar-track-transparent relative flex-1 lg:min-h-0 lg:overflow-y-auto">
+ <DataList
+ table={table}
+ getGroup={getGroup}
+ getRowClassName={getRowClassName}
+ rowGapClassName="gap-y-1"
+ // py-4 to match DataList's own px-4: its default py-2 leaves the
+ // last row's vote control close to the panel's edge.
+ className="grid-cols-[minmax(0,1fr)_auto] py-4 sm:grid-cols-[minmax(0,1fr)_auto_auto]"
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-view-switcher.tsx b/apps/web/src/features/poll/vote/components/vote-view-switcher.tsx
new file mode 100644
index 000000000..49406bfc2
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-view-switcher.tsx
@@ -0,0 +1,63 @@
+"use client";
+import {
+ SegmentedControl,
+ SegmentedControlItem,
+} from "@rallly/ui/segmented-control";
+import { CalendarIcon, ColumnsIcon, ListIcon } from "lucide-react";
+import type { VoteViewId } from "@/features/poll/vote/types";
+import { useTranslation } from "@/i18n/client";
+
+const icons: Record<VoteViewId, typeof ListIcon> = {
+ list: ListIcon,
+ calendar: CalendarIcon,
+ week: ColumnsIcon,
+};
+
+/**
+ * Picks the voting view. The views share a props interface and read their
+ * votes from the form context, so switching keeps the selection. Which
+ * views exist is the panel's call, since it depends on the poll's shape.
+ */
+export function VoteViewSwitcher({
+ views,
+ value,
+ onChange,
+}: {
+ views: VoteViewId[];
+ value: VoteViewId;
+ onChange: (value: VoteViewId) => void;
+}) {
+ const { t } = useTranslation();
+
+ const labels: Record<VoteViewId, string> = {
+ list: t("voteViewList", { defaultValue: "List" }),
+ calendar: t("voteViewCalendar", { defaultValue: "Calendar" }),
+ week: t("voteViewWeek", { defaultValue: "Week" }),
+ };
+
+ return (
+ <SegmentedControl
+ aria-label={t("voteView", { defaultValue: "View" })}
+ value={value}
+ onValueChange={(next) => {
+ if (next) {
+ onChange(next as VoteViewId);
+ }
+ }}
+ >
+ {views.map((view) => {
+ const Icon = icons[view];
+ return (
+ <SegmentedControlItem
+ key={view}
+ value={view}
+ aria-label={labels[view]}
+ className="w-9"
+ >
+ <Icon className="size-4" />
+ </SegmentedControlItem>
+ );
+ })}
+ </SegmentedControl>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/components/vote-view-week.tsx b/apps/web/src/features/poll/vote/components/vote-view-week.tsx
new file mode 100644
index 000000000..45443f4dd
--- /dev/null
+++ b/apps/web/src/features/poll/vote/components/vote-view-week.tsx
@@ -0,0 +1,327 @@
+"use client";
+import { cn } from "@rallly/ui";
+import { Button } from "@rallly/ui/button";
+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
+import * as React from "react";
+import VoteIcon from "@/features/poll/components/vote-icon";
+import { VoteSegmentedControl } from "@/features/poll/components/vote-segmented-control";
+import type { VoteType } from "@/features/poll/constants";
+import { useVote } from "@/features/poll/vote/components/vote-form";
+import { VoteScore } from "@/features/poll/vote/components/vote-score";
+import type { VoteResult, VoteViewProps } from "@/features/poll/vote/types";
+import { Trans, useTranslation } from "@/i18n/client";
+import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";
+import { getLocaleDefaults } from "@/lib/datetime/locales";
+import { getCalendarDate } from "@/lib/datetime/utils";
+import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+type Day = { key: string; date: Date; results: VoteResult[] };
+type Week = { start: Date; days: Day[] };
+
+/**
+ * Groups options into weeks of seven days, keeping only weeks that hold at
+ * least one option. Navigation then steps between weeks that have something
+ * to vote on rather than walking through empty ones.
+ */
+function buildWeeks(
+ results: VoteResult[],
+ weekStart: number,
+ keyOf: (value: Date) => string,
+): Week[] {
+ const byDay = new Map<string, VoteResult[]>();
+ for (const result of results) {
+ const key = keyOf(result.startTime);
+ const bucket = byDay.get(key);
+ if (bucket) {
+ bucket.push(result);
+ } else {
+ byDay.set(key, [result]);
+ }
+ }
+
+ const weeks = new Map<number, Week>();
+ for (const [key, dayResults] of byDay) {
+ // The key is a calendar date, so midnight UTC anchors it without the
+ // viewer's offset shifting which day it lands on.
+ const date = new Date(`${key}T00:00:00Z`);
+ const offset = (date.getUTCDay() - weekStart + 7) % 7;
+ const start = new Date(date.getTime() - offset * DAY_MS);
+ const stamp = start.getTime();
+
+ let week = weeks.get(stamp);
+ if (!week) {
+ week = {
+ start,
+ days: Array.from({ length: 7 }, (_, index) => {
+ const dayDate = new Date(stamp + index * DAY_MS);
+ return {
+ key: dayDate.toISOString().slice(0, 10),
+ date: dayDate,
+ results: [],
+ };
+ }),
+ };
+ weeks.set(stamp, week);
+ }
+ const day = week.days.find((candidate) => candidate.key === key);
+ if (day) {
+ day.results = dayResults.sort(
+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),
+ );
+ }
+ }
+
+ return [...weeks.values()].sort(
+ (a, b) => a.start.getTime() - b.start.getTime(),
+ );
+}
+
+function TimeOption({
+ result,
+ timeZone,
+ readZone,
+ savedVote,
+ participantCount,
+ hasSavedResponse,
+ allowTentativeVotes,
+ canVote,
+}: {
+ result: VoteResult;
+ timeZone: string | null;
+ readZone: string | undefined;
+ savedVote: VoteType | undefined;
+ participantCount: number | null;
+ hasSavedResponse: boolean;
+ allowTentativeVotes: boolean;
+ canVote: boolean;
+}) {
+ const { formatDateTime, formatDateTimeRange } = useDateTime();
+ const { value, setVote, isEditing } = useVote(result.optionId);
+ const shown = isEditing ? value : savedVote;
+ const end = new Date(result.startTime.getTime() + result.duration * 60_000);
+
+ const label = `${formatDateTime(result.startTime, "dateFull", {
+ timeZone: readZone,
+ })}, ${formatDateTimeRange(result.startTime, end, "time", {
+ timeZone: readZone,
+ })}`;
+
+ return (
+ <li className="rounded-lg border bg-card p-2">
+ <p className="truncate font-medium text-sm tabular-nums">
+ {formatDateTimeRange(result.startTime, end, "time", {
+ timeZone: readZone,
+ })}
+ </p>
+ <div className="mt-1.5">
+ <VoteScore
+ optionId={result.optionId}
+ score={result.score}
+ savedVote={savedVote}
+ participantCount={participantCount}
+ hasSavedResponse={hasSavedResponse}
+ allowTentativeVotes={allowTentativeVotes}
+ className="w-full"
+ />
+ </div>
+ <div className="mt-2">
+ {canVote && isEditing ? (
+ <VoteSegmentedControl
+ value={value}
+ onChange={setVote}
+ optionLabel={label}
+ allowTentativeVotes={allowTentativeVotes}
+ className="w-full"
+ />
+ ) : (
+ <span className="flex h-9 items-center justify-center">
+ {shown ? <VoteIcon type={shown} /> : null}
+ </span>
+ )}
+ </div>
+ </li>
+ );
+}
+
+/**
+ * A week of seven day columns with each day's times stacked beneath it.
+ * Only weeks holding options are reachable, so navigation never lands on an
+ * empty one.
+ */
+export function VoteViewWeek({
+ poll,
+ results,
+ participantCount,
+ response,
+ canVote,
+}: VoteViewProps) {
+ const { t } = useTranslation();
+ const { locale } = useDateTimeConfig();
+ const { formatDateTime, formatDateTimeRange } = useDateTime();
+ const [hideEmptyDays, setHideEmptyDays] = React.useState(false);
+ const [weekIndex, setWeekIndex] = React.useState(0);
+
+ // A zoned time poll is read in the viewer's zone; a floating one is
+ // stored as UTC wall time and read back in UTC.
+ const readZone = poll.timeZone ? undefined : "UTC";
+
+ const savedVotes = React.useMemo(() => {
+ const map = new Map<string, VoteType>();
+ for (const vote of response?.votes ?? []) {
+ map.set(vote.optionId, vote.type);
+ }
+ return map;
+ }, [response]);
+
+ const { weekStart } = getLocaleDefaults(locale);
+ // The calendar date an option falls on, in the zone it is read in, so a
+ // late-evening slot groups under its own day rather than the next one.
+ const keyZone = readZone ?? getBrowserTimeZone();
+ const weeks = React.useMemo(
+ () =>
+ buildWeeks(results, weekStart, (value) =>
+ getCalendarDate(value, keyZone),
+ ),
+ [results, weekStart, keyZone],
+ );
+
+ // Options can change under the viewer (the past filter, a refresh), so
+ // clamp rather than trusting the stored index.
+ const index = Math.min(weekIndex, Math.max(weeks.length - 1, 0));
+ const week = weeks[index];
+
+ if (!week) {
+ return null;
+ }
+
+ const days = hideEmptyDays
+ ? week.days.filter((day) => day.results.length > 0)
+ : week.days;
+ const emptyDayCount = week.days.length - days.length;
+ // Kept while hiding is on, so a fully booked week still offers the way
+ // back.
+ const hasEmptyDays =
+ hideEmptyDays || week.days.some((day) => day.results.length === 0);
+
+ return (
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ <div className="flex shrink-0 items-center justify-between gap-2 px-4 py-2">
+ <div className="flex items-center gap-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t("previousWeek", { defaultValue: "Previous week" })}
+ disabled={index === 0}
+ onClick={() => setWeekIndex(index - 1)}
+ >
+ <ChevronLeftIcon />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t("nextWeek", { defaultValue: "Next week" })}
+ disabled={index >= weeks.length - 1}
+ onClick={() => setWeekIndex(index + 1)}
+ >
+ <ChevronRightIcon />
+ </Button>
+ {/* A range rather than one month: a week can straddle two, and
+ formatRange collapses "May 4 – 10" when it does not. */}
+ <p className="ms-1 font-medium text-sm">
+ {formatDateTimeRange(
+ week.start,
+ new Date(week.start.getTime() + 6 * DAY_MS),
+ "date",
+ { timeZone: "UTC" },
+ )}
+ </p>
+ </div>
+ {hasEmptyDays ? (
+ <Button
+ type="button"
+ variant="ghost"
+ aria-pressed={hideEmptyDays}
+ onClick={() => setHideEmptyDays(!hideEmptyDays)}
+ >
+ {hideEmptyDays ? (
+ <Trans i18nKey="showEmptyDays" defaults="Show empty days" />
+ ) : (
+ <Trans i18nKey="hideEmptyDays" defaults="Hide empty days" />
+ )}
+ </Button>
+ ) : null}
+ </div>
+ <div className="lg:scrollbar-thin min-h-0 flex-1 lg:overflow-y-auto">
+ <div
+ className={cn(
+ "grid gap-2 px-4 pb-4",
+ // Seven across only when there is room; below that the columns
+ // would be too narrow to hold a time and its vote control.
+ days.length > 0 && "grid-cols-2 sm:grid-cols-4 lg:grid-cols-7",
+ )}
+ style={
+ hideEmptyDays && days.length < 7
+ ? {
+ gridTemplateColumns: `repeat(${days.length}, minmax(0, 1fr))`,
+ }
+ : undefined
+ }
+ >
+ {days.map((day) => (
+ <section key={day.key} className="min-w-0">
+ <h3 className="sticky top-0 z-10 bg-card pb-2 text-center">
+ {/* The two lines read as one date to a screen reader, which
+ would otherwise hear "Sunday" and "4" as separate words. */}
+ <span className="sr-only">
+ {formatDateTime(day.date, "dateFull", { timeZone: "UTC" })}
+ </span>
+ <span aria-hidden="true">
+ <span className="block text-muted-foreground text-xs">
+ {formatDateTime(day.date, "weekday", { timeZone: "UTC" })}
+ </span>
+ <span className="block font-medium text-sm tabular-nums">
+ {formatDateTime(day.date, "day", { timeZone: "UTC" })}
+ </span>
+ </span>
+ </h3>
+ {day.results.length > 0 ? (
+ <ul className="flex flex-col gap-2">
+ {day.results.map((result) => (
+ <TimeOption
+ key={result.optionId}
+ result={result}
+ timeZone={poll.timeZone}
+ readZone={readZone}
+ savedVote={savedVotes.get(result.optionId)}
+ participantCount={participantCount}
+ hasSavedResponse={response !== null}
+ allowTentativeVotes={poll.allowTentativeVotes}
+ canVote={canVote}
+ />
+ ))}
+ </ul>
+ ) : (
+ <p className="rounded-lg border border-dashed py-4 text-center text-muted-foreground text-xs">
+ <Trans i18nKey="noTimesShort" defaults="None" />
+ </p>
+ )}
+ </section>
+ ))}
+ </div>
+ {hideEmptyDays && emptyDayCount > 0 ? (
+ <p className="px-4 pb-4 text-muted-foreground text-xs">
+ <Trans
+ i18nKey="emptyDaysHidden"
+ defaults="{count, plural, one {# day hidden} other {# days hidden}}"
+ values={{ count: emptyDayCount }}
+ />
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/vote/data.ts b/apps/web/src/features/poll/vote/data.ts
new file mode 100644
index 000000000..c2a777437
--- /dev/null
+++ b/apps/web/src/features/poll/vote/data.ts
@@ -0,0 +1,80 @@
+import "server-only";
+
+import { prisma } from "@rallly/database";
+
+/**
+ * Yes and if-need-be counts per option, aggregated in the database so a
+ * page that only shows totals never loads individual votes.
+ */
+export async function getOptionScores({ pollId }: { pollId: string }) {
+ const rows = await prisma.vote.groupBy({
+ by: ["optionId", "type"],
+ where: { pollId, type: { in: ["yes", "ifNeedBe"] } },
+ _count: { _all: true },
+ });
+
+ const scores = new Map<string, { yes: number; ifNeedBe: number }>();
+ for (const row of rows) {
+ const score = scores.get(row.optionId) ?? { yes: 0, ifNeedBe: 0 };
+ if (row.type === "yes") {
+ score.yes = row._count._all;
+ } else if (row.type === "ifNeedBe") {
+ score.ifNeedBe = row._count._all;
+ }
+ scores.set(row.optionId, score);
+ }
+ return scores;
+}
+
+/**
+ * The viewer's own response: the most recently created one they may edit.
+ * A viewer can hold several (a signed-in user who also voted as a guest),
+ * but the page offers one response, so the loader picks it here rather
+ * than leaving the choice to the client.
+ */
+export async function getViewerResponse({
+ pollId,
+ userId,
+ participantIds,
+}: {
+ pollId: string;
+ userId?: string;
+ participantIds: string[];
+}) {
+ if (!userId && participantIds.length === 0) {
+ return null;
+ }
+
+ const participant = await prisma.participant.findFirst({
+ where: {
+ pollId,
+ OR: [
+ ...(userId ? [{ userId }] : []),
+ ...(participantIds.length > 0 ? [{ id: { in: participantIds } }] : []),
+ ],
+ },
+ select: {
+ id: true,
+ name: true,
+ votes: { select: { optionId: true, type: true } },
+ user: { select: { image: true } },
+ },
+ orderBy: { createdAt: "desc" },
+ });
+
+ if (!participant) {
+ return null;
+ }
+
+ return {
+ participantId: participant.id,
+ name: participant.name,
+ image: participant.user?.image ?? null,
+ votes: participant.votes,
+ };
+}
+
+/** How many people have responded, for the per-option tallies. */
+export async function countParticipants({ pollId }: { pollId: string }) {
+ return prisma.participant.count({ where: { pollId } });
+}
diff --git a/apps/web/src/features/poll/vote/loaders.ts b/apps/web/src/features/poll/vote/loaders.ts
new file mode 100644
index 000000000..37be38ee1
--- /dev/null
+++ b/apps/web/src/features/poll/vote/loaders.ts
@@ -0,0 +1,132 @@
+import "server-only";
+
+import { notFound } from "next/navigation";
+import { cache } from "react";
+import {
+ canUserManagePoll,
+ getPollDetails,
+ listParticipantIdsByToken,
+} from "@/features/poll/data";
+import {
+ countParticipants,
+ getOptionScores,
+ getViewerResponse,
+} from "@/features/poll/vote/data";
+import type { VotePageView } from "@/features/poll/vote/types";
+import { getSession } from "@/lib/auth";
+
+/**
+ * Everything the vote page renders, in one read, with visibility already
+ * resolved: a hidden score is absent from the result rather than filtered
+ * on the client, and the viewer's single response is chosen here.
+ */
+export const loadVotePage = cache(
+ async ({
+ pollId,
+ token,
+ }: {
+ pollId: string;
+ token?: string;
+ }): Promise<VotePageView> => {
+ const poll = await getPollDetails({ pollId });
+
+ if (!poll) {
+ notFound();
+ }
+
+ const [session, participantIds] = await Promise.all([
+ getSession(),
+ token ? listParticipantIdsByToken({ pollId, token }) : [],
+ ]);
+
+ const userId = session?.user?.id;
+
+ const responsePromise = getViewerResponse({
+ pollId,
+ userId,
+ participantIds,
+ });
+
+ const [response, scores, participantCount] = await Promise.all([
+ responsePromise,
+ // Scores stay hidden until the viewer has responded, so they are not
+ // read at all when they cannot be shown.
+ poll.hideScores
+ ? responsePromise.then((found) =>
+ found ? getOptionScores({ pollId }) : null,
+ )
+ : getOptionScores({ pollId }),
+ countParticipants({ pollId }),
+ ]);
+
+ // hideScores reveals the tally only once the viewer has responded.
+ const scoresVisible = !poll.hideScores || response !== null;
+
+ return {
+ poll: {
+ id: poll.id,
+ title: poll.title,
+ description: poll.description,
+ location: poll.location,
+ conferencing: poll.conferencing,
+ status: poll.status,
+ closedReason: poll.closedReason,
+ allowTentativeVotes: poll.allowTentativeVotes,
+ timeZone: poll.timeZone,
+ userId: poll.userId,
+ spaceId: poll.spaceId,
+ requireParticipantEmail: poll.requireParticipantEmail,
+ user: poll.user ? { name: poll.user.name } : null,
+ space: poll.space
+ ? {
+ name: poll.space.name,
+ image: poll.space.image,
+ showBranding: poll.space.showBranding,
+ hideAttribution: poll.space.hideAttribution,
+ primaryColor: poll.space.primaryColor,
+ }
+ : null,
+ event: poll.event
+ ? {
+ id: poll.event.id,
+ start: poll.event.start,
+ duration: poll.event.duration,
+ conferencingUri: poll.event.conferencingUri,
+ }
+ : null,
+ },
+ participantCount: scoresVisible ? participantCount : null,
+ results: poll.options.map((option) => ({
+ optionId: option.id,
+ startTime: option.startTime,
+ duration: option.duration,
+ score:
+ scoresVisible && scores
+ ? (scores.get(option.id) ?? { yes: 0, ifNeedBe: 0 })
+ : null,
+ })),
+ response,
+ canVote: poll.status === "open",
+ };
+ },
+);
+
+/**
+ * Whether the viewer may manage this poll: its owner, or a member of the
+ * space it belongs to when that space is shared. Returns false rather than
+ * redirecting, because the vote page shows everyone the participant view
+ * and only offers the host a way through to the admin page.
+ */
+export const loadCanManagePoll = cache(async (pollId: string) => {
+ const [poll, session] = await Promise.all([
+ getPollDetails({ pollId }),
+ getSession(),
+ ]);
+
+ const user = session?.user;
+ if (!poll || !user) {
+ return false;
+ }
+
+ return canUserManagePoll(user, poll);
+});
diff --git a/apps/web/src/features/poll/vote/types.ts b/apps/web/src/features/poll/vote/types.ts
new file mode 100644
index 000000000..2f4565f0f
--- /dev/null
+++ b/apps/web/src/features/poll/vote/types.ts
@@ -0,0 +1,78 @@
+import type { PollConferencing } from "@/features/conferencing/schema";
+import type { VoteType } from "@/features/poll/constants";
+import type { PollClosedReason, PollStatus } from "@/features/poll/schema";
+
+/** One option with its tally. `score` is null when the poll hides scores. */
+export type VoteResult = {
+ optionId: string;
+ startTime: Date;
+ duration: number;
+ score: { yes: number; ifNeedBe: number } | null;
+};
+
+/** The viewer's own response. */
+export type VoteResponse = {
+ participantId: string;
+ name: string;
+ image: string | null;
+ votes: { optionId: string; type: VoteType }[];
+};
+
+/**
+ * Everything the vote page renders, with visibility already resolved: a
+ * hidden score is absent rather than filtered client side, and the viewer's
+ * response is chosen here rather than derived from a participant list.
+ */
+export type VotePageView = {
+ poll: {
+ id: string;
+ title: string;
+ description: string | null;
+ location: string | null;
+ conferencing: PollConferencing | null;
+ status: PollStatus;
+ closedReason: PollClosedReason | null;
+ allowTentativeVotes: boolean;
+ timeZone: string | null;
+ userId: string | null;
+ spaceId: string | null;
+ requireParticipantEmail: boolean;
+ user: { name: string } | null;
+ space: {
+ name: string;
+ image: string | null;
+ showBranding: boolean;
+ hideAttribution: boolean;
+ primaryColor: string | null;
+ } | null;
+ event: {
+ id: string;
+ start: Date;
+ duration: number;
+ /** The minted meeting's link, once the poll is finalized. */
+ conferencingUri: string | null;
+ } | null;
+ };
+ results: VoteResult[];
+ /** Denominator for the per-option tallies; null when scores are hidden. */
+ participantCount: number | null;
+ response: VoteResponse | null;
+ /** False once the poll is closed or scheduled. */
+ canVote: boolean;
+};
+
+/**
+ * What every voting view receives. The votes being composed are not in
+ * here: views read and write them through the form context, so switching
+ * view keeps the selection.
+ */
+export type VoteViewProps = {
+ poll: VotePageView["poll"];
+ results: VoteResult[];
+ participantCount: number | null;
+ response: VoteResponse | null;
+ canVote: boolean;
+};
+
+/** Which voting view is on screen. */
+export type VoteViewId = "list" | "calendar" | "week";
diff --git a/apps/web/src/lib/datetime/format.test.ts b/apps/web/src/lib/datetime/format.test.ts
index 1635841df..4d3fef689 100644
--- a/apps/web/src/lib/datetime/format.test.ts
+++ b/apps/web/src/lib/datetime/format.test.ts
@@ -19,6 +19,20 @@ const ctx = (locale: string, timeFormat?: TimeFormat, timeZone = "UTC") => ({
});
describe("formatDateTime", () => {
+ it("formats a year on its own, for a date poll's group heading", () => {
+ expect(formatDateTime(at(9), { preset: "year", ...ctx("en") })).toBe(
+ "2026",
+ );
+ });
+
+ it("formats a weekday and day for a row inside a month group", () => {
+ // The locale decides the order ("26 Fri" in en, "Fri 26" in en-GB).
+ const out = formatDateTime(at(9), { preset: "weekdayDay", ...ctx("en") });
+ expect(out).toContain("Fri");
+ expect(out).toContain("26");
+ expect(out).not.toContain("Jun");
+ });
+
it("formats 24-hour time", () => {
expect(
formatDateTime(at(13), { preset: "time", ...ctx("en", "hours24") }),
diff --git a/apps/web/src/lib/datetime/format.ts b/apps/web/src/lib/datetime/format.ts
index f6719bd77..33a612dda 100644
--- a/apps/web/src/lib/datetime/format.ts
+++ b/apps/web/src/lib/datetime/format.ts
@@ -8,7 +8,11 @@ export type DatePreset =
| "weekday"
| "weekdayMonthDay"
| "monthYear"
- | "monthDay";
+ | "monthDay"
+ | "weekdayDay"
+ | "weekdayMonthDayShort"
+ | "year"
+ | "day";
export type DateTimePreset = DatePreset | "time" | "datetime";
@@ -96,8 +100,16 @@ function presetOptions(
return { weekday: "long", month: "long", day: "numeric" };
case "monthYear":
return { month: "long", year: "numeric" };
+ case "weekdayMonthDayShort":
+ return { weekday: "short", month: "short", day: "numeric" };
+ case "year":
+ return { year: "numeric" };
+ case "day":
+ return { day: "numeric" };
case "monthDay":
return { month: "long", day: "numeric" };
+ case "weekdayDay":
+ return { weekday: "short", day: "numeric" };
case "datetime":
return {
year: "numeric",
diff --git a/apps/web/tests/accessibility.spec.ts b/apps/web/tests/accessibility.spec.ts
index 4f472c3b9..9c34ded58 100644
--- a/apps/web/tests/accessibility.spec.ts
+++ b/apps/web/tests/accessibility.spec.ts
@@ -85,4 +85,28 @@ test.describe("accessibility (axe-core, WCAG 2.1 A/AA)", () => {
expect(await scan(page)).toEqual([]);
});
});
+
+ test.describe("vote page calendar", () => {
+ let voteUrl: string;
+
+ test.beforeAll(async ({ browser }) => {
+ const page = await browser.newPage();
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ await newPollPage.create({ name: "Accessibility Dates", allDay: true });
+ const match = page.url().match(/\/poll\/([a-zA-Z0-9]+)/);
+ if (!match) {
+ throw new Error(`could not extract poll id from ${page.url()}`);
+ }
+ voteUrl = `/invite/${match[1]}/vote`;
+ await page.close();
+ });
+
+ test("month grid", async ({ page }) => {
+ await page.goto(voteUrl);
+ await page.getByRole("radio", { name: "Calendar" }).click();
+ await page.getByRole("grid").waitFor();
+ expect(await scan(page)).toEqual([]);
+ });
+ });
});
diff --git a/apps/web/tests/new-poll-page.ts b/apps/web/tests/new-poll-page.ts
index 8b7f39b47..7ef743aec 100644
--- a/apps/web/tests/new-poll-page.ts
+++ b/apps/web/tests/new-poll-page.ts
@@ -12,9 +12,12 @@ export class NewPollPage {
async create({
name,
enableComments,
+ allDay,
}: {
name: string;
enableComments?: boolean;
+ /** Creates a date poll rather than the default time poll. */
+ allDay?: boolean;
}): Promise<PollPage> {
const page = this.page;
@@ -61,6 +64,10 @@ export class NewPollPage {
await page.getByText("10", { exact: true }).first().click();
await page.getByText("15", { exact: true }).first().click();
+ if (allDay) {
+ await page.getByTestId("all-day-option").click();
+ }
+
if (enableComments) {
// Comments are off by default; opt in to the legacy comments setting
await page.getByRole("switch", { name: /comments/i }).click();
diff --git a/apps/web/tests/vote-page.spec.ts b/apps/web/tests/vote-page.spec.ts
new file mode 100644
index 000000000..2fcb9d594
--- /dev/null
+++ b/apps/web/tests/vote-page.spec.ts
@@ -0,0 +1,277 @@
+import type { Locator } from "@playwright/test";
+import { expect, test } from "@playwright/test";
+import { NewPollPage } from "./new-poll-page";
+
+/**
+ * The list row an option sits in, which is what carries its geometry.
+ * A grouped list nests rows inside a group item, so this excludes anything
+ * holding another row.
+ */
+function optionRow(main: Locator) {
+ // has/hasNot resolve inside each li, so they are built from the page: a
+ // locator scoped to main would look for main inside the row.
+ const page = main.page();
+ return main
+ .locator("li")
+ .filter({ has: page.getByTestId("poll-option") })
+ .filter({ hasNot: page.locator("li") });
+}
+
+async function box(locator: Locator) {
+ const rect = await locator.boundingBox();
+ if (!rect) {
+ throw new Error("Element has no bounding box");
+ }
+ return rect;
+}
+
+test.describe("vote page", () => {
+ let voteUrl: string;
+
+ test.beforeAll(async ({ browser }) => {
+ const page = await browser.newPage();
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ const pollPage = await newPollPage.create({ name: "Vote Page Meetup" });
+ const inviteUrl = await pollPage.copyInviteLink();
+ voteUrl = `${inviteUrl.replace(/\?.*$/, "")}/vote`;
+ await page.close();
+ });
+
+ test("desktop shows the event beside the list and saves a response", async ({
+ page,
+ }) => {
+ await page.goto(voteUrl);
+
+ const main = page.locator("#main-content");
+ const sidebar = main.getByRole("complementary");
+ await expect(sidebar.getByRole("heading", { level: 1 })).toHaveText(
+ "Vote Page Meetup",
+ );
+
+ // Sidebar sits to the left of the list at desktop width
+ const sidebarBox = await box(sidebar);
+ // The row, not the option cell: the cell holds a time that renders
+ // only after hydration, so it has no box until then.
+ const optionBox = await box(optionRow(main).first());
+ expect(optionBox.x).toBeGreaterThan(sidebarBox.x + sidebarBox.width - 1);
+
+ // The grid never renders on this page
+ await expect(page.getByTestId("add-participant-button")).toHaveCount(0);
+
+ // The page itself never scrolls; only the list column does
+ const overflow = await page.evaluate(
+ () =>
+ document.documentElement.scrollHeight -
+ document.documentElement.clientHeight,
+ );
+ expect(overflow).toBe(0);
+
+ // The selection count follows the votes
+ const bar = main.locator("footer");
+ await expect(bar.getByText("0 yes, 0 if need be")).toBeVisible();
+ await page
+ .getByTestId("vote-selector")
+ .first()
+ .getByRole("radio", { name: "Yes" })
+ .click();
+ await expect(bar.getByText("1 yes, 0 if need be")).toBeVisible();
+
+ await page.getByRole("button", { name: "Continue" }).click();
+ await page.getByPlaceholder("Jessie Smith").fill("Test user");
+ await page.getByRole("button", { name: "Save availability" }).click();
+ await expect(page.getByText("Your response has been saved")).toBeVisible();
+ await page.getByRole("button", { name: "Back to poll" }).click();
+
+ // Saved: the footer names the response and offers Edit, the prompt
+ // goes away, and the controls give way to the recorded votes
+ await expect(bar.getByText("Test user")).toBeVisible();
+ await expect(bar.getByRole("button", { name: "Edit" })).toBeVisible();
+
+ // The header carries filters and display settings, never the response
+ const header = main.locator("header");
+ await expect(header.getByText("Test user")).toHaveCount(0);
+
+ // Time format is its own control beside the time zone, and switching it
+ // reformats the options
+ const displays = header.getByTestId("display-settings");
+ await expect(
+ displays.getByRole("radio", { name: "12-hour" }),
+ ).toBeVisible();
+ const firstRow = main.getByTestId("poll-option").first();
+ await expect(firstRow).toContainText("PM");
+ await displays.getByRole("radio", { name: "24-hour" }).click();
+ await expect(firstRow).not.toContainText("PM");
+
+ // Edit opens the form for editing and stops there. Save replaces Edit
+ // in the same slot, so if the two footers share DOM nodes the pointer
+ // release lands on Save and the response saves as editing begins.
+ const submits = await page.evaluate(() => {
+ const state = { count: 0 };
+ (window as unknown as { __submits: typeof state }).__submits = state;
+ document.querySelector("#vote-form")?.addEventListener("submit", () => {
+ state.count++;
+ });
+ return true;
+ });
+ expect(submits).toBe(true);
+
+ await bar.getByRole("button", { name: "Edit" }).click();
+ await expect(bar.getByRole("button", { name: "Save" })).toBeVisible();
+ await expect(page.getByTestId("vote-selector").first()).toBeVisible();
+ expect(
+ await page.evaluate(
+ () =>
+ (window as unknown as { __submits: { count: number } }).__submits
+ .count,
+ ),
+ ).toBe(0);
+
+ await bar.getByRole("button", { name: "Cancel" }).click();
+ await expect(bar.getByRole("button", { name: "Edit" })).toBeVisible();
+
+ // Renaming and deleting live in the overflow menu, so changing a
+ // response to a no is the prominent path
+ await expect(bar.getByRole("button", { name: "Delete" })).toHaveCount(0);
+ await bar.getByTestId("participant-menu").click();
+ const menu = page.getByRole("menu");
+ await expect(menu.getByRole("menuitem")).toHaveText([
+ "Change name",
+ "Delete",
+ ]);
+ await page.keyboard.press("Escape");
+ await expect(page.getByTestId("vote-selector")).toHaveCount(0);
+
+ // The saved yes shows as a vote icon, and the tally counts it without
+ // naming who voted. Both sit beside the option in its row.
+ const votedRow = optionRow(main).first();
+ await expect(votedRow).toContainText("Yes");
+ await expect(votedRow).toContainText("yes");
+ });
+
+ test("mobile stacks the event above the list", async ({ browser }) => {
+ const context = await browser.newContext({
+ viewport: { width: 375, height: 667 },
+ });
+ const page = await context.newPage();
+ await page.goto(voteUrl);
+
+ const main = page.locator("#main-content");
+ const sidebar = main.getByRole("complementary");
+ await expect(sidebar.getByRole("heading", { level: 1 })).toHaveText(
+ "Vote Page Meetup",
+ );
+ const sidebarBox = await box(sidebar);
+ const optionBox = await box(optionRow(main).first());
+ expect(optionBox.y).toBeGreaterThan(sidebarBox.y + sidebarBox.height - 1);
+
+ // Filters sit on the left of the header and display settings on the
+ // right, so the header holds the controls rather than the response
+ const header = main.locator("header");
+ await expect(header.getByTestId("filters")).toHaveCount(1);
+ await expect(header.getByTestId("display-settings")).toBeVisible();
+ await expect(header.getByRole("heading", { level: 2 })).toHaveCount(0);
+
+ await context.close();
+ });
+
+ test("week view groups times by day and navigates between weeks", async ({
+ page,
+ }) => {
+ await page.goto(voteUrl);
+ const main = page.locator("#main-content");
+ const footer = main.locator("footer");
+ await expect(main.getByTestId("poll-option").first()).toBeVisible();
+
+ await main.getByRole("radio", { name: "Week" }).click();
+
+ // Seven columns whatever the week holds, so the days stay in place
+ const columns = main.locator("section section");
+ await expect(columns).toHaveCount(7);
+
+ // The first week is the earliest, so there is nothing before it
+ await expect(
+ main.getByRole("button", { name: "Previous week" }),
+ ).toBeDisabled();
+ await main.getByRole("button", { name: "Next week" }).click();
+ await expect(
+ main.getByRole("button", { name: "Next week" }),
+ ).toBeDisabled();
+ await main.getByRole("button", { name: "Previous week" }).click();
+
+ // Hiding empty days leaves only the days that hold options
+ await main.getByRole("button", { name: "Hide empty days" }).click();
+ const shown = await columns.count();
+ expect(shown).toBeGreaterThan(0);
+ expect(shown).toBeLessThan(7);
+ await main.getByRole("button", { name: "Show empty days" }).click();
+ await expect(columns).toHaveCount(7);
+
+ // The views share the form, so a vote cast here survives the switch
+ await main
+ .getByTestId("vote-selector")
+ .first()
+ .getByRole("radio", { name: "Yes" })
+ .click();
+ await expect(footer.getByText("1 yes, 0 if need be")).toBeVisible();
+ await main.getByRole("radio", { name: "List" }).click();
+ await expect(footer.getByText("1 yes, 0 if need be")).toBeVisible();
+ });
+});
+
+test.describe("vote page calendar view", () => {
+ let voteUrl: string;
+
+ test.beforeAll(async ({ browser }) => {
+ const page = await browser.newPage();
+ const newPollPage = new NewPollPage(page);
+ await newPollPage.goto();
+ const pollPage = await newPollPage.create({
+ name: "Vote Page Dates",
+ allDay: true,
+ });
+ const inviteUrl = await pollPage.copyInviteLink();
+ voteUrl = `${inviteUrl.replace(/\?.*$/, "")}/vote`;
+ await page.close();
+ });
+
+ test("keeps the selection when switching views", async ({ page }) => {
+ await page.goto(voteUrl);
+ const main = page.locator("#main-content");
+ const footer = main.locator("footer");
+
+ // A new response starts as a no on every date
+ await expect(footer.getByText("0 yes, 0 if need be")).toBeVisible();
+
+ // Vote in the list, then switch to the calendar
+ await main
+ .getByTestId("vote-selector")
+ .first()
+ .getByRole("radio", { name: "Yes" })
+ .click();
+ await expect(footer.getByText("1 yes, 0 if need be")).toBeVisible();
+
+ await main.getByRole("radio", { name: "Calendar" }).click();
+ await expect(main.getByRole("grid")).toBeVisible();
+
+ // The vote survives the switch, and the day carries its own icon.
+ // Only the poll's own days show one, so this skips the inert days.
+ await expect(footer.getByText("1 yes, 0 if need be")).toBeVisible();
+ const days = main
+ .getByRole("gridcell")
+ .getByRole("button")
+ .filter({ has: page.getByRole("img") });
+ await expect(days.first().getByRole("img", { name: "Yes" })).toBeVisible();
+
+ // Clicking a day advances it through the vote types
+ const next = days.nth(1);
+ await next.click();
+ await expect(footer.getByText("2 yes, 0 if need be")).toBeVisible();
+ await next.click();
+ await expect(footer.getByText("1 yes, 1 if need be")).toBeVisible();
+
+ // And back in the list, the calendar's votes are there
+ await main.getByRole("radio", { name: "List" }).click();
+ await expect(footer.getByText("1 yes, 1 if need be")).toBeVisible();
+ });
+});
diff --git a/packages/tailwind-config/shared-styles.css b/packages/tailwind-config/shared-styles.css
index 54f4750a4..3889223c6 100644
--- a/packages/tailwind-config/shared-styles.css
+++ b/packages/tailwind-config/shared-styles.css
@@ -213,6 +213,8 @@
--ease-in-expo: cubic-bezier(0.68, -0.6, 0.32, 1.6);
--ease-out-expo: cubic-bezier(0.19, 1, 0.22, 1);
+ /* Strong ease-out for UI that enters or changes value. */
+ --ease-out-ui: cubic-bezier(0.23, 1, 0.32, 1);
--animate-caret-blink: caret-blink 1.25s ease-out infinite;
--animate-switch-thumb-on: switch-thumb-on 350ms
diff --git a/packages/ui/src/button-group.tsx b/packages/ui/src/button-group.tsx
index 15a19ae39..3a4cdcd6e 100644
--- a/packages/ui/src/button-group.tsx
+++ b/packages/ui/src/button-group.tsx
@@ -30,7 +30,9 @@ function ButtonGroup({
}
}}
className={cn(
- "inline-flex h-9 items-center gap-0.5 rounded-lg border border-input bg-background p-0.5",
+ // Matches SegmentedControl and Tabs: a recessed track with the
+ // active item floating above it.
+ "inline-flex h-9 items-center gap-0.5 rounded-[10px] border border-input bg-muted p-0.5 dark:bg-gray-900",
className,
)}
{...props}
@@ -43,7 +45,7 @@ function ButtonGroupItem({ className, ...props }: Toggle.Props) {
<Toggle
data-slot="button-group-item"
className={cn(
- "inline-flex h-full flex-1 cursor-pointer select-none items-center justify-center whitespace-nowrap rounded-md px-3 font-medium text-muted-foreground text-sm transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-disabled:pointer-events-none data-pressed:bg-accent data-pressed:text-foreground data-disabled:opacity-50",
+ "inline-flex h-full flex-1 cursor-pointer select-none items-center justify-center whitespace-nowrap rounded-[8px] px-3 font-medium text-muted-foreground text-sm transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-disabled:pointer-events-none data-pressed:bg-card data-pressed:text-foreground data-disabled:opacity-50 data-pressed:shadow-xs dark:data-pressed:bg-gray-800",
className,
)}
{...props}
diff --git a/packages/ui/src/month-grid.tsx b/packages/ui/src/month-grid.tsx
new file mode 100644
index 000000000..e050e19a3
--- /dev/null
+++ b/packages/ui/src/month-grid.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
+import * as React from "react";
+import type { DayButtonProps, Matcher } from "react-day-picker";
+import { DayPicker } from "react-day-picker";
+
+import { cn } from "./lib/utils";
+
+export type MonthGridDay = DayButtonProps["day"];
+
+const navButtonClassName = cn(
+ "inline-flex size-8 items-center justify-center rounded-lg text-muted-foreground transition-colors",
+ "hover:bg-muted hover:text-foreground",
+ // A month with nowhere to go reads as spent: dimmed, no hover, and it
+ // does not take the pointer.
+ "aria-disabled:pointer-events-none aria-disabled:opacity-40",
+);
+
+/**
+ * A month calendar whose cells are large enough to hold content, rather than
+ * the compact one `Calendar` renders for date selection.
+ *
+ * Callers own what a cell contains via `renderDay`, and tint cells through
+ * `modifiers` plus `modifiersClassNames`, so no domain meaning lives here.
+ *
+ * `onDayClick` is required: DayPicker only renders a day button when it has
+ * a selection mode or a click handler, and this grid has no selection.
+ *
+ * The grid stretches to its container's height, so give it a parent with a
+ * definite height to fill.
+ */
+export function MonthGrid({
+ renderDay,
+ className,
+ classNames,
+ ...props
+}: Extract<React.ComponentProps<typeof DayPicker>, { mode?: undefined }> & {
+ renderDay: (props: DayButtonProps) => React.ReactNode;
+ onDayClick: NonNullable<React.ComponentProps<typeof DayPicker>["onDayClick"]>;
+}) {
+ const DayButton = React.useCallback(
+ (dayProps: DayButtonProps) => <>{renderDay(dayProps)}</>,
+ [renderDay],
+ );
+
+ return (
+ <DayPicker
+ showOutsideDays
+ components={{
+ DayButton,
+ // DayPicker's own chevron is an unclassed svg filled with
+ // currentColor, which ignores the button's text colour.
+ Chevron: ({ orientation, className: chevronClassName }) => {
+ const Icon =
+ orientation === "left" ? ChevronLeftIcon : ChevronRightIcon;
+ return <Icon className={cn("size-4", chevronClassName)} />;
+ },
+ }}
+ className={cn("flex w-full flex-col", className)}
+ classNames={{
+ // The weeks share the leftover height, so the grid fills its parent.
+ root: "flex min-h-0 flex-1 flex-col",
+ months: "flex min-h-0 flex-1 flex-col",
+ month: "flex min-h-0 flex-1 flex-col gap-2",
+ month_caption:
+ "flex h-8 items-center justify-center font-medium text-sm",
+ nav: "flex items-center justify-between",
+ // DayPicker marks an unavailable month with aria-disabled, not the
+ // disabled property, so the spent state keys on that.
+ button_previous: navButtonClassName,
+ button_next: navButtonClassName,
+ month_grid: "flex min-h-0 flex-1 flex-col",
+ weekdays: "flex gap-2",
+ weekday:
+ "flex-1 pb-1 text-center font-normal text-muted-foreground text-xs",
+ weeks: "flex min-h-0 flex-1 flex-col gap-2",
+ week: "flex w-full min-h-0 flex-1 gap-2",
+ // The cell owns the rounding and the border; its content fills it.
+ day: "min-h-16 flex-1 overflow-hidden rounded-lg border",
+ ...classNames,
+ }}
+ {...props}
+ />
+ );
+}
+
+export type { DayButtonProps as MonthGridDayProps, Matcher };
diff --git a/packages/ui/src/segmented-control.tsx b/packages/ui/src/segmented-control.tsx
index f161fd8fb..d63334e5a 100644
--- a/packages/ui/src/segmented-control.tsx
+++ b/packages/ui/src/segmented-control.tsx
@@ -10,7 +10,9 @@ function SegmentedControl({ className, ...props }: RadioGroupPrimitive.Props) {
<RadioGroupPrimitive
data-slot="segmented-control"
className={cn(
- "inline-flex h-8 shrink-0 items-center justify-center rounded-xl border border-input bg-muted dark:bg-gray-900",
+ // A recessed track with the selection floating above it. Tabs use
+ // the same treatment, so the two read as one family.
+ "inline-flex h-9 shrink-0 items-center justify-center gap-0.5 rounded-[10px] border border-input bg-muted p-0.5 dark:bg-gray-900",
className,
)}
{...props}
@@ -26,7 +28,7 @@ function SegmentedControlItem({
<RadioPrimitive.Root
data-slot="segmented-control-item"
className={cn(
- "relative inline-flex h-full cursor-pointer touch-manipulation items-center justify-center rounded-xl ring-offset-background [-webkit-tap-highlight-color:transparent] before:absolute before:inset-x-0 before:-inset-y-1 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 data-checked:bg-white data-checked:ring-1 data-checked:ring-gray-200 data-unchecked:active:bg-black/5 dark:data-checked:bg-gray-800 dark:data-checked:ring-gray-700 dark:data-unchecked:active:bg-white/5",
+ "relative inline-flex h-full cursor-pointer touch-manipulation select-none items-center justify-center rounded-[8px] transition-colors [-webkit-tap-highlight-color:transparent] before:absolute before:inset-x-0 before:-inset-y-1 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-card data-checked:shadow-xs dark:data-checked:bg-gray-800",
className,
)}
{...props}
diff --git a/packages/ui/src/tabs.tsx b/packages/ui/src/tabs.tsx
index 2a60a68a4..5452d1700 100644
--- a/packages/ui/src/tabs.tsx
+++ b/packages/ui/src/tabs.tsx
@@ -14,7 +14,9 @@ function TabsList({ className, ...props }: TabsPrimitive.List.Props) {
data-slot="tabs-list"
activateOnFocus
className={cn(
- "inline-flex h-8 items-center justify-center rounded-lg border border-input bg-muted text-input-foreground dark:bg-gray-900",
+ // Matches SegmentedControl: a recessed track with the active tab
+ // floating above it.
+ "inline-flex h-9 items-center justify-center gap-0.5 rounded-xl border border-input bg-muted p-0.5 text-input-foreground dark:bg-gray-900",
className,
)}
{...props}
@@ -27,7 +29,7 @@ function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
<TabsPrimitive.Tab
data-slot="tabs-trigger"
className={cn(
- "inline-flex h-full items-center justify-center whitespace-nowrap rounded-lg px-3 font-normal text-muted-foreground text-sm ring-offset-background focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-active:bg-white data-active:text-foreground data-active:ring-1 data-active:ring-gray-200 dark:data-active:bg-gray-800 dark:data-active:ring-gray-700",
+ "inline-flex h-full items-center justify-center whitespace-nowrap rounded-lg px-3 font-normal text-muted-foreground text-sm ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-active:bg-card data-active:text-foreground data-active:shadow-xs dark:data-active:bg-gray-800",
className,
)}
{...props}