Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Share Cap settings wrapup
Richie McIlroyd6a7fb6ba8ea
diff --git a/apps/web/app/api/caps/share/route.ts b/apps/web/app/api/caps/share/route.tsnew file mode 100644index 000000000..26a4c6c2d--- /dev/null+++ b/apps/web/app/api/caps/share/route.ts@@ -0,0 +1,63 @@+import { NextRequest, NextResponse } from "next/server";+import { db } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";+import { sharedVideos, videos } from "@cap/database/schema";+import { eq, and } from "drizzle-orm";+import { nanoId } from "@cap/database/helpers";++export async function POST(request: NextRequest) {+ const user = await getCurrentUser();+ if (!user) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { capId, spaceIds } = await request.json();++ try {+ // Check if the user owns the cap+ const [cap] = await db.select().from(videos).where(eq(videos.id, capId));+ if (!cap || cap.ownerId !== user.id) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 403 });+ }++ // Get current shared spaces+ const currentSharedSpaces = await db+ .select()+ .from(sharedVideos)+ .where(eq(sharedVideos.videoId, capId));++ // Remove spaces that are no longer shared+ for (const sharedSpace of currentSharedSpaces) {+ if (!spaceIds.includes(sharedSpace.spaceId)) {+ await db+ .delete(sharedVideos)+ .where(+ and(+ eq(sharedVideos.videoId, capId),+ eq(sharedVideos.spaceId, sharedSpace.spaceId)+ )+ );+ }+ }++ // Add new shared spaces+ for (const spaceId of spaceIds) {+ const existingShare = currentSharedSpaces.find(+ (share) => share.spaceId === spaceId+ );+ if (!existingShare) {+ await db.insert(sharedVideos).values({+ id: nanoId(),+ videoId: capId,+ spaceId: spaceId,+ sharedByUserId: user.id,+ });+ }+ }++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error updating shared spaces:", error);+ return NextResponse.json({ error: "Internal server error" }, { status: 500 });+ }+}\ No newline at end of filediff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsxindex f7a66412f..f4605f631 100644--- a/apps/web/app/dashboard/caps/Caps.tsx+++ b/apps/web/app/dashboard/caps/Caps.tsx@@ -14,9 +14,19 @@ type VideoData = {createdAt: Date;totalComments: number;totalReactions: number;+ sharedSpaces: { id: string; name: string }[];+ ownerName: string;}[];-export const Caps = ({ data, count }: { data: VideoData; count: number }) => {+export const Caps = ({+ data,+ count,+ userSpaces,+}: {+ data: VideoData;+ count: number;+ userSpaces: { id: string; name: string }[];+}) => {const { refresh, replace } = useRouter();const params = useSearchParams();const page = Number(params.get("page")) || 1;@@ -72,16 +82,16 @@ export const Caps = ({ data, count }: { data: VideoData; count: number }) => {};return (- <>+ <div className="flex flex-col min-h-[calc(100vh-30px)] h-full"><div className="mb-3"><h1 className="text-3xl font-medium">My Caps</h1></div>- <div className="inner min-h-full h-full">+ <div className="flex-grow flex inner">{data.length === 0 ? (<EmptyCapState userName={user?.name || ""} />) : (- <div>- <div className="inner grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">+ <div className="flex flex-col w-full h-full">+ <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">{data.map((cap) => (<CapCardkey={cap.id}@@ -89,6 +99,7 @@ export const Caps = ({ data, count }: { data: VideoData; count: number }) => {analytics={analytics[cap.id] || 0}onDelete={deleteCap}userId={user?.id}+ userSpaces={userSpaces}/>))}</div>@@ -100,6 +111,6 @@ export const Caps = ({ data, count }: { data: VideoData; count: number }) => {</div>)}</div>- </>+ </div>);};diff --git a/apps/web/app/dashboard/caps/components/CapCard.tsx b/apps/web/app/dashboard/caps/components/CapCard.tsxindex 77a59747b..c29a85cd5 100644--- a/apps/web/app/dashboard/caps/components/CapCard.tsx+++ b/apps/web/app/dashboard/caps/components/CapCard.tsx@@ -5,7 +5,9 @@ import { CapCardAnalytics } from "@/app/dashboard/caps/components/CapCardAnalytiimport { toast } from "react-hot-toast";import moment from "moment";import { Tooltip } from "react-tooltip";-import { ShareIcon } from "lucide-react";+import { ShareIcon, ChevronDown } from "lucide-react";+import { SharingDialog } from "@/app/dashboard/caps/components/SharingDialog";+import { useRouter } from "next/navigation"; // Add this importinterface CapCardProps {cap: {@@ -16,10 +18,12 @@ interface CapCardProps {totalComments: number;totalReactions: number;sharedSpaces: { id: string; name: string }[];+ ownerName: string;};analytics: number;onDelete: (videoId: string) => Promise<void>;userId: string;+ userSpaces: { id: string; name: string }[];}export const CapCard: React.FC<CapCardProps> = ({@@ -27,9 +31,13 @@ export const CapCard: React.FC<CapCardProps> = ({analytics,onDelete,userId,+ userSpaces,}) => {const [isEditing, setIsEditing] = useState(false);const [title, setTitle] = useState(cap.name);+ const [isSharingDialogOpen, setIsSharingDialogOpen] = useState(false);+ const [sharedSpaces, setSharedSpaces] = useState(cap.sharedSpaces);+ const router = useRouter(); // Add this lineconst handleTitleBlur = async () => {if (!title) {@@ -66,6 +74,43 @@ export const CapCard: React.FC<CapCardProps> = ({? Math.max(cap.totalComments, cap.totalReactions): analytics;+ const isOwner = userId === cap.ownerId;++ const renderSharedStatus = () => {+ const baseClassName =+ "text-gray-400 text-sm cursor-pointer flex items-center";+ if (isOwner) {+ if (cap.sharedSpaces.length === 0) {+ return (+ <span+ className={baseClassName}+ onClick={() => setIsSharingDialogOpen(true)}+ >+ Not shared <ChevronDown className="ml-1" size={16} />+ </span>+ );+ } else {+ return (+ <span+ className={baseClassName}+ onClick={() => setIsSharingDialogOpen(true)}+ >+ Shared <ChevronDown className="ml-1" size={16} />+ </span>+ );+ }+ } else {+ return <span className={baseClassName}>Shared with you</span>;+ }+ };++ const handleSharingUpdated = (updatedSharedSpaces: string[]) => {+ setSharedSpaces(+ userSpaces.filter((space) => updatedSharedSpaces.includes(space.id))+ );+ router.refresh(); // Add this line to refresh the page+ };+return (<divclassName="rounded-xl border-[1px] border-gray-200 relative"@@ -88,6 +133,16 @@ export const CapCard: React.FC<CapCardProps> = ({/></a><div className="flex flex-col p-4">+ <div className="mb-2">+ <div>+ <span className="text-[0.875rem] leading-[1.25rem] text-gray-400">+ {isOwner ? cap.ownerName : cap.sharedSpaces[0]?.name}+ </span>+ </div>+ <div>+ <span>{renderSharedStatus()}</span>+ </div>+ </div>{isEditing ? (<textarearows={1}@@ -126,16 +181,16 @@ export const CapCard: React.FC<CapCardProps> = ({totalComments={cap.totalComments}totalReactions={cap.totalReactions}/>- {cap.sharedSpaces.length > 0 && (- <div className="mt-2 flex items-center">- <ShareIcon className="w-4 h-4 mr-2 text-gray-400" />- <span className="text-[0.875rem] leading-[1.25rem] text-gray-400">- Shared to:{" "}- {cap.sharedSpaces.map((space) => space.name).join(", ")}- </span>- </div>- )}</div>+ <SharingDialog+ isOpen={isSharingDialogOpen}+ onClose={() => setIsSharingDialogOpen(false)}+ capId={cap.id}+ capName={cap.name}+ sharedSpaces={sharedSpaces}+ userSpaces={userSpaces}+ onSharingUpdated={handleSharingUpdated}+ /></div>);};diff --git a/apps/web/app/dashboard/caps/components/EmptyCapState.tsx b/apps/web/app/dashboard/caps/components/EmptyCapState.tsxindex 16f8ed139..5b8575162 100644--- a/apps/web/app/dashboard/caps/components/EmptyCapState.tsx+++ b/apps/web/app/dashboard/caps/components/EmptyCapState.tsx@@ -6,7 +6,7 @@ interface EmptyCapStateProps {export const EmptyCapState: React.FC<EmptyCapStateProps> = ({ userName }) => {return (- <div className="flex flex-col items-center justify-center">+ <div className="w-full flex flex-col items-center justify-center"><div className="w-full max-w-md mx-auto"><imgclassName="w-full h-auto"diff --git a/apps/web/app/dashboard/caps/components/SharingDialog.tsx b/apps/web/app/dashboard/caps/components/SharingDialog.tsxnew file mode 100644index 000000000..f3a83981f--- /dev/null+++ b/apps/web/app/dashboard/caps/components/SharingDialog.tsx@@ -0,0 +1,135 @@+import { useState, useEffect } from "react";+import { Dialog } from "@headlessui/react";+import { toast } from "react-hot-toast";+import { Search, Plus } from "lucide-react";+import { Button } from "@cap/ui";++interface SharingDialogProps {+ isOpen: boolean;+ onClose: () => void;+ capId: string;+ capName: string;+ sharedSpaces: { id: string; name: string }[];+ userSpaces: { id: string; name: string }[];+ onSharingUpdated: (updatedSharedSpaces: string[]) => void;+}++export const SharingDialog: React.FC<SharingDialogProps> = ({+ isOpen,+ onClose,+ capId,+ capName,+ sharedSpaces,+ userSpaces,+ onSharingUpdated,+}) => {+ const [selectedSpaces, setSelectedSpaces] = useState<Set<string>>(+ new Set(sharedSpaces.map((space) => space.id))+ );+ const [searchTerm, setSearchTerm] = useState("");++ useEffect(() => {+ if (isOpen) {+ setSelectedSpaces(new Set(sharedSpaces.map((space) => space.id)));+ setSearchTerm("");+ }+ }, [isOpen, sharedSpaces]);++ const handleToggleSpace = (spaceId: string) => {+ setSelectedSpaces((prev) => {+ const newSet = new Set(prev);+ if (newSet.has(spaceId)) {+ newSet.delete(spaceId);+ } else {+ newSet.add(spaceId);+ }+ return newSet;+ });+ };++ const handleSave = async () => {+ try {+ const response = await fetch("/api/caps/share", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ capId, spaceIds: Array.from(selectedSpaces) }),+ });++ if (!response.ok) {+ throw new Error("Failed to update sharing settings");+ }++ toast.success("Sharing settings updated successfully");+ onSharingUpdated(Array.from(selectedSpaces));+ onClose();+ } catch (error) {+ console.error("Error updating sharing settings:", error);+ toast.error("Failed to update sharing settings");+ }+ };++ const filteredSpaces = userSpaces.filter((space) =>+ space.name.toLowerCase().includes(searchTerm.toLowerCase())+ );++ return (+ <Dialog open={isOpen} onClose={onClose} className="relative z-50">+ <div className="fixed inset-0 bg-black/30" aria-hidden="true" />+ <div className="fixed inset-0 flex items-center justify-center p-4">+ <Dialog.Panel className="w-full max-w-md rounded-lg bg-white p-6">+ <Dialog.Title className="text-xl font-semibold mb-4">+ Share {capName} to Spaces+ </Dialog.Title>+ <div className="relative mb-4">+ <input+ type="text"+ placeholder="Search"+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500"+ />+ <Search+ className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"+ size={20}+ />+ </div>+ <div className="space-y-2 max-h-60 overflow-y-auto">+ {filteredSpaces.map((space) => (+ <div+ key={space.id}+ className={`flex items-center justify-between p-3 rounded-lg cursor-pointer ${+ selectedSpaces.has(space.id)+ ? "bg-gray-200"+ : "hover:bg-gray-100"+ }`}+ onClick={() => handleToggleSpace(space.id)}+ >+ <div className="flex items-center">+ <div className="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center text-white font-semibold mr-3">+ {space.name.charAt(0).toUpperCase()}+ </div>+ <span className="text-sm font-medium">{space.name}</span>+ </div>+ {selectedSpaces.has(space.id) ? (+ <span className="text-blue-500 font-medium text-sm">+ Added+ </span>+ ) : (+ <Plus className="text-gray-400" size={20} />+ )}+ </div>+ ))}+ </div>+ <div className="mt-6 flex justify-end space-x-2">+ <Button size="sm" variant="gray" onClick={onClose}>+ Cancel+ </Button>+ <Button size="sm" variant="primary" onClick={handleSave}>+ Share+ </Button>+ </div>+ </Dialog.Panel>+ </div>+ </Dialog>+ );+};diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsxindex a8bab661e..798512506 100644--- a/apps/web/app/dashboard/caps/page.tsx+++ b/apps/web/app/dashboard/caps/page.tsx@@ -1,7 +1,14 @@import { Caps } from "./Caps";import { db } from "@cap/database";-import { comments, videos, sharedVideos, spaces } from "@cap/database/schema";-import { desc, eq, sql, count } from "drizzle-orm";+import {+ comments,+ videos,+ sharedVideos,+ spaces,+ users,+ spaceMembers,+} from "@cap/database/schema";+import { desc, eq, sql, count, or } from "drizzle-orm";import { getCurrentUser } from "@cap/database/auth/session";import { Metadata } from "next";@@ -38,31 +45,54 @@ export default async function CapsPage({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)`,sharedSpaces: sql<{ id: string; name: string }[]>`- JSON_ARRAYAGG(- JSON_OBJECT(- 'id', ${spaces.id},- 'name', ${spaces.name}- )+ COALESCE(+ JSON_ARRAYAGG(+ JSON_OBJECT(+ 'id', ${spaces.id},+ 'name', ${spaces.name}+ )+ ),+ JSON_ARRAY())`,+ ownerName: users.name,}).from(videos).leftJoin(comments, eq(videos.id, comments.videoId)).leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId)).leftJoin(spaces, eq(sharedVideos.spaceId, spaces.id))+ .leftJoin(users, eq(videos.ownerId, users.id)).where(eq(videos.ownerId, userId))- .groupBy(videos.id, videos.ownerId, videos.name, videos.createdAt)+ .groupBy(+ videos.id,+ videos.ownerId,+ videos.name,+ videos.createdAt,+ users.name+ ).orderBy(desc(videos.createdAt)).limit(limit).offset(offset);+ const userSpaces = await db+ .select({+ id: spaces.id,+ name: spaces.name,+ })+ .from(spaces)+ .leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))+ .where(eq(spaceMembers.userId, userId));+const processedVideoData = videoData.map((video) => ({...video,sharedSpaces: video.sharedSpaces.filter((space) => space.id !== null),}));- console.log("processedVideoData:");- console.log(processedVideoData);-- return <Caps data={processedVideoData} count={totalCount} />;+ return (+ <Caps+ data={processedVideoData}+ count={totalCount}+ userSpaces={userSpaces}+ />+ );}diff --git a/apps/web/app/dashboard/layout.tsx b/apps/web/app/dashboard/layout.tsxindex 4f6394f22..942776f5b 100644--- a/apps/web/app/dashboard/layout.tsx+++ b/apps/web/app/dashboard/layout.tsx@@ -124,9 +124,6 @@ export default async function DashboardLayout({findActiveSpace = spaceSelect[0];}- console.log("spaceSelect", spaceSelect);- console.log("findActiveSpace", findActiveSpace);-const isSubscribed =(user.stripeSubscriptionId &&user.stripeSubscriptionStatus !== "cancelled") ||diff --git a/apps/web/app/dashboard/shared-caps/SharedCaps.tsx b/apps/web/app/dashboard/shared-caps/SharedCaps.tsxnew file mode 100644index 000000000..426ddfa74--- /dev/null+++ b/apps/web/app/dashboard/shared-caps/SharedCaps.tsx@@ -0,0 +1,87 @@+"use client";+import { useRouter, useSearchParams } from "next/navigation";+import { useEffect, useState } from "react";+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";+import { SharedCapCard } from "./components/SharedCapCard";+import { EmptySharedCapState } from "./components/EmptySharedCapState";+import { CapPagination } from "../caps/components/CapPagination";++type SharedVideoData = {+ id: string;+ ownerId: string;+ name: string;+ createdAt: Date;+ totalComments: number;+ totalReactions: number;+ ownerName: string;+}[];++export const SharedCaps = ({+ data,+ count,+ activeSpaceId,+}: {+ data: SharedVideoData;+ count: number;+ activeSpaceId: string;+}) => {+ const { refresh } = useRouter();+ const params = useSearchParams();+ const page = Number(params.get("page")) || 1;+ const [analytics, setAnalytics] = useState<Record<string, number>>({});+ const { user, activeSpace } = useSharedContext();+ const limit = 15;+ const totalPages = Math.ceil(count / limit);++ useEffect(() => {+ const fetchAnalytics = async () => {+ const analyticsData: Record<string, number> = {};++ for (const video of data) {+ const response = await fetch(+ `/api/video/analytics?videoId=${video.id}`,+ {+ cache: "force-cache",+ }+ );+ const data = await response.json();++ analyticsData[video.id] = data.count || 0;+ }+ setAnalytics(analyticsData);+ };++ fetchAnalytics();+ }, [data]);++ return (+ <div className="flex flex-col min-h-[calc(100vh-30px)] h-full">+ <div className="mb-3">+ <h1 className="text-3xl font-medium">Shared Caps</h1>+ </div>+ <div className="flex-grow flex inner">+ {data.length === 0 ? (+ <EmptySharedCapState spaceName={activeSpace?.space.name || ""} />+ ) : (+ <div className="flex flex-col w-full h-full">+ <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">+ {data.map((cap) => (+ <SharedCapCard+ key={cap.id}+ cap={cap}+ analytics={analytics[cap.id] || 0}+ spaceName={activeSpace?.space.name || ""}+ />+ ))}+ </div>+ {(data.length > limit || data.length === limit || page !== 1) && (+ <div className="mt-4">+ <CapPagination currentPage={page} totalPages={totalPages} />+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ );+};diff --git a/apps/web/app/dashboard/shared-caps/components/EmptySharedCapState.tsx b/apps/web/app/dashboard/shared-caps/components/EmptySharedCapState.tsxnew file mode 100644index 000000000..51d702548--- /dev/null+++ b/apps/web/app/dashboard/shared-caps/components/EmptySharedCapState.tsx@@ -0,0 +1,28 @@+interface EmptySharedCapStateProps {+ spaceName: string;+}++export const EmptySharedCapState: React.FC<EmptySharedCapStateProps> = ({+ spaceName,+}) => {+ return (+ <div className="w-full flex flex-col items-center justify-center">+ <div className="w-full max-w-md mx-auto">+ <img+ className="w-full h-auto"+ src="/illustrations/person-microphone.svg"+ alt="Person using microphone"+ />+ </div>+ <div className="text-center pb-[30px]">+ <h1 className="text-2xl font-semibold mb-3">+ <span className="block">No shared Caps yet!</span>+ </h1>+ <p className="text-xl max-w-md">+ There are no Caps shared with {spaceName} yet. Ask your team members+ to share their Caps with this space.+ </p>+ </div>+ </div>+ );+};diff --git a/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx b/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsxnew file mode 100644index 000000000..d35d30004--- /dev/null+++ b/apps/web/app/dashboard/shared-caps/components/SharedCapCard.tsx@@ -0,0 +1,89 @@+import { useState } from "react";+import { VideoThumbnail } from "@/components/VideoThumbnail";+import { CapCardAnalytics } from "@/app/dashboard/caps/components/CapCardAnalytics";+import moment from "moment";+import { Tooltip } from "react-tooltip";++interface SharedCapCardProps {+ cap: {+ id: string;+ ownerId: string;+ name: string;+ createdAt: Date;+ totalComments: number;+ totalReactions: number;+ ownerName: string;+ };+ analytics: number;+ spaceName: string;+}++export const SharedCapCard: React.FC<SharedCapCardProps> = ({+ cap,+ analytics,+ spaceName,+}) => {+ const [isEditing, setIsEditing] = useState(false);+ const [title, setTitle] = useState(cap.name);++ const displayCount =+ analytics === 0+ ? Math.max(cap.totalComments, cap.totalReactions)+ : analytics;++ return (+ <div+ className="rounded-xl border-[1px] border-gray-200 relative"+ style={{ boxShadow: "0px 8px 16px rgba(18, 22, 31, 0.04)" }}+ >+ <a+ className="group block"+ href={+ process.env.NEXT_PUBLIC_IS_CAP &&+ process.env.NEXT_ENV === "production"+ ? `https://cap.link/${cap.id}`+ : `${process.env.NEXT_PUBLIC_URL}/s/${cap.id}`+ }+ >+ <VideoThumbnail+ userId={cap.ownerId}+ videoId={cap.id}+ alt={`${cap.name} Thumbnail`}+ />+ </a>+ <div className="flex flex-col p-4">+ <div className="mb-2">+ <div>+ <span className="text-[0.875rem] leading-[1.25rem] text-gray-400">+ {cap.ownerName}+ </span>+ </div>+ <div>+ <span className="text-[0.875rem] leading-[1.25rem] text-gray-400">+ Shared with {spaceName}+ </span>+ </div>+ </div>+ <p className="text-[0.875rem] leading-[1.25rem] text-gray-500 font-medium">+ {title}+ </p>+ <p>+ <span+ className="text-[0.875rem] leading-[1.25rem] text-gray-400"+ data-tooltip-id={cap.id + "_createdAt"}+ data-tooltip-content={`Cap created at ${cap.createdAt}`}+ >+ {moment(cap.createdAt).fromNow()}+ </span>+ <Tooltip id={cap.id + "_createdAt"} />+ </p>+ <CapCardAnalytics+ capId={cap.id}+ displayCount={displayCount}+ totalComments={cap.totalComments}+ totalReactions={cap.totalReactions}+ />+ </div>+ </div>+ );+};diff --git a/apps/web/app/dashboard/shared-caps/loading.tsx b/apps/web/app/dashboard/shared-caps/loading.tsxnew file mode 100644index 000000000..3713704df--- /dev/null+++ b/apps/web/app/dashboard/shared-caps/loading.tsx@@ -0,0 +1,7 @@+"use client";++import { SkeletonRows } from "@cap/ui";++export default function Loading() {+ return <SkeletonRows />;+}diff --git a/apps/web/app/dashboard/shared-caps/page.tsx b/apps/web/app/dashboard/shared-caps/page.tsxnew file mode 100644index 000000000..348d66b40--- /dev/null+++ b/apps/web/app/dashboard/shared-caps/page.tsx@@ -0,0 +1,123 @@+import { SharedCaps } from "./SharedCaps";+import { db } from "@cap/database";+import {+ comments,+ videos,+ sharedVideos,+ spaces,+ users,+ spaceMembers,+} from "@cap/database/schema";+import { desc, eq, sql, count, and } from "drizzle-orm";+import { getCurrentUser } from "@cap/database/auth/session";+import { Metadata } from "next";++export const metadata: Metadata = {+ title: "Shared Caps — Cap",+};++export const revalidate = 0;++export default async function SharedCapsPage({+ searchParams,+}: {+ searchParams: { [key: string]: string | string[] | undefined };+}) {+ const page = Number(searchParams.page) || 1;+ const limit = Number(searchParams.limit) || 15;+ const user = await getCurrentUser();+ const userId = user?.id as string;++ let activeSpaceId = user?.activeSpaceId;+ if (!activeSpaceId) {+ // Get the first available space if activeSpaceId doesn't exist+ const firstSpace = await db+ .select({ id: spaces.id })+ .from(spaces)+ .innerJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))+ .where(eq(spaceMembers.userId, userId))+ .limit(1)+ .then((result) => result[0]);++ activeSpaceId = firstSpace?.id;+ }++ if (!activeSpaceId) {+ // Handle the case where the user has no spaces+ return <div>No spaces available. Please create or join a space.</div>;+ }++ const offset = (page - 1) * limit;++ const totalCountResult = await db+ .select({ count: count() })+ .from(sharedVideos)+ .where(eq(sharedVideos.spaceId, activeSpaceId));++ const totalCount = totalCountResult[0]?.count || 0;++ const sharedVideoData = await db+ .select({+ id: videos.id,+ ownerId: videos.ownerId,+ name: videos.name,+ createdAt: videos.createdAt,+ 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)`,+ ownerName: users.name,+ })+ .from(sharedVideos)+ .innerJoin(videos, eq(sharedVideos.videoId, videos.id))+ .leftJoin(comments, eq(videos.id, comments.videoId))+ .leftJoin(users, eq(videos.ownerId, users.id))+ .where(eq(sharedVideos.spaceId, activeSpaceId))+ .groupBy(+ videos.id,+ videos.ownerId,+ videos.name,+ videos.createdAt,+ users.name+ )+ .orderBy(desc(videos.createdAt))+ .limit(limit)+ .offset(offset);++ console.log("sharedVideoData:");+ console.log(sharedVideoData);++ // Debug: Check if there are any shared videos for this space+ const debugSharedVideos = await db+ .select({+ id: sharedVideos.id,+ videoId: sharedVideos.videoId,+ spaceId: sharedVideos.spaceId,+ })+ .from(sharedVideos)+ .where(eq(sharedVideos.spaceId, activeSpaceId));++ console.log("Debug: Shared videos for this space:");+ console.log(debugSharedVideos);++ // Debug: Check if the videos exist+ if (debugSharedVideos.length > 0) {+ const debugVideos = await db+ .select({+ id: videos.id,+ name: videos.name,+ ownerId: videos.ownerId,+ })+ .from(videos)+ .where(eq(videos.id, debugSharedVideos[0].videoId));++ console.log("Debug: Video details:");+ console.log(debugVideos);+ }++ return (+ <SharedCaps+ data={sharedVideoData}+ count={totalCount}+ activeSpaceId={activeSpaceId}+ />+ );+}