Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Tabs+about+comments

Tim Wilson6fb911e67d99
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/about/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/about/page-client.tsx
index 05b240ffe3..7bc25c443e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/about/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/about/page-client.tsx
@@ -1,51 +1,12 @@
"use client";
import usePartner from "@/lib/swr/use-partner";
-import { OnlinePresenceSummary } from "@/ui/partners/online-presence-summary";
+import { PartnerAbout } from "@/ui/partners/partner-about";
import { useParams } from "next/navigation";
export function ProgramPartnerAboutPageClient() {
const { partnerId } = useParams() as { partnerId: string };
const { partner, error } = usePartner({ partnerId });
- return partner ? (
- <>
- <div className="flex flex-col gap-2">
- <h3 className="text-content-emphasis text-xs font-semibold">
- Description
- </h3>
- <p className="text-content-default text-xs">
- {partner.description || (
- <span className="italic text-neutral-400">
- No description provided
- </span>
- )}
- </p>
- </div>
-
- <div className="flex flex-col gap-2">
- <h3 className="text-content-emphasis text-xs font-semibold">
- Website and socials
- </h3>
- <OnlinePresenceSummary
- partner={partner}
- showLabels={false}
- className="gap-y-2"
- />
- </div>
- </>
- ) : error ? (
- <div className="flex justify-center py-16">
- <span className="text-content-subtle text-sm">
- Failed to load partner links
- </span>
- </div>
- ) : (
- [...Array(2)].map((_, index) => (
- <div key={index} className="flex flex-col gap-2">
- <div className="h-4 w-20 animate-pulse rounded-md bg-neutral-200" />
- <div className="h-4 w-40 animate-pulse rounded-md bg-neutral-200" />
- </div>
- ))
- );
+ return <PartnerAbout partner={partner} error={error} />;
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/comments/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/comments/page-client.tsx
index 961d6dd819..66db2a7398 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/comments/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/comments/page-client.tsx
@@ -1,385 +1,10 @@
"use client";
-import { createPartnerCommentAction } from "@/lib/actions/partners/create-partner-comment";
-import { deletePartnerCommentAction } from "@/lib/actions/partners/delete-partner-comment";
-import { updatePartnerCommentAction } from "@/lib/actions/partners/update-partner-comment";
-import { mutatePrefix } from "@/lib/swr/mutate";
-import { usePartnerComments } from "@/lib/swr/use-partner-comments";
-import useUser from "@/lib/swr/use-user";
-import useWorkspace from "@/lib/swr/use-workspace";
-import { PartnerCommentProps } from "@/lib/types";
-import { ThreeDots } from "@/ui/shared/icons";
-import { MessageInput } from "@/ui/shared/message-input";
-import {
- AnimatedSizeContainer,
- Button,
- LoadingSpinner,
- PenWriting,
- Popover,
- Trash,
-} from "@dub/ui";
-import { OG_AVATAR_URL, cn, formatDate } from "@dub/utils";
-import Linkify from "linkify-react";
-import { useAction } from "next-safe-action/hooks";
+import { PartnerComments } from "@/ui/partners/partner-comments";
import { useParams } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { KeyedMutator } from "swr";
-import { v4 as uuid } from "uuid";
export function ProgramPartnerCommentsPageClient() {
const { partnerId } = useParams() as { partnerId: string };
- const { user } = useUser();
- const { id: workspaceId, defaultProgramId: programId } = useWorkspace();
- const { comments, loading, mutate } = usePartnerComments(
- { partnerId },
- { keepPreviousData: true },
- );
- const { executeAsync: createPartnerComment } = useAction(
- createPartnerCommentAction,
- );
-
- return (
- <div className="mt-4">
- <MessageInput
- onSendMessage={(text) => {
- if (!user) return false;
-
- const createdAt = new Date();
-
- const optimisticComment: PartnerCommentProps & {
- delivered?: false;
- } = {
- id: `tmp_${uuid()}`,
- createdAt,
- updatedAt: createdAt,
- programId: programId!,
- partnerId,
- userId: user.id,
- user: {
- id: user.id,
- name: user.name,
- image: user.image || null,
- },
- text,
- delivered: false,
- };
-
- mutate(
- async (data) => {
- const result = await createPartnerComment({
- workspaceId: workspaceId!,
- partnerId,
- text,
- createdAt,
- });
-
- if (!result?.data?.comment)
- throw new Error(
- result?.serverError || "Failed to post comment",
- );
-
- return data
- ? [result.data.comment, ...data]
- : [result.data.comment];
- },
- {
- optimisticData: (data) =>
- data ? [optimisticComment, ...data] : [optimisticComment],
- rollbackOnError: true,
- },
- )
- .then(() => mutatePrefix(`/api/partners/${partnerId}/comments`))
- .catch((e) => {
- console.log("Failed to post comment", e);
- toast.error("Failed to post comment");
- });
- }}
- placeholder="Leave a comment"
- sendButtonText="Post"
- className="shadow-sm"
- />
-
- <div className="mt-4 flex flex-col gap-4">
- {comments ? (
- comments.length > 0 ? (
- comments.map((comment) => (
- <CommentCard key={comment.id} comment={comment} mutate={mutate} />
- ))
- ) : (
- <div className="text-content-muted py-2 text-center text-xs">
- No comments yet
- </div>
- )
- ) : loading ? (
- <CommentCard className="opacity-50" />
- ) : (
- <div className="text-content-muted py-4 text-center text-xs">
- Failed to load comments
- </div>
- )}
- </div>
- </div>
- );
-}
-
-function CommentCard({
- comment,
- mutate,
- className,
-}: {
- comment?: PartnerCommentProps & { delivered?: false };
- mutate?: KeyedMutator<(PartnerCommentProps & { delivered?: false })[]>;
- className?: string;
-}) {
- const { partnerId } = useParams() as { partnerId: string };
- const { user } = useUser();
- const { id: workspaceId } = useWorkspace();
-
- const [isEditing, setIsEditing] = useState(false);
-
- const { executeAsync: updateComment, isExecuting: isUpdating } = useAction(
- updatePartnerCommentAction,
- {
- onSuccess: () => {
- toast.success("Comment edited successfully");
- mutatePrefix(`/api/partners/${partnerId}/comments`);
- },
- },
- );
-
- const { executeAsync: deleteComment, isExecuting: isDeleting } = useAction(
- deletePartnerCommentAction,
- {
- onSuccess: () => {
- toast.success("Comment deleted successfully");
- mutatePrefix(`/api/partners/${partnerId}/comments`);
- },
- onError: ({ error }) => {
- toast.error(error.serverError || `Failed to delete comment`);
- },
- },
- );
-
- const [openPopover, setOpenPopover] = useState(false);
-
- const timestamp = comment ? new Date(comment.createdAt) : undefined;
-
- return (
- <div
- className={cn(
- "border-border-subtle rounded-xl border pb-4 pl-4 pr-3.5 pt-2.5 shadow-sm",
- className,
- )}
- >
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-1.5">
- {comment ? (
- <img
- src={comment.user.image || `${OG_AVATAR_URL}${comment.user.name}`}
- alt={`${comment.user.name} avatar`}
- className="size-4 shrink-0 rounded-full"
- />
- ) : (
- <div className="size-4 animate-pulse rounded-full bg-neutral-200" />
- )}
- {comment ? (
- <>
- <span className="text-content-emphasis text-xs font-semibold">
- {comment.user.name}
- </span>
- <div className="bg-content-muted size-0.5 shrink-0 rounded-full" />
- <span className="text-content-subtle text-xs">
- {new Date().getTime() - timestamp!.getTime() <
- 1000 * 60 * 60 * 24
- ? timestamp!.toLocaleTimeString("en-US", {
- hour: "numeric",
- minute: "numeric",
- })
- : formatDate(timestamp!, {
- month: "short",
- year:
- timestamp!.getFullYear() !== new Date().getFullYear()
- ? "numeric"
- : undefined,
- })}
- </span>
- {comment.delivered === false && (
- <LoadingSpinner className="size-2.5" />
- )}
- </>
- ) : (
- <div className="h-4 w-24 animate-pulse rounded bg-neutral-200" />
- )}
- </div>
- {comment && !isEditing ? (
- <Popover
- content={
- <div className="grid w-full grid-cols-1 gap-px p-2 sm:w-48">
- {comment.userId === user?.id && (
- <Button
- text="Edit comment"
- variant="outline"
- loading={isUpdating}
- disabled={comment.delivered === false}
- onClick={async () => {
- setOpenPopover(false);
- setIsEditing(true);
- }}
- icon={<PenWriting className="size-4" />}
- className="h-9 justify-start px-2 font-medium"
- />
- )}
- <Button
- text="Delete comment"
- variant="danger-outline"
- onClick={async () => {
- setOpenPopover(false);
-
- if (
- !confirm("Are you sure you want to delete this comment?")
- )
- return;
-
- await deleteComment({
- workspaceId: workspaceId!,
- commentId: comment.id,
- });
- }}
- loading={isDeleting}
- disabled={comment.delivered === false}
- icon={<Trash className="size-4" />}
- className="h-9 justify-start px-2 font-medium"
- />
- </div>
- }
- align="end"
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- <Button
- variant="secondary"
- className={cn(
- "size-7 p-0",
- "data-[state=open]:border-border-emphasis sm:group-hover/card:data-[state=closed]:border-border-subtle border-transparent",
- )}
- icon={
- isDeleting ? (
- <LoadingSpinner className="size-4 shrink-0" />
- ) : (
- <ThreeDots className="size-4 shrink-0" />
- )
- }
- onClick={() => {
- setOpenPopover(!openPopover);
- }}
- />
- </Popover>
- ) : (
- <div className="size-7" />
- )}
- </div>
-
- <div className="mt-2">
- {comment ? (
- <AnimatedSizeContainer
- height
- transition={{ duration: 0.2, ease: "easeOut" }}
- className="-m-0.5 overflow-clip"
- >
- <div className="p-0.5">
- {isEditing ? (
- <MessageInput
- defaultValue={comment.text}
- onCancel={() => setIsEditing(false)}
- onSendMessage={(text) => {
- if (!user) return false;
-
- setIsEditing(false);
-
- mutate?.(
- async (data) => {
- const result = await updateComment({
- workspaceId: workspaceId!,
- id: comment.id,
- text,
- });
-
- if (!result?.data?.comment)
- throw new Error(
- result?.serverError || "Failed to update comment",
- );
-
- if (!data) return [];
- const idx = data.findIndex(
- (c) => c.id === result.data?.comment.id,
- );
- if (idx === -1) return data;
-
- return data
- ? data.toSpliced(idx, 1, result.data.comment)
- : [];
- },
- {
- optimisticData: (data) => {
- if (!data) return [];
- const idx = data.findIndex(
- (c) => c.id === comment.id,
- );
- if (idx === -1) return data;
-
- return data.toSpliced(idx, 1, {
- ...data[idx],
- text,
- delivered: false,
- });
- },
- rollbackOnError: true,
- },
- )
- .then(() =>
- mutatePrefix(`/api/partners/${partnerId}/comments`),
- )
- .catch((e) => {
- console.log("Failed to update comment", e);
- toast.error("Failed to update comment");
- });
- }}
- onMount={({ textarea }) => {
- if (!textarea) return;
-
- // Programmatically focus and move cursor to the end, since React's autoFocus is putting the cursor at the start
- textarea.focus();
- textarea.setSelectionRange(
- textarea.value.length,
- textarea.value.length,
- );
- }}
- className="animate-fade-in"
- placeholder="Edit comment"
- sendButtonText="Save"
- />
- ) : (
- <Linkify
- as="p"
- className="text-content-subtle whitespace-pre-wrap text-sm font-medium"
- options={{
- target: "_blank",
- rel: "noopener noreferrer nofollow",
- className:
- "underline underline-offset-4 hover:text-content-default",
- }}
- >
- {comment?.text}
- </Linkify>
- )}
- </div>
- </AnimatedSizeContainer>
- ) : (
- <div className="h-5 w-48 animate-pulse rounded bg-neutral-200" />
- )}
- </div>
- </div>
- );
+ return <PartnerComments partnerId={partnerId} />;
}
diff --git a/apps/web/ui/partners/partner-about.tsx b/apps/web/ui/partners/partner-about.tsx
new file mode 100644
index 0000000000..0418531dc2
--- /dev/null
+++ b/apps/web/ui/partners/partner-about.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { EnrolledPartnerProps } from "@/lib/types";
+import { OnlinePresenceSummary } from "@/ui/partners/online-presence-summary";
+
+export function PartnerAbout({
+ partner,
+ error,
+}: {
+ partner?: EnrolledPartnerProps;
+ error?: any;
+}) {
+ return partner ? (
+ <>
+ <div className="flex flex-col gap-2">
+ <h3 className="text-content-emphasis text-xs font-semibold">
+ Description
+ </h3>
+ <p className="text-content-default text-xs">
+ {partner.description || (
+ <span className="italic text-neutral-400">
+ No description provided
+ </span>
+ )}
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <h3 className="text-content-emphasis text-xs font-semibold">
+ Website and socials
+ </h3>
+ <OnlinePresenceSummary
+ partner={partner}
+ showLabels={false}
+ className="gap-y-2"
+ />
+ </div>
+ </>
+ ) : error ? (
+ <div className="flex justify-center py-16">
+ <span className="text-content-subtle text-sm">
+ Failed to load partner links
+ </span>
+ </div>
+ ) : (
+ [...Array(2)].map((_, index) => (
+ <div key={index} className="flex flex-col gap-2">
+ <div className="h-4 w-20 animate-pulse rounded-md bg-neutral-200" />
+ <div className="h-4 w-40 animate-pulse rounded-md bg-neutral-200" />
+ </div>
+ ))
+ );
+}
diff --git a/apps/web/ui/partners/partner-application-sheet.tsx b/apps/web/ui/partners/partner-application-sheet.tsx
index 7fae37a66b..a8dd7b8138 100644
--- a/apps/web/ui/partners/partner-application-sheet.tsx
+++ b/apps/web/ui/partners/partner-application-sheet.tsx
@@ -16,7 +16,9 @@ import { Dispatch, SetStateAction, useState } from "react";
import { toast } from "sonner";
import useSWRImmutable from "swr/immutable";
import { GroupSelector } from "./groups/group-selector";
-import { OnlinePresenceSummary } from "./online-presence-summary";
+import { PartnerAbout } from "./partner-about";
+import { PartnerApplicationTabs } from "./partner-application-tabs";
+import { PartnerComments } from "./partner-comments";
type PartnerApplicationSheetProps = {
partner: EnrolledPartnerProps;
@@ -27,6 +29,8 @@ function PartnerApplicationSheetContent({
partner,
setIsOpen,
}: PartnerApplicationSheetProps) {
+ const [currentTabId, setCurrentTabId] = useState<string>("about");
+
return (
<div className="flex h-full flex-col">
<div className="flex h-16 items-center justify-between border-b border-neutral-200 px-6 py-4">
@@ -57,9 +61,17 @@ function PartnerApplicationSheetContent({
<div className="@3xl/sheet:order-2">Partner info</div>
<div className="@3xl/sheet:order-1">
<div className="border-border-subtle overflow-hidden rounded-xl border bg-neutral-100">
- Partner nav
+ <PartnerApplicationTabs
+ currentTabId={currentTabId}
+ setCurrentTabId={setCurrentTabId}
+ />
<div className="border-border-subtle -mx-px -mb-px rounded-xl border bg-white p-4">
- Content
+ {currentTabId === "about" && (
+ <PartnerApplicationAbout partner={partner} />
+ )}
+ {currentTabId === "comments" && (
+ <PartnerApplicationComments partnerId={partner.id} />
+ )}
</div>
</div>
</div>
@@ -74,30 +86,23 @@ function PartnerApplicationSheetContent({
);
}
-function PendingPartnerSummary({ partner }: { partner: EnrolledPartnerProps }) {
+function PartnerApplicationAbout({
+ partner,
+}: {
+ partner: EnrolledPartnerProps;
+}) {
return (
- <div className="grid grid-cols-1 gap-6 text-sm text-neutral-600">
- <div>
- <h4 className="text-content-emphasis font-semibold">Description</h4>
- <p className="mt-1">
- {partner.description || (
- <span className="text-content-muted italic">
- No description provided
- </span>
- )}
- </p>
- </div>
- <hr className="border-neutral-200" />
+ <div className="grid grid-cols-1 gap-5 text-sm text-neutral-600">
{partner.applicationId && (
<>
+ <h3 className="text-content-emphasis text-lg font-semibold">
+ Application
+ </h3>
<PartnerApplication applicationId={partner.applicationId} />
<hr className="border-neutral-200" />
</>
)}
- <div>
- <h4 className="text-content-emphasis font-semibold">Online presence</h4>
- <OnlinePresenceSummary partner={partner} className="mt-3" />
- </div>
+ <PartnerAbout partner={partner} />
</div>
);
}
@@ -125,11 +130,11 @@ function PartnerApplication({ applicationId }: { applicationId: string }) {
];
return (
- <div className="grid grid-cols-1 gap-6 text-sm">
+ <div className="grid grid-cols-1 gap-6 text-xs">
{fields.map((field) => (
<div key={field.title}>
<h4 className="text-content-emphasis font-semibold">{field.title}</h4>
- <div className="mt-1">
+ <div className="mt-2">
{field.value || field.value === "" ? (
<Linkify
as="p"
@@ -156,6 +161,15 @@ function PartnerApplication({ applicationId }: { applicationId: string }) {
);
}
+function PartnerApplicationComments({ partnerId }: { partnerId: string }) {
+ return (
+ <div>
+ <h3 className="text-content-emphasis text-lg font-semibold">Comments</h3>
+ <PartnerComments partnerId={partnerId} />
+ </div>
+ );
+}
+
export function PartnerApplicationSheet({
isOpen,
nested,
diff --git a/apps/web/ui/partners/partner-application-tabs.tsx b/apps/web/ui/partners/partner-application-tabs.tsx
new file mode 100644
index 0000000000..0a400fa7ae
--- /dev/null
+++ b/apps/web/ui/partners/partner-application-tabs.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { usePartnerCommentsCount } from "@/lib/swr/use-partner-comments-count";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Msg, User } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { LayoutGroup, motion } from "framer-motion";
+import { useParams } from "next/navigation";
+import { Dispatch, SetStateAction, useId, useMemo } from "react";
+
+export function PartnerApplicationTabs({
+ currentTabId,
+ setCurrentTabId,
+}: {
+ currentTabId: string;
+ setCurrentTabId: Dispatch<SetStateAction<string>>;
+}) {
+ const { partnerId } = useParams() as { partnerId: string };
+ const { slug: workspaceSlug } = useWorkspace();
+
+ const { count: commentsCount } = usePartnerCommentsCount(
+ {
+ partnerId,
+ },
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const tabs = useMemo(
+ () => [
+ {
+ id: "about",
+ label: "About",
+ icon: User,
+ },
+ {
+ id: "comments",
+ label: "Comments",
+ badge: commentsCount
+ ? commentsCount > 99
+ ? "99+"
+ : commentsCount
+ : undefined,
+ icon: Msg,
+ },
+ ],
+ [commentsCount],
+ );
+
+ const layoutGroupId = useId();
+
+ return (
+ <div className="scrollbar-hide relative z-0 flex items-center justify-between gap-1 overflow-x-auto p-2">
+ <LayoutGroup id={layoutGroupId}>
+ <motion.div
+ layout
+ className={cn("relative z-0 inline-flex items-center gap-1")}
+ >
+ {tabs.map(({ id, label, icon: Icon, badge }) => {
+ const isSelected = id === currentTabId;
+ return (
+ <button
+ key={id}
+ type="button"
+ onClick={() => setCurrentTabId(id)}
+ data-selected={isSelected}
+ className={cn(
+ "text-content-emphasis relative z-10 flex items-center gap-2 px-2.5 py-1 text-sm font-medium",
+ !isSelected &&
+ "hover:text-content-subtle z-[11] transition-colors",
+ badge && "pr-1",
+ )}
+ >
+ <Icon className="size-4" />
+ <span>{label}</span>
+ {badge && (
+ <span className="rounded-md bg-blue-600 px-2 py-0.5 text-xs font-semibold text-white">
+ {badge}
+ </span>
+ )}
+ {isSelected && (
+ <motion.div
+ layoutId={layoutGroupId}
+ className={cn(
+ "border-border-subtle bg-bg-default absolute left-0 top-0 -z-[1] size-full rounded-lg border shadow-sm",
+ )}
+ transition={{ duration: 0.25 }}
+ />
+ )}
+ </button>
+ );
+ })}
+ </motion.div>
+ </LayoutGroup>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/partner-comments.tsx b/apps/web/ui/partners/partner-comments.tsx
new file mode 100644
index 0000000000..68446ae809
--- /dev/null
+++ b/apps/web/ui/partners/partner-comments.tsx
@@ -0,0 +1,384 @@
+"use client";
+
+import { createPartnerCommentAction } from "@/lib/actions/partners/create-partner-comment";
+import { deletePartnerCommentAction } from "@/lib/actions/partners/delete-partner-comment";
+import { updatePartnerCommentAction } from "@/lib/actions/partners/update-partner-comment";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { usePartnerComments } from "@/lib/swr/use-partner-comments";
+import useUser from "@/lib/swr/use-user";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { PartnerCommentProps } from "@/lib/types";
+import { ThreeDots } from "@/ui/shared/icons";
+import { MessageInput } from "@/ui/shared/message-input";
+import {
+ AnimatedSizeContainer,
+ Button,
+ LoadingSpinner,
+ PenWriting,
+ Popover,
+ Trash,
+} from "@dub/ui";
+import { OG_AVATAR_URL, cn, formatDate } from "@dub/utils";
+import Linkify from "linkify-react";
+import { useAction } from "next-safe-action/hooks";
+import { useParams } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { KeyedMutator } from "swr";
+import { v4 as uuid } from "uuid";
+
+export function PartnerComments({ partnerId }: { partnerId: string }) {
+ const { user } = useUser();
+ const { id: workspaceId, defaultProgramId: programId } = useWorkspace();
+ const { comments, loading, mutate } = usePartnerComments(
+ { partnerId },
+ { keepPreviousData: true },
+ );
+
+ const { executeAsync: createPartnerComment } = useAction(
+ createPartnerCommentAction,
+ );
+
+ return (
+ <div className="mt-4">
+ <MessageInput
+ onSendMessage={(text) => {
+ if (!user) return false;
+
+ const createdAt = new Date();
+
+ const optimisticComment: PartnerCommentProps & {
+ delivered?: false;
+ } = {
+ id: `tmp_${uuid()}`,
+ createdAt,
+ updatedAt: createdAt,
+ programId: programId!,
+ partnerId,
+ userId: user.id,
+ user: {
+ id: user.id,
+ name: user.name,
+ image: user.image || null,
+ },
+ text,
+ delivered: false,
+ };
+
+ mutate(
+ async (data) => {
+ const result = await createPartnerComment({
+ workspaceId: workspaceId!,
+ partnerId,
+ text,
+ createdAt,
+ });
+
+ if (!result?.data?.comment)
+ throw new Error(
+ result?.serverError || "Failed to post comment",
+ );
+
+ return data
+ ? [result.data.comment, ...data]
+ : [result.data.comment];
+ },
+ {
+ optimisticData: (data) =>
+ data ? [optimisticComment, ...data] : [optimisticComment],
+ rollbackOnError: true,
+ },
+ )
+ .then(() => mutatePrefix(`/api/partners/${partnerId}/comments`))
+ .catch((e) => {
+ console.log("Failed to post comment", e);
+ toast.error("Failed to post comment");
+ });
+ }}
+ placeholder="Leave a comment"
+ sendButtonText="Post"
+ className="shadow-sm"
+ />
+
+ <div className="mt-4 flex flex-col gap-4">
+ {comments ? (
+ comments.length > 0 ? (
+ comments.map((comment) => (
+ <CommentCard key={comment.id} comment={comment} mutate={mutate} />
+ ))
+ ) : (
+ <div className="text-content-muted py-2 text-center text-xs">
+ No comments yet
+ </div>
+ )
+ ) : loading ? (
+ <CommentCard className="opacity-50" />
+ ) : (
+ <div className="text-content-muted py-4 text-center text-xs">
+ Failed to load comments
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function CommentCard({
+ comment,
+ mutate,
+ className,
+}: {
+ comment?: PartnerCommentProps & { delivered?: false };
+ mutate?: KeyedMutator<(PartnerCommentProps & { delivered?: false })[]>;
+ className?: string;
+}) {
+ const { partnerId } = useParams() as { partnerId: string };
+ const { user } = useUser();
+ const { id: workspaceId } = useWorkspace();
+
+ const [isEditing, setIsEditing] = useState(false);
+
+ const { executeAsync: updateComment, isExecuting: isUpdating } = useAction(
+ updatePartnerCommentAction,
+ {
+ onSuccess: () => {
+ toast.success("Comment edited successfully");
+ mutatePrefix(`/api/partners/${partnerId}/comments`);
+ },
+ },
+ );
+
+ const { executeAsync: deleteComment, isExecuting: isDeleting } = useAction(
+ deletePartnerCommentAction,
+ {
+ onSuccess: () => {
+ toast.success("Comment deleted successfully");
+ mutatePrefix(`/api/partners/${partnerId}/comments`);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError || `Failed to delete comment`);
+ },
+ },
+ );
+
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const timestamp = comment ? new Date(comment.createdAt) : undefined;
+
+ return (
+ <div
+ className={cn(
+ "border-border-subtle rounded-xl border pb-4 pl-4 pr-3.5 pt-2.5 shadow-sm",
+ className,
+ )}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1.5">
+ {comment ? (
+ <img
+ src={comment.user.image || `${OG_AVATAR_URL}${comment.user.name}`}
+ alt={`${comment.user.name} avatar`}
+ className="size-4 shrink-0 rounded-full"
+ />
+ ) : (
+ <div className="size-4 animate-pulse rounded-full bg-neutral-200" />
+ )}
+ {comment ? (
+ <>
+ <span className="text-content-emphasis text-xs font-semibold">
+ {comment.user.name}
+ </span>
+ <div className="bg-content-muted size-0.5 shrink-0 rounded-full" />
+ <span className="text-content-subtle text-xs">
+ {new Date().getTime() - timestamp!.getTime() <
+ 1000 * 60 * 60 * 24
+ ? timestamp!.toLocaleTimeString("en-US", {
+ hour: "numeric",
+ minute: "numeric",
+ })
+ : formatDate(timestamp!, {
+ month: "short",
+ year:
+ timestamp!.getFullYear() !== new Date().getFullYear()
+ ? "numeric"
+ : undefined,
+ })}
+ </span>
+ {comment.delivered === false && (
+ <LoadingSpinner className="size-2.5" />
+ )}
+ </>
+ ) : (
+ <div className="h-4 w-24 animate-pulse rounded bg-neutral-200" />
+ )}
+ </div>
+ {comment && !isEditing ? (
+ <Popover
+ content={
+ <div className="grid w-full grid-cols-1 gap-px p-2 sm:w-48">
+ {comment.userId === user?.id && (
+ <Button
+ text="Edit comment"
+ variant="outline"
+ loading={isUpdating}
+ disabled={comment.delivered === false}
+ onClick={async () => {
+ setOpenPopover(false);
+ setIsEditing(true);
+ }}
+ icon={<PenWriting className="size-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ )}
+ <Button
+ text="Delete comment"
+ variant="danger-outline"
+ onClick={async () => {
+ setOpenPopover(false);
+
+ if (
+ !confirm("Are you sure you want to delete this comment?")
+ )
+ return;
+
+ await deleteComment({
+ workspaceId: workspaceId!,
+ commentId: comment.id,
+ });
+ }}
+ loading={isDeleting}
+ disabled={comment.delivered === false}
+ icon={<Trash className="size-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ </div>
+ }
+ align="end"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <Button
+ variant="secondary"
+ className={cn(
+ "size-7 p-0",
+ "data-[state=open]:border-border-emphasis sm:group-hover/card:data-[state=closed]:border-border-subtle border-transparent",
+ )}
+ icon={
+ isDeleting ? (
+ <LoadingSpinner className="size-4 shrink-0" />
+ ) : (
+ <ThreeDots className="size-4 shrink-0" />
+ )
+ }
+ onClick={() => {
+ setOpenPopover(!openPopover);
+ }}
+ />
+ </Popover>
+ ) : (
+ <div className="size-7" />
+ )}
+ </div>
+
+ <div className="mt-2">
+ {comment ? (
+ <AnimatedSizeContainer
+ height
+ transition={{ duration: 0.2, ease: "easeOut" }}
+ className="-m-0.5 overflow-clip"
+ >
+ <div className="p-0.5">
+ {isEditing ? (
+ <MessageInput
+ defaultValue={comment.text}
+ onCancel={() => setIsEditing(false)}
+ onSendMessage={(text) => {
+ if (!user) return false;
+
+ setIsEditing(false);
+
+ mutate?.(
+ async (data) => {
+ const result = await updateComment({
+ workspaceId: workspaceId!,
+ id: comment.id,
+ text,
+ });
+
+ if (!result?.data?.comment)
+ throw new Error(
+ result?.serverError || "Failed to update comment",
+ );
+
+ if (!data) return [];
+ const idx = data.findIndex(
+ (c) => c.id === result.data?.comment.id,
+ );
+ if (idx === -1) return data;
+
+ return data
+ ? data.toSpliced(idx, 1, result.data.comment)
+ : [];
+ },
+ {
+ optimisticData: (data) => {
+ if (!data) return [];
+ const idx = data.findIndex(
+ (c) => c.id === comment.id,
+ );
+ if (idx === -1) return data;
+
+ return data.toSpliced(idx, 1, {
+ ...data[idx],
+ text,
+ delivered: false,
+ });
+ },
+ rollbackOnError: true,
+ },
+ )
+ .then(() =>
+ mutatePrefix(`/api/partners/${partnerId}/comments`),
+ )
+ .catch((e) => {
+ console.log("Failed to update comment", e);
+ toast.error("Failed to update comment");
+ });
+ }}
+ onMount={({ textarea }) => {
+ if (!textarea) return;
+
+ // Programmatically focus and move cursor to the end, since React's autoFocus is putting the cursor at the start
+ textarea.focus();
+ textarea.setSelectionRange(
+ textarea.value.length,
+ textarea.value.length,
+ );
+ }}
+ className="animate-fade-in"
+ placeholder="Edit comment"
+ sendButtonText="Save"
+ />
+ ) : (
+ <Linkify
+ as="p"
+ className="text-content-subtle whitespace-pre-wrap text-sm font-medium"
+ options={{
+ target: "_blank",
+ rel: "noopener noreferrer nofollow",
+ className:
+ "underline underline-offset-4 hover:text-content-default",
+ }}
+ >
+ {comment?.text}
+ </Linkify>
+ )}
+ </div>
+ </AnimatedSizeContainer>
+ ) : (
+ <div className="h-5 w-48 animate-pulse rounded bg-neutral-200" />
+ )}
+ </div>
+ </div>
+ );
+}