feat: update comments

This commit is contained in:
Henry
2024-11-19 23:33:41 +00:00
parent d7074814ae
commit ce9a1f5148
8 changed files with 281 additions and 47 deletions

View File

@@ -1,13 +1,16 @@
import { twMerge } from "tailwind-merge";
import LoadingSpinner from "./LoadingSpinner";
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "primary" | "secondary" | "danger";
variant?: "primary" | "secondary" | "danger" | "ghost";
size?: "sm" | "md" | "lg";
isLoading?: boolean;
icon?: React.ReactNode;
}
const Button = ({
children,
size = "md",
icon,
isLoading,
variant = "primary",
@@ -17,12 +20,16 @@ const Button = ({
<button
className={twMerge(
"inline-flex items-center justify-center rounded-md px-3 py-2 text-sm font-semibold text-light-50 shadow-sm focus-visible:outline-none",
size === "sm" && "text-xs",
size === "lg" && "px-4 py-3 text-lg",
variant === "primary" &&
"bg-light-1000 dark:bg-dark-1000 dark:text-dark-50",
variant === "secondary" &&
"border-[1px] border-light-600 bg-light-50 text-light-1000 dark:border-dark-600 dark:bg-dark-300 dark:text-dark-1000",
variant === "danger" &&
"dark:text-red-1000 border-[1px] border-red-600 bg-red-50 dark:border-red-600 dark:bg-red-500",
variant === "ghost" &&
"bg-none text-light-1000 shadow-none hover:bg-light-300 dark:text-dark-1000 dark:hover:bg-dark-200",
props.disabled && "opacity-50",
)}
disabled={isLoading ?? props.disabled}
@@ -30,27 +37,8 @@ const Button = ({
>
<span className="relative flex items-center justify-center">
{isLoading && (
<span className="absolute inset-0 flex items-center justify-center">
<svg
className="h-5 w-5 animate-spin text-white dark:text-dark-800"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
<span className="absolute">
<LoadingSpinner size={size} />
</span>
)}
<div

View File

@@ -1,5 +1,6 @@
import { WorkspaceProvider } from "~/providers/workspace";
import Dashboard from "~/components/dashboard";
import Popup from "~/components/Popup";
import CardView from "~/views/card";
export default function CardPage() {
@@ -8,6 +9,7 @@ export default function CardPage() {
<Dashboard>
<CardView />
</Dashboard>
<Popup />
</WorkspaceProvider>
);
}

View File

@@ -226,6 +226,80 @@ export const cardRouter = createTRPCRouter({
return newComment;
}),
updateComment: protectedProcedure
.meta({
openapi: {
summary: "Update a comment",
method: "PUT",
path: "/cards/{cardPublicId}/comments/{commentPublicId}",
description: "Updates a comment",
tags: ["Cards"],
protect: true,
},
})
.input(
z.object({
cardPublicId: z.string().min(12),
commentPublicId: z.string().min(12),
comment: z.string().min(1),
}),
)
.output(z.custom<Awaited<ReturnType<typeof cardCommentRepo.update>>>())
.mutation(async ({ ctx, input }) => {
const userId = ctx.user?.id;
if (!userId)
throw new TRPCError({
message: `User not authenticated`,
code: "UNAUTHORIZED",
});
const card = await cardRepo.getByPublicId(ctx.db, input.cardPublicId);
const existingComment = await cardCommentRepo.getByPublicId(
ctx.db,
input.commentPublicId,
);
if (!card)
throw new TRPCError({
message: `Card with public ID ${input.cardPublicId} not found`,
code: "NOT_FOUND",
});
if (!existingComment)
throw new TRPCError({
message: `Comment with public ID ${input.commentPublicId} not found`,
code: "NOT_FOUND",
});
if (existingComment.createdBy !== userId)
throw new TRPCError({
message: `You do not have permission to update this comment`,
code: "FORBIDDEN",
});
const updatedComment = await cardCommentRepo.update(ctx.db, {
id: existingComment.id,
comment: input.comment,
});
if (!updatedComment?.id)
throw new TRPCError({
message: `Failed to update comment`,
code: "INTERNAL_SERVER_ERROR",
});
await cardActivityRepo.create(ctx.db, {
type: "card.updated.comment.updated" as const,
cardId: card.id,
commentId: updatedComment.id,
fromComment: existingComment.comment,
toComment: updatedComment.comment,
createdBy: userId,
});
return updatedComment;
}),
addOrRemoveLabel: protectedProcedure
.meta({
openapi: {

View File

@@ -275,7 +275,8 @@ export const getWithListAndMembersByPublicId = async (
comment:card_comments!card_activity_commentId_card_comments_id_fk (
publicId,
comment,
createdBy
createdBy,
updatedAt
)
)
`,

View File

@@ -24,3 +24,39 @@ export const create = async (
return data;
};
export const getByPublicId = async (
db: SupabaseClient<Database>,
publicId: string,
) => {
const { data } = await db
.from("card_comments")
.select(`id, publicId, comment, createdBy`)
.eq("publicId", publicId)
.limit(1)
.single();
return data;
};
export const update = async (
db: SupabaseClient<Database>,
commentInput: {
id: number;
comment: string;
},
) => {
const { data } = await db
.from("card_comments")
.update({
comment: commentInput.comment,
updatedAt: new Date().toISOString(),
})
.eq("id", commentInput.id)
.select(`id, publicId, comment`)
.limit(1)
.order("id", { ascending: false })
.single();
return data;
};

View File

@@ -9,6 +9,7 @@ import {
} from "react-icons/hi2";
import Avatar from "~/components/Avatar";
import Comment from "./Comment";
import { type GetCardByIdOutput } from "~/types/router.types";
@@ -126,9 +127,11 @@ const getActivityIcon = (type: ActivityType): React.ReactNode | null => {
const ActivityList = ({
activities,
cardPublicId,
isLoading,
}: {
activities: NonNullable<GetCardByIdOutput>["activities"];
cardPublicId: string;
isLoading: boolean;
}) => {
return (
@@ -146,31 +149,17 @@ const ActivityList = ({
if (activity.type === "card.updated.comment.added")
return (
<div
<Comment
key={activity.publicId}
className="relative flex flex w-full flex-col rounded-xl border border-light-600 bg-light-200 p-5 text-light-900 focus-visible:outline-none dark:border-dark-600 dark:bg-dark-100 dark:text-dark-1000 sm:text-sm sm:leading-6"
>
<div className="flex items-center space-x-2">
<Avatar
size="sm"
name={activity.user?.name ?? ""}
email={activity.user?.email ?? ""}
isLoading={isLoading}
/>
<p className="text-sm">
<span className="font-medium dark:text-dark-1000">{`${activity.user?.name} `}</span>
<span className="mx-1 text-light-900 dark:text-dark-800">
·
</span>
<span className="space-x-1 text-light-900 dark:text-dark-800">
{formatDistanceToNow(new Date(activity.createdAt), {
addSuffix: true,
})}
</span>
</p>
</div>
<p className="mt-2 text-sm">{activity.comment?.comment}</p>
</div>
publicId={activity.comment?.publicId}
cardPublicId={cardPublicId}
name={activity.user?.name ?? ""}
email={activity.user?.email ?? ""}
isLoading={isLoading}
createdAt={activity.createdAt}
comment={activity.comment?.comment}
isEdited={!!activity.comment?.updatedAt}
/>
);
if (!activityText) return null;

View File

@@ -0,0 +1,143 @@
import { useState } from "react";
import { useForm } from "react-hook-form";
import ContentEditable from "react-contenteditable";
import { formatDistanceToNow } from "date-fns";
import { api } from "~/utils/api";
import { usePopup } from "~/providers/popup";
import Avatar from "~/components/Avatar";
import Button from "~/components/Button";
import Dropdown from "~/components/Dropdown";
import { HiEllipsisHorizontal } from "react-icons/hi2";
interface FormValues {
comment: string;
}
const Comment = ({
publicId,
cardPublicId,
name,
email,
isLoading,
createdAt,
comment,
isEdited = false,
}: {
publicId: string | undefined;
cardPublicId: string;
name: string;
email: string;
isLoading: boolean;
createdAt: string;
comment: string | undefined;
isEdited: boolean;
}) => {
const [isEditing, setIsEditing] = useState(false);
const utils = api.useUtils();
const { showPopup } = usePopup();
const { handleSubmit, setValue, watch } = useForm<FormValues>({
defaultValues: {
comment,
},
});
if (!publicId) return null;
const updateCommentMutation = api.card.updateComment.useMutation({
onSuccess: async () => {
await utils.card.byId.refetch();
setIsEditing(false);
},
onError: () => {
showPopup({
header: "Unable to update comment",
message: "Please try again later, or contact customer support.",
});
},
});
const onSubmit = (data: FormValues) => {
updateCommentMutation.mutate({
cardPublicId,
comment: data.comment,
commentPublicId: publicId,
});
};
return (
<div
key={publicId}
className="group relative flex w-full flex-col rounded-xl border border-light-600 bg-light-200 p-5 text-light-900 focus-visible:outline-none dark:border-dark-600 dark:bg-dark-100 dark:text-dark-1000 sm:text-sm sm:leading-6"
>
<div className="flex justify-between">
<div className="flex items-center space-x-2">
<Avatar
size="sm"
name={name ?? ""}
email={email ?? ""}
isLoading={isLoading}
/>
<p className="text-sm">
<span className="font-medium dark:text-dark-1000">{`${name} `}</span>
<span className="mx-1 text-light-900 dark:text-dark-800">·</span>
<span className="space-x-1 text-light-900 dark:text-dark-800">
{formatDistanceToNow(new Date(createdAt), {
addSuffix: true,
})}
</span>
{isEdited && (
<span className="text-light-900 dark:text-dark-800">
{" (edited)"}
</span>
)}
</p>
</div>
<Dropdown
items={[
{
label: "Edit",
action: () => setIsEditing(true),
},
]}
>
<HiEllipsisHorizontal className="h-5 w-5" />
</Dropdown>
</div>
{!isEditing ? (
<p className="mt-2 text-sm">{comment}</p>
) : (
<form onSubmit={handleSubmit(onSubmit)}>
<ContentEditable
placeholder="Add a comment..."
html={watch("comment")}
disabled={false}
onChange={(e) => setValue("comment", e.target.value)}
className="block w-full border-0 bg-transparent py-1.5 text-light-900 focus-visible:outline-none dark:text-dark-1000 sm:text-sm sm:leading-6"
/>
<div className="flex justify-end space-x-2">
<Button
size="sm"
variant="ghost"
onClick={() => setIsEditing(false)}
>
Cancel
</Button>
<Button
isLoading={updateCommentMutation.isPending}
type="submit"
size="sm"
>
Save
</Button>
</div>
</form>
)}
</div>
);
};
export default Comment;

View File

@@ -181,6 +181,7 @@ export default function CardPage() {
</h2>
<div>
<ActivityList
cardPublicId={cardId}
activities={activities ?? []}
isLoading={isLoading}
/>