Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Implement analytics into share page
Richie McIlroy8551d81c6271
diff --git a/apps/web/app/dashboard/caps/components/CapCardAnalytics.tsx b/apps/web/app/dashboard/caps/components/CapCardAnalytics.tsxindex 178d0a775..33666b500 100644--- a/apps/web/app/dashboard/caps/components/CapCardAnalytics.tsx+++ b/apps/web/app/dashboard/caps/components/CapCardAnalytics.tsx@@ -15,7 +15,7 @@ export const CapCardAnalytics: React.FC<CapCardAnalyticsProps> = ({totalReactions,}) => {return (- <div className="flex items-center space-x-3 mt-2 text-sm text-gray-60">+ <div className="flex items-center space-x-3 text-sm text-gray-60"><divclassName="flex items-center"data-tooltip-id={capId + "_analytics"}diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex cfc11e867..7c3ae9b2c 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -19,25 +19,34 @@ interface Analytics {reactions: number;}-export const Share = ({- data,- user,- comments,- individualFiles,-}: {- data: typeof videos.$inferSelect;+type VideoWithSpaceInfo = typeof videos.$inferSelect & {+ spaceMembers?: string[];+ spaceId?: string;+};++interface ShareProps {+ data: VideoWithSpaceInfo;user: typeof userSelectProps | null;comments: CommentWithAuthor[];individualFiles: {fileName: string;url: string;}[];+ initialAnalytics: {+ views: number;+ comments: number;+ reactions: number;+ };+}++export const Share: React.FC<ShareProps> = ({+ data,+ user,+ comments,+ individualFiles,+ initialAnalytics,}) => {- const [analytics, setAnalytics] = useState<Analytics>({- views: 0,- comments: 0,- reactions: 0,- });+ const [analytics, setAnalytics] = useState(initialAnalytics);const videoRef = useRef<HTMLVideoElement>(null);@@ -48,27 +57,34 @@ export const Share = ({};useEffect(() => {- const fetchAnalytics = async () => {+ const fetchViewCount = async () => {try {const response = await fetch(`/api/video/analytics?videoId=${data.id}`);if (!response.ok) {throw new Error("Failed to fetch analytics");}- const analyticsData = await response.json();- const metadata = (data.metadata as { reactions?: number }) || {};-- setAnalytics({- views: analyticsData.count || 0,- comments: comments.length,- reactions: metadata.reactions || 0,- });+ const viewData = await response.json();++ setAnalytics((prev) => ({+ ...prev,+ views: viewData.count || 0,+ }));} catch (error) {- console.error("Error fetching analytics:", error);+ console.error("Error fetching view count:", error);}};- fetchAnalytics();- }, [data.id, comments.length, data.metadata]);+ fetchViewCount();+ }, [data.id]);++ // Update analytics when comments change+ useEffect(() => {+ setAnalytics((prev) => ({+ ...prev,+ comments: comments.filter((c) => c.type === "text").length,+ reactions: comments.filter((c) => c.type === "emoji").length,+ }));+ }, [comments]);return (<div className="min-h-screen flex flex-col bg-[#F7F8FA]">@@ -102,6 +118,7 @@ export const Share = ({comments={comments}analytics={analytics}onSeek={handleSeek}+ videoId={data.id}/></div></div>@@ -116,7 +133,7 @@ export const Share = ({<atarget="_blank"href={`${process.env.NEXT_PUBLIC_URL}?ref=video_${data.id}`}- className="flex items-center justify-center space-x-2 py-2 px-4 bg-gray-100 border border-gray-200 rounded-full mx-auto w-fit"+ className="flex items-center justify-center space-x-2 py-2 px-4 bg-gray-100 new-card-style rounded-full mx-auto w-fit"><span className="text-sm">Recorded with</span><Logo className="w-14 h-auto" />diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsxindex 96d51b144..c2b879ad5 100644--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx@@ -10,16 +10,28 @@ import { classNames } from "@cap/utils";type TabType = "activity" | "transcript" | "settings";+type CommentType = typeof commentsSchema.$inferSelect & {+ authorName?: string | null;+};++type VideoWithSpaceInfo = typeof videos.$inferSelect & {+ spaceMembers?: string[];+ spaceId?: string;+};++interface Analytics {+ views: number;+ comments: number;+ reactions: number;+}+interface SidebarProps {- data: typeof videos.$inferSelect;+ data: VideoWithSpaceInfo;user: typeof userSelectProps | null;- comments: (typeof commentsSchema.$inferSelect)[];- analytics: {- views: number;- comments: number;- reactions: number;- };+ comments: CommentType[];+ analytics: Analytics;onSeek?: (time: number) => void;+ videoId: string;}export const Sidebar: React.FC<SidebarProps> = ({@@ -28,7 +40,13 @@ export const Sidebar: React.FC<SidebarProps> = ({comments,analytics,onSeek,+ videoId,}) => {+ const isOwnerOrMember: boolean = Boolean(+ user?.id === data.ownerId ||+ (data.spaceId && data.spaceMembers?.includes(user?.id ?? ""))+ );+const [activeTab, setActiveTab] = useState<TabType>("activity");const tabs = [@@ -45,6 +63,8 @@ export const Sidebar: React.FC<SidebarProps> = ({comments={comments}user={user}onSeek={onSeek}+ videoId={videoId}+ isOwnerOrMember={isOwnerOrMember}/>);case "transcript":diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity.tsxindex 1a269a9b9..0533efdbc 100644--- a/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx@@ -8,6 +8,7 @@ import { formatDistanceToNow } from "date-fns";import { Tooltip } from "react-tooltip";import { AnimatePresence, motion } from "framer-motion";import { AuthOverlay } from "../AuthOverlay";+import { CapCardAnalytics } from "@/app/dashboard/caps/components/CapCardAnalytics";type CommentType = typeof commentsSchema.$inferSelect & {authorName?: string | null;@@ -22,6 +23,8 @@ interface ActivityProps {comments: CommentType[];user: typeof userSelectProps | null;onSeek?: (time: number) => void;+ videoId: string;+ isOwnerOrMember?: boolean;}const Avatar: React.FC<{@@ -291,10 +294,12 @@ const Comment: React.FC<{};export const Activity: React.FC<ActivityProps> = ({- analytics,+ analytics: initialAnalytics,comments: initialComments,user,onSeek,+ videoId,+ isOwnerOrMember = false,}) => {const [replyingTo, setReplyingTo] = useState<string | null>(null);const [comments, setComments] = useState(initialComments);@@ -302,8 +307,33 @@ export const Activity: React.FC<ActivityProps> = ({[]);const [showAuthOverlay, setShowAuthOverlay] = useState(false);+ const [analytics, setAnalytics] = useState(initialAnalytics);const commentsContainerRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const fetchAnalytics = async () => {+ try {+ const response = await fetch(`/api/video/analytics?videoId=${videoId}`);+ if (!response.ok) {+ throw new Error("Failed to fetch analytics");+ }+ const analyticsData = await response.json();++ setAnalytics({+ views:+ analyticsData.count === 0 ? comments.length : analyticsData.count,+ comments: comments.length,+ reactions:+ (analyticsData.metadata as { reactions?: number })?.reactions || 0,+ });+ } catch (error) {+ console.error("Error fetching analytics:", error);+ }+ };++ fetchAnalytics();+ }, [videoId, comments.length]);+useEffect(() => {if (commentsContainerRef.current) {commentsContainerRef.current.scrollTop =@@ -493,28 +523,18 @@ export const Activity: React.FC<ActivityProps> = ({return (<div className="flex flex-col h-full">- <div className="flex-none border-b border-gray-200">- <div className="flex justify-between p-4">- <div className="flex items-center space-x-6">- <div className="flex items-center space-x-2">- <EyeIcon className="w-4 h-4 text-gray-400" />- <span className="text-sm text-gray-600">{analytics.views}</span>- </div>- <div className="flex items-center space-x-2">- <MessageSquare className="w-4 h-4 text-gray-400" />- <span className="text-sm text-gray-600">- {analytics.comments}- </span>- </div>- <div className="flex items-center space-x-2">- <SmileIcon className="w-4 h-4 text-gray-400" />- <span className="text-sm text-gray-600">- {analytics.reactions}- </span>- </div>+ {user && isOwnerOrMember && (+ <div className="flex-none border-b border-gray-200">+ <div className="flex justify-between p-4">+ <CapCardAnalytics+ capId={videoId}+ displayCount={analytics.views}+ totalComments={analytics.comments}+ totalReactions={analytics.reactions}+ /></div></div>- </div>+ )}<divref={commentsContainerRef}diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex 5ec14b3d4..6615af824 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -1,7 +1,13 @@import { Share } from "./Share";import { db } from "@cap/database";-import { eq } from "drizzle-orm";-import { videos, comments, users } from "@cap/database/schema";+import { eq, desc, sql, count } from "drizzle-orm";+import {+ videos,+ comments,+ users,+ sharedVideos,+ spaceMembers,+} from "@cap/database/schema";import { getCurrentUser, userSelectProps } from "@cap/database/auth/session";import type { Metadata, ResolvingMetadata } from "next";import { notFound } from "next/navigation";@@ -19,6 +25,18 @@ type CommentWithAuthor = typeof comments.$inferSelect & {authorName: string | null;};+type VideoWithSpace = typeof videos.$inferSelect & {+ sharedSpace?: {+ spaceId: string;+ } | null;+ spaceMembers?: string[];+ spaceId?: string;+};++type SpaceMember = {+ userId: string;+};+export async function generateMetadata({ params }: Props,parent: ResolvingMetadata@@ -84,24 +102,49 @@ export default async function ShareVideoPage(props: Props) {const userId = user?.id as string | undefined;console.log("[ShareVideoPage] Current user:", userId);- const query = await db.select().from(videos).where(eq(videos.id, videoId));+ const videoWithSpace = await db+ .select({+ id: videos.id,+ name: videos.name,+ ownerId: videos.ownerId,+ createdAt: videos.createdAt,+ updatedAt: videos.updatedAt,+ awsRegion: videos.awsRegion,+ awsBucket: videos.awsBucket,+ bucket: videos.bucket,+ metadata: videos.metadata,+ public: videos.public,+ videoStartTime: videos.videoStartTime,+ audioStartTime: videos.audioStartTime,+ xStreamInfo: videos.xStreamInfo,+ jobId: videos.jobId,+ jobStatus: videos.jobStatus,+ isScreenshot: videos.isScreenshot,+ skipProcessing: videos.skipProcessing,+ transcriptionStatus: videos.transcriptionStatus,+ source: videos.source,+ sharedSpace: {+ spaceId: sharedVideos.spaceId,+ },+ })+ .from(videos)+ .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))+ .where(eq(videos.id, videoId))+ .execute();- if (query.length === 0) {+ const video = videoWithSpace[0];++ if (!video) {console.log("[ShareVideoPage] No video found for videoId:", videoId);return <p>No video found</p>;}- const video = query[0];-- if (!video) {- console.log("[ShareVideoPage] Video object is null for videoId:", videoId);- return notFound();- }+ const videoSource = video.source as (typeof videos.$inferSelect)["source"];if (video.jobId === null &&video.skipProcessing === false &&- video.source.type === "MediaConvert"+ videoSource.type === "MediaConvert") {console.log("[ShareVideoPage] Creating MUX job for video:", videoId);const res = await fetch(@@ -199,12 +242,46 @@ export default async function ShareVideoPage(props: Props) {}console.log("[ShareVideoPage] Rendering Share component for video:", videoId);++ const analyticsData = await db+ .select({+ id: videos.id,+ totalComments: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'text' THEN ${comments.id} END)`,+ totalReactions: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'emoji' THEN ${comments.id} END)`,+ })+ .from(videos)+ .leftJoin(comments, eq(videos.id, comments.videoId))+ .where(eq(videos.id, videoId))+ .groupBy(videos.id);++ const initialAnalytics = {+ views: 0,+ comments: analyticsData[0]?.totalComments || 0,+ reactions: analyticsData[0]?.totalReactions || 0,+ };++ const membersList = video.sharedSpace?.spaceId+ ? await db+ .select({+ userId: spaceMembers.userId,+ })+ .from(spaceMembers)+ .where(eq(spaceMembers.spaceId, video.sharedSpace.spaceId))+ : [];++ const videoWithSpaceInfo: VideoWithSpace = {+ ...video,+ spaceMembers: membersList.map((member) => member.userId),+ spaceId: video.sharedSpace?.spaceId ?? undefined,+ };+return (<Share- data={video}+ data={videoWithSpaceInfo}user={user}comments={commentsQuery}individualFiles={individualFiles}+ initialAnalytics={initialAnalytics}/>);}diff --git a/apps/web/app/s/loading.tsx b/apps/web/app/s/loading.tsxindex cc4b95565..b86a17bb5 100644--- a/apps/web/app/s/loading.tsx+++ b/apps/web/app/s/loading.tsx@@ -2,8 +2,8 @@export default function Loading() {return (- <div className="flex flex-col h-screen max-w-6xl mx-auto px-4">- <div className="flex-shrink-0 py-4">+ <div className="min-h-screen flex flex-col bg-[#F7F8FA]">+ <div className="flex-1 container mx-auto px-4 py-4">{/* ShareHeader placeholder */}<div className="flex items-center justify-between"><div>@@ -14,43 +14,88 @@ export default function Loading() {<div className="mt-2 w-20 h-4 bg-gray-200 rounded-lg animate-pulse"></div></div></div>- </div>- <div className="md:flex-grow md:flex md:flex-col min-h-0">- <div className="flex-grow relative">- <div className="md:absolute inset-0">- {/* ShareVideo placeholder */}- <div className="relative w-full h-full overflow-hidden shadow-lg rounded-lg">- <div- className="relative block w-full h-full rounded-lg bg-gray-200 animate-pulse"- style={{ paddingBottom: "56.25%" }}- >- <div className="absolute inset-0 bg-gray-300 animate-pulse"></div>++ <div className="mt-4">+ <div className="flex flex-col lg:flex-row gap-4">+ <div className="flex-1">+ <div className="relative aspect-video new-card-style p-3">+ {/* ShareVideo placeholder */}+ <div className="relative w-full h-full overflow-hidden shadow-lg rounded-lg">+ <div+ className="relative block w-full h-full rounded-lg bg-gray-200 animate-pulse"+ style={{ paddingBottom: "56.25%" }}+ >+ <div className="absolute inset-0 bg-gray-300 animate-pulse"></div>+ </div>+ {/* Video controls placeholder */}+ <div className="absolute bottom-0 w-full bg-gray-800 bg-opacity-50">+ <div className="flex items-center justify-between px-4 py-2">+ <div className="flex items-center space-x-3">+ <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>+ <div className="w-24 h-4 bg-gray-400 rounded animate-pulse"></div>+ </div>+ <div className="flex space-x-2">+ <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>+ <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>+ <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>+ <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ <div className="mt-4 lg:hidden">+ {/* Mobile Toolbar placeholder */}+ <div className="flex justify-center">+ <div className="w-64 h-10 bg-gray-200 rounded animate-pulse"></div>+ </div></div>- {/* Video controls placeholder */}- <div className="absolute bottom-0 w-full bg-gray-800 bg-opacity-50">- <div className="flex items-center justify-between px-4 py-2">- <div className="flex items-center space-x-3">- <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>- <div className="w-24 h-4 bg-gray-400 rounded animate-pulse"></div>+ </div>++ {/* Sidebar placeholder */}+ <div className="lg:w-80 flex flex-col">+ <div className="new-card-style p-4">+ <div className="space-y-4">+ {/* Analytics placeholder */}+ <div className="flex justify-between">+ <div className="w-20 h-6 bg-gray-200 rounded animate-pulse"></div>+ <div className="w-20 h-6 bg-gray-200 rounded animate-pulse"></div>+ <div className="w-20 h-6 bg-gray-200 rounded animate-pulse"></div></div>- <div className="flex space-x-2">- <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>- <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>- <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>- <div className="w-8 h-8 bg-gray-400 rounded-full animate-pulse"></div>++ {/* Comments placeholder */}+ <div className="space-y-4">+ {[1, 2, 3].map((i) => (+ <div key={i} className="flex space-x-3">+ <div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse"></div>+ <div className="flex-1 space-y-2">+ <div className="w-32 h-4 bg-gray-200 rounded animate-pulse"></div>+ <div className="w-full h-4 bg-gray-200 rounded animate-pulse"></div>+ </div>+ </div>+ ))}</div></div></div></div></div>- </div>- <div className="flex-shrink-0 py-4">- {/* Toolbar placeholder */}- <div className="flex justify-center">- <div className="w-64 h-10 bg-gray-200 rounded animate-pulse"></div>++ <div className="hidden lg:block mt-4">+ {/* Desktop Toolbar placeholder */}+ <div className="flex justify-center">+ <div className="w-64 h-10 bg-gray-200 rounded animate-pulse"></div>+ </div></div></div></div>++ {/* Footer placeholder */}+ <div className="mt-auto py-4">+ <div className="flex items-center justify-center space-x-2 py-2 px-4 bg-gray-100 border border-gray-200 rounded-full mx-auto w-fit">+ <div className="w-20 h-4 bg-gray-200 rounded animate-pulse"></div>+ <div className="w-14 h-6 bg-gray-200 rounded animate-pulse"></div>+ </div>+ </div></div>);}