Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: Comments UI (#817)

Ameer Al Ashhab53bdc4f5ef13
diff --git a/apps/web/actions/videos/delete-comment.ts b/apps/web/actions/videos/delete-comment.ts
new file mode 100644
index 000000000..5e9e623c4
--- /dev/null
+++ b/apps/web/actions/videos/delete-comment.ts
@@ -0,0 +1,47 @@
+"use server";
+
+import { db } from "@cap/database";
+import { comments } from "@cap/database/schema";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { revalidatePath } from "next/cache";
+import { eq, and } from "drizzle-orm";
+
+export async function deleteComment({
+ commentId,
+ videoId,
+}: {
+ commentId: string;
+ videoId: string;
+}) {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("User not authenticated");
+ }
+
+ if (!commentId || !videoId) {
+ throw new Error("Comment ID and video ID are required");
+ }
+
+ // First, verify the comment exists and belongs to the current user
+ const existingComment = await db()
+ .select()
+ .from(comments)
+ .where(and(eq(comments.id, commentId), eq(comments.authorId, user.id)))
+ .limit(1);
+
+ if (existingComment.length === 0) {
+ throw new Error(
+ "Comment not found or you don't have permission to delete it"
+ );
+ }
+
+ // Delete the comment
+ await db()
+ .delete(comments)
+ .where(and(eq(comments.id, commentId), eq(comments.authorId, user.id)));
+
+ revalidatePath(`/s/${videoId}`);
+
+ return { success: true, commentId };
+}
diff --git a/apps/web/actions/videos/new-comment.ts b/apps/web/actions/videos/new-comment.ts
new file mode 100644
index 000000000..be874e824
--- /dev/null
+++ b/apps/web/actions/videos/new-comment.ts
@@ -0,0 +1,55 @@
+"use server";
+
+import { db } from "@cap/database";
+import { comments } from "@cap/database/schema";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { revalidatePath } from "next/cache";
+import { nanoId } from "@cap/database/helpers";
+
+export async function newComment(data: {
+ content: string;
+ videoId: string;
+ type: "text" | "emoji";
+ parentCommentId: string;
+}) {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("User not authenticated");
+ }
+
+ const content = data.content;
+ const videoId = data.videoId;
+ const type = data.type;
+ const parentCommentId = data.parentCommentId;
+
+ if (!content || !videoId) {
+ throw new Error("Content and videoId are required");
+ }
+ const id = nanoId();
+
+ const newComment = {
+ id: id,
+ authorId: user.id,
+ type: type,
+ content: content,
+ videoId: videoId,
+ timestamp: null,
+ parentCommentId: parentCommentId,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ await db().insert(comments).values(newComment);
+
+ // Add author name to the returned data
+ const commentWithAuthor = {
+ ...newComment,
+ authorName: user.name,
+ sending: false,
+ };
+
+ revalidatePath(`/s/${videoId}`);
+
+ return commentWithAuthor;
+}
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 1fe5635d2..ec5f311e1 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -4,7 +4,7 @@ import { getVideoStatus, VideoStatusResult } from "@/actions/videos/get-status";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { useQuery } from "@tanstack/react-query";
-import { useMemo, useRef } from "react";
+import { startTransition, use, useCallback, useMemo, useOptimistic, useRef, useState } from "react";
import { ShareVideo } from "./_components/ShareVideo";
import { Sidebar } from "./_components/Sidebar";
import { Toolbar } from "./_components/Toolbar";
@@ -21,6 +21,11 @@ type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
};
+export type CommentType = typeof commentsSchema.$inferSelect & {
+ authorName?: string | null;
+ sending?: boolean;
+};
+
type VideoWithOrganizationInfo = typeof videos.$inferSelect & {
organizationMembers?: string[];
organizationId?: string;
@@ -132,6 +137,16 @@ export const Share = ({
: data.createdAt;
const playerRef = useRef<HTMLVideoElement | null>(null);
+ const activityRef = useRef<{ scrollToBottom: () => void }>(null);
+ const initialComments: CommentType[] =
+ comments instanceof Promise ? use(comments) : comments;
+ const [commentsData, setCommentsData] = useState<CommentType[]>(initialComments);
+ const [optimisticComments, setOptimisticComments] = useOptimistic(
+ commentsData,
+ (state, newComment: CommentType) => {
+ return [...state, newComment];
+ }
+ );
const { data: videoStatus } = useVideoStatus(data.id, aiGenerationEnabled, {
transcriptionStatus: data.transcriptionStatus,
@@ -188,6 +203,22 @@ export const Share = ({
}
};
+ const handleOptimisticComment = useCallback((comment: CommentType) => {
+ setOptimisticComments(comment);
+ setTimeout(() => {
+ activityRef.current?.scrollToBottom();
+ }, 100);
+ }, [setOptimisticComments]);
+
+ const handleCommentSuccess = useCallback((realComment: CommentType) => {
+ startTransition(() => {
+ setCommentsData((prev) => [...prev, realComment]);
+ });
+ setTimeout(() => {
+ activityRef.current?.scrollToBottom();
+ }, 100);
+ }, []);
+
return (
<div className="mt-4">
<div className="flex flex-col gap-4 lg:flex-row">
@@ -207,7 +238,12 @@ export const Share = ({
</div>
</div>
<div className="mt-4 lg:hidden">
- <Toolbar data={data} user={user} />
+ <Toolbar
+ onOptimisticComment={handleOptimisticComment}
+ onCommentSuccess={handleCommentSuccess}
+ data={data}
+ user={user}
+ />
</div>
</div>
@@ -219,19 +255,29 @@ export const Share = ({
transcriptionStatus,
}}
user={user}
- comments={comments}
+ commentsData={commentsData}
+ setCommentsData={setCommentsData}
+ optimisticComments={optimisticComments}
+ setOptimisticComments={setOptimisticComments}
+ handleCommentSuccess={handleCommentSuccess}
views={views}
onSeek={handleSeek}
videoId={data.id}
aiData={aiData}
aiGenerationEnabled={aiGenerationEnabled}
+ ref={activityRef}
/>
</div>
</div>
<div className="hidden mt-4 lg:block">
<div>
- <Toolbar data={data} user={user} />
+ <Toolbar
+ onOptimisticComment={handleOptimisticComment}
+ onCommentSuccess={handleCommentSuccess}
+ data={data}
+ user={user}
+ />
</div>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
index 0426dceaf..8ca141123 100644
--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
@@ -1,10 +1,8 @@
-"use client";
-
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { classNames } from "@cap/utils";
import { AnimatePresence, motion } from "framer-motion";
-import { Suspense, useState } from "react";
+import { Suspense, useState, forwardRef } from "react";
import { Activity } from "./tabs/Activity";
import { Settings } from "./tabs/Settings";
import { Summary } from "./tabs/Summary";
@@ -24,7 +22,11 @@ type VideoWithOrganizationInfo = typeof videos.$inferSelect & {
interface SidebarProps {
data: VideoWithOrganizationInfo;
user: typeof userSelectProps | null;
- comments: MaybePromise<CommentType[]>;
+ commentsData: CommentType[];
+ optimisticComments: CommentType[];
+ handleCommentSuccess: (comment: CommentType) => void;
+ setOptimisticComments: (newComment: CommentType) => void;
+ setCommentsData: React.Dispatch<React.SetStateAction<CommentType[]>>;
views: MaybePromise<number>;
onSeek?: (time: number) => void;
videoId: string;
@@ -61,16 +63,20 @@ const tabTransition = {
opacity: { duration: 0.2 },
};
-export const Sidebar: React.FC<SidebarProps> = ({
+export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(({
data,
user,
- comments,
+ commentsData,
+ setCommentsData,
+ optimisticComments,
+ handleCommentSuccess,
+ setOptimisticComments,
views,
onSeek,
videoId,
aiData,
aiGenerationEnabled = false,
-}) => {
+}, ref) => {
const isOwnerOrMember: boolean = Boolean(
user?.id === data.ownerId ||
(data.organizationId &&
@@ -89,7 +95,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
{ id: "transcript", label: "Transcript" },
];
- const paginate = (newDirection: number, tabId: TabType) => {
+ const paginate = (tabId: TabType) => {
const currentIndex = tabs.findIndex((tab) => tab.id === activeTab);
const newIndex = tabs.findIndex((tab) => tab.id === tabId);
const direction = newIndex > currentIndex ? 1 : -1;
@@ -111,9 +117,14 @@ export const Sidebar: React.FC<SidebarProps> = ({
}
>
<Activity
+ ref={ref}
views={views}
- comments={comments}
+ comments={commentsData}
+ setComments={setCommentsData}
user={user}
+ optimisticComments={optimisticComments}
+ setOptimisticComments={setOptimisticComments}
+ handleCommentSuccess={handleCommentSuccess}
isOwnerOrMember={isOwnerOrMember}
onSeek={onSeek}
videoId={videoId}
@@ -149,7 +160,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
<button
key={tab.id}
onClick={() =>
- paginate(tab.id === activeTab ? 0 : 1, tab.id as TabType)
+ paginate(tab.id as TabType)
}
className={classNames(
"flex-1 px-5 py-3 text-sm font-medium relative transition-colors duration-200",
@@ -201,4 +212,4 @@ export const Sidebar: React.FC<SidebarProps> = ({
</div>
</div>
);
-};
+});
diff --git a/apps/web/app/s/[videoId]/_components/Toolbar.tsx b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
index b85ae6b38..3630bf339 100644
--- a/apps/web/app/s/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
@@ -1,24 +1,28 @@
-"use client";
import { userSelectProps } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
import { Button } from "@cap/ui";
-import { useEffect, useState } from "react";
-import { toast } from "sonner";
+import { startTransition, useEffect, useState } from "react";
import { AuthOverlay } from "./AuthOverlay";
-import { useRouter } from "next/navigation";
import { AnimatePresence, motion } from "motion/react";
+import { CommentType } from "../Share";
+import { newComment } from "@/actions/videos/new-comment";
const MotionButton = motion(Button);
// million-ignore
+interface ToolbarProps {
+ data: typeof videos.$inferSelect;
+ user: typeof userSelectProps | null;
+ onOptimisticComment: (comment: CommentType) => void;
+ onCommentSuccess: (comment: CommentType) => void;
+}
+
export const Toolbar = ({
data,
user,
-}: {
- data: typeof videos.$inferSelect;
- user: typeof userSelectProps | null;
-}) => {
- const router = useRouter();
+ onOptimisticComment,
+ onCommentSuccess,
+}: ToolbarProps) => {
const [commentBoxOpen, setCommentBoxOpen] = useState(false);
const [comment, setComment] = useState("");
const [showAuthOverlay, setShowAuthOverlay] = useState(false);
@@ -53,33 +57,38 @@ export const Toolbar = ({
const handleEmojiClick = async (emoji: string) => {
- const timestamp = getTimestamp();
+ const optimisticComment: CommentType = {
+ id: `temp-${Date.now()}`,
+ authorId: user?.id || "anonymous",
+ authorName: user?.name || "Anonymous",
+ content: emoji,
+ createdAt: new Date(),
+ videoId: data.id,
+ parentCommentId: "",
+ type: "emoji",
+ timestamp: getTimestamp(),
+ updatedAt: new Date(),
+ sending: true,
+ };
- const response = await fetch("/api/video/comment", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- type: "emoji",
+ onOptimisticComment(optimisticComment);
+
+ try {
+ const newCommentData = await newComment({
content: emoji,
videoId: data.id,
- parentCommentId: null,
- timestamp: timestamp,
- }),
- });
-
- if (response.status === 429) {
- toast.error("Too many requests - please try again later.");
- return;
- }
-
- if (!response.ok) {
- console.error("Failed to record emoji reaction");
- return;
+ parentCommentId: "",
+ type: "emoji",
+ });
+ startTransition(() => {
+ onCommentSuccess(newCommentData);
+ });
+ } catch (error) {
+ console.error("Error posting comment:", error);
+ } finally {
+ setCommentBoxOpen(false);
+ setComment("");
}
-
- router.refresh();
};
const handleCommentSubmit = async () => {
@@ -87,35 +96,37 @@ export const Toolbar = ({
return;
}
- try {
- const timestamp = getTimestamp();
-
- const response = await fetch("/api/video/comment", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- type: "text",
- content: comment,
- videoId: data.id,
- timestamp: timestamp || null,
- parentCommentId: null,
- }),
- });
+ const optimisticComment: CommentType = {
+ id: `temp-${Date.now()}`,
+ authorId: user?.id || "anonymous",
+ authorName: user?.name || "Anonymous",
+ content: comment,
+ createdAt: new Date(),
+ videoId: data.id,
+ parentCommentId: "",
+ type: "text",
+ timestamp: null,
+ updatedAt: new Date(),
+ sending: true,
+ };
- if (!response.ok) {
- const errorData = await response.json();
- console.error("Comment submission error:", errorData);
- return;
- }
+ onOptimisticComment(optimisticComment);
- setComment("");
- setCommentBoxOpen(false);
-
- router.refresh();
+ try {
+ const newCommentData = await newComment({
+ content: comment,
+ videoId: data.id,
+ parentCommentId: "",
+ type: "text",
+ });
+ startTransition(() => {
+ onCommentSuccess(newCommentData);
+ });
} catch (error) {
- console.error("Failed to submit comment:", error);
+ console.error("Error posting comment:", error);
+ } finally {
+ setCommentBoxOpen(false);
+ setComment("");
}
};
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx
deleted file mode 100644
index b20a6bcdb..000000000
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx
+++ /dev/null
@@ -1,722 +0,0 @@
-"use client";
-
-import { getVideoAnalytics } from "@/actions/videos/get-analytics";
-import { CapCardAnalytics } from "@/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics";
-import { userSelectProps } from "@cap/database/auth/session";
-import { comments as commentsSchema } from "@cap/database/schema";
-import { Avatar, Button } from "@cap/ui";
-import { AnimatePresence, motion } from "framer-motion";
-import {
- ComponentProps,
- PropsWithChildren,
- Suspense,
- use,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { Tooltip } from "react-tooltip";
-
-import { AuthOverlay } from "../AuthOverlay";
-import clsx from "clsx";
-
-type CommentType = typeof commentsSchema.$inferSelect & {
- authorName?: string | null;
-};
-
-interface ActivityProps {
- views: MaybePromise<number>;
- comments: MaybePromise<CommentType[]>;
- user: typeof userSelectProps | null;
- onSeek?: (time: number) => void;
- videoId: string;
- isOwnerOrMember?: boolean;
-}
-
-interface CommentInputProps {
- onSubmit?: (content: string) => void;
- onCancel?: () => void;
- placeholder?: string;
- showCancelButton?: boolean;
- buttonLabel?: string;
- user?: typeof userSelectProps | null;
- autoFocus?: boolean;
- disabled?: boolean;
-}
-
-const CommentInput: React.FC<CommentInputProps> = ({
- onSubmit,
- onCancel,
- placeholder,
- showCancelButton = false,
- buttonLabel = "Reply",
- user,
- autoFocus = false,
- disabled,
-}) => {
- const [content, setContent] = useState("");
- const inputRef = useRef<HTMLTextAreaElement>(null);
-
- useEffect(() => {
- if (autoFocus && inputRef.current) {
- inputRef.current.focus();
- }
- }, [autoFocus]);
-
- const handleSubmit = (e?: React.FormEvent) => {
- e?.preventDefault();
- if (content.trim()) {
- onSubmit?.(content);
- setContent("");
- }
- };
-
- const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSubmit();
- }
- };
-
- return (
- <div className="flex items-start space-x-3">
- <div className="flex-1">
- <div className="p-2 rounded-lg bg-gray-1">
- <textarea
- ref={inputRef}
- value={content}
- disabled={disabled}
- onChange={(e) => setContent(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder={placeholder || "Leave a comment"}
- className="w-full text-[15px] leading-[22px] text-gray-12 bg-transparent focus:outline-none"
- />
- <div className="flex mt-2 space-x-2">
- <Button
- size="sm"
- variant="primary"
- onClick={() => handleSubmit()}
- disabled={disabled}
- >
- {buttonLabel}
- </Button>
- {showCancelButton && onCancel && (
- <Button size="sm" variant="white" onClick={onCancel}>
- Cancel
- </Button>
- )}
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-const formatTimestamp = (date: Date) => {
- return new Intl.DateTimeFormat("en-US", {
- hour: "numeric",
- minute: "numeric",
- hour12: true,
- year: "numeric",
- month: "long",
- day: "numeric",
- }).format(date);
-};
-
-const formatTimeAgo = (date: Date) => {
- const now = new Date();
- const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
-
- if (diffInSeconds < 60) return "now";
-
- const diffInMinutes = Math.floor(diffInSeconds / 60);
- if (diffInMinutes < 60) return `${diffInMinutes}m ago`;
-
- const diffInHours = Math.floor(diffInMinutes / 60);
- if (diffInHours < 24) return `${diffInHours}h ago`;
-
- const diffInDays = Math.floor(diffInHours / 24);
- if (diffInDays < 30) return `${diffInDays}d ago`;
-
- const diffInMonths = Math.floor(diffInDays / 30);
- if (diffInMonths < 12) return `${diffInMonths}mo ago`;
-
- const diffInYears = Math.floor(diffInDays / 365);
- return `${diffInYears}y ago`;
-};
-
-const Comment: React.FC<{
- comment: CommentType;
- replies: CommentType[];
- onReply: (commentId: string) => void;
- replyingToId: string | null;
- handleReply: (content: string) => void;
- onCancelReply: () => void;
- onDelete: (commentId: string) => void;
- user: typeof userSelectProps | null;
- level?: number;
- onSeek?: (time: number) => void;
-}> = ({
- comment,
- replies,
- onReply,
- replyingToId,
- handleReply,
- onCancelReply,
- onDelete,
- user,
- level = 0,
- onSeek,
-}) => {
- const isReplying = replyingToId === comment.id;
- const isOwnComment = user?.id === comment.authorId;
- const nestedReplies =
- level === 0
- ? replies.filter((reply) => {
- if (reply.parentCommentId === comment.id) return true;
- const parentComment = replies.find(
- (r) => r.id === reply.parentCommentId
- );
- return parentComment && parentComment.parentCommentId === comment.id;
- })
- : [];
-
- const handleDelete = () => {
- if (window.confirm("Are you sure you want to delete this comment?")) {
- onDelete(comment.id);
- }
- };
-
- const canReply = true;
- const commentDate = new Date(comment.createdAt);
-
- return (
- <motion.div
- id={`comment-${comment.id}`}
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: -20 }}
- transition={{ duration: 0.2 }}
- className={clsx(`space-y-3`, level > 0 ? "ml-8 border-l-2 border-gray-100 pl-4" : "")}
- >
- <div className="flex items-start space-x-3">
- <Avatar className="size-8" letterClass="text-sm" name={comment.authorName} />
- <div className="flex-1">
- <div className="flex items-center space-x-2">
- <span className="font-medium text-gray-12">
- {comment.authorName || "Anonymous"}
- </span>
- <span
- className="text-sm text-gray-8"
- data-tooltip-id={`comment-${comment.id}-timestamp`}
- data-tooltip-content={formatTimestamp(commentDate)}
- >
- {formatTimeAgo(commentDate)}
- </span>
- <Tooltip id={`comment-${comment.id}-timestamp`} />
- {comment.timestamp && (
- <button
- onClick={() => onSeek?.(comment.timestamp!)}
- className="text-sm text-blue-500 cursor-pointer hover:text-blue-700"
- >
- {new Date(comment.timestamp * 1000).toISOString().substr(11, 8)}
- </button>
- )}
- </div>
- <p className="mt-1 text-gray-11">{comment.content}</p>
- <div className="flex items-center mt-2 space-x-4">
- {user && !isReplying && canReply && (
- <button
- onClick={() => onReply(comment.id)}
- className="text-sm text-gray-10 hover:text-gray-12"
- >
- Reply
- </button>
- )}
- {isOwnComment && (
- <button
- onClick={handleDelete}
- className="text-sm text-red-500 hover:text-red-700"
- >
- Delete
- </button>
- )}
- </div>
- </div>
- </div>
-
- {isReplying && canReply && (
- <div className="ml-5">
- <CommentInput
- onSubmit={handleReply}
- onCancel={onCancelReply}
- placeholder="Write a reply..."
- showCancelButton={true}
- user={user}
- autoFocus={true}
- />
- </div>
- )}
-
- {nestedReplies.length > 0 && (
- <div className="mt-3 space-y-3">
- {nestedReplies.map((reply) => (
- <Comment
- key={reply.id}
- comment={reply}
- replies={replies}
- onReply={onReply}
- replyingToId={replyingToId}
- handleReply={handleReply}
- onCancelReply={onCancelReply}
- onDelete={onDelete}
- user={user}
- level={1}
- onSeek={onSeek}
- />
- ))}
- </div>
- )}
- </motion.div>
- );
- };
-
-const EmptyState = () => (
- <div className="flex flex-col justify-center items-center p-8 h-full text-center animate-in fade-in">
- <div className="space-y-2 text-gray-300">
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="mx-auto w-8 h-8"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
- />
- </svg>
- <h3 className="text-sm font-medium text-gray-12">No comments yet</h3>
- <p className="text-sm text-gray-10">
- Be the first to share your thoughts!
- </p>
- </div>
- </div>
-);
-
-export const Activity = Object.assign(
- ({ user, videoId, isOwnerOrMember = false, ...props }: ActivityProps) => {
- const initialComments =
- props.comments instanceof Promise ? use(props.comments) : props.comments;
-
- // Lift comments state up so both Analytics and Comments can share it
- const [comments, setComments] = useState(initialComments);
-
- // Sync local state with props when they change (after revalidation)
- useEffect(() => {
- setComments(initialComments);
- }, [initialComments]);
-
- return (
- <Activity.Shell
- analytics={
- <Suspense fallback={<CapCardAnalytics.Skeleton />}>
- <Analytics
- videoId={videoId}
- views={props.views}
- comments={comments}
- />
- </Suspense>
- }
- user={user}
- isOwnerOrMember={isOwnerOrMember}
- >
- {({ setShowAuthOverlay }) => (
- <Comments
- comments={comments}
- setComments={setComments}
- user={user}
- videoId={videoId}
- setShowAuthOverlay={setShowAuthOverlay}
- />
- )}
- </Activity.Shell>
- );
- },
- {
- Shell: (props: {
- analytics?: JSX.Element;
- user: typeof userSelectProps | null;
- isOwnerOrMember: boolean;
- children?: (props: {
- setShowAuthOverlay: (show: boolean) => void;
- }) => JSX.Element;
- }) => {
- const [showAuthOverlay, setShowAuthOverlay] = useState(false);
-
- return (
- <div className="flex flex-col h-full">
- {props.user && props.isOwnerOrMember && (
- <div className="flex flex-row items-center p-4 h-12 border-b border-gray-200">
- {props.analytics}
- </div>
- )}
-
- {props.children?.({ setShowAuthOverlay })}
-
- <AuthOverlay
- isOpen={showAuthOverlay}
- onClose={() => setShowAuthOverlay(false)}
- />
- </div>
- );
- },
- Skeleton: (props: {
- user: typeof userSelectProps | null;
- isOwnerOrMember: boolean;
- }) => (
- <Activity.Shell {...props} analytics={<CapCardAnalytics.Skeleton />}>
- {({ setShowAuthOverlay }) => (
- <Comments.Skeleton
- setShowAuthOverlay={setShowAuthOverlay}
- user={props.user}
- />
- )}
- </Activity.Shell>
- ),
- }
-);
-
-function Analytics(props: {
- videoId: string;
- views: MaybePromise<number>;
- comments: CommentType[];
-}) {
- const [views, setViews] = useState(
- props.views instanceof Promise ? use(props.views) : props.views
- );
-
- useEffect(() => {
- const fetchAnalytics = async () => {
- try {
- const result = await getVideoAnalytics(props.videoId);
-
- setViews(result.count);
- } catch (error) {
- console.error("Error fetching analytics:", error);
- }
- };
-
- fetchAnalytics();
- }, [props.videoId]);
-
- const totalComments = useMemo(
- () => props.comments.filter((c) => c.type === "text").length,
- [props.comments]
- );
-
- const totalReactions = useMemo(
- () => props.comments.filter((c) => c.type === "emoji").length,
- [props.comments]
- );
-
- return (
- <CapCardAnalytics
- capId={props.videoId}
- displayCount={views}
- totalComments={totalComments}
- totalReactions={totalReactions}
- />
- );
-}
-
-const Comments = Object.assign(
- (props: {
- comments: CommentType[];
- setComments: React.Dispatch<React.SetStateAction<CommentType[]>>;
- user: typeof userSelectProps | null;
- videoId: string;
- onSeek?: (time: number) => void;
- setShowAuthOverlay: (v: boolean) => void;
- }) => {
- // Use shared state from parent instead of local state
- const { comments, setComments } = props;
-
- const { user } = props;
- const [replyingTo, setReplyingTo] = useState<string | null>(null);
- const [optimisticComments, setOptimisticComments] = useState<CommentType[]>(
- []
- );
-
- const allComments = [...comments, ...optimisticComments];
- const rootComments = allComments.filter(
- (comment) => !comment.parentCommentId || comment.parentCommentId === ""
- );
-
- const commentsContainerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (commentsContainerRef.current) {
- commentsContainerRef.current.scrollTop =
- commentsContainerRef.current.scrollHeight;
- }
- }, []);
-
- const scrollToBottom = () => {
- if (commentsContainerRef.current) {
- commentsContainerRef.current.scrollTo({
- top: commentsContainerRef.current.scrollHeight,
- behavior: "smooth",
- });
- }
- };
-
- useEffect(() => {
- setTimeout(scrollToBottom, 100);
- }, [comments]);
-
-
- const addOptimisticComment = (newComment: CommentType) => {
- setOptimisticComments((prev) => [...prev, newComment]);
- };
-
- const handleNewComment = async (content: string) => {
- const optimisticComment: CommentType = {
- id: `temp-${Date.now()}`,
- authorId: user?.id || "anonymous",
- authorName: user?.name || "Anonymous",
- content,
- createdAt: new Date(),
- videoId: props.videoId,
- parentCommentId: "",
- type: "text",
- timestamp: null,
- updatedAt: new Date(),
- };
-
- addOptimisticComment(optimisticComment);
-
- try {
- const response = await fetch("/api/video/comment", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- type: "text",
- content,
- videoId: props.videoId,
- parentCommentId: "",
- }),
- });
-
- if (!response.ok) {
- throw new Error("Failed to post comment");
- }
-
- const data = await response.json();
-
- setOptimisticComments((prev) =>
- prev.filter((c) => c.id !== optimisticComment.id)
- );
-
- setComments((prev) => [...prev, data]);
-
- } catch (error) {
- console.error("Error posting comment:", error);
- setOptimisticComments((prev) =>
- prev.filter((c) => c.id !== optimisticComment.id)
- );
- }
- };
-
- const handleReply = async (content: string) => {
- if (!replyingTo) return;
-
- const parentComment = comments.find((c) => c.id === replyingTo);
- const actualParentId = parentComment?.parentCommentId
- ? parentComment.parentCommentId
- : replyingTo;
-
- const optimisticReply: CommentType = {
- id: `temp-${Date.now()}`,
- authorId: user?.id || "anonymous",
- authorName: user?.name || "Anonymous",
- content,
- createdAt: new Date(),
- videoId: comments[0]?.videoId || "",
- parentCommentId: actualParentId,
- type: "text",
- timestamp: null,
- updatedAt: new Date(),
- };
-
- addOptimisticComment(optimisticReply);
-
- try {
- const response = await fetch("/api/video/comment", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- type: "text",
- content,
- videoId: comments[0]?.videoId,
- parentCommentId: actualParentId,
- }),
- });
-
- if (!response.ok) {
- throw new Error("Failed to post reply");
- }
-
- const data = await response.json();
-
- setOptimisticComments((prev) =>
- prev.filter((c) => c.id !== optimisticReply.id)
- );
-
- setComments((prev) => [...prev, data]);
-
- const newReplyElement = document.getElementById(`comment-${data.id}`);
- if (newReplyElement) {
- newReplyElement.scrollIntoView({
- behavior: "smooth",
- block: "center",
- });
- }
-
- setReplyingTo(null);
- } catch (error) {
- console.error("Error posting reply:", error);
- setOptimisticComments((prev) =>
- prev.filter((c) => c.id !== optimisticReply.id)
- );
- }
- };
-
- const handleCancelReply = () => {
- setReplyingTo(null);
- };
-
- const handleDeleteComment = async (commentId: string) => {
- try {
- const response = await fetch(
- `/api/video/comment/delete?commentId=${commentId}`,
- {
- method: "DELETE",
- }
- );
-
- if (!response.ok) {
- const data = await response.json();
- throw new Error(data.error || "Failed to delete comment");
- }
-
- // Remove the comment and its replies from the state
- setComments((prev) =>
- prev.filter(
- (comment) =>
- comment.id !== commentId && comment.parentCommentId !== commentId
- )
- );
- } catch (error) {
- console.error("Error deleting comment:", error);
- // You might want to show an error toast here
- }
- };
-
- return (
- <Comments.Shell
- commentInputProps={{ onSubmit: handleNewComment }}
- setShowAuthOverlay={props.setShowAuthOverlay}
- user={user}
- commentsContainerRef={commentsContainerRef}
- >
- {rootComments.length === 0 ? (
- <EmptyState />
- ) : (
- <div className="p-4 space-y-6">
- <AnimatePresence mode="sync">
- {rootComments
- .sort(
- (a, b) =>
- new Date(a.createdAt).getTime() -
- new Date(b.createdAt).getTime()
- )
- .map((comment) => (
- <Comment
- key={comment.id}
- comment={comment}
- replies={allComments.sort(
- (a, b) =>
- new Date(a.createdAt).getTime() -
- new Date(b.createdAt).getTime()
- )}
- onReply={(id) => {
- if (!user) {
- props.setShowAuthOverlay(true);
- } else {
- setReplyingTo(id);
- }
- }}
- replyingToId={replyingTo}
- handleReply={handleReply}
- onCancelReply={handleCancelReply}
- onDelete={handleDeleteComment}
- user={user}
- onSeek={props.onSeek}
- />
- ))}
- </AnimatePresence>
- </div>
- )}
- </Comments.Shell>
- );
- },
- {
- Shell: (
- props: PropsWithChildren<{
- user: typeof userSelectProps | null;
- setShowAuthOverlay: (v: boolean) => void;
- commentInputProps?: Omit<
- ComponentProps<typeof CommentInput>,
- "user" | "placholder" | "buttonLabel"
- >;
- commentsContainerRef?: React.RefObject<HTMLDivElement>;
- }>
- ) => (
- <>
- <div
- ref={props.commentsContainerRef}
- className="overflow-y-auto flex-1 min-h-0"
- >
- {props.children}
- </div>
-
- <div className="flex-none p-2 border-t border-gray-200 bg-gray-1">
- {props.user ? (
- <CommentInput
- {...props.commentInputProps}
- placeholder="Leave a comment"
- buttonLabel="Comment"
- user={props.user}
- />
- ) : (
- <Button className="min-w-full" variant="primary" onClick={() => props.setShowAuthOverlay(true)}>
- Sign in to leave a comment
- </Button>
- )}
- </div>
- </>
- ),
- Skeleton: (props: {
- user: typeof userSelectProps | null;
- setShowAuthOverlay: (v: boolean) => void;
- }) => <Comments.Shell {...props} commentInputProps={{ disabled: true }} />,
- }
-);
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Analytics.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Analytics.tsx
new file mode 100644
index 000000000..32bb9f58a
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Analytics.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { getVideoAnalytics } from "@/actions/videos/get-analytics";
+import { CapCardAnalytics } from "@/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics";
+import { CommentType } from "../../../Share";
+import { useState, useEffect, useMemo, use } from "react";
+
+const Analytics = (props: {
+ videoId: string;
+ views: MaybePromise<number>;
+ comments: CommentType[];
+}) => {
+ const [views, setViews] = useState(
+ props.views instanceof Promise ? use(props.views) : props.views
+ );
+
+ useEffect(() => {
+ const fetchAnalytics = async () => {
+ try {
+ const result = await getVideoAnalytics(props.videoId);
+
+ setViews(result.count);
+ } catch (error) {
+ console.error("Error fetching analytics:", error);
+ }
+ };
+
+ fetchAnalytics();
+ }, [props.videoId]);
+
+ const totalComments = useMemo(
+ () => props.comments.filter((c) => c.type === "text").length,
+ [props.comments]
+ );
+
+ const totalReactions = useMemo(
+ () => props.comments.filter((c) => c.type === "emoji").length,
+ [props.comments]
+ );
+
+ return (
+ <CapCardAnalytics
+ capId={props.videoId}
+ displayCount={views}
+ totalComments={totalComments}
+ totalReactions={totalReactions}
+ />
+ );
+}
+
+export default Analytics;
+
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
new file mode 100644
index 000000000..989436859
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
@@ -0,0 +1,151 @@
+import { userSelectProps } from "@cap/database/auth/session";
+import { Avatar, Button } from "@cap/ui";
+import { motion } from "framer-motion";
+import React from "react";
+import { Tooltip } from "@/components/Tooltip";
+
+import clsx from "clsx";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { faReply, faTrash } from "@fortawesome/free-solid-svg-icons";
+import { CommentType } from "../../../Share";
+import CommentInput from "./CommentInput";
+import { formatTimeAgo, formatTimestamp } from "./utils";
+
+const Comment: React.FC<{
+ comment: CommentType;
+ replies: CommentType[];
+ onReply: (commentId: string) => void;
+ replyingToId: string | null;
+ handleReply: (content: string) => void;
+ onCancelReply: () => void;
+ onDelete: (commentId: string) => void;
+ user: typeof userSelectProps | null;
+ level?: number;
+ onSeek?: (time: number) => void;
+}> = ({
+ comment,
+ replies,
+ onReply,
+ replyingToId,
+ handleReply,
+ onCancelReply,
+ onDelete,
+ user,
+ level = 0,
+ onSeek,
+}) => {
+ const isReplying = replyingToId === comment.id;
+ const isOwnComment = user?.id === comment.authorId;
+ const nestedReplies =
+ level === 0
+ ? replies.filter((reply) => {
+ if (reply.parentCommentId === comment.id) return true;
+ const parentComment = replies.find(
+ (r) => r.id === reply.parentCommentId
+ );
+ return parentComment && parentComment.parentCommentId === comment.id;
+ })
+ : [];
+
+ const handleDelete = () => {
+ if (window.confirm("Are you sure you want to delete this comment?")) {
+ onDelete(comment.id);
+ }
+ };
+
+ const canReply = true;
+ const commentDate = new Date(comment.createdAt);
+
+ return (
+ <motion.div
+ key={`comment-${comment.id}`}
+ className={clsx(`space-y-3`, level > 0 ? "ml-8 border-l-2 border-gray-100 pl-4" : "", comment.sending ? "opacity-20" : "opacity-100")}
+ >
+ <div className="flex items-start space-x-2.5">
+ <Avatar className="size-6" letterClass="text-sm" name={comment.authorName} />
+ <div className="flex-1 p-3 rounded-xl border bg-gray-2 border-gray-3">
+ <div className="flex items-center space-x-2">
+ <p className="text-base font-medium text-gray-12">
+ {comment.authorName || "Anonymous"}
+ </p>
+ <Tooltip content={formatTimestamp(commentDate)}>
+ <p
+ className="text-sm text-gray-8"
+ >
+ {formatTimeAgo(commentDate)}
+ </p>
+ </Tooltip>
+ {comment.timestamp && (
+ <button
+ onClick={() => onSeek?.(comment.timestamp!)}
+ className="text-sm text-blue-500 cursor-pointer hover:text-blue-700"
+ >
+ {new Date(comment.timestamp * 1000).toISOString().substr(11, 8)}
+ </button>
+ )}
+ </div>
+ <p className="text-sm text-gray-11">{comment.content}</p>
+ <div className="flex items-center pt-2 mt-2.5 space-x-3 border-t border-gray-3">
+ {user && !isReplying && canReply && (
+ <Tooltip content="Reply">
+ <Button
+ onClick={() => onReply(comment.id)}
+ size="icon"
+ variant="outline"
+ icon={<FontAwesomeIcon className="size-[10px]" icon={faReply} />}
+ className="text-[13px] p-0 size-6"
+ />
+ </Tooltip>
+ )}
+ {isOwnComment && (
+ <Tooltip content="Delete comment">
+ <Button
+ onClick={handleDelete}
+ size="icon"
+ variant="outline"
+ icon={<FontAwesomeIcon className="size-[10px]" icon={faTrash} />}
+ className="text-[13px] p-0 size-6"
+ />
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {isReplying && canReply && (
+ <div className="ml-5">
+ <CommentInput
+ onSubmit={handleReply}
+ onCancel={onCancelReply}
+ placeholder="Write a reply..."
+ showCancelButton={true}
+ user={user}
+ autoFocus={true}
+ />
+ </div>
+ )}
+
+ {nestedReplies.length > 0 && (
+ <div className="mt-3 space-y-3">
+ {nestedReplies.map((reply) => (
+ <Comment
+ key={reply.id}
+ comment={reply}
+ replies={replies}
+ onReply={onReply}
+ replyingToId={replyingToId}
+ handleReply={handleReply}
+ onCancelReply={onCancelReply}
+ onDelete={onDelete}
+ user={user}
+ level={1}
+ onSeek={onSeek}
+ />
+ ))}
+ </div>
+ )}
+ </motion.div>
+ );
+ };
+
+export default Comment;
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx
new file mode 100644
index 000000000..ffe573949
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/CommentInput.tsx
@@ -0,0 +1,87 @@
+import { userSelectProps } from "@cap/database/auth/session";
+import { Button } from "@cap/ui";
+import React, {
+ useEffect, useRef,
+ useState
+} from "react";
+
+interface CommentInputProps {
+ onSubmit?: (content: string) => void;
+ onCancel?: () => void;
+ placeholder?: string;
+ showCancelButton?: boolean;
+ buttonLabel?: string;
+ user?: typeof userSelectProps | null;
+ autoFocus?: boolean;
+ disabled?: boolean;
+}
+
+const CommentInput: React.FC<CommentInputProps> = ({
+ onSubmit,
+ onCancel,
+ placeholder,
+ showCancelButton = false,
+ buttonLabel = "Reply",
+ user,
+ autoFocus = false,
+ disabled,
+}) => {
+ const [content, setContent] = useState("");
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ useEffect(() => {
+ if (autoFocus && inputRef.current) {
+ inputRef.current.focus();
+ }
+ }, [autoFocus]);
+
+ const handleSubmit = (e?: React.FormEvent) => {
+ e?.preventDefault();
+ if (content.trim()) {
+ onSubmit?.(content);
+ setContent("");
+ }
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ };
+
+ return (
+ <div className="flex items-start space-x-3">
+ <div className="flex-1">
+ <div className="p-2 rounded-lg border bg-gray-1 border-gray-3">
+ <textarea
+ ref={inputRef}
+ value={content}
+ disabled={disabled}
+ onChange={(e) => setContent(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder || "Leave a comment"}
+ className="w-full text-[15px] leading-[22px] text-gray-12 bg-transparent focus:outline-none"
+ />
+ <div className="flex items-center mt-2 space-x-2">
+ <Button
+ size="xs"
+ variant="primary"
+ onClick={() => handleSubmit()}
+ disabled={!content}
+ >
+ {buttonLabel}
+ </Button>
+ {showCancelButton && onCancel && (
+ <Button size="xs" variant="outline" onClick={onCancel}>
+ Cancel
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default CommentInput;
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
new file mode 100644
index 000000000..65764b335
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
@@ -0,0 +1,245 @@
+import { newComment } from "@/actions/videos/new-comment";
+import { deleteComment } from "@/actions/videos/delete-comment";
+import { userSelectProps } from "@cap/database/auth/session";
+import { Button } from "@cap/ui";
+import { AnimatePresence } from "framer-motion";
+import React, {
+ ComponentProps,
+ PropsWithChildren, useEffect, useRef,
+ useState, forwardRef,
+ useImperativeHandle
+} from "react";
+import Comment from "./Comment";
+import { CommentType } from "../../../Share";
+import CommentInput from "./CommentInput";
+import EmptyState from "./EmptyState";
+
+export const Comments = Object.assign(
+ forwardRef<{ scrollToBottom: () => void }, {
+ setComments: React.Dispatch<React.SetStateAction<CommentType[]>>;
+ user: typeof userSelectProps | null;
+ videoId: string;
+ optimisticComments: CommentType[];
+ setOptimisticComments: (newComment: CommentType) => void;
+ handleCommentSuccess: (comment: CommentType) => void;
+ onSeek?: (time: number) => void;
+ setShowAuthOverlay: (v: boolean) => void;
+ }>(
+ (props, ref) => {
+
+ const { optimisticComments, setOptimisticComments, setComments, handleCommentSuccess } = props;
+
+ const { user } = props;
+ const [replyingTo, setReplyingTo] = useState<string | null>(null);
+
+ const commentsContainerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (commentsContainerRef.current) {
+ commentsContainerRef.current.scrollTop =
+ commentsContainerRef.current.scrollHeight;
+ }
+ }, []);
+
+ const scrollToBottom = () => {
+ if (commentsContainerRef.current) {
+ commentsContainerRef.current.scrollTo({
+ top: commentsContainerRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ }
+ };
+
+ useImperativeHandle(ref, () => ({
+ scrollToBottom
+ }), []);
+
+ const rootComments = optimisticComments.filter(
+ (comment) => !comment.parentCommentId || comment.parentCommentId === ""
+ );
+
+ const handleNewComment = async (content: string) => {
+ const optimisticComment: CommentType = {
+ id: `temp-${Date.now()}`,
+ authorId: user?.id || "anonymous",
+ authorName: user?.name || "Anonymous",
+ content,
+ createdAt: new Date(),
+ videoId: props.videoId,
+ parentCommentId: "",
+ type: "text",
+ timestamp: null,
+ updatedAt: new Date(),
+ sending: true,
+ };
+
+ setOptimisticComments(optimisticComment);
+
+ try {
+ const data = await newComment({
+ content,
+ videoId: props.videoId,
+ parentCommentId: "",
+ type: "text",
+ });
+ handleCommentSuccess(data);
+ } catch (error) {
+ console.error("Error posting comment:", error);
+ }
+ }
+
+ const handleReply = async (content: string) => {
+ if (!replyingTo) return;
+
+ const parentComment = optimisticComments.find((c) => c.id === replyingTo);
+ const actualParentId = parentComment?.parentCommentId
+ ? parentComment.parentCommentId
+ : replyingTo;
+
+ const optimisticReply: CommentType = {
+ id: `temp-reply-${Date.now()}`,
+ authorId: user?.id || "anonymous",
+ authorName: user?.name || "Anonymous",
+ content,
+ createdAt: new Date(),
+ videoId: props.videoId,
+ parentCommentId: actualParentId,
+ type: "text",
+ timestamp: null,
+ updatedAt: new Date(),
+ sending: true,
+ };
+
+ setOptimisticComments(optimisticReply);
+
+ try {
+
+ const data = await newComment({
+ content,
+ videoId: props.videoId,
+ parentCommentId: actualParentId,
+ type: "text",
+ });
+
+ handleCommentSuccess(data);
+
+ const newReplyElement = document.getElementById(`comment-${data.id}`);
+ if (newReplyElement) {
+ newReplyElement.scrollIntoView({
+ behavior: "smooth",
+ block: "center",
+ });
+ }
+ setReplyingTo(null);
+ } catch (error) {
+ console.error("Error posting reply:", error);
+ }
+ };
+
+ const handleCancelReply = () => {
+ setReplyingTo(null);
+ };
+
+ const handleDeleteComment = async (commentId: string) => {
+ try {
+ await deleteComment({
+ commentId,
+ videoId: props.videoId,
+ });
+ setComments((prev) => prev.filter((c) => c.id !== commentId));
+ } catch (error) {
+ console.error("Failed to delete comment:", error);
+ }
+ };
+
+ return (
+ <Comments.Shell
+ commentInputProps={{ onSubmit: handleNewComment }}
+ setShowAuthOverlay={props.setShowAuthOverlay}
+ user={user}
+ commentsContainerRef={commentsContainerRef}
+ >
+ {rootComments.length === 0 ? (
+ <EmptyState />
+ ) : (
+ <div className="p-4 space-y-6">
+ <AnimatePresence>
+ {rootComments
+ .sort(
+ (a, b) =>
+ new Date(a.createdAt).getTime() -
+ new Date(b.createdAt).getTime()
+ )
+ .map((comment) => (
+ <Comment
+ key={comment.id}
+ comment={comment}
+ replies={optimisticComments.sort(
+ (a, b) =>
+ new Date(a.createdAt).getTime() -
+ new Date(b.createdAt).getTime()
+ )}
+ onReply={(id) => {
+ if (!user) {
+ props.setShowAuthOverlay(true);
+ } else {
+ setReplyingTo(id);
+ }
+ }}
+ replyingToId={replyingTo}
+ handleReply={handleReply}
+ onCancelReply={handleCancelReply}
+ onDelete={handleDeleteComment}
+ user={user}
+ onSeek={props.onSeek}
+ />
+ ))}
+ </AnimatePresence>
+ </div>
+ )}
+ </Comments.Shell>
+ );
+ }
+ ),
+ {
+ Shell: (
+ props: PropsWithChildren<{
+ user: typeof userSelectProps | null;
+ setShowAuthOverlay: (v: boolean) => void;
+ commentInputProps?: Omit<
+ ComponentProps<typeof CommentInput>,
+ "user" | "placholder" | "buttonLabel"
+ >;
+ commentsContainerRef?: React.RefObject<HTMLDivElement>;
+ }>
+ ) => (
+ <>
+ <div
+ ref={props.commentsContainerRef}
+ className="overflow-y-auto flex-1 min-h-0"
+ >
+ {props.children}
+ </div>
+
+ <div className="flex-none p-2 border-t border-gray-200 bg-gray-1">
+ {props.user ? (
+ <CommentInput
+ {...props.commentInputProps}
+ placeholder="Leave a comment"
+ buttonLabel="Comment"
+ user={props.user}
+ />
+ ) : (
+ <Button className="min-w-full" variant="primary" onClick={() => props.setShowAuthOverlay(true)}>
+ Sign in to leave a comment
+ </Button>
+ )}
+ </div>
+ </>
+ ),
+ Skeleton: (props: {
+ user: typeof userSelectProps | null;
+ setShowAuthOverlay: (v: boolean) => void;
+ }) => <Comments.Shell {...props} commentInputProps={{ disabled: true }} />,
+ }
+);
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/EmptyState.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/EmptyState.tsx
new file mode 100644
index 000000000..a51eda05c
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/EmptyState.tsx
@@ -0,0 +1,16 @@
+
+import { LoadingSpinner } from "@cap/ui";
+
+const EmptyState = () => (
+ <div className="flex flex-col justify-center items-center p-8 h-full text-center animate-in fade-in">
+ <div className="space-y-2 text-gray-300">
+ <LoadingSpinner />
+ <h3 className="text-sm font-medium text-gray-12">No comments yet</h3>
+ <p className="text-sm text-gray-10">
+ Be the first to share your thoughts!
+ </p>
+ </div>
+ </div>
+);
+
+export default EmptyState;
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx
new file mode 100644
index 000000000..bf3200556
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/index.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { CapCardAnalytics } from "@/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics";
+import { userSelectProps } from "@cap/database/auth/session";
+import React, { Suspense, useState, forwardRef } from "react";
+
+import { AuthOverlay } from "../../AuthOverlay";
+import { CommentType } from "../../../Share";
+import Analytics from "./Analytics";
+import { Comments } from "./Comments";
+
+
+interface ActivityProps {
+ views: MaybePromise<number>;
+ comments: CommentType[];
+ setComments: React.Dispatch<React.SetStateAction<CommentType[]>>;
+ user: typeof userSelectProps | null;
+ onSeek?: (time: number) => void;
+ handleCommentSuccess: (comment: CommentType) => void;
+ videoId: string;
+ optimisticComments: CommentType[];
+ setOptimisticComments: (newComment: CommentType) => void;
+ isOwnerOrMember: boolean;
+}
+
+export const Activity = Object.assign(
+ forwardRef<{ scrollToBottom: () => void }, ActivityProps>(
+ ({ user, videoId, isOwnerOrMember, comments, handleCommentSuccess, optimisticComments, setOptimisticComments, setComments, ...props }, ref) => {
+
+ return (
+ <Activity.Shell
+ analytics={
+ <Suspense fallback={<CapCardAnalytics.Skeleton />}>
+ <Analytics
+ videoId={videoId}
+ views={props.views}
+ comments={comments}
+ />
+ </Suspense>
+ }
+ user={user}
+ isOwnerOrMember={isOwnerOrMember}
+ >
+ {({ setShowAuthOverlay }) => (
+ <Comments
+ ref={ref}
+ handleCommentSuccess={handleCommentSuccess}
+ optimisticComments={optimisticComments}
+ setOptimisticComments={setOptimisticComments}
+ setComments={setComments}
+ user={user}
+ videoId={videoId}
+ setShowAuthOverlay={setShowAuthOverlay}
+ />
+ )}
+ </Activity.Shell>
+ );
+ }
+ ),
+ {
+ Shell: (props: {
+ analytics?: JSX.Element;
+ user: typeof userSelectProps | null;
+ isOwnerOrMember: boolean;
+ children?: (props: {
+ setShowAuthOverlay: (show: boolean) => void;
+ }) => JSX.Element;
+ }) => {
+ const [showAuthOverlay, setShowAuthOverlay] = useState(false);
+
+ return (
+ <div className="flex flex-col h-full">
+ {props.user && props.isOwnerOrMember && (
+ <div className="flex flex-row items-center p-4 h-12 border-b border-gray-200">
+ {props.analytics}
+ </div>
+ )}
+
+ {props.children?.({ setShowAuthOverlay })}
+
+ <AuthOverlay
+ isOpen={showAuthOverlay}
+ onClose={() => setShowAuthOverlay(false)}
+ />
+ </div>
+ );
+ },
+ Skeleton: (props: {
+ user: typeof userSelectProps | null;
+ isOwnerOrMember: boolean;
+ }) => (
+ <Activity.Shell {...props} analytics={<CapCardAnalytics.Skeleton />}>
+ {({ setShowAuthOverlay }) => (
+ <Comments.Skeleton
+ setShowAuthOverlay={setShowAuthOverlay}
+ user={props.user}
+ />
+ )}
+ </Activity.Shell>
+ ),
+ }
+);
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/utils.ts b/apps/web/app/s/[videoId]/_components/tabs/Activity/utils.ts
new file mode 100644
index 000000000..4fb6eb926
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/utils.ts
@@ -0,0 +1,32 @@
+export const formatTimestamp = (date: Date) => {
+ return new Intl.DateTimeFormat("en-US", {
+ hour: "numeric",
+ minute: "numeric",
+ hour12: true,
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ }).format(date);
+};
+
+export const formatTimeAgo = (date: Date) => {
+ const now = new Date();
+ const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
+
+ if (diffInSeconds < 60) return "now";
+
+ const diffInMinutes = Math.floor(diffInSeconds / 60);
+ if (diffInMinutes < 60) return `${diffInMinutes}m ago`;
+
+ const diffInHours = Math.floor(diffInMinutes / 60);
+ if (diffInHours < 24) return `${diffInHours}h ago`;
+
+ const diffInDays = Math.floor(diffInHours / 24);
+ if (diffInDays < 30) return `${diffInDays}d ago`;
+
+ const diffInMonths = Math.floor(diffInDays / 30);
+ if (diffInMonths < 12) return `${diffInMonths}mo ago`;
+
+ const diffInYears = Math.floor(diffInDays / 365);
+ return `${diffInYears}y ago`;
+};
diff --git a/packages/ui/src/components/Button.tsx b/packages/ui/src/components/Button.tsx
index 3c6090ff6..a44cd82ed 100644
--- a/packages/ui/src/components/Button.tsx
+++ b/packages/ui/src/components/Button.tsx
@@ -17,7 +17,7 @@ const buttonVariants = cva(
blue: "bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-6 disabled:text-gray-9",
destructive:
"bg-red-500 text-white hover:bg-red-600 disabled:bg-red-200",
- outline: "border border-gray-8 text-gray-12 hover:bg-gray-2 disabled:bg-gray-8",
+ outline: "border border-gray-4 hover:border-gray-12 hover:bg-gray-12 hover:text-gray-1 text-gray-12 disabled:bg-gray-8",
white: "bg-gray-1 text-gray-12 hover:bg-gray-2 disabled:bg-gray-8",
ghost: "hover:bg-white/20 hover:text-white",
gray: "bg-gray-4 text-gray-12 hover:bg-gray-5 disabled:bg-gray-6 disabled:text-gray-9",