The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add comments
Tim Wilson440162da2edb
diff --git a/apps/web/app/(ee)/api/partners/[partnerId]/comments/route.ts b/apps/web/app/(ee)/api/partners/[partnerId]/comments/route.tsindex 93fbe5d952..ea59ca4f35 100644--- a/apps/web/app/(ee)/api/partners/[partnerId]/comments/route.ts+++ b/apps/web/app/(ee)/api/partners/[partnerId]/comments/route.ts@@ -27,8 +27,12 @@ export const GET = withWorkspace(},});+ const comments = programEnrollment.comments.sort((a, b) => {+ return b.createdAt.getTime() - a.createdAt.getTime();+ });+return NextResponse.json(- z.array(ProgramPartnerCommentSchema).parse(programEnrollment.comments),+ z.array(ProgramPartnerCommentSchema).parse(comments),);},{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.tsxindex 26cb270a27..b523a13366 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,11 +1,247 @@"use client";+import { createPartnerCommentAction } from "@/lib/actions/partners/create-partner-comment";+import { deletePartnerCommentAction } from "@/lib/actions/partners/delete-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 { ProgramPartnerCommentProps } from "@/lib/types";+import { ThreeDots } from "@/ui/shared/icons";+import { MessageInput } from "@/ui/shared/message-input";+import { Button, LoadingSpinner, Popover, Trash } from "@dub/ui";+import { OG_AVATAR_URL, cn, formatDate } from "@dub/utils";+import { useAction } from "next-safe-action/hooks";import { useParams } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";+import { v4 as uuid } from "uuid";export function ProgramPartnerCommentsPageClient() {const { partnerId } = useParams() as { partnerId: string };- const { comments } = usePartnerComments({ partnerId });+ const { user } = useUser();+ const { id: workspaceId } = useWorkspace();+ const { comments, loading, mutate } = usePartnerComments(+ { partnerId },+ { keepPreviousData: true },+ );- return <div>WIP {JSON.stringify(comments)}</div>;+ const { executeAsync: createPartnerComment } = useAction(+ createPartnerCommentAction,+ );++ return (+ <div className="mt-4">+ <MessageInput+ onSendMessage={(text) => {+ if (!user) return false;++ const createdAt = new Date();++ const optimisticComment: ProgramPartnerCommentProps & {+ delivered?: false;+ } = {+ id: `tmp_${uuid()}`,+ createdAt,+ updatedAt: createdAt,+ programEnrollmentId: "pge_d21G4zVfQuuLElDdTHL7BNLA", // TODO+ 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(() => `/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?.map((comment) => (+ <CommentCard key={comment.id} comment={comment} />+ ))+ ) : loading ? (+ <CommentCard className="opacity-50" />+ ) : (+ <div className="text-content-subtle py-12 text-center text-sm">+ Failed to load comments+ </div>+ )}+ </div>+ </div>+ );+}++function CommentCard({+ comment,+ className,+}: {+ comment?: ProgramPartnerCommentProps & { delivered?: false };+ className?: string;+}) {+ const { partnerId } = useParams() as { partnerId: string };+ const { id: workspaceId } = useWorkspace();++ 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 ? (+ <Popover+ content={+ <div className="grid w-full grid-cols-1 gap-px p-2 sm:w-48">+ <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,+ });+ }}+ 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 ? (+ <p className="text-content-subtle text-sm font-medium">+ {comment?.text}+ </p>+ ) : (+ <div className="h-5 w-48 animate-pulse rounded bg-neutral-200" />+ )}+ </div>+ </div>+ );}diff --git a/apps/web/lib/actions/partners/create-partner-comment.ts b/apps/web/lib/actions/partners/create-partner-comment.tsindex 06ecf32485..890840451d 100644--- a/apps/web/lib/actions/partners/create-partner-comment.ts+++ b/apps/web/lib/actions/partners/create-partner-comment.ts@@ -3,7 +3,10 @@import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";import { prisma } from "@dub/prisma";-import { createProgramPartnerCommentSchema } from "../../zod/schemas/programs";+import {+ ProgramPartnerCommentSchema,+ createProgramPartnerCommentSchema,+} from "../../zod/schemas/programs";import { authActionClient } from "../safe-action";// Create a partner comment@@ -11,7 +14,7 @@ export const createPartnerCommentAction = authActionClient.schema(createProgramPartnerCommentSchema).action(async ({ parsedInput, ctx }) => {const { workspace, user } = ctx;- const { partnerId, text } = parsedInput;+ const { partnerId, text, createdAt } = parsedInput;const programId = getDefaultProgramIdOrThrow(workspace);@@ -21,11 +24,19 @@ export const createPartnerCommentAction = authActionClientincludePartner: true,});- await prisma.programPartnerComment.create({+ const comment = await prisma.programPartnerComment.create({data: {programEnrollmentId: programEnrollment.id,userId: user.id,text,+ createdAt,+ },+ include: {+ user: true,},});++ return {+ comment: ProgramPartnerCommentSchema.parse(comment),+ };});diff --git a/apps/web/lib/swr/use-partner-comments.ts b/apps/web/lib/swr/use-partner-comments.tsindex 3ea8362ea7..5ff5404eea 100644--- a/apps/web/lib/swr/use-partner-comments.ts+++ b/apps/web/lib/swr/use-partner-comments.ts@@ -1,7 +1,6 @@import { fetcher } from "@dub/utils";import useSWR, { SWRConfiguration } from "swr";-import { z } from "zod";-import { ProgramPartnerCommentSchema } from "../zod/schemas/programs";+import { ProgramPartnerCommentProps } from "../types";import useWorkspace from "./use-workspace";export function usePartnerComments(@@ -14,8 +13,8 @@ export function usePartnerComments() {const { id: workspaceId } = useWorkspace();- const { data, isLoading, error } = useSWR<- z.infer<typeof ProgramPartnerCommentSchema>[]+ const { data, isLoading, error, mutate } = useSWR<+ (ProgramPartnerCommentProps & { delivered?: false })[]>(workspaceId? `/api/partners/${partnerId}/comments?${new URLSearchParams({@@ -30,5 +29,6 @@ export function usePartnerComments(comments: data,loading: isLoading,error,+ mutate,};}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 0001fe4387..bb6ce17139 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -82,6 +82,7 @@ import {ProgramEnrollmentSchema,ProgramInviteSchema,ProgramMetricsSchema,+ ProgramPartnerCommentSchema,ProgramPartnerLinkSchema,ProgramSchema,ProgramWithLanderDataSchema,@@ -549,6 +550,10 @@ export type PartnerGroupProps = PartnerGroup & {additionalLinks: PartnerGroupAdditionalLink[];};+export type ProgramPartnerCommentProps = z.infer<+ typeof ProgramPartnerCommentSchema+>;+export type BountyProps = z.infer<typeof BountySchema>;export type BountyListProps = z.infer<typeof BountyListSchema>;export type BountyExtendedProps = z.infer<typeof BountySchemaExtended>;diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.tsindex e1a08ea3ae..98b5782f08 100644--- a/apps/web/lib/zod/schemas/programs.ts+++ b/apps/web/lib/zod/schemas/programs.ts@@ -192,10 +192,22 @@ export const ProgramPartnerCommentSchema = z.object({export const MAX_PROGRAM_PARTNER_COMMENT_LENGTH = 2000;export const createProgramPartnerCommentSchema = z.object({+ workspaceId: z.string(),partnerId: z.string(),text: z.string().min(1).max(MAX_PROGRAM_PARTNER_COMMENT_LENGTH),+ createdAt: z.coerce+ .date()+ .refine(+ (date) =>+ date.getTime() <= Date.now() &&+ date.getTime() >= Date.now() - 1000 * 60,+ {+ message: "Comment timestamp must be within the last 60 seconds",+ },+ ),});export const deleteProgramPartnerCommentSchema = z.object({+ workspaceId: z.string(),commentId: z.string(),});diff --git a/apps/web/ui/messages/messages-panel.tsx b/apps/web/ui/messages/messages-panel.tsxindex 190c2977d2..0c1da70a8a 100644--- a/apps/web/ui/messages/messages-panel.tsx+++ b/apps/web/ui/messages/messages-panel.tsx@@ -1,18 +1,9 @@import { Message } from "@/lib/types";-import { MAX_MESSAGE_LENGTH } from "@/lib/zod/schemas/messages";-import {- ArrowTurnLeft,- Button,- Check2,- LoadingSpinner,- Tooltip,- useMediaQuery,-} from "@dub/ui";+import { Check2, LoadingSpinner, Tooltip, useMediaQuery } from "@dub/ui";import { OG_AVATAR_URL, cn, formatDate } from "@dub/utils";import Linkify from "linkify-react";-import { Fragment, useRef, useState } from "react";-import ReactTextareaAutosize from "react-textarea-autosize";-import { EmojiPicker } from "./emoji-picker";+import { Fragment, useRef } from "react";+import { MessageInput } from "../shared/message-input";export function MessagesPanel({messages,@@ -32,17 +23,12 @@ export function MessagesPanel({error?: any;}) {const { isMobile } = useMediaQuery();-const scrollRef = useRef<HTMLDivElement>(null);- const textAreaRef = useRef<HTMLTextAreaElement>(null);- const selectionStartRef = useRef<number | null>(null);- const [typedMessage, setTypedMessage] = useState("");- const sendMessage = () => {- if (!messages || !typedMessage.trim()) return;+ const sendMessage = (message: string) => {+ if (!messages) return false;- onSendMessage(typedMessage.trim());- setTypedMessage("");+ onSendMessage(message);scrollRef.current?.scrollTo({ top: 0 });};@@ -207,60 +193,11 @@ export function MessagesPanel({</div>)}<div className="border-border-subtle border-t p-3 sm:p-6">- <div className="border-border-subtle overflow-hidden rounded-xl border has-[textarea:focus]:border-neutral-500 has-[textarea:focus]:ring-1 has-[textarea:focus]:ring-neutral-500">- <ReactTextareaAutosize- ref={textAreaRef}- autoFocus={!isMobile}- className="placeholder:text-content-subtle block max-h-24 w-full resize-none border-none p-3 text-base focus:ring-0 sm:text-sm"- placeholder={placeholder}- value={typedMessage}- maxLength={MAX_MESSAGE_LENGTH}- onChange={(e) => setTypedMessage(e.currentTarget.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {- e.preventDefault();- sendMessage();- }- }}- onBlur={(e) =>- (selectionStartRef.current = e.target.selectionStart)- }- />-- <div className="flex items-center justify-between gap-4 px-3 pb-3">- <div className="flex items-center gap-2">- <EmojiPicker- onSelect={(emoji) => {- const pos = selectionStartRef.current;- setTypedMessage((prev) =>- pos !== null- ? prev.slice(0, pos) + emoji + prev.slice(pos)- : prev + emoji,- );- textAreaRef.current?.focus();- }}- />- </div>- <Button- variant="primary"- text={- <span className="flex items-center gap-2">- Send- <span className="hidden items-center gap-1 sm:flex">- <span className="flex size-4 items-center justify-center rounded border border-neutral-700 text-[0.625rem]">- {navigator.platform.startsWith("Mac") ? "⌘" : "^"}- </span>- <span className="flex size-4 items-center justify-center rounded border border-neutral-700">- <ArrowTurnLeft className="text-content-inverted size-2.5" />- </span>- </span>- </span>- }- onClick={sendMessage}- className="h-8 w-fit rounded-lg px-4"- />- </div>- </div>+ <MessageInput+ placeholder={placeholder}+ onSendMessage={sendMessage}+ autoFocus={!isMobile}+ /></div></div>);@@ -286,9 +223,9 @@ function StatusIndicator({<divclassName={cn("text-content-subtle flex items-center",- message.readInApp+ message.readInApp? "text-blue-500"- : (message.readInEmail && "text-violet-500"),+ : message.readInEmail && "text-violet-500",)}>{message.delivered === false ? (diff --git a/apps/web/ui/messages/emoji-picker.tsx b/apps/web/ui/shared/emoji-picker.tsxsimilarity index 100%rename from apps/web/ui/messages/emoji-picker.tsxrename to apps/web/ui/shared/emoji-picker.tsxdiff --git a/apps/web/ui/shared/message-input.tsx b/apps/web/ui/shared/message-input.tsxnew file mode 100644index 0000000000..4a7218b9bb--- /dev/null+++ b/apps/web/ui/shared/message-input.tsx@@ -0,0 +1,91 @@+import { MAX_MESSAGE_LENGTH } from "@/lib/zod/schemas/messages";+import { ArrowTurnLeft, Button } from "@dub/ui";+import { cn } from "@dub/utils";+import { useRef, useState } from "react";+import ReactTextareaAutosize from "react-textarea-autosize";+import { EmojiPicker } from "../shared/emoji-picker";++export function MessageInput({+ onSendMessage,+ autoFocus,+ placeholder = "Type a message...",+ sendButtonText = "Send",+ className,+}: {+ onSendMessage: (message: string) => void | false;+ autoFocus?: boolean;+ placeholder?: string;+ sendButtonText?: string;+ className?: string;+}) {+ const textAreaRef = useRef<HTMLTextAreaElement>(null);+ const selectionStartRef = useRef<number | null>(null);+ const [typedMessage, setTypedMessage] = useState("");++ const sendMessage = () => {+ const message = typedMessage.trim();+ if (!message) return;++ if (onSendMessage(message) !== false) setTypedMessage("");+ };++ return (+ <div+ className={cn(+ "border-border-subtle overflow-hidden rounded-xl border has-[textarea:focus]:border-neutral-500 has-[textarea:focus]:ring-1 has-[textarea:focus]:ring-neutral-500",+ className,+ )}+ >+ <ReactTextareaAutosize+ ref={textAreaRef}+ autoFocus={autoFocus}+ className="placeholder:text-content-subtle block max-h-24 w-full resize-none border-none p-3 text-base focus:ring-0 sm:text-sm"+ placeholder={placeholder}+ value={typedMessage}+ maxLength={MAX_MESSAGE_LENGTH}+ onChange={(e) => setTypedMessage(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ sendMessage();+ }+ }}+ onBlur={(e) => (selectionStartRef.current = e.target.selectionStart)}+ />++ <div className="flex items-center justify-between gap-4 px-3 pb-3">+ <div className="flex items-center gap-2">+ <EmojiPicker+ onSelect={(emoji) => {+ const pos = selectionStartRef.current;+ setTypedMessage((prev) =>+ pos !== null+ ? prev.slice(0, pos) + emoji + prev.slice(pos)+ : prev + emoji,+ );+ textAreaRef.current?.focus();+ }}+ />+ </div>+ <Button+ variant="primary"+ text={+ <span className="flex items-center gap-2">+ {sendButtonText}+ <span className="hidden items-center gap-1 sm:flex">+ <span className="flex size-4 items-center justify-center rounded border border-neutral-700 text-[0.625rem]">+ {navigator.platform.startsWith("Mac") ? "⌘" : "^"}+ </span>+ <span className="flex size-4 items-center justify-center rounded border border-neutral-700">+ <ArrowTurnLeft className="text-content-inverted size-2.5" />+ </span>+ </span>+ </span>+ }+ onClick={sendMessage}+ className="h-8 w-fit rounded-lg px-4"+ />+ </div>+ </div>+ );+}