Skip to content

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

✨ Edit a poll on one page and record what each edit changed (#3413)

Luke Vellac8ea445340e0
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index a452e70f6..51a311be6 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -78,6 +78,12 @@ const nextConfig: NextConfig = {
destination: "/settings/profile",
permanent: true,
},
+ // Details, dates and settings used to be edited on separate pages.
+ {
+ source: "/poll/:urlId/:page(edit-details|edit-options|edit-settings)",
+ destination: "/poll/:urlId/edit",
+ permanent: true,
+ },
// Login and registration are a single flow on /login: entering an
// unknown email creates an account on OTP verification. redirectTo
// and other query params are passed through automatically.
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 43bd32083..79febe1e5 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -315,11 +315,7 @@
"earlySupporterRateEndsNoPrice": "Your early supporter rate ends with your subscription.",
"earlySupporterRateKept": "You keep this rate for as long as your subscription stays active.",
"edit": "Edit",
- "editDetails": "Edit details",
- "editDetailsDescription": "Change the details of your event.",
"editEventTypeTitle": "Edit event type",
- "editOptions": "Edit options",
- "editSettings": "Edit settings",
"editVotes": "Edit votes",
"email": "Email",
"emailAddress": "Email address",
@@ -723,13 +719,24 @@
"planRenewsOn": "Renews on {date}",
"planResumedToast": "Your plan will renew",
"poll": "Poll",
+ "pollActivityConferencingAdded": "Video call added",
+ "pollActivityConferencingChanged": "Video call changed from <b>{from}</b>",
+ "pollActivityConferencingRemoved": "Video call <b>{from}</b> removed",
+ "pollActivityDescriptionAdded": "Description added",
+ "pollActivityDescriptionChanged": "Description changed",
+ "pollActivityDescriptionRemoved": "Description removed",
"pollActivityInviteOpened": "<b>{email}</b> opened their invite",
"pollActivityInviteReminded": "Reminder sent to <b>{email}</b>",
"pollActivityInviteRevoked": "Invite to <b>{email}</b> revoked",
"pollActivityInviteSent": "Invite sent to <b>{email}</b>",
"pollActivityInvitesRevokedBulk": "{count, plural, one {1 invite revoked} other {# invites revoked}}",
+ "pollActivityLocationAdded": "Location added",
+ "pollActivityLocationChanged": "Location changed from <b>{from}</b>",
+ "pollActivityLocationRemoved": "Location <b>{from}</b> removed",
"pollActivityOptionAdded": "Date added",
"pollActivityOptionDeleted": "Date removed",
+ "pollActivityOptionsAdded": "{count, plural, one {Date added} other {# dates added}}",
+ "pollActivityOptionsDeleted": "{count, plural, one {Date removed} other {# dates removed}}",
"pollActivityPageEmptyDescription": "Activity on this poll will show up here.",
"pollActivityPollClosed": "Poll closed",
"pollActivityPollClosedAuto": "Poll closed automatically",
@@ -741,6 +748,9 @@
"pollActivityResponseCreated": "<b>{name}</b> responded",
"pollActivityResponseDeleted": "Response from <b>{name}</b> deleted",
"pollActivityResponseUpdated": "<b>{name}</b> updated their response",
+ "pollActivitySettingsChanged": "Settings changed",
+ "pollActivityTimeZoneChanged": "Time zone changed",
+ "pollActivityTitleChanged": "Title changed from <b>{from}</b>",
"pollAdminMenu": "Poll options",
"pollAutoClosedBadge": "Automatically closed",
"pollAutoClosedDescription": "This poll was closed automatically because all of its dates have passed. No more responses are being accepted.",
@@ -881,6 +891,7 @@
"rsvpVerifySendError": "We couldn't send a code. Please try again.",
"rsvpVerifyTitle": "Verify your email",
"save": "Save",
+ "saveChanges": "Save changes",
"saved": "Saved",
"saving": "Saving...",
"scheduledPollLockedDescription": "A scheduled poll can no longer be edited.",
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/components/edit-details-form.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/components/edit-details-form.tsx
deleted file mode 100644
index 1af2a8321..000000000
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/components/edit-details-form.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-"use client";
-import { buttonVariants } from "@rallly/ui";
-import { Button } from "@rallly/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
-} from "@rallly/ui/card";
-import { Form } from "@rallly/ui/form";
-import { useRouter } from "next/navigation";
-import { useForm } from "react-hook-form";
-import { Link } from "@/components/link";
-import type { ConferencingOptions } from "@/features/conferencing/components/conferencing-field";
-import {
- toConferencingFormValues,
- toPollConferencing,
-} from "@/features/conferencing/components/conferencing-field";
-import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";
-import type { PollDetailsData } from "@/features/poll/components/forms/types";
-import { useUpdatePollMutation } from "@/features/poll/components/mutations";
-import { usePoll } from "@/features/poll/components/poll-context";
-import { Trans } from "@/i18n/client";
-
-export function EditDetailsForm({
- conferencing,
-}: {
- conferencing: ConferencingOptions;
-}) {
- const { poll } = usePoll();
- const { mutate: updatePollMutation, isPending: isUpdating } =
- useUpdatePollMutation();
- const router = useRouter();
-
- const pollLink = `/poll/${poll.id}`;
-
- const redirectBackToPoll = () => {
- router.push(pollLink);
- };
-
- const form = useForm<PollDetailsData>({
- defaultValues: {
- title: poll.title,
- location: poll.location ?? "",
- description: poll.description ?? "",
- ...toConferencingFormValues(poll.conferencing),
- },
- });
-
- return (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit((data) => {
- //submit
- updatePollMutation(
- {
- pollId: poll.id,
- title: data.title,
- location: data.location,
- description: data.description,
- conferencing: toPollConferencing(data) ?? null,
- },
- {
- onSuccess: (res) => {
- if (res.ok) {
- redirectBackToPoll();
- }
- },
- },
- );
- })}
- >
- <Card>
- <CardHeader>
- <CardTitle>
- <Trans i18nKey="editDetails" defaults="Edit details" />
- </CardTitle>
- <CardDescription>
- <Trans
- i18nKey="editDetailsDescription"
- defaults="Change the details of your event."
- />
- </CardDescription>
- </CardHeader>
- <CardContent>
- <PollDetailsForm conferencing={conferencing} />
- </CardContent>
- <CardFooter className="justify-between">
- <Link href={pollLink} className={buttonVariants()}>
- <Trans i18nKey="cancel" />
- </Link>
- <Button type="submit" loading={isUpdating} variant="primary">
- <Trans i18nKey="save" />
- </Button>
- </CardFooter>
- </Card>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/page.tsx
deleted file mode 100644
index cd80efa2c..000000000
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-details/page.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Suspense } from "react";
-import { loadPollConferencingOptions } from "@/features/poll/loaders";
-import { EditDetailsForm } from "./components/edit-details-form";
-
-async function EditDetails({ params }: { params: Promise<{ urlId: string }> }) {
- const { urlId } = await params;
- const conferencing = await loadPollConferencingOptions(urlId);
- return <EditDetailsForm conferencing={conferencing} />;
-}
-
-export default function Page({
- params,
-}: {
- params: Promise<{ urlId: string }>;
-}) {
- return (
- <Suspense>
- <EditDetails params={params} />
- </Suspense>
- );
-}
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-options/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-options/page.tsx
deleted file mode 100644
index 3bc5af376..000000000
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-options/page.tsx
+++ /dev/null
@@ -1,191 +0,0 @@
-"use client";
-import { buttonVariants } from "@rallly/ui";
-import { Button } from "@rallly/ui/button";
-import { CardFooter } from "@rallly/ui/card";
-import { Form } from "@rallly/ui/form";
-import { useRouter } from "next/navigation";
-import { useForm } from "react-hook-form";
-import { Link } from "@/components/link";
-import { useModalContext } from "@/components/modal/modal-provider";
-import { useParticipants } from "@/features/poll/client";
-import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";
-import { useUpdatePollMutation } from "@/features/poll/components/mutations";
-import { usePoll } from "@/features/poll/components/poll-context";
-import { filterParticipantsByVote } from "@/features/poll/utils";
-import { useUser } from "@/features/user/client";
-import { Trans, useTranslation } from "@/i18n/client";
-import {
- addMinutesToWallTime,
- instantToWallTime,
-} from "@/lib/datetime/wall-time";
-import {
- encodeDateOption,
- getBrowserTimeZone,
-} from "@/lib/utils/date-time-utils";
-
-const toPollWallTime = (value: Date, timeZone: string | null) =>
- instantToWallTime(value, timeZone ?? "UTC");
-
-const convertOptionToString = (
- option: { startTime: Date; duration: number },
- timeZone: string | null,
-) => {
- const start = toPollWallTime(option.startTime, timeZone);
- return option.duration === 0
- ? start.slice(0, 10)
- : `${start}/${addMinutesToWallTime(start, option.duration)}`;
-};
-
-const Page = () => {
- const { poll } = usePoll();
- const { participants } = useParticipants();
- const hasVotes = participants.some(
- (participant) => participant.votes.length > 0,
- );
- const { mutate: updatePollMutation, isPending: isUpdating } =
- useUpdatePollMutation();
- const { t } = useTranslation();
- const { user } = useUser();
- const modalContext = useModalContext();
- const router = useRouter();
- const pollLink = `/poll/${poll.id}`;
-
- const redirectBackToPoll = () => {
- router.push(pollLink);
- };
-
- const firstDate = toPollWallTime(
- poll.options[0]?.startTime ?? new Date(),
- poll.timeZone,
- );
-
- const form = useForm({
- defaultValues: {
- navigationDate: firstDate.slice(0, 10),
- view: "month" as const,
- options: poll.options.map((option) => {
- const start = toPollWallTime(option.startTime, poll.timeZone);
- return option.duration > 0
- ? {
- type: "timeSlot" as const,
- start,
- duration: option.duration,
- end: addMinutesToWallTime(start, option.duration),
- }
- : {
- type: "date" as const,
- date: start.slice(0, 10),
- };
- }),
- timeZone: poll.timeZone ?? "",
- // A timed poll with no stored zone was locked to a single wall-clock time.
- // All-day polls are neutral (lock doesn't apply).
- lockTimeZone:
- !poll.timeZone && poll.options.some((option) => option.duration > 0),
- allDay:
- poll.options.length > 0 &&
- poll.options.every((option) => option.duration === 0),
- duration: poll.options[0]?.duration || 60,
- },
- });
- return (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit((data) => {
- // The submitted timeZone frame for the options: null when locked or
- // all-day (floating), else the organizer's zone.
- const submittedTimeZone =
- !data.lockTimeZone && !data.allDay
- ? data.timeZone || user?.timeZone || getBrowserTimeZone()
- : null;
-
- const encodedOptions = data.options.map(encodeDateOption);
-
- // When the timezone frame changes (e.g. the organizer toggled the
- // lock), the stored instants no longer match the frame, so re-store
- // every option from the form's wall-clock under the new frame — this
- // keeps the displayed times put (3pm stays 3pm). When the frame is
- // unchanged, diff normally so we only touch what the user edited.
- const frameChanged = submittedTimeZone !== poll.timeZone;
-
- const optionsToDelete = frameChanged
- ? poll.options
- : poll.options.filter(
- (option) =>
- !encodedOptions.includes(
- convertOptionToString(option, poll.timeZone),
- ),
- );
-
- const optionsToAdd = frameChanged
- ? encodedOptions
- : encodedOptions.filter(
- (encodedOption) =>
- !poll.options.find(
- (o) =>
- convertOptionToString(o, poll.timeZone) === encodedOption,
- ),
- );
-
- const onOk = () => {
- updatePollMutation(
- {
- pollId: poll.id,
- timeZone: submittedTimeZone,
- optionsToDelete: optionsToDelete.map(({ id }) => id),
- optionsToAdd,
- },
- {
- onSuccess: (res) => {
- if (res.ok) {
- redirectBackToPoll();
- }
- },
- },
- );
- };
-
- const optionsToDeleteThatHaveVotes = optionsToDelete.filter(
- (option) =>
- filterParticipantsByVote(participants, option.id, "yes").length >
- 0,
- );
-
- if (optionsToDeleteThatHaveVotes.length > 0) {
- modalContext.render({
- title: t("areYouSure", { defaultValue: "Are you sure?" }),
- content: (
- <Trans
- i18nKey="deletingOptionsWarning"
- defaults="You are deleting options that participants have voted for. Their votes will also be deleted."
- components={{ b: <strong /> }}
- />
- ),
- onOk,
- okButtonProps: {
- variant: "destructive",
- },
- okText: t("delete"),
- cancelText: t("cancel"),
- });
- } else {
- onOk();
- }
- })}
- >
- <PollOptionsForm disableTimeZoneChange={hasVotes}>
- <CardFooter className="justify-between">
- <Link href={pollLink} className={buttonVariants()}>
- <Trans i18nKey="cancel" />
- </Link>
- <Button type="submit" loading={isUpdating} variant="primary">
- <Trans i18nKey="save" />
- </Button>
- </CardFooter>
- </PollOptionsForm>
- </form>
- </Form>
- );
-};
-
-export default Page;
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-settings/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-settings/page.tsx
deleted file mode 100644
index 387052160..000000000
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit-settings/page.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client";
-import { buttonVariants } from "@rallly/ui";
-import { Button } from "@rallly/ui/button";
-import { CardFooter } from "@rallly/ui/card";
-import { Form } from "@rallly/ui/form";
-import { useRouter } from "next/navigation";
-import { useForm } from "react-hook-form";
-import { Link } from "@/components/link";
-import { useParticipants, usePoll } from "@/features/poll/client";
-import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";
-import { useUpdatePollMutation } from "@/features/poll/components/mutations";
-import { Trans } from "@/i18n/client";
-
-const Page = () => {
- const poll = usePoll();
- const { participants } = useParticipants();
-
- // The answer set is locked once a response uses the tentative vote, so those
- // votes stay re-saveable by their owner. Derived from the participants the
- // layout already loads rather than a dedicated count query.
- const hasTentativeVotes = participants.some((participant) =>
- participant.votes.some((vote) => vote.type === "ifNeedBe"),
- );
-
- const router = useRouter();
-
- const pollLink = `/poll/${poll.id}`;
-
- const redirectBackToPoll = () => {
- router.push(pollLink);
- };
-
- const update = useUpdatePollMutation();
-
- const form = useForm({
- defaultValues: {
- hideParticipants: poll.hideParticipants,
- hideScores: poll.hideScores,
- enableComments: !poll.disableComments,
- allowTentativeVotes: poll.allowTentativeVotes,
- requireParticipantEmail: poll.requireParticipantEmail,
- },
- });
-
- return (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(async ({ enableComments, ...data }) => {
- const res = await update.mutateAsync({
- pollId: poll.id,
- ...data,
- disableComments: !enableComments,
- });
- if (res.ok) {
- redirectBackToPoll();
- }
- })}
- >
- <PollSettingsForm hasTentativeVotes={hasTentativeVotes}>
- <CardFooter className="justify-between">
- <Link href={pollLink} className={buttonVariants()}>
- <Trans i18nKey="cancel" />
- </Link>
- <Button type="submit" variant="primary">
- <Trans i18nKey="save" />
- </Button>
- </CardFooter>
- </PollSettingsForm>
- </form>
- </Form>
- );
-};
-
-export default Page;
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit/page.tsx
new file mode 100644
index 000000000..8d0bff821
--- /dev/null
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/edit/page.tsx
@@ -0,0 +1,82 @@
+import { buttonVariants } from "@rallly/ui";
+import { Card } from "@rallly/ui/card";
+import { CalendarCheck2Icon } from "lucide-react";
+import { Suspense } from "react";
+import {
+ EmptyState,
+ EmptyStateDescription,
+ EmptyStateFooter,
+ EmptyStateIcon,
+ EmptyStateTitle,
+} from "@/components/empty-state";
+import { Link } from "@/components/link";
+import { EditPoll } from "@/features/poll/components/edit-poll";
+import {
+ loadAdminPoll,
+ loadPollConferencingOptions,
+} from "@/features/poll/loaders";
+import { Trans } from "@/i18n/client";
+
+async function EditPollPage({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ urlId: string }>;
+ searchParams: Promise<{ from?: string | string[] }>;
+}) {
+ const [{ urlId }, { from }] = await Promise.all([params, searchParams]);
+ // Only a known surface can be returned to, so the param can't redirect
+ // off site.
+ const returnHref = from === "admin" ? `/polls/${urlId}` : `/poll/${urlId}`;
+ const [{ poll }, conferencing] = await Promise.all([
+ loadAdminPoll(urlId),
+ loadPollConferencingOptions(urlId),
+ ]);
+
+ // A booked event keeps its own copy of the poll's details, so edits made
+ // after booking would never reach it. The server rejects them too.
+ if (poll.status === "scheduled") {
+ return (
+ <Card>
+ <EmptyState>
+ <EmptyStateIcon>
+ <CalendarCheck2Icon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans
+ i18nKey="scheduledPollLockedTitle"
+ defaults="This poll is scheduled"
+ />
+ </EmptyStateTitle>
+ <EmptyStateDescription>
+ <Trans
+ i18nKey="scheduledPollLockedDescription"
+ defaults="A scheduled poll can no longer be edited."
+ />
+ </EmptyStateDescription>
+ <EmptyStateFooter>
+ <Link href={returnHref} className={buttonVariants()}>
+ <Trans i18nKey="backToPoll" defaults="Back to poll" />
+ </Link>
+ </EmptyStateFooter>
+ </EmptyState>
+ </Card>
+ );
+ }
+
+ return <EditPoll conferencing={conferencing} returnHref={returnHref} />;
+}
+
+export default function Page({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ urlId: string }>;
+ searchParams: Promise<{ from?: string | string[] }>;
+}) {
+ return (
+ <Suspense>
+ <EditPollPage params={params} searchParams={searchParams} />
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/layout.tsx
deleted file mode 100644
index 1e44cc770..000000000
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/(edit)/layout.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-"use client";
-import { buttonVariants } from "@rallly/ui";
-import { Card } from "@rallly/ui/card";
-import { CalendarCheck2Icon } from "lucide-react";
-import type React from "react";
-import {
- EmptyState,
- EmptyStateDescription,
- EmptyStateFooter,
- EmptyStateIcon,
- EmptyStateTitle,
-} from "@/components/empty-state";
-import { Link } from "@/components/link";
-import { usePoll } from "@/features/poll/client";
-import { Trans } from "@/i18n/client";
-
-// A booked event keeps its own copy of the poll's details, so edits made after
-// booking would never reach it. The server rejects them too; this covers deep
-// links to the edit pages.
-export default function Layout({ children }: { children: React.ReactNode }) {
- const poll = usePoll();
-
- if (poll.status !== "scheduled") {
- return children;
- }
-
- return (
- <Card>
- <EmptyState>
- <EmptyStateIcon>
- <CalendarCheck2Icon />
- </EmptyStateIcon>
- <EmptyStateTitle>
- <Trans
- i18nKey="scheduledPollLockedTitle"
- defaults="This poll is scheduled"
- />
- </EmptyStateTitle>
- <EmptyStateDescription>
- <Trans
- i18nKey="scheduledPollLockedDescription"
- defaults="A scheduled poll can no longer be edited."
- />
- </EmptyStateDescription>
- <EmptyStateFooter>
- <Link href={`/poll/${poll.id}`} className={buttonVariants()}>
- <Trans i18nKey="backToPoll" defaults="Back to poll" />
- </Link>
- </EmptyStateFooter>
- </EmptyState>
- </Card>
- );
-}
diff --git a/apps/web/src/features/activity/components/poll-activity-list.tsx b/apps/web/src/features/activity/components/poll-activity-list.tsx
index 402baa007..9c64a2674 100644
--- a/apps/web/src/features/activity/components/poll-activity-list.tsx
+++ b/apps/web/src/features/activity/components/poll-activity-list.tsx
@@ -3,23 +3,31 @@
import { cn } from "@rallly/ui";
import type { LucideIcon } from "lucide-react";
import {
+ AlignLeftIcon,
BellIcon,
CalendarCheckIcon,
CalendarMinusIcon,
CalendarPlusIcon,
CircleStopIcon,
+ GlobeIcon,
MailIcon,
MailOpenIcon,
MailXIcon,
+ MapPinIcon,
PencilIcon,
PlayIcon,
PlusIcon,
+ Settings2Icon,
TrashIcon,
+ TypeIcon,
UserMinusIcon,
UserPenIcon,
UserPlusIcon,
+ VideoIcon,
} from "lucide-react";
-import type { PollActivityEvent } from "@/features/activity/schema";
+import type { PollActivityEvent, PollChange } from "@/features/activity/schema";
+import type { PollConferencing } from "@/features/conferencing/schema";
+import { conferencingProviderLabels } from "@/features/conferencing/utils";
import {
EventDate,
EventTimeRange,
@@ -50,6 +58,8 @@ const iconByType: Record<PollActivityEvent["type"], LucideIcon> = {
response_deleted: UserMinusIcon,
option_added: CalendarPlusIcon,
option_deleted: CalendarMinusIcon,
+ options_added: CalendarPlusIcon,
+ options_deleted: CalendarMinusIcon,
};
// Tints group events by what they did to the poll. Colour only reinforces
@@ -83,8 +93,31 @@ const toneByType: Record<
response_deleted: "removed",
option_added: "added",
option_deleted: "removed",
+ options_added: "added",
+ options_deleted: "removed",
};
+function OptionChips({
+ options,
+ timeZone,
+}: {
+ options: { optionId: string; start: string; duration: number }[];
+ timeZone: string | null;
+}) {
+ return (
+ <span className="mt-1.5 flex flex-wrap gap-1.5">
+ {options.map((option) => (
+ <OptionChip
+ key={option.optionId}
+ start={option.start}
+ duration={option.duration}
+ timeZone={timeZone}
+ />
+ ))}
+ </span>
+ );
+}
+
function OptionChip({
start,
duration,
@@ -117,6 +150,116 @@ function OptionChip({
);
}
+const iconByChange: Record<PollChange["field"], LucideIcon> = {
+ title: TypeIcon,
+ description: AlignLeftIcon,
+ location: MapPinIcon,
+ conferencing: VideoIcon,
+ timeZone: GlobeIcon,
+ settings: Settings2Icon,
+};
+
+function toneOfChange(change: PollChange): keyof typeof toneClassName {
+ if ("action" in change) {
+ return change.action === "added"
+ ? "added"
+ : change.action === "removed"
+ ? "removed"
+ : "changed";
+ }
+ return "changed";
+}
+
+const conferencingName = (conferencing: PollConferencing) =>
+ conferencing.provider === "custom"
+ ? conferencing.label
+ : conferencingProviderLabels[conferencing.provider];
+
+function ChangeDescription({ change }: { change: PollChange }) {
+ const b = <b className="font-medium" />;
+ switch (change.field) {
+ case "title":
+ return (
+ <Trans
+ i18nKey="pollActivityTitleChanged"
+ defaults="Title changed from <b>{from}</b>"
+ values={{ from: change.from }}
+ components={{ b }}
+ />
+ );
+ case "description":
+ return change.action === "added" ? (
+ <Trans
+ i18nKey="pollActivityDescriptionAdded"
+ defaults="Description added"
+ />
+ ) : change.action === "removed" ? (
+ <Trans
+ i18nKey="pollActivityDescriptionRemoved"
+ defaults="Description removed"
+ />
+ ) : (
+ <Trans
+ i18nKey="pollActivityDescriptionChanged"
+ defaults="Description changed"
+ />
+ );
+ case "location":
+ return change.action === "added" ? (
+ <Trans i18nKey="pollActivityLocationAdded" defaults="Location added" />
+ ) : change.action === "removed" ? (
+ <Trans
+ i18nKey="pollActivityLocationRemoved"
+ defaults="Location <b>{from}</b> removed"
+ values={{ from: change.from }}
+ components={{ b }}
+ />
+ ) : (
+ <Trans
+ i18nKey="pollActivityLocationChanged"
+ defaults="Location changed from <b>{from}</b>"
+ values={{ from: change.from }}
+ components={{ b }}
+ />
+ );
+ case "conferencing":
+ return change.action === "added" || !change.from ? (
+ <Trans
+ i18nKey="pollActivityConferencingAdded"
+ defaults="Video call added"
+ />
+ ) : change.action === "removed" ? (
+ <Trans
+ i18nKey="pollActivityConferencingRemoved"
+ defaults="Video call <b>{from}</b> removed"
+ values={{ from: conferencingName(change.from) }}
+ components={{ b }}
+ />
+ ) : (
+ <Trans
+ i18nKey="pollActivityConferencingChanged"
+ defaults="Video call changed from <b>{from}</b>"
+ values={{ from: conferencingName(change.from) }}
+ components={{ b }}
+ />
+ );
+ case "timeZone":
+ return (
+ <Trans
+ i18nKey="pollActivityTimeZoneChanged"
+ defaults="Time zone changed"
+ />
+ );
+ case "settings":
+ return (
+ <Trans
+ i18nKey="pollActivitySettingsChanged"
+ defaults="Settings changed"
+ />
+ );
+ }
+}
+
function ActivityDescription({
event,
timeZone,
@@ -239,6 +382,42 @@ function ActivityDescription({
components={{ b }}
/>
);
+ case "options_added":
+ return (
+ <>
+ <Trans
+ i18nKey="pollActivityOptionsAdded"
+ defaults="{count, plural, one {Date added} other {# dates added}}"
+ values={{ count: event.payload.options.length }}
+ />
+ <OptionChips
+ options={event.payload.options}
+ timeZone={
+ event.payload.timeZone === undefined
+ ? timeZone
+ : event.payload.timeZone
+ }
+ />
+ </>
+ );
+ case "options_deleted":
+ return (
+ <>
+ <Trans
+ i18nKey="pollActivityOptionsDeleted"
+ defaults="{count, plural, one {Date removed} other {# dates removed}}"
+ values={{ count: event.payload.options.length }}
+ />
+ <OptionChips
+ options={event.payload.options}
+ timeZone={
+ event.payload.timeZone === undefined
+ ? timeZone
+ : event.payload.timeZone
+ }
+ />
+ </>
+ );
case "option_added":
return (
<>
@@ -275,43 +454,67 @@ export function PollActivityList({
}) {
return (
<ol className={cn("flex flex-col", className)}>
- {activity.map(({ id, createdAt, event }) => {
- const Icon = iconByType[event.type];
- const note =
- event.type === "response_created" ? event.payload.note : undefined;
- return (
- <li key={id} className="group relative flex gap-3 pb-6 last:pb-0">
- {/* The rail joining this event's icon to the next one */}
- <div
- aria-hidden
- className="absolute top-9 bottom-1 left-4 w-px -translate-x-1/2 bg-border group-last:hidden"
- />
- <div
- className={cn(
- "flex size-8 shrink-0 items-center justify-center rounded-full",
- toneClassName[toneByType[event.type]],
- )}
- >
- <Icon aria-hidden className="size-4" />
- </div>
- <div className="min-w-0 flex-1 space-y-1 pt-1.5">
- <p className="text-sm leading-5">
+ {activity
+ .flatMap(({ id, createdAt, event }) => {
+ // An itemized edit shows one line per field it changed.
+ if (event.type === "poll_updated" && event.payload.changes?.length) {
+ return event.payload.changes.map((change, index) => ({
+ key: `${id}:${index}`,
+ createdAt,
+ Icon: iconByChange[change.field],
+ tone: toneOfChange(change),
+ description: <ChangeDescription change={change} />,
+ note: undefined,
+ }));
+ }
+ return [
+ {
+ key: id,
+ createdAt,
+ Icon: iconByType[event.type],
+ tone: toneByType[event.type],
+ description: (
<ActivityDescription event={event} timeZone={timeZone} />
- </p>
- <Time
- value={createdAt}
- preset="datetime"
- className="block text-muted-foreground text-xs"
+ ),
+ note:
+ event.type === "response_created"
+ ? event.payload.note
+ : undefined,
+ },
+ ];
+ })
+ .map(({ key, createdAt, Icon, tone, description, note }) => {
+ return (
+ <li key={key} className="group relative flex gap-3 pb-6 last:pb-0">
+ {/* The rail joining this event's icon to the next one */}
+ <div
+ aria-hidden
+ className="absolute top-9 bottom-1 left-4 w-px -translate-x-1/2 bg-border group-last:hidden"
/>
- {note ? (
- <p className="mt-2 whitespace-pre-wrap rounded-lg border bg-card px-3 py-2 text-sm">
- {note}
- </p>
- ) : null}
- </div>
- </li>
- );
- })}
+ <div
+ className={cn(
+ "flex size-8 shrink-0 items-center justify-center rounded-full",
+ toneClassName[tone],
+ )}
+ >
+ <Icon aria-hidden className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1 space-y-1 pt-1.5">
+ <p className="text-sm leading-5">{description}</p>
+ <Time
+ value={createdAt}
+ preset="datetime"
+ className="block text-muted-foreground text-xs"
+ />
+ {note ? (
+ <p className="mt-2 whitespace-pre-wrap rounded-lg border bg-card px-3 py-2 text-sm">
+ {note}
+ </p>
+ ) : null}
+ </div>
+ </li>
+ );
+ })}
</ol>
);
}
diff --git a/apps/web/src/features/activity/schema.test.ts b/apps/web/src/features/activity/schema.test.ts
index bdcf7bcea..8d7d5701c 100644
--- a/apps/web/src/features/activity/schema.test.ts
+++ b/apps/web/src/features/activity/schema.test.ts
@@ -50,6 +50,41 @@ describe("pollActivitySchema", () => {
expect(withoutNote?.payload).toEqual({ name: "Jessie Smith" });
});
+ it("reads a batch of added dates as one event", () => {
+ const event = parsePollActivity({
+ ...emptyRefs,
+ type: "options_added",
+ payload: {
+ options: [
+ { optionId: "o1", start: "2026-10-11T00:00:00.000Z", duration: 0 },
+ { optionId: "o2", start: "2026-10-12T00:00:00.000Z", duration: 0 },
+ ],
+ },
+ });
+
+ expect(event?.type).toBe("options_added");
+ });
+
+ it("rejects an empty batch of dates", () => {
+ const result = pollActivitySchema.safeParse({
+ type: "options_deleted",
+ userId: "u1",
+ payload: { options: [] },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("reads a poll scheduled for a time that isn't one of its options", () => {
+ const event = parsePollActivity({
+ ...emptyRefs,
+ type: "poll_scheduled",
+ payload: { start: "2026-10-11T09:00:00.000Z", duration: 60 },
+ });
+
+ expect(event?.type).toBe("poll_scheduled");
+ });
+
it("requires the subject ref of a response event", () => {
const result = pollActivitySchema.safeParse({
type: "response_created",
diff --git a/apps/web/src/features/activity/schema.ts b/apps/web/src/features/activity/schema.ts
index 4cea060bb..8d9e10b78 100644
--- a/apps/web/src/features/activity/schema.ts
+++ b/apps/web/src/features/activity/schema.ts
@@ -1,4 +1,5 @@
import * as z from "zod";
+import { pollConferencingSchema } from "@/features/conferencing/schema";
/** Why a poll closed: the organizer, or every option having passed. */
export const pollClosedReasonSchema = z.enum(["auto", "manual"]);
@@ -33,6 +34,47 @@ const voteSnapshotSchema = z.object({
type: z.enum(["yes", "no", "ifNeedBe"]),
});
+// One event per edit rather than per date, so replacing a poll's dates reads
+// as one change in the timeline.
+const optionsSnapshotSchema = z.object({
+ options: z
+ .array(optionSnapshotSchema.extend({ optionId: z.string() }))
+ .min(1),
+ // The zone the dates were stored in (null when floating). A time zone edit
+ // re-stores every date, so the poll's current zone can't render the old
+ // ones. Absent on entries written before it was recorded.
+ timeZone: z.string().nullable().optional(),
+});
+
+const changeActionSchema = z.enum(["added", "changed", "removed"]);
+
+/**
+ * One field a poll_updated edit touched, with the value it had before. The
+ * current value lives on the poll, so only the old one is snapshotted.
+ */
+export const pollChangeSchema = z.discriminatedUnion("field", [
+ z.object({ field: z.literal("title"), from: z.string() }),
+ z.object({
+ field: z.literal("description"),
+ action: changeActionSchema,
+ from: z.string().nullable(),
+ }),
+ z.object({
+ field: z.literal("location"),
+ action: changeActionSchema,
+ from: z.string().nullable(),
+ }),
+ z.object({
+ field: z.literal("conferencing"),
+ action: changeActionSchema,
+ from: pollConferencingSchema.nullable(),
+ }),
+ z.object({ field: z.literal("timeZone"), from: z.string().nullable() }),
+ z.object({ field: z.literal("settings") }),
+]);
+
+export type PollChange = z.infer<typeof pollChangeSchema>;
+
const inviteePayloadSchema = z.object({
email: z.string(),
});
@@ -46,7 +88,8 @@ export const pollActivitySchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("poll_updated"),
...actor,
- payload: z.object({}),
+ // Absent on entries written before changes were itemized.
+ payload: z.object({ changes: z.array(pollChangeSchema).optional() }),
}),
z.object({
type: z.literal("poll_closed"),
@@ -66,7 +109,9 @@ export const pollActivitySchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("poll_scheduled"),
...actor,
- optionId: z.string(),
+ // The payload is the scheduled time. The option is optional because a
+ // poll can be scheduled for a time that isn't one of its options.
+ optionId: z.string().optional(),
payload: optionSnapshotSchema,
}),
z.object({
@@ -121,6 +166,18 @@ export const pollActivitySchema = z.discriminatedUnion("type", [
votes: z.array(voteSnapshotSchema),
}),
}),
+ z.object({
+ type: z.literal("options_added"),
+ ...actor,
+ payload: optionsSnapshotSchema,
+ }),
+ z.object({
+ type: z.literal("options_deleted"),
+ ...actor,
+ payload: optionsSnapshotSchema,
+ }),
+ // One event per date, written before edits were batched into
+ // options_added and options_deleted. Still read for that history.
z.object({
type: z.literal("option_added"),
...actor,
diff --git a/apps/web/src/features/activity/utils.test.ts b/apps/web/src/features/activity/utils.test.ts
new file mode 100644
index 000000000..19f327658
--- /dev/null
+++ b/apps/web/src/features/activity/utils.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import { getPollChanges } from "./utils";
+
+const prior = {
+ title: "Team lunch",
+ description: null,
+ location: "Cafe",
+ conferencing: null,
+ timeZone: "Europe/London",
+};
+
+const unchanged = { timeZone: "Europe/London", settingsChanged: false };
+
+describe("getPollChanges", () => {
+ it("records nothing when the edit leaves every field as it was", () => {
+ expect(
+ getPollChanges({
+ prior,
+ next: { ...unchanged, title: "Team lunch", location: "Cafe" },
+ }),
+ ).toEqual([]);
+ });
+
+ it("keeps the old title", () => {
+ expect(
+ getPollChanges({ prior, next: { ...unchanged, title: "Team dinner" } }),
+ ).toEqual([{ field: "title", from: "Team lunch" }]);
+ });
+
+ it("tells an added value from a changed or removed one", () => {
+ expect(
+ getPollChanges({
+ prior,
+ next: { ...unchanged, description: "Bring snacks", location: "" },
+ }),
+ ).toEqual([
+ { field: "description", action: "added", from: null },
+ { field: "location", action: "removed", from: "Cafe" },
+ ]);
+ });
+
+ it("treats an empty string as no value", () => {
+ expect(
+ getPollChanges({
+ prior: { ...prior, description: "" },
+ next: { ...unchanged, description: "" },
+ }),
+ ).toEqual([]);
+ });
+
+ it("records a changed video call with the previous one", () => {
+ expect(
+ getPollChanges({
+ prior: { ...prior, conferencing: { provider: "zoom" } },
+ next: { ...unchanged, conferencing: { provider: "meet" } },
+ }),
+ ).toEqual([
+ { field: "conferencing", action: "changed", from: { provider: "zoom" } },
+ ]);
+ });
+
+ it("records time zone and settings changes", () => {
+ expect(
+ getPollChanges({
+ prior,
+ next: { timeZone: null, settingsChanged: true },
+ }),
+ ).toEqual([
+ { field: "timeZone", from: "Europe/London" },
+ { field: "settings" },
+ ]);
+ });
+});
diff --git a/apps/web/src/features/activity/utils.ts b/apps/web/src/features/activity/utils.ts
new file mode 100644
index 000000000..5970724ff
--- /dev/null
+++ b/apps/web/src/features/activity/utils.ts
@@ -0,0 +1,72 @@
+import type { PollConferencing } from "@/features/conferencing/schema";
+import type { PollChange } from "./schema";
+
+type ChangeAction = "added" | "changed" | "removed";
+
+const getChangeAction = (from: unknown, to: unknown): ChangeAction =>
+ from === null ? "added" : to === null ? "removed" : "changed";
+
+/**
+ * The fields an edit changed, each with its previous value. `next` holds only
+ * what the edit sent; an omitted field is unchanged. Empty strings and null
+ * are the same absent value to the reader, so they compare equal.
+ */
+export function getPollChanges({
+ prior,
+ next,
+}: {
+ prior: {
+ title: string;
+ description: string | null;
+ location: string | null;
+ conferencing: PollConferencing | null;
+ timeZone: string | null;
+ };
+ next: {
+ title?: string;
+ description?: string;
+ location?: string;
+ conferencing?: PollConferencing | null;
+ timeZone: string | null;
+ settingsChanged: boolean;
+ };
+}): PollChange[] {
+ const changes: PollChange[] = [];
+
+ if (next.title !== undefined && next.title !== prior.title) {
+ changes.push({ field: "title", from: prior.title });
+ }
+
+ for (const field of ["description", "location"] as const) {
+ const value = next[field];
+ if (value === undefined) {
+ continue;
+ }
+ const from = prior[field] || null;
+ const to = value || null;
+ if (from !== to) {
+ changes.push({ field, action: getChangeAction(from, to), from });
+ }
+ }
+
+ if (
+ next.conferencing !== undefined &&
+ JSON.stringify(next.conferencing) !== JSON.stringify(prior.conferencing)
+ ) {
+ changes.push({
+ field: "conferencing",
+ action: getChangeAction(prior.conferencing, next.conferencing),
+ from: prior.conferencing,
+ });
+ }
+
+ if (next.timeZone !== prior.timeZone) {
+ changes.push({ field: "timeZone", from: prior.timeZone });
+ }
+
+ if (next.settingsChanged) {
+ changes.push({ field: "settings" });
+ }
+
+ return changes;
+}
diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsx
index b3563967b..3ef1e8e26 100644
--- a/apps/web/src/features/poll/components/create-poll.tsx
+++ b/apps/web/src/features/poll/components/create-poll.tsx
@@ -24,6 +24,7 @@ import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-f
import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";
import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";
import type { NewEventData } from "@/features/poll/components/forms/types";
+import { SelectedOptionsCount } from "@/features/poll/components/selected-options-count";
import { SHARE_POLL_FLASH_KEY } from "@/features/poll/constants";
import { useUser } from "@/features/user/client";
import { UserDropdown } from "@/features/user/components/user-dropdown";
@@ -71,30 +72,6 @@ const GuestModeBadge = () => {
);
};
-const SelectedOptionsCount = () => {
- const form = useFormContext<NewEventData>();
- const optionCount = form.watch("options").length;
- const allDay = form.watch("allDay");
-
- if (allDay) {
- return (
- <Trans
- i18nKey="createPollFooterDatesSelected"
- defaults="{count, plural, =0 {No dates selected} one {1 date selected} other {# dates selected}}"
- values={{ count: optionCount }}
- />
- );
- }
-
- return (
- <Trans
- i18nKey="createPollFooterTimesSelected"
- defaults="{count, plural, =0 {No times selected} one {1 time selected} other {# times selected}}"
- values={{ count: optionCount }}
- />
- );
-};
-
const CreatePollActions = ({
createdPollId,
}: {
diff --git a/apps/web/src/features/poll/components/edit-poll.tsx b/apps/web/src/features/poll/components/edit-poll.tsx
new file mode 100644
index 000000000..cc439c8f5
--- /dev/null
+++ b/apps/web/src/features/poll/components/edit-poll.tsx
@@ -0,0 +1,329 @@
+"use client";
+
+import { buttonVariants } from "@rallly/ui";
+import { Button } from "@rallly/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@rallly/ui/card";
+import { Form } from "@rallly/ui/form";
+import { useRouter } from "next/navigation";
+import React from "react";
+import { useForm } from "react-hook-form";
+import { Link } from "@/components/link";
+import { useModalContext } from "@/components/modal/modal-provider";
+import type { ConferencingOptions } from "@/features/conferencing/components/conferencing-field";
+import {
+ toConferencingFormValues,
+ toPollConferencing,
+} from "@/features/conferencing/components/conferencing-field";
+import { useParticipants, usePoll } from "@/features/poll/client";
+import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";
+import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";
+import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";
+import type {
+ NewEventData,
+ PollOptionsData,
+} from "@/features/poll/components/forms/types";
+import { useUpdatePollMutation } from "@/features/poll/components/mutations";
+import { SelectedOptionsCount } from "@/features/poll/components/selected-options-count";
+import type { PollDetails } from "@/features/poll/types";
+import { filterParticipantsByVote } from "@/features/poll/utils";
+import { useUser } from "@/features/user/client";
+import { Trans, useTranslation } from "@/i18n/client";
+import {
+ addMinutesToWallTime,
+ instantToWallTime,
+} from "@/lib/datetime/wall-time";
+import {
+ encodeDateOption,
+ getBrowserTimeZone,
+} from "@/lib/utils/date-time-utils";
+
+const toPollWallTime = (value: Date, timeZone: string | null) =>
+ instantToWallTime(value, timeZone ?? "UTC");
+
+const encodeStoredOption = (
+ option: { startTime: Date; duration: number },
+ timeZone: string | null,
+) => {
+ const start = toPollWallTime(option.startTime, timeZone);
+ return option.duration === 0
+ ? start.slice(0, 10)
+ : `${start}/${addMinutesToWallTime(start, option.duration)}`;
+};
+
+function getDefaultValues(poll: PollDetails): NewEventData {
+ const firstDate = toPollWallTime(
+ poll.options[0]?.startTime ?? new Date(),
+ poll.timeZone,
+ );
+
+ return {
+ title: poll.title,
+ location: poll.location ?? "",
+ description: poll.description ?? "",
+ ...toConferencingFormValues(poll.conferencing),
+ navigationDate: firstDate.slice(0, 10),
+ view: "month",
+ options: poll.options.map((option) => {
+ const start = toPollWallTime(option.startTime, poll.timeZone);
+ return option.duration > 0
+ ? {
+ type: "timeSlot" as const,
+ start,
+ end: addMinutesToWallTime(start, option.duration),
+ }
+ : { type: "date" as const, date: start.slice(0, 10) };
+ }),
+ timeZone: poll.timeZone ?? "",
+ // A timed poll with no stored zone was locked to a single wall-clock time.
+ // All-day polls are neutral (lock doesn't apply).
+ lockTimeZone:
+ !poll.timeZone && poll.options.some((option) => option.duration > 0),
+ allDay:
+ poll.options.length > 0 &&
+ poll.options.every((option) => option.duration === 0),
+ duration: poll.options[0]?.duration || 60,
+ hideParticipants: poll.hideParticipants,
+ hideScores: poll.hideScores,
+ enableComments: !poll.disableComments,
+ allowTentativeVotes: poll.allowTentativeVotes,
+ requireParticipantEmail: poll.requireParticipantEmail,
+ };
+}
+
+/**
+ * What changed in the dates, or null when the options and their time zone
+ * frame are as stored.
+ */
+function getDateChanges({
+ poll,
+ data,
+ fallbackTimeZone,
+}: {
+ poll: PollDetails;
+ data: PollOptionsData;
+ fallbackTimeZone: string;
+}) {
+ // The submitted frame for the options: null when locked or all-day
+ // (floating), else the organizer's zone.
+ const timeZone =
+ !data.lockTimeZone && !data.allDay
+ ? data.timeZone || fallbackTimeZone
+ : null;
+
+ const encodedOptions = data.options.map(encodeDateOption);
+
+ // When the frame changes the stored instants no longer match it, so every
+ // option is re-stored from the form's wall-clock under the new frame, which
+ // keeps the displayed times put (3pm stays 3pm). Otherwise only what the
+ // organizer edited is touched.
+ const frameChanged = timeZone !== poll.timeZone;
+
+ const optionsToDelete = frameChanged
+ ? poll.options
+ : poll.options.filter(
+ (option) =>
+ !encodedOptions.includes(encodeStoredOption(option, poll.timeZone)),
+ );
+
+ const optionsToAdd = frameChanged
+ ? encodedOptions
+ : encodedOptions.filter(
+ (encoded) =>
+ !poll.options.some(
+ (option) => encodeStoredOption(option, poll.timeZone) === encoded,
+ ),
+ );
+
+ if (
+ !frameChanged &&
+ optionsToDelete.length === 0 &&
+ optionsToAdd.length === 0
+ ) {
+ return null;
+ }
+
+ return { timeZone, optionsToDelete, optionsToAdd };
+}
+
+const detailFields = [
+ "title",
+ "location",
+ "description",
+ "conferencingProvider",
+ "conferencingUrl",
+ "conferencingLabel",
+] as const;
+
+const settingFields = [
+ "hideParticipants",
+ "hideScores",
+ "enableComments",
+ "allowTentativeVotes",
+ "requireParticipantEmail",
+] as const;
+
+/**
+ * The whole poll as one form, laid out like the create page and filled with
+ * the poll's current values. Save sends only what changed.
+ */
+export function EditPoll({
+ conferencing,
+ returnHref,
+}: {
+ conferencing: ConferencingOptions | null;
+ returnHref: string;
+}) {
+ const poll = usePoll();
+ const { participants } = useParticipants();
+ const { user } = useUser();
+ const { t } = useTranslation();
+ const router = useRouter();
+ const modalContext = useModalContext();
+ const update = useUpdatePollMutation();
+
+ // The answer set is locked once a response uses the tentative vote, so
+ // those votes stay re-saveable by their owner.
+ const hasTentativeVotes = participants.some((participant) =>
+ participant.votes.some((vote) => vote.type === "ifNeedBe"),
+ );
+ const hasVotes = participants.some(
+ (participant) => participant.votes.length > 0,
+ );
+
+ const [defaultValues] = React.useState(() => getDefaultValues(poll));
+ const form = useForm<NewEventData>({ defaultValues });
+
+ const onSubmit = form.handleSubmit((data) => {
+ const input: Parameters<typeof update.mutate>[0] = { pollId: poll.id };
+
+ // Compared against the starting values rather than dirtyFields: the
+ // Remove buttons clear a field with setValue, which doesn't mark it dirty.
+ const isChanged = (
+ field: (typeof detailFields)[number] | (typeof settingFields)[number],
+ ) => (data[field] ?? "") !== (defaultValues[field] ?? "");
+
+ const detailsChanged = detailFields.some(isChanged);
+ if (detailsChanged) {
+ input.title = data.title;
+ input.location = data.location;
+ input.description = data.description;
+ input.conferencing = toPollConferencing(data) ?? null;
+ }
+
+ const dateChanges = getDateChanges({
+ poll,
+ data,
+ fallbackTimeZone: user?.timeZone || getBrowserTimeZone(),
+ });
+ if (dateChanges) {
+ input.timeZone = dateChanges.timeZone;
+ input.optionsToDelete = dateChanges.optionsToDelete.map(({ id }) => id);
+ input.optionsToAdd = dateChanges.optionsToAdd;
+ }
+
+ const settingsChanged = settingFields.some(isChanged);
+ if (settingsChanged) {
+ input.hideParticipants = data.hideParticipants;
+ input.hideScores = data.hideScores;
+ input.disableComments = !data.enableComments;
+ input.allowTentativeVotes = data.allowTentativeVotes;
+ input.requireParticipantEmail = data.requireParticipantEmail;
+ }
+
+ if (!detailsChanged && !dateChanges && !settingsChanged) {
+ router.push(returnHref);
+ return;
+ }
+
+ const submit = () => {
+ update.mutate(input, {
+ onSuccess: (res) => {
+ if (res.ok) {
+ router.push(returnHref);
+ }
+ },
+ });
+ };
+
+ const deletesVotedOptions = dateChanges?.optionsToDelete.some(
+ (option) =>
+ filterParticipantsByVote(participants, option.id, "yes").length > 0,
+ );
+
+ if (deletesVotedOptions) {
+ modalContext.render({
+ title: t("areYouSure", { defaultValue: "Are you sure?" }),
+ content: (
+ <Trans
+ i18nKey="deletingOptionsWarning"
+ defaults="You are deleting options that participants have voted for. Their votes will also be deleted."
+ components={{ b: <strong /> }}
+ />
+ ),
+ onOk: submit,
+ okButtonProps: { variant: "destructive" },
+ okText: t("delete"),
+ cancelText: t("cancel"),
+ });
+ } else {
+ submit();
+ }
+ });
+
+ return (
+ <Form {...form}>
+ <form id="edit-poll" onSubmit={onSubmit} className="space-y-4">
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans i18nKey="event" defaults="Event" />
+ </CardTitle>
+ <CardDescription>
+ <Trans
+ i18nKey="describeYourEvent"
+ defaults="Describe what your event is about"
+ />
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <PollDetailsForm conferencing={conferencing} />
+ </CardContent>
+ </Card>
+ <PollOptionsForm disableTimeZoneChange={hasVotes} />
+ <PollSettingsForm hasTentativeVotes={hasTentativeVotes} />
+ <div className="sticky bottom-0 z-20 flex justify-center pt-2 pb-6">
+ <div className="flex w-full max-w-md items-center justify-between gap-x-4 rounded-full border border-popover-border bg-popover py-2 pr-2 pl-5 shadow-2xl shadow-black/40">
+ <p className="min-w-0 truncate text-muted-foreground text-sm">
+ <SelectedOptionsCount />
+ </p>
+ <div className="flex shrink-0 items-center gap-x-2">
+ <Link
+ href={returnHref}
+ className={buttonVariants({
+ variant: "ghost",
+ className: "rounded-full",
+ })}
+ >
+ <Trans i18nKey="cancel" defaults="Cancel" />
+ </Link>
+ <Button
+ type="submit"
+ variant="primary"
+ className="rounded-full px-4"
+ loading={update.isPending}
+ >
+ <Trans i18nKey="saveChanges" defaults="Save changes" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/web/src/features/poll/components/manage-poll.tsx b/apps/web/src/features/poll/components/manage-poll.tsx
index 40a46325c..cfdd3b053 100644
--- a/apps/web/src/features/poll/components/manage-poll.tsx
+++ b/apps/web/src/features/poll/components/manage-poll.tsx
@@ -15,8 +15,6 @@ import {
DownloadIcon,
PencilIcon,
PlayIcon,
- Settings2Icon,
- TableIcon,
TrashIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
@@ -99,22 +97,10 @@ const ManagePoll: React.FunctionComponent<{
{canEdit ? (
<>
<DropdownMenuItem
- render={<Link href={`/poll/${poll.id}/edit-details`} />}
+ render={<Link href={`/poll/${poll.id}/edit`} />}
>
<PencilIcon />
- <Trans i18nKey="editDetails" />
- </DropdownMenuItem>
- <DropdownMenuItem
- render={<Link href={`/poll/${poll.id}/edit-options`} />}
- >
- <TableIcon />
- <Trans i18nKey="editOptions" />
- </DropdownMenuItem>
- <DropdownMenuItem
- render={<Link href={`/poll/${poll.id}/edit-settings`} />}
- >
- <Settings2Icon />
- <Trans i18nKey="editSettings" defaults="Edit settings" />
+ <Trans i18nKey="edit" defaults="Edit" />
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
diff --git a/apps/web/src/features/poll/components/poll-admin-menu.tsx b/apps/web/src/features/poll/components/poll-admin-menu.tsx
index 2c62ac102..d5cccaf84 100644
--- a/apps/web/src/features/poll/components/poll-admin-menu.tsx
+++ b/apps/web/src/features/poll/components/poll-admin-menu.tsx
@@ -15,10 +15,12 @@ import {
CopyIcon,
DownloadIcon,
MoreHorizontalIcon,
+ PencilIcon,
PlayIcon,
TrashIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
+import { Link } from "@/components/link";
import { showPayWall, useIsFree } from "@/features/billing/client";
import { ProBadge } from "@/features/billing/components/pro-badge";
import { usePoll } from "@/features/poll/client";
@@ -69,6 +71,17 @@ export function PollAdminMenu() {
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ {poll.status === "scheduled" ? null : (
+ <>
+ <DropdownMenuItem
+ render={<Link href={`/poll/${poll.id}/edit?from=admin`} />}
+ >
+ <PencilIcon />
+ <Trans i18nKey="edit" defaults="Edit" />
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
<DropdownMenuItem onClick={exportToCsv}>
<DownloadIcon />
<Trans i18nKey="exportToCsv" defaults="Export to CSV" />
diff --git a/apps/web/src/features/poll/components/selected-options-count.tsx b/apps/web/src/features/poll/components/selected-options-count.tsx
new file mode 100644
index 000000000..8ede5d30e
--- /dev/null
+++ b/apps/web/src/features/poll/components/selected-options-count.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { useFormContext } from "react-hook-form";
+import type { PollOptionsData } from "@/features/poll/components/forms/types";
+import { Trans } from "@/i18n/client";
+
+/** How many dates or times the poll form currently has selected. */
+export const SelectedOptionsCount = () => {
+ const form = useFormContext<PollOptionsData>();
+ const optionCount = form.watch("options").length;
+ const allDay = form.watch("allDay");
+
+ if (allDay) {
+ return (
+ <Trans
+ i18nKey="createPollFooterDatesSelected"
+ defaults="{count, plural, =0 {No dates selected} one {1 date selected} other {# dates selected}}"
+ values={{ count: optionCount }}
+ />
+ );
+ }
+
+ return (
+ <Trans
+ i18nKey="createPollFooterTimesSelected"
+ defaults="{count, plural, =0 {No times selected} one {1 time selected} other {# times selected}}"
+ values={{ count: optionCount }}
+ />
+ );
+};
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 2f4077897..036f40793 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -10,6 +10,7 @@ import * as z from "zod";
import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
import { toEmailConferencing } from "@/emails/conferencing";
import { recordPollActivities } from "@/features/activity/mutations";
+import { getPollChanges } from "@/features/activity/utils";
import {
getConnectedConferencingProviders,
parsePollConferencing,
@@ -125,6 +126,16 @@ async function mintConferencing({
});
}
+const toOptionSnapshot = (option: {
+ id: string;
+ startTime: Date;
+ duration: number;
+}) => ({
+ optionId: option.id,
+ start: option.startTime.toISOString(),
+ duration: option.duration,
+});
+
export const polls = router({
invites,
infiniteChronological: spaceProcedure
@@ -528,6 +539,12 @@ export const polls = router({
}
}) ?? [];
+ // Lock the poll row for the rest of the transaction. Concurrent edits
+ // then queue, so each reads the values the previous one committed and
+ // records the right previous value. It is also the lock vote writes
+ // take, which the tentative vote check below relies on.
+ await tx.$queryRaw`SELECT id FROM polls WHERE id = ${pollId} FOR UPDATE`;
+
// Prior persisted values, read before the update so poll_updated is
// recorded only when a detail or setting actually changes (the edit
// forms always send some fields, e.g. timeZone on option-only edits).
@@ -558,12 +575,9 @@ export const polls = router({
// poll whose responses are all yes/no can still be switched, and an
// organizer who turned it off can always turn it back on.
if (input.allowTentativeVotes === false && prior.allowTentativeVotes) {
- // Take the same row lock the vote writes take, so a tentative vote
- // committing concurrently either lands before this count sees it or
- // waits and then fails its own check. Without the lock, READ
- // COMMITTED lets one slip in between the count and the update.
- await tx.$queryRaw`SELECT id FROM polls WHERE id = ${pollId} FOR UPDATE`;
-
+ // The row lock taken above makes a tentative vote committing
+ // concurrently either land before this count sees it or wait and
+ // then fail its own check.
const tentativeVoteCount = await tx.vote.count({
where: { pollId, type: "ifNeedBe" },
});
@@ -678,59 +692,71 @@ export const polls = router({
: input.timeZone
: null;
- // Empty strings and null are the same absent value to the reader, so
- // normalize before comparing.
- const detailsOrSettingsChanged =
- (input.title !== undefined && input.title !== prior.title) ||
- (input.location !== undefined &&
- (input.location || null) !== (prior.location || null)) ||
- (input.description !== undefined &&
- (input.description || null) !== (prior.description || null)) ||
- (conferencing !== undefined &&
- JSON.stringify(conferencing) !==
- JSON.stringify(
- parsePollConferencing(prior.conferencing, { pollId }),
- )) ||
- nextTimeZone !== prior.timeZone ||
- (input.hideParticipants !== undefined &&
- input.hideParticipants !== prior.hideParticipants) ||
- (input.disableComments !== undefined &&
- input.disableComments !== prior.disableComments) ||
- (input.allowTentativeVotes !== undefined &&
- input.allowTentativeVotes !== prior.allowTentativeVotes) ||
- (input.hideScores !== undefined &&
- input.hideScores !== prior.hideScores) ||
- (input.requireParticipantEmail !== undefined &&
- input.requireParticipantEmail !== prior.requireParticipantEmail);
+ const changes = getPollChanges({
+ prior: {
+ title: prior.title,
+ description: prior.description,
+ location: prior.location,
+ conferencing: parsePollConferencing(prior.conferencing, {
+ pollId,
+ }),
+ timeZone: prior.timeZone,
+ },
+ next: {
+ title: input.title,
+ description: input.description,
+ location: input.location,
+ conferencing,
+ timeZone: nextTimeZone,
+ settingsChanged:
+ (input.hideParticipants !== undefined &&
+ input.hideParticipants !== prior.hideParticipants) ||
+ (input.disableComments !== undefined &&
+ input.disableComments !== prior.disableComments) ||
+ (input.allowTentativeVotes !== undefined &&
+ input.allowTentativeVotes !== prior.allowTentativeVotes) ||
+ (input.hideScores !== undefined &&
+ input.hideScores !== prior.hideScores) ||
+ (input.requireParticipantEmail !== undefined &&
+ input.requireParticipantEmail !==
+ prior.requireParticipantEmail),
+ },
+ });
await recordPollActivities(tx, [
- ...deletedOptions.map((option) => ({
- pollId,
- type: "option_deleted" as const,
- userId: ctx.user.id,
- optionId: option.id,
- payload: {
- start: option.startTime.toISOString(),
- duration: option.duration,
- },
- })),
- ...addedOptions.map((option) => ({
- pollId,
- type: "option_added" as const,
- userId: ctx.user.id,
- optionId: option.id,
- payload: {
- start: option.startTime.toISOString(),
- duration: option.duration,
- },
- })),
- ...(detailsOrSettingsChanged
+ ...(deletedOptions.length > 0
+ ? [
+ {
+ pollId,
+ type: "options_deleted" as const,
+ userId: ctx.user.id,
+ payload: {
+ options: deletedOptions.map(toOptionSnapshot),
+ timeZone: prior.timeZone,
+ },
+ },
+ ]
+ : []),
+ ...(addedOptions.length > 0
+ ? [
+ {
+ pollId,
+ type: "options_added" as const,
+ userId: ctx.user.id,
+ payload: {
+ options: addedOptions.map(toOptionSnapshot),
+ timeZone: nextTimeZone,
+ },
+ },
+ ]
+ : []),
+ ...(changes.length > 0
? [
{
pollId,
type: "poll_updated" as const,
userId: ctx.user.id,
- payload: {},
+ payload: { changes },
},
]
: []),
diff --git a/apps/web/tests/edit-options.spec.ts b/apps/web/tests/edit-options.spec.ts
index b7cb9212c..c5a37e73d 100644
--- a/apps/web/tests/edit-options.spec.ts
+++ b/apps/web/tests/edit-options.spec.ts
@@ -21,7 +21,7 @@ test.describe("edit options", () => {
// Polls default to timed options. Selecting all-day replaces the voted
// time options with date options, which deletes the options that have votes.
await editOptionsPage.selectAllDay();
- await page.getByRole("button", { name: "Save" }).click();
+ await page.getByRole("button", { name: "Save changes" }).click();
await expect(page.locator('text="Are you sure?"')).toBeVisible();
await page.click("text='Delete'");
});
diff --git a/apps/web/tests/poll-page.ts b/apps/web/tests/poll-page.ts
index c9e82b07e..b8c6de9b4 100644
--- a/apps/web/tests/poll-page.ts
+++ b/apps/web/tests/poll-page.ts
@@ -47,9 +47,9 @@ export class PollPage {
const pollUrl = page.url();
await page.getByRole("button", { name: "Manage" }).click();
- await page.getByRole("menuitem", { name: "Edit options" }).click();
+ await page.getByRole("menuitem", { name: "Edit" }).click();
- await page.waitForURL(`${pollUrl}/edit-options`);
+ await page.waitForURL(`${pollUrl}/edit`);
return new EditOptionsPage(page);
}