Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Emoji reactions + comments + editable title

Richie McIlroy95065e989327
diff --git a/apps/web/app/api/video/comment/route.ts b/apps/web/app/api/video/comment/route.ts
new file mode 100644
index 000000000..f291d4cac
--- /dev/null
+++ b/apps/web/app/api/video/comment/route.ts
@@ -0,0 +1,44 @@
+import { type NextRequest } from "next/server";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { nanoId } from "@cap/database/helpers";
+import { comments } from "@cap/database/schema";
+import { db } from "@cap/database";
+
+export async function POST(request: NextRequest) {
+ const user = await getCurrentUser();
+ const { type, content, videoId, timestamp, parentCommentId } =
+ await request.json();
+ const userId = user?.userId as string;
+
+ if (!type || !content || !videoId) {
+ console.error("Missing required data in /api/video/comment/route.ts");
+
+ return new Response(JSON.stringify({ error: true }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ const id = nanoId();
+
+ await db.insert(comments).values({
+ id: id,
+ authorId: userId ?? "anonymous",
+ type: type,
+ content: content,
+ videoId: videoId,
+ timestamp: timestamp || null,
+ parentCommentId: parentCommentId || null,
+ });
+
+ return new Response(
+ JSON.stringify({
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ })
+ );
+}
diff --git a/apps/web/app/api/video/title/route.ts b/apps/web/app/api/video/title/route.ts
new file mode 100644
index 000000000..a20d38db0
--- /dev/null
+++ b/apps/web/app/api/video/title/route.ts
@@ -0,0 +1,61 @@
+import { type NextRequest } from "next/server";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { nanoId } from "@cap/database/helpers";
+import { videos } from "@cap/database/schema";
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+
+export async function PUT(request: NextRequest) {
+ const user = await getCurrentUser();
+ const { title, videoId } = await request.json();
+ const userId = user?.userId as string;
+
+ if (!user || !title || !videoId) {
+ console.error("Missing required data in /api/video/title/route.ts");
+
+ return new Response(JSON.stringify({ error: true }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ const query = await db.select().from(videos).where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return new Response(JSON.stringify({ error: true }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ const ownerId = query[0].ownerId;
+
+ if (ownerId !== userId) {
+ return new Response(JSON.stringify({ error: true }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ await db
+ .update(videos)
+ .set({
+ name: title,
+ })
+ .where(eq(videos.id, videoId));
+
+ return new Response(
+ JSON.stringify({
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ })
+ );
+}
diff --git a/apps/web/app/share/[videoId]/Share.tsx b/apps/web/app/share/[videoId]/Share.tsx
index 93a7259a9..0d01b8d3f 100644
--- a/apps/web/app/share/[videoId]/Share.tsx
+++ b/apps/web/app/share/[videoId]/Share.tsx
@@ -2,24 +2,26 @@
import { ShareHeader } from "./_components/ShareHeader";
import { ShareVideo } from "./_components/ShareVideo";
-import { videos } from "@cap/database/schema";
+import { comments as commentsSchema, videos } from "@cap/database/schema";
import { userSelectProps } from "@cap/database/auth/session";
import { Toolbar } from "./_components/Toolbar";
// million-ignore
export const Share = ({
data,
user,
+ comments,
}: {
data: typeof videos.$inferSelect;
user: typeof userSelectProps | null;
+ comments: (typeof commentsSchema.$inferSelect)[];
}) => {
return (
- <div className="wrapper py-5">
+ <div className="wrapper py-8">
<div className="space-y-6">
<ShareHeader data={data} user={user} />
- <ShareVideo data={data} user={user} />
+ <ShareVideo data={data} user={user} comments={comments} />
<div className="flex justify-center">
- <Toolbar />
+ <Toolbar data={data} user={user} />
</div>
</div>
</div>
diff --git a/apps/web/app/share/[videoId]/_components/ShareHeader.tsx b/apps/web/app/share/[videoId]/_components/ShareHeader.tsx
index ea4aeea05..d04f5d1a9 100644
--- a/apps/web/app/share/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareHeader.tsx
@@ -3,6 +3,8 @@ import { videos } from "@cap/database/schema";
import moment from "moment";
import { userSelectProps } from "@cap/database/auth/session";
import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "react-hot-toast";
export const ShareHeader = ({
data,
@@ -11,7 +13,32 @@ export const ShareHeader = ({
data: typeof videos.$inferSelect;
user: typeof userSelectProps | null;
}) => {
- const { push } = useRouter();
+ const { push, refresh } = useRouter();
+ const [isEditing, setIsEditing] = useState(false);
+ const [title, setTitle] = useState(data.name);
+
+ const handleBlur = async () => {
+ setIsEditing(false);
+ const response = await fetch(
+ `${process.env.NEXT_PUBLIC_URL}/api/video/title`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title, videoId: data.id }),
+ }
+ );
+ if (!response.ok) {
+ toast.error("Failed to update title - please try again.");
+ }
+
+ refresh();
+ };
+
+ const handleKeyDown = async (event: { key: string }) => {
+ if (event.key === "Enter") {
+ handleBlur();
+ }
+ };
return (
<div>
@@ -26,7 +53,30 @@ export const ShareHeader = ({
</a>
</div>
<div>
- <h1 className="text-2xl">{data.name}</h1>
+ {isEditing ? (
+ <input
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ onBlur={handleBlur}
+ onKeyDown={handleKeyDown}
+ autoFocus
+ className="text-2xl font-semibold"
+ />
+ ) : (
+ <h1
+ className="text-2xl"
+ onClick={() => {
+ if (
+ user !== null &&
+ user.userId.toString() === data.ownerId
+ ) {
+ setIsEditing(true);
+ }
+ }}
+ >
+ {title}
+ </h1>
+ )}
<p className="text-gray-400 text-sm">
{moment(data.createdAt).fromNow()}
</p>
diff --git a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
index 7f8c50ff7..1b537c6ba 100644
--- a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
@@ -1,9 +1,17 @@
-import { videos } from "@cap/database/schema";
+import { comments as commentsSchema, videos } from "@cap/database/schema";
import { VideoPlayer } from "./VideoPlayer";
import { useState, useEffect, useRef } from "react";
-import { Play, Pause, Maximize, VolumeX, Volume2 } from "lucide-react";
+import {
+ Play,
+ Pause,
+ Maximize,
+ VolumeX,
+ Volume2,
+ MessageSquare,
+} from "lucide-react";
import { LogoSpinner } from "@cap/ui";
import { userSelectProps } from "@cap/database/auth/session";
+import { Tooltip } from "react-tooltip";
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60);
@@ -16,10 +24,15 @@ const formatTime = (time: number) => {
export const ShareVideo = ({
data,
user,
+ comments,
}: {
data: typeof videos.$inferSelect;
user: typeof userSelectProps | null;
+ comments: (typeof commentsSchema.$inferSelect)[];
}) => {
+ console.log("comments:");
+ console.log(comments);
+
const videoRef = useRef<HTMLVideoElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
@@ -157,9 +170,7 @@ export const ShareVideo = ({
setSeeking(true);
};
- // Changes specifically in handleSeekMouseMove, handleSeekMouseUp to use applyTimeToVideos directly
const handleSeekMouseUp = (event: any) => {
- // Similar change as handleSeekMouseMove, no need for isPlaying check here
if (!seeking) return;
setSeeking(false);
const seekBar = event.currentTarget;
@@ -174,7 +185,7 @@ export const ShareVideo = ({
if (!seeking) return;
const seekBar = event.currentTarget;
const seekTo = calculateNewTime(event, seekBar);
- applyTimeToVideos(seekTo); // This will just update the current time in state but not the video currentTime because that should happen on mouse up to avoid too many updates.
+ applyTimeToVideos(seekTo);
};
const handleMuteClick = () => {
@@ -274,6 +285,45 @@ export const ShareVideo = ({
onMouseLeave={() => setSeeking(false)}
onTouchEnd={handleSeekMouseUp}
>
+ {comments !== null && (
+ <div className="w-full -mt-5">
+ {comments.map((comment) => {
+ if (comment.timestamp === null) return null;
+
+ return (
+ <>
+ <Tooltip id={comment.id} />
+ <div
+ key={comment.id}
+ className="absolute z-10 text-[16px]"
+ style={{
+ left: `${(comment.timestamp / longestDuration) * 100}%`,
+ }}
+ data-tooltip-id={comment.id}
+ data-tooltip-content={`${
+ comment.type === "text"
+ ? "User: " + comment.content
+ : comment.authorId === "anonymous"
+ ? "Anonymous"
+ : "User"
+ }`}
+ >
+ <span>
+ {comment.type === "text" ? (
+ <MessageSquare
+ fill="#646464"
+ className="w-auto h-[22px] text-white"
+ />
+ ) : (
+ comment.content
+ )}
+ </span>
+ </div>
+ </>
+ );
+ })}
+ </div>
+ )}
<div className="absolute top-1.5 w-full h-1 bg-white bg-opacity-50 rounded-full z-0" />
<div
className="absolute top-1.5 h-1 bg-white rounded-full cursor-pointer transition-all duration-300 z-0"
diff --git a/apps/web/app/share/[videoId]/_components/Toolbar.tsx b/apps/web/app/share/[videoId]/_components/Toolbar.tsx
index 52ae61412..6710a54f2 100644
--- a/apps/web/app/share/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/share/[videoId]/_components/Toolbar.tsx
@@ -1,9 +1,29 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { MessageSquare } from "lucide-react";
+import { videos } from "@cap/database/schema";
+import { userSelectProps } from "@cap/database/auth/session";
+import { useRouter } from "next/navigation";
+import { Button } from "@cap/ui";
// million-ignore
-export const Toolbar = () => {
+export const Toolbar = ({
+ data,
+ user,
+}: {
+ data: typeof videos.$inferSelect;
+ user: typeof userSelectProps | null;
+}) => {
+ const { refresh, push } = useRouter();
+ const [commentBoxOpen, setCommentBoxOpen] = useState(false);
+ const [comment, setComment] = useState("");
+ const videoElement = useRef<HTMLVideoElement | null>(null);
+ useEffect(() => {
+ videoElement.current = document.getElementById(
+ "video-player"
+ ) as HTMLVideoElement;
+ }, []);
+
const [currentEmoji, setCurrentEmoji] = useState<{
emoji: string;
id: number;
@@ -18,6 +38,9 @@ export const Toolbar = () => {
};
}, []);
+ const timestamp =
+ videoElement && videoElement.current ? videoElement.current.currentTime : 0;
+
const handleEmojiClick = async (emoji: string) => {
// Clear any existing timeout
if (clearEmojiTimeout.current) {
@@ -30,10 +53,65 @@ export const Toolbar = () => {
// Remove the emoji after the animation duration
clearEmojiTimeout.current = setTimeout(() => {
setCurrentEmoji(null);
- }, 3000); // Adjust this duration to match your animation
+ }, 3000);
+
+ const videoElement = document.getElementById(
+ "video-player"
+ ) as HTMLVideoElement;
+ console.log("videoElement", videoElement.currentTime);
+ const timestamp = videoElement ? videoElement.currentTime : 0;
- // Record the reaction in the database
- // or do something else
+ const response = await fetch(
+ `${process.env.NEXT_PUBLIC_URL}/api/video/comment`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ type: "emoji",
+ content: emoji,
+ videoId: data.id,
+ parentCommentId: null,
+ timestamp: timestamp,
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ console.error("Failed to record emoji reaction");
+ }
+
+ refresh();
+ };
+
+ const handleCommentSubmit = async () => {
+ if (comment.length === 0) {
+ return;
+ }
+
+ const response = await fetch("/api/video/comment", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ type: "text",
+ content: comment,
+ videoId: data.id,
+ parentCommentId: null,
+ timestamp: timestamp,
+ }),
+ });
+
+ if (!response.ok) {
+ console.error("Failed to record comment");
+ }
+
+ setComment("");
+ setCommentBoxOpen(false);
+
+ refresh();
};
const Emoji = ({ label, emoji }: { label: string; emoji: string }) => (
@@ -60,25 +138,94 @@ export const Toolbar = () => {
return (
<>
- <div className="bg-white border border-gray-200 rounded-full mx-auto shadow-lg">
- <div className="grid items-center justify-start">
- <div className="p-2">
- <div className="grid items-center justify-start grid-flow-col">
- {REACTIONS.map((reaction) => (
- <Emoji
- key={reaction.emoji}
- emoji={reaction.emoji}
- label={reaction.label}
+ <div
+ className={`bg-white border border-gray-200 rounded-full mx-auto shadow-lg transition-all ${
+ commentBoxOpen === true && "w-full"
+ }`}
+ >
+ <div
+ className={`${
+ commentBoxOpen === true ? "flex w-full" : "grid"
+ } items-center justify-start`}
+ >
+ <div className="w-full p-2">
+ {commentBoxOpen === true ? (
+ <div className="w-full flex items-center justify-between">
+ <input
+ autoFocus
+ type="text"
+ value={comment}
+ onChange={(e) => setComment(e.target.value)}
+ placeholder="Add a comment"
+ className="flex-grow h-full outline-none px-3"
+ maxLength={255}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleCommentSubmit();
+ }
+ if (e.key === "Escape") {
+ setCommentBoxOpen(false);
+ setComment("");
+ }
+ }}
/>
- ))}
- <div className="w-[2px] bg-gray-200 h-full mx-2"></div>
- <div className="flex items-center">
- <button className="text-sm font-medium bg-transparent py-1 px-2 relative transition-bg-color duration-600 flex justify-center items-center rounded-full ease-in-out hover:bg-gray-200 active:bg-gray-400 active:duration-0">
- <MessageSquare className="w-[22px] h-auto" />
- <span className="ml-1">Comment</span>
- </button>
+ <div className="flex items-center space-x-2">
+ <Button
+ className="min-w-[160px]"
+ disabled={comment.length === 0}
+ variant="default"
+ size="sm"
+ onClick={() => {
+ handleCommentSubmit();
+ }}
+ >
+ Comment at {timestamp.toFixed(2)}
+ </Button>
+ <Button
+ className="min-w-[100px]"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setCommentBoxOpen(false);
+ setComment("");
+ }}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="grid items-center justify-start grid-flow-col">
+ {REACTIONS.map((reaction) => (
+ <Emoji
+ key={reaction.emoji}
+ emoji={reaction.emoji}
+ label={reaction.label}
+ />
+ ))}
+ <div className="w-[2px] bg-gray-200 h-full mx-2"></div>
+ <div className="flex items-center">
+ <button
+ onClick={() => {
+ if (!user) {
+ push(`/login?next=${window.location.pathname}`);
+ return;
+ }
+ const videoElement = document.getElementById(
+ "video-player"
+ ) as HTMLVideoElement;
+ videoElement.pause();
+ setCommentBoxOpen(true);
+ }}
+ className="text-sm font-medium bg-transparent py-1 px-2 relative transition-bg-color duration-600 flex justify-center items-center rounded-full ease-in-out hover:bg-gray-200 active:bg-gray-400 active:duration-0"
+ >
+ <MessageSquare className="w-[22px] h-auto" />
+ <span className="ml-1">Comment</span>
+ </button>
+ </div>
</div>
- </div>
+ )}
</div>
</div>
</div>
diff --git a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
index e24c64ac4..27da4a7f5 100644
--- a/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/share/[videoId]/_components/VideoPlayer.tsx
@@ -90,6 +90,7 @@ export const VideoPlayer = memo(
return (
<>
<video
+ id="video-player"
ref={videoRef}
className="absolute top-0 left-0 rounded-lg w-full h-full object-contain"
preload="metadata"
@@ -102,6 +103,8 @@ export const VideoPlayer = memo(
ref={audioRef}
style={{ display: "none" }}
preload="metadata"
+ controls={false}
+ playsInline
/>
)}
</>
diff --git a/apps/web/app/share/[videoId]/page.tsx b/apps/web/app/share/[videoId]/page.tsx
index df4ad99f6..b34684abb 100644
--- a/apps/web/app/share/[videoId]/page.tsx
+++ b/apps/web/app/share/[videoId]/page.tsx
@@ -2,7 +2,7 @@
import { Share } from "./Share";
import { db } from "@cap/database";
import { eq } from "drizzle-orm";
-import { videos } from "@cap/database/schema";
+import { videos, comments } from "@cap/database/schema";
import { getCurrentUser, userSelectProps } from "@cap/database/auth/session";
type Props = {
@@ -29,5 +29,10 @@ export default async function ShareVideoPage(props: Props) {
}
}
- return <Share data={video} user={user} />;
+ const commentsQuery = await db
+ .select()
+ .from(comments)
+ .where(eq(comments.videoId, videoId));
+
+ return <Share data={video} user={user} comments={commentsQuery} />;
}
diff --git a/apps/web/package.json b/apps/web/package.json
index aa25a57d8..de034a76a 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -42,6 +42,7 @@
"react-hot-toast": "^2.4.1",
"react-player": "^2.14.1",
"react-scroll-parallax": "^3.4.5",
+ "react-tooltip": "^5.26.3",
"resend": "1.1.0",
"server-only": "^0.0.1",
"tailwind-merge": "^2.1.0",
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index fe934789a..e90ff227a 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -10,8 +10,7 @@ import {
boolean,
uniqueIndex,
varchar,
- bigint,
- decimal,
+ float,
} from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm/relations";
import { nanoIdLength } from "./helpers";
@@ -178,6 +177,43 @@ export const sharedVideos = mysqlTable(
})
);
+export const comments = mysqlTable(
+ "comments",
+ {
+ id: nanoId("id").notNull().primaryKey().unique(),
+ type: varchar("type", { length: 6, enum: ["emoji", "text"] }).notNull(),
+ content: text("content").notNull(),
+ timestamp: float("timestamp"),
+ authorId: nanoId("authorId").notNull(),
+ videoId: nanoId("videoId").notNull(),
+ createdAt: timestamp("createdAt").notNull().defaultNow(),
+ updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
+ parentCommentId: nanoId("parentCommentId"),
+ },
+ (table) => ({
+ videoIdIndex: index("video_id_idx").on(table.videoId),
+ authorIdIndex: index("author_id_idx").on(table.authorId),
+ parentCommentIdIndex: index("parent_comment_id_idx").on(
+ table.parentCommentId
+ ),
+ })
+);
+
+export const commentsRelations = relations(comments, ({ one }) => ({
+ author: one(users, {
+ fields: [comments.authorId],
+ references: [users.id],
+ }),
+ video: one(videos, {
+ fields: [comments.videoId],
+ references: [videos.id],
+ }),
+ parentComment: one(comments, {
+ fields: [comments.parentCommentId],
+ references: [comments.id],
+ }),
+}));
+
// Define Relationships
export const usersRelations = relations(users, ({ many }) => ({
accounts: many(accounts),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 72eadaf39..09c1508e4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -207,6 +207,9 @@ importers:
react-scroll-parallax:
specifier: ^3.4.5
+ react-tooltip:
+ specifier: ^5.26.3
resend:
specifier: 1.1.0
version: 1.1.0
@@ -2067,6 +2070,13 @@ packages:
'@floating-ui/utils': 0.2.1
dev: false
+ /@floating-ui/[email protected]:
+ resolution: {integrity: sha512-RnDthu3mzPlQ31Ss/BTwQ1zjzIhr3lk1gZB1OC56h/1vEtaXkESrOqL5fQVMfXpwGtRwX+YsZBdyHtJMQnkArw==}
+ dependencies:
+ '@floating-ui/core': 1.5.3
+ '@floating-ui/utils': 0.2.1
+ dev: false
+
resolution: {integrity: sha512-IB8aCRFxr8nFkdYZgH+Otd9EVQPJoynxeFRGTB8voPoZMRWo8XjYuCRgpI1btvuKY69XMiLnW+ym7zoBHM90Rw==}
peerDependencies:
@@ -5144,6 +5154,10 @@ packages:
clsx: 2.0.0
dev: false
+ resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
+ dev: false
+
resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==}
engines: {node: '>=6'}
@@ -8953,6 +8967,18 @@ packages:
tslib: 2.6.2
dev: false
+ resolution: {integrity: sha512-MpYAws8CEHUd/RC4GaDCdoceph/T4KHM5vS5Dbk8FOmLMvvIht2ymP2htWdrke7K6lqPO8rz8+bnwWUIXeDlzg==}
+ peerDependencies:
+ react: '>=16.14.0'
+ react-dom: '>=16.14.0'
+ dependencies:
+ '@floating-ui/dom': 1.6.3
+ classnames: 2.5.1
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==}
engines: {node: '>=0.10.0'}