Skip to content

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

♻️ Serve the poll invite list through a tRPC query (#3228)

Luke Vellae481cf5b2c6d
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index e6be5e894..cb577af7d 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -786,6 +786,7 @@
"shareDialogInvitedCount": "{count, plural, one {# invited} other {# invited}}",
"shareDialogInviteRemoved": "Invite for {email} removed",
"shareDialogInviteSent": "Invite sent to {email}",
+ "shareDialogInvitesLoadFailed": "Couldn't load invites",
"shareDialogNoInvitesDescription": "Enter an address above to send the first invite.",
"shareDialogNoInvitesTitle": "No one invited yet",
"shareDialogPersonalLinkCopied": "Personal link for {email} copied",
@@ -862,6 +863,7 @@
"today": "Today",
"tooManyVerificationAttempts": "Too many incorrect attempts. Request a new code to continue.",
"totalSeats": "Total seats",
+ "tryAgain": "Try again",
"unbanUser": "Unban user",
"unconfirmedEventsEmptyStateDescription": "Unconfirmed events will show up here.",
"unconfirmedEventsEmptyStateTitle": "No unconfirmed events",
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx
index f78f36164..2140f5623 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/layout.tsx
@@ -5,7 +5,6 @@ import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { PollLayout } from "@/features/poll/components/poll-layout";
-import { loadPollInvites } from "@/features/poll/invite/loaders";
import { createPublicSSRHelper } from "@/trpc/server/create-ssr-helper";
export default async function Layout(
@@ -30,15 +29,14 @@ export default async function Layout(
redirect(`/invite/${params.urlId}`);
}
- const [invites] = await Promise.all([
- loadPollInvites(params.urlId),
+ await Promise.all([
trpc.polls.participants.list.prefetch({ pollId: params.urlId }),
trpc.polls.comments.list.prefetch({ pollId: params.urlId }),
]);
return (
<HydrationBoundary state={dehydrate(trpc.queryClient)}>
- <PollLayout invites={invites}>{children}</PollLayout>
+ <PollLayout>{children}</PollLayout>
</HydrationBoundary>
);
}
diff --git a/apps/web/src/components/animated-height.tsx b/apps/web/src/components/animated-height.tsx
new file mode 100644
index 000000000..387312ad8
--- /dev/null
+++ b/apps/web/src/components/animated-height.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import { cn } from "@rallly/ui";
+import React from "react";
+
+/**
+ * Eases between content heights instead of snapping, for containers whose
+ * content swaps or grows (an empty state giving way to a list). Height is the
+ * one property with no transform equivalent here. The first measurement sets
+ * the height without a transition: browsers do not animate from `auto`.
+ */
+export function AnimatedHeight({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ const contentRef = React.useRef<HTMLDivElement>(null);
+ const [height, setHeight] = React.useState<number>();
+
+ React.useLayoutEffect(() => {
+ const content = contentRef.current;
+ if (!content) {
+ return;
+ }
+ const observer = new ResizeObserver(([entry]) => {
+ setHeight(entry.contentRect.height);
+ });
+ observer.observe(content);
+ return () => observer.disconnect();
+ }, []);
+
+ return (
+ <div
+ className={cn(
+ "overflow-y-clip transition-[height] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
+ className,
+ )}
+ style={{ height }}
+ >
+ <div ref={contentRef}>{children}</div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/poll/components/invite-by-email.tsx b/apps/web/src/features/poll/components/invite-by-email.tsx
index 8499e7555..c8fedc973 100644
--- a/apps/web/src/features/poll/components/invite-by-email.tsx
+++ b/apps/web/src/features/poll/components/invite-by-email.tsx
@@ -11,14 +11,17 @@ import { toast } from "@rallly/ui/sonner";
import { MailIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
+import { AnimatedHeight } from "@/components/animated-height";
import {
EmptyState,
EmptyStateDescription,
+ EmptyStateFooter,
EmptyStateIcon,
EmptyStateTitle,
} from "@/components/empty-state";
import { LoginLink } from "@/components/login-link";
import { RegisterLink } from "@/components/register-link";
+import { Spinner } from "@/components/spinner";
import { showPayWall, useIsFree } from "@/features/billing/client";
import { ProBadge } from "@/features/billing/components/pro-badge";
import { usePoll } from "@/features/poll/client";
@@ -29,10 +32,10 @@ import {
} from "@/features/poll/components/invitee-list";
import { sendPollInviteAction } from "@/features/poll/invite/actions";
import { sendPollInviteSchema } from "@/features/poll/invite/schema";
-import type { PollInviteListItem } from "@/features/poll/invite/types";
import { useUser } from "@/features/user/client";
import { Trans, useTranslation } from "@/i18n/client";
import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
type Row = {
id: string;
@@ -46,17 +49,22 @@ const inviteFormSchema = sendPollInviteSchema.pick({ email: true });
type InviteFormValues = { email: string };
/**
- * `invites` is server data passed down from the route; the send action's
- * success handler refreshes the route, which is what replaces an optimistic
- * "Sending" row with the real one.
+ * The list is fetched when the dialog mounts rather than with the page: most
+ * page views never open it. The send action's success refetches it, which is
+ * what replaces an optimistic "Sending" row with the real one.
*/
-export function InviteByEmail({ invites }: { invites: PollInviteListItem[] }) {
+export function InviteByEmail() {
const poll = usePoll();
const { user } = useUser();
const isFree = useIsFree();
const { t } = useTranslation();
const isGuest = !user || user.isGuest;
+ const invitesQuery = trpc.polls.invites.list.useQuery(
+ { pollId: poll.id },
+ { enabled: !isGuest },
+ );
+ const invites = invitesQuery.data ?? [];
const isOpen = poll.status === "open";
const form = useForm<InviteFormValues>({
@@ -273,8 +281,42 @@ export function InviteByEmail({ invites }: { invites: PollInviteListItem[] }) {
</p>
) : null}
- <div className="mt-3">
- {rows.length === 0 ? (
+ <AnimatedHeight className="mt-3">
+ {invitesQuery.isPending ? (
+ <div className="relative mt-2">
+ <InviteeListPreview />
+ <output
+ aria-label={t("loading", { defaultValue: "Loading..." })}
+ className="absolute inset-0 grid place-items-center backdrop-blur-[2px]"
+ >
+ <Spinner />
+ </output>
+ </div>
+ ) : invitesQuery.isError ? (
+ <div className="relative mt-2">
+ <InviteeListPreview />
+ <EmptyState className="absolute inset-0 py-0 backdrop-blur-[2px]">
+ <EmptyStateIcon>
+ <MailIcon />
+ </EmptyStateIcon>
+ <EmptyStateTitle>
+ <Trans
+ i18nKey="shareDialogInvitesLoadFailed"
+ defaults="Couldn't load invites"
+ />
+ </EmptyStateTitle>
+ <EmptyStateFooter className="mt-3">
+ <Button
+ size="sm"
+ onClick={() => invitesQuery.refetch()}
+ disabled={invitesQuery.isFetching}
+ >
+ <Trans i18nKey="tryAgain" defaults="Try again" />
+ </Button>
+ </EmptyStateFooter>
+ </EmptyState>
+ </div>
+ ) : rows.length === 0 ? (
<div className="relative mt-2">
<InviteeListPreview />
<EmptyState className="absolute inset-0 py-0 backdrop-blur-[2px]">
@@ -316,7 +358,7 @@ export function InviteByEmail({ invites }: { invites: PollInviteListItem[] }) {
</ul>
</>
)}
- </div>
+ </AnimatedHeight>
</>
)}
diff --git a/apps/web/src/features/poll/components/invitee-list.tsx b/apps/web/src/features/poll/components/invitee-list.tsx
index 42c6e7a71..8d534c81c 100644
--- a/apps/web/src/features/poll/components/invitee-list.tsx
+++ b/apps/web/src/features/poll/components/invitee-list.tsx
@@ -82,7 +82,7 @@ function InviteeRowMenu({
const { t } = useTranslation();
const [state, copyToClipboard] = useCopyToClipboard();
- // The success handler refreshes the route, which is what drops the row.
+ // The success handler refetches the list, which is what drops the row.
const revoke = useSafeAction(revokePollInviteAction, {
onSuccess: ({ data }) => {
if (!data) return;
diff --git a/apps/web/src/features/poll/components/poll-layout.tsx b/apps/web/src/features/poll/components/poll-layout.tsx
index c030b0386..dce18578e 100644
--- a/apps/web/src/features/poll/components/poll-layout.tsx
+++ b/apps/web/src/features/poll/components/poll-layout.tsx
@@ -16,23 +16,19 @@ import ManagePoll from "@/features/poll/components/manage-poll";
import { NotificationToggle } from "@/features/poll/components/notification-toggle";
import { LegacyPollContextProvider } from "@/features/poll/components/poll-context-provider";
import { ShareDialog } from "@/features/poll/components/share-dialog";
-import type { PollInviteListItem } from "@/features/poll/invite/types";
import { Trans } from "@/i18n/client";
-const AdminControls = ({ invites }: { invites: PollInviteListItem[] }) => {
+const AdminControls = () => {
return (
<div className="flex items-center gap-x-2">
<NotificationToggle />
<ManagePoll />
- <ShareDialog invites={invites} />
+ <ShareDialog />
</div>
);
};
-const Layout = ({
- children,
- invites,
-}: React.PropsWithChildren<{ invites: PollInviteListItem[] }>) => {
+const Layout = ({ children }: React.PropsWithChildren) => {
const poll = usePoll();
const pollLink = `/poll/${poll.id}`;
const pathname = usePathname();
@@ -71,7 +67,7 @@ const Layout = ({
</Breadcrumb>
</div>
<div>
- <AdminControls invites={invites} />
+ <AdminControls />
</div>
</div>
</div>
@@ -82,10 +78,7 @@ const Layout = ({
);
};
-export const PollLayout = ({
- children,
- invites,
-}: React.PropsWithChildren<{ invites: PollInviteListItem[] }>) => {
+export const PollLayout = ({ children }: React.PropsWithChildren) => {
const params = useParams();
const urlId = params?.urlId as string;
@@ -97,7 +90,7 @@ export const PollLayout = ({
return (
<LegacyPollContextProvider>
- <Layout invites={invites}>{children}</Layout>
+ <Layout>{children}</Layout>
</LegacyPollContextProvider>
);
};
diff --git a/apps/web/src/features/poll/components/share-dialog.tsx b/apps/web/src/features/poll/components/share-dialog.tsx
index e3123b7d5..4b3e96d86 100644
--- a/apps/web/src/features/poll/components/share-dialog.tsx
+++ b/apps/web/src/features/poll/components/share-dialog.tsx
@@ -18,11 +18,10 @@ import { usePoll } from "@/features/poll/client";
import { InviteByEmail } from "@/features/poll/components/invite-by-email";
import { InviteLinkRow } from "@/features/poll/components/invite-link-row";
import { SHARE_POLL_FLASH_KEY } from "@/features/poll/constants";
-import type { PollInviteListItem } from "@/features/poll/invite/types";
import { Trans } from "@/i18n/client";
import { useFlash } from "@/lib/flash/client";
-export function ShareDialog({ invites }: { invites: PollInviteListItem[] }) {
+export function ShareDialog() {
const poll = usePoll();
const dialog = useDialog();
const isFree = useIsFree();
@@ -74,7 +73,7 @@ export function ShareDialog({ invites }: { invites: PollInviteListItem[] }) {
</DialogHeader>
<InviteLinkRow inviteLink={poll.inviteLink} />
<Separator />
- <InviteByEmail invites={invites} />
+ <InviteByEmail />
</DialogContent>
</Dialog>
</>
diff --git a/apps/web/src/features/poll/invite/loaders.ts b/apps/web/src/features/poll/invite/loaders.ts
deleted file mode 100644
index 163a76f1b..000000000
--- a/apps/web/src/features/poll/invite/loaders.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import "server-only";
-
-import { absoluteUrl } from "@rallly/utils/absolute-url";
-import { cache } from "react";
-import { hasPollAdminAccess } from "@/features/poll/data";
-import { listPollInvites } from "@/features/poll/invite/data";
-import type { PollInviteListItem } from "@/features/poll/invite/types";
-import {
- derivePollInviteStatus,
- getPollInvitePath,
-} from "@/features/poll/invite/utils";
-import { getCurrentUser } from "@/features/user/loaders";
-
-/**
- * The invites a viewer may see for a poll. Guests and non-admins get an
- * empty list rather than a redirect: the poll page renders for them and the
- * share dialog hides the email section itself.
- */
-export const loadPollInvites = cache(
- async (pollId: string): Promise<PollInviteListItem[]> => {
- const user = await getCurrentUser();
-
- if (!user || !(await hasPollAdminAccess(pollId, user.id))) {
- return [];
- }
-
- const invites = await listPollInvites({ pollId });
-
- return invites.map((invite) => ({
- id: invite.id,
- email: invite.email,
- status: derivePollInviteStatus(invite),
- inviteUrl: absoluteUrl(
- getPollInvitePath({ pollId, token: invite.token }),
- ),
- }));
- },
-);
diff --git a/apps/web/src/lib/safe-action/client.ts b/apps/web/src/lib/safe-action/client.ts
index 065b695f7..fe445934a 100644
--- a/apps/web/src/lib/safe-action/client.ts
+++ b/apps/web/src/lib/safe-action/client.ts
@@ -1,5 +1,6 @@
"use client";
import { toast } from "@rallly/ui/sonner";
+import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useAction } from "next-safe-action/hooks";
import { useTranslation } from "@/i18n/client";
@@ -8,10 +9,14 @@ import type { AppErrorCode } from "@/lib/errors/app-error";
export const useSafeAction: typeof useAction = (action, options) => {
const { t } = useTranslation();
const router = useRouter();
+ const queryClient = useQueryClient();
return useAction(action, {
...options,
onSuccess: (args) => {
router.refresh();
+ // Same blanket invalidation the tRPC mutation override does, so a
+ // client query never shows stale data after a write.
+ void queryClient.invalidateQueries();
options?.onSuccess?.(args);
},
onError: (args) => {
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 39a047b9b..1a5bedbeb 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -37,6 +37,7 @@ import {
spaceProcedure,
} from "../trpc";
import { comments } from "./polls/comments";
+import { invites } from "./polls/invites";
import { participants } from "./polls/participants";
import { getScheduledEventTimes } from "./polls/scheduled-event-times";
import { timeZoneInput } from "./polls/schema";
@@ -53,6 +54,7 @@ const optionEndsInFuture = (option: { startTime: Date; duration: number }) =>
export const polls = router({
participants,
comments,
+ invites,
infiniteChronological: spaceProcedure
.input(
z.object({
diff --git a/apps/web/src/trpc/routers/polls/invites.ts b/apps/web/src/trpc/routers/polls/invites.ts
new file mode 100644
index 000000000..d49a75dd8
--- /dev/null
+++ b/apps/web/src/trpc/routers/polls/invites.ts
@@ -0,0 +1,32 @@
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import { TRPCError } from "@trpc/server";
+import * as z from "zod";
+import { hasPollAdminAccess } from "@/features/poll/data";
+import { listPollInvites } from "@/features/poll/invite/data";
+import type { PollInviteListItem } from "@/features/poll/invite/types";
+import {
+ derivePollInviteStatus,
+ getPollInvitePath,
+} from "@/features/poll/invite/utils";
+import { privateProcedure, router } from "../../trpc";
+
+export const invites = router({
+ list: privateProcedure
+ .input(z.object({ pollId: z.string() }))
+ .query(async ({ ctx, input }): Promise<PollInviteListItem[]> => {
+ if (!(await hasPollAdminAccess(input.pollId, ctx.user.id))) {
+ throw new TRPCError({ code: "NOT_FOUND", message: "Poll not found" });
+ }
+
+ const invites = await listPollInvites({ pollId: input.pollId });
+
+ return invites.map((invite) => ({
+ id: invite.id,
+ email: invite.email,
+ status: derivePollInviteStatus(invite),
+ inviteUrl: absoluteUrl(
+ getPollInvitePath({ pollId: input.pollId, token: invite.token }),
+ ),
+ }));
+ }),
+});