Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Move poll comments into a sheet opened from a floating trigger (#2879)
Luke Vella445c10b465e9
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 68607db2f..9b3fa23eb 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -144,6 +144,9 @@"commentsSettingLegacyBadge": "Legacy","commentsSettingPhaseOutHint": "Comments are being phased out. Participants can include a note with their response instead.","commentsSettingTitle": "Comments",+ "commentsSheetDescription": "View and add comments on this poll",+ "commentsSheetEmpty": "No comments yet",+ "commentsSheetSubmitted": "Your comment has been added","configuredByEnvironmentVariable": "This setting has been configured by environment variable.","confirm": "Confirm","confirmSpaceName": "Please type the space name to confirm:",diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsxindex 9bf91a5b3..9b5d0e287 100644--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/admin-page.tsx@@ -1,5 +1,5 @@"use client";-import Discussion from "@/features/poll/components/discussion";+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";@@ -14,8 +14,11 @@ export function AdminPage() {<VotingForm><ResponsiveResults /></VotingForm>- <Discussion />+ <div className="fixed right-4 bottom-4 z-40 lg:right-6 lg:bottom-6">+ <CommentsSheet className="rounded-full shadow-lg" />+ </div><PollFooter />+ <div className="h-12 lg:hidden" /></div>);}diff --git a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsxindex 41e8a8215..dfbb65647 100644--- a/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx+++ b/apps/web/src/app/[locale]/invite/[urlId]/invite-page.tsx@@ -4,7 +4,7 @@ import { Alert, AlertAction, AlertDescription } from "@rallly/ui/alert";import { ArrowUpRightIcon, CrownIcon } from "lucide-react";import Link from "next/link";import { usePoll } from "@/features/poll/client";-import Discussion from "@/features/poll/components/discussion";+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";@@ -58,8 +58,11 @@ export function InvitePage() {<VotingForm><ResponsiveResults /></VotingForm>- <Discussion /><PollFooter />+ <div className="fixed right-4 bottom-4 z-40 lg:right-6 lg:bottom-6">+ <CommentsSheet className="rounded-full shadow-lg" />+ </div>+ <div className="h-12 lg:hidden" /></main></div>);diff --git a/apps/web/src/features/poll/components/comments-sheet.tsx b/apps/web/src/features/poll/components/comments-sheet.tsxnew file mode 100644index 000000000..cd61ddf09--- /dev/null+++ b/apps/web/src/features/poll/components/comments-sheet.tsx@@ -0,0 +1,355 @@+"use client";+import { Badge } from "@rallly/ui/badge";+import { Button } from "@rallly/ui/button";+import { useDialog } from "@rallly/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";+import {+ InputGroup,+ InputGroupAddon,+ InputGroupButton,+ InputGroupInput,+ InputGroupText,+ InputGroupTextarea,+} from "@rallly/ui/input-group";+import { MaxCharLength } from "@rallly/ui/max-char-length";+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+} from "@rallly/ui/sheet";+import { toast } from "@rallly/ui/sonner";+import {+ CheckCircle2Icon,+ CornerDownLeftIcon,+ MessageCircleIcon,+ MoreHorizontalIcon,+ TrashIcon,+} from "lucide-react";+import * as React from "react";+import { Controller, useForm } from "react-hook-form";+import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";+import { usePoll, useRole } from "@/features/poll/client";+import { useEditToken } from "@/features/poll/components/mutations";+import {+ Participant,+ ParticipantName,+} from "@/features/poll/components/participant";+import { useParticipants } from "@/features/poll/components/participants-provider";+import TruncatedLinkify from "@/features/poll/components/truncated-linkify";+import {+ MAX_COMMENT_AUTHOR_NAME_LENGTH,+ MAX_COMMENT_LENGTH,+} from "@/features/poll/schema";+import { useUser } from "@/features/user/client";+import { Trans, useTranslation } from "@/i18n/client";+import { RelativeTime } from "@/lib/datetime/relative-time";+import { requiredString } from "@/lib/utils/form-validation";+import { trpc } from "@/trpc/client";++interface CommentForm {+ authorName: string;+ content: string;+}++function NewCommentForm({ onSubmitted }: { onSubmitted: () => void }) {+ const { t } = useTranslation();+ const poll = usePoll();+ const { user, createGuestIfNeeded } = useUser();+ const { participants } = useParticipants();++ const authorName = React.useMemo(() => {+ if (user) {+ if (!user.isGuest) {+ return user.name;+ }+ const participant = participants.find((p) => p.userId === user.id);+ return participant?.name ?? "";+ }+ return "";+ }, [user, participants]);++ const pollId = poll.id;++ const { register, reset, control, handleSubmit, formState, watch } =+ useForm<CommentForm>({+ defaultValues: {+ authorName,+ content: "",+ },+ });++ const contentLength = watch("content").length;++ const queryClient = trpc.useUtils();++ const addComment = trpc.polls.comments.add.useMutation({+ onError: (error) => {+ toast.error(error.message);+ },+ });+ return (+ <form+ className="w-full"+ onSubmit={handleSubmit(async ({ authorName, content }) => {+ await createGuestIfNeeded();+ await addComment.mutateAsync({ authorName, content, pollId });+ await queryClient.polls.comments.list.invalidate({ pollId });+ reset({ authorName, content: "" });+ onSubmitted();+ })}+ >+ <InputGroup className="bg-background shadow-lg dark:bg-card">+ <InputGroupAddon align="block-start" className="border-b">+ {user && !user.isGuest ? (+ <>+ <OptimizedAvatarImage+ size="sm"+ src={user.image}+ name={user.name}+ />+ <InputGroupText>{user.name}</InputGroupText>+ </>+ ) : (+ <>+ <OptimizedAvatarImage size="sm" name={watch("authorName")} />+ <Controller+ name="authorName"+ key={user?.id}+ control={control}+ rules={{ validate: requiredString }}+ render={({ field }) => (+ <InputGroupInput+ placeholder={t("yourName")}+ maxLength={MAX_COMMENT_AUTHOR_NAME_LENGTH}+ data-1p-ignore="true"+ aria-invalid={!!formState.errors.authorName}+ {...field}+ />+ )}+ />+ </>+ )}+ </InputGroupAddon>+ <div className="flex w-full items-end">+ <InputGroupTextarea+ id="comment"+ maxLength={MAX_COMMENT_LENGTH}+ placeholder={t("commentPlaceholder")}+ aria-invalid={!!formState.errors.content}+ {...register("content", { validate: requiredString })}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ e.currentTarget.form?.requestSubmit();+ }+ }}+ />+ <InputGroupAddon align="inline-end" className="pb-1.5">+ <MaxCharLength+ length={contentLength}+ maxLength={MAX_COMMENT_LENGTH}+ label={t("charactersRemaining", {+ defaultValue:+ "{count, plural, one {# character remaining} other {# characters remaining}}",+ count: MAX_COMMENT_LENGTH - contentLength,+ })}+ />+ <InputGroupButton+ type="submit"+ size="icon-sm"+ aria-label={t("addComment", { defaultValue: "Add Comment" })}+ loading={formState.isSubmitting}+ >+ <CornerDownLeftIcon />+ </InputGroupButton>+ </InputGroupAddon>+ </div>+ </InputGroup>+ </form>+ );+}++function CommentsSheetInner({ className }: { className?: string }) {+ const { t } = useTranslation();+ const poll = usePoll();+ const dialog = useDialog();++ const pollId = poll.id;+ const token = useEditToken();++ const { data: comments } = trpc.polls.comments.list.useQuery({ pollId });++ const queryClient = trpc.useUtils();++ const deleteComment = trpc.polls.comments.delete.useMutation({+ onMutate: ({ commentId }) => {+ const previousComments = queryClient.polls.comments.list.getData({+ pollId,+ });+ queryClient.polls.comments.list.setData(+ { pollId },+ (existingComments = []) => {+ return existingComments.filter(({ id }) => id !== commentId);+ },+ );+ return { previousComments };+ },+ onError: (_error, _variables, context) => {+ queryClient.polls.comments.list.setData(+ { pollId },+ context?.previousComments,+ );+ },+ onSettled: () => {+ queryClient.polls.comments.list.invalidate({ pollId });+ },+ });++ const session = useUser();++ const role = useRole();++ const [hasCommented, setHasCommented] = React.useState(false);++ const count = comments?.length ?? 0;++ return (+ <>+ <Button className={className} onClick={() => dialog.trigger()}>+ <MessageCircleIcon data-icon="inline-start" />+ <Trans i18nKey="comments" defaults="Comments" />+ {count > 0 ? <Badge>{count}</Badge> : null}+ </Button>+ <Sheet {...dialog.dialogProps}>+ <SheetContent className="flex w-full flex-col sm:max-w-md">+ <SheetHeader>+ <div className="flex items-center gap-2">+ <SheetTitle>+ <Trans i18nKey="comments" defaults="Comments" />+ </SheetTitle>+ {count > 0 ? <Badge>{count}</Badge> : null}+ </div>+ <SheetDescription className="sr-only">+ <Trans+ i18nKey="commentsSheetDescription"+ defaults="View and add comments on this poll"+ />+ </SheetDescription>+ </SheetHeader>+ <div className="-mx-6 -mb-6 flex grow flex-col overflow-y-auto px-6">+ <div className="flex grow flex-col">+ {count > 0 ? (+ <div className="space-y-4">+ {comments?.map((comment) => {+ const canDelete =+ role === "admin" || session.ownsObject(comment);++ return (+ <div data-testid="comment" key={comment.id}>+ <div className="mb-1 flex items-center space-x-2">+ <Participant>+ <OptimizedAvatarImage+ name={comment.authorName}+ size="sm"+ />+ <ParticipantName>+ {comment.authorName}+ </ParticipantName>+ {session.ownsObject(comment) ? (+ <Badge>+ <Trans i18nKey="you" />+ </Badge>+ ) : null}+ </Participant>+ <div className="flex items-center gap-2 text-sm">+ <div className="text-muted-foreground">+ <RelativeTime value={comment.createdAt} />+ </div>+ {canDelete && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ aria-label={t("moreOptions", {+ defaultValue: "More options",+ })}+ variant="ghost"+ size="icon-xs"+ />+ }+ >+ <MoreHorizontalIcon />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuItem+ variant="destructive"+ onClick={() => {+ deleteComment.mutate({+ commentId: comment.id,+ token,+ });+ }}+ >+ <TrashIcon />+ <Trans i18nKey="delete" />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ </div>+ <div className="w-fit whitespace-pre-wrap pl-8 text-sm leading-relaxed">+ <TruncatedLinkify>{comment.content}</TruncatedLinkify>+ </div>+ </div>+ );+ })}+ </div>+ ) : (+ <div className="flex grow flex-col items-center justify-center gap-2 text-center">+ <MessageCircleIcon className="size-5 text-muted-foreground" />+ <p className="text-muted-foreground text-sm">+ <Trans+ i18nKey="commentsSheetEmpty"+ defaults="No comments yet"+ />+ </p>+ </div>+ )}+ </div>+ {!poll.event ? (+ <div className="sticky bottom-0 pt-3 pb-6">+ {hasCommented ? (+ <div className="flex items-center gap-2 rounded-lg border bg-background p-3 text-muted-foreground text-sm shadow-lg dark:bg-card">+ <CheckCircle2Icon className="size-4 text-green-600 dark:text-green-500" />+ <Trans+ i18nKey="commentsSheetSubmitted"+ defaults="Your comment has been added"+ />+ </div>+ ) : (+ <NewCommentForm onSubmitted={() => setHasCommented(true)} />+ )}+ </div>+ ) : null}+ </div>+ </SheetContent>+ </Sheet>+ </>+ );+}++export function CommentsSheet({ className }: { className?: string }) {+ const poll = usePoll();+ if (poll.disableComments) {+ return null;+ }+ return <CommentsSheetInner className={className} />;+}diff --git a/apps/web/src/features/poll/components/discussion.tsx b/apps/web/src/features/poll/components/discussion.tsxdeleted file mode 100644index 96588fa71..000000000--- a/apps/web/src/features/poll/components/discussion.tsx+++ /dev/null@@ -1,305 +0,0 @@-"use client";-import { cn } from "@rallly/ui";-import { Badge } from "@rallly/ui/badge";-import { Button } from "@rallly/ui/button";-import {- Card,- CardContent,- CardFooter,- CardHeader,- CardTitle,-} from "@rallly/ui/card";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@rallly/ui/dropdown-menu";-import { Input } from "@rallly/ui/input";-import { MaxCharLength } from "@rallly/ui/max-char-length";-import { toast } from "@rallly/ui/sonner";-import { Textarea } from "@rallly/ui/textarea";-import { MoreHorizontalIcon, TrashIcon } from "lucide-react";-import * as React from "react";-import { Controller, useForm } from "react-hook-form";-import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";-import { usePoll, useRole } from "@/features/poll/client";-import { useEditToken } from "@/features/poll/components/mutations";-import {- Participant,- ParticipantName,-} from "@/features/poll/components/participant";-import { useParticipants } from "@/features/poll/components/participants-provider";-import TruncatedLinkify from "@/features/poll/components/truncated-linkify";-import {- MAX_COMMENT_AUTHOR_NAME_LENGTH,- MAX_COMMENT_LENGTH,-} from "@/features/poll/schema";-import { useUser } from "@/features/user/client";-import { Trans, useTranslation } from "@/i18n/client";-import { RelativeTime } from "@/lib/datetime/relative-time";-import { requiredString } from "@/lib/utils/form-validation";-import { trpc } from "@/trpc/client";--interface CommentForm {- authorName: string;- content: string;-}--function NewCommentForm({- onSubmit,- onCancel,-}: {- onSubmit?: () => void;- onCancel?: () => void;-}) {- const { t } = useTranslation();- const poll = usePoll();- const { user, createGuestIfNeeded } = useUser();- const { participants } = useParticipants();-- const authorName = React.useMemo(() => {- if (user) {- if (!user.isGuest) {- return user.name;- }- const participant = participants.find((p) => p.userId === user.id);- return participant?.name ?? "";- }- return "";- }, [user, participants]);-- const pollId = poll.id;-- const { register, reset, control, handleSubmit, formState, watch } =- useForm<CommentForm>({- defaultValues: {- authorName,- content: "",- },- });-- const contentLength = watch("content").length;-- const addComment = trpc.polls.comments.add.useMutation({- onError: (error) => {- toast.error(error.message);- },- });- return (- <form- className="w-full space-y-2.5"- onSubmit={handleSubmit(async ({ authorName, content }) => {- await createGuestIfNeeded();- await addComment.mutateAsync({ authorName, content, pollId });- reset({ authorName, content: "" });- onSubmit?.();- })}- >- <div>- <Textarea- id="comment"- className="w-full"- autoFocus={true}- maxLength={MAX_COMMENT_LENGTH}- placeholder={t("commentPlaceholder")}- {...register("content", { validate: requiredString })}- />- <MaxCharLength- className="mt-1 flex justify-end"- length={contentLength}- maxLength={MAX_COMMENT_LENGTH}- label={t("charactersRemaining", {- defaultValue:- "{count, plural, one {# character remaining} other {# characters remaining}}",- count: MAX_COMMENT_LENGTH - contentLength,- })}- />- </div>- <div- className={cn("mb-2", {- hidden: user && !user.isGuest,- })}- >- <Controller- name="authorName"- key={user?.id}- control={control}- rules={{ validate: requiredString }}- render={({ field }) => (- <Input- placeholder={t("yourName")}- className="lg:w-48"- maxLength={MAX_COMMENT_AUTHOR_NAME_LENGTH}- data-1p-ignore="true"- aria-invalid={!!formState.errors.authorName}- {...field}- />- )}- />- </div>- <div className="flex gap-2.5">- <Button- type="submit"- variant="primary"- loading={formState.isSubmitting}- >- <Trans defaults="Add Comment" i18nKey="addComment" />- </Button>- <Button- onClick={() => {- reset();- onCancel?.();- }}- >- {t("cancel")}- </Button>- </div>- </form>- );-}--function DiscussionInner() {- const { t } = useTranslation();- const poll = usePoll();-- const pollId = poll.id;- const token = useEditToken();-- const { data: comments } = trpc.polls.comments.list.useQuery({ pollId });-- const queryClient = trpc.useUtils();-- const deleteComment = trpc.polls.comments.delete.useMutation({- onMutate: ({ commentId }) => {- queryClient.polls.comments.list.setData(- { pollId },- (existingComments = []) => {- return [...existingComments].filter(({ id }) => id !== commentId);- },- );- },- });-- const session = useUser();-- const [isWriting, setIsWriting] = React.useState(false);- const role = useRole();-- if (!comments) {- return null;- }-- return (- <Card>- <CardHeader>- <CardTitle>- {t("comments")}- <Badge>{comments.length}</Badge>- </CardTitle>- </CardHeader>- {comments.length ? (- <CardContent>- <div className="space-y-4">- {comments.map((comment) => {- const canDelete = role === "admin" || session.ownsObject(comment);-- return (- <div className="" key={comment.id}>- <div data-testid="comment">- <div className="mb-1 flex items-center space-x-2">- <Participant>- <OptimizedAvatarImage- name={comment.authorName}- size="sm"- />- <ParticipantName>{comment.authorName}</ParticipantName>- {session.ownsObject(comment) ? (- <Badge>- <Trans i18nKey="you" />- </Badge>- ) : null}- </Participant>- <div className="flex items-center gap-2 text-sm">- <div className="text-muted-foreground">- <RelativeTime value={comment.createdAt} />- </div>- {canDelete && (- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- aria-label={t("moreOptions", {- defaultValue: "More options",- })}- variant="ghost"- size="icon-xs"- />- }- >- <MoreHorizontalIcon />- </DropdownMenuTrigger>- <DropdownMenuContent align="start">- <DropdownMenuItem- variant="destructive"- onClick={() => {- deleteComment.mutate({- commentId: comment.id,- token,- });- }}- >- <TrashIcon />- <Trans i18nKey="delete" />- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </div>- </div>- <div className="w-fit whitespace-pre-wrap pl-8 text-sm leading-relaxed">- <TruncatedLinkify>{comment.content}</TruncatedLinkify>- </div>- </div>- </div>- );- })}- </div>- </CardContent>- ) : null}- {!poll.event ? (- <CardFooter>- {isWriting ? (- <NewCommentForm- onSubmit={() => {- setIsWriting(false);- }}- onCancel={() => {- setIsWriting(false);- }}- />- ) : (- <button- type="button"- className="flex w-full rounded-lg border border-input bg-transparent px-2 py-2 text-left text-muted-foreground text-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-offset-1"- onClick={() => setIsWriting(true)}- >- <Trans- i18nKey="commentPlaceholder"- defaults="Leave a comment on this poll (visible to everyone)"- />- </button>- )}- </CardFooter>- ) : null}- </Card>- );-}--export default function Discussion() {- const poll = usePoll();- if (poll.disableComments) {- return null;- }- return <DiscussionInner />;-}diff --git a/apps/web/tests/poll-page.ts b/apps/web/tests/poll-page.tsindex 026a413df..e6c5c99a9 100644--- a/apps/web/tests/poll-page.ts+++ b/apps/web/tests/poll-page.ts@@ -23,13 +23,15 @@ export class PollPage {async addComment() {const page = this.page;- await page.getByText("Leave a comment on this poll").click();- await page+ await page.getByRole("button", { name: "Comments" }).click();++ const sheet = page.getByRole("dialog", { name: "Comments" });+ await sheet.getByPlaceholder("Leave a comment on this poll").fill("This is a comment!");- await page.getByPlaceholder("Your name…").fill("Test user");+ await sheet.getByPlaceholder("Your name…").fill("Test user");- await page.getByRole("button", { name: "Add Comment" }).click();+ await sheet.getByRole("button", { name: "Add Comment" }).click();}async openShareDialog() {diff --git a/apps/web/tests/vote-and-comment.spec.ts b/apps/web/tests/vote-and-comment.spec.tsindex 1fd5a3512..673ab955e 100644--- a/apps/web/tests/vote-and-comment.spec.ts+++ b/apps/web/tests/vote-and-comment.spec.ts@@ -34,6 +34,11 @@ test.describe(() => {const comment = page.locator("data-testid=comment");await expect(comment.locator("text='This is a comment!'")).toBeVisible();await expect(comment.locator("text=You")).toBeVisible();++ // The comments sheet is modal; close it so later tests can reach the page.+ const sheet = page.getByRole("dialog", { name: "Comments" });+ await sheet.getByRole("button", { name: "Close" }).click();+ await expect(sheet).toBeHidden();});test("copy participant link", async () => {