diff options
| author | Zaid-maker <53424436+Zaid-maker@users.noreply.github.com> | 2025-06-24 16:59:44 +0500 |
|---|---|---|
| committer | Zaid-maker <53424436+Zaid-maker@users.noreply.github.com> | 2025-06-24 16:59:44 +0500 |
| commit | 62051de6c11dde40e2929c030e4418f87b137e42 (patch) | |
| tree | 3492ed2abd6a127512a6ce09543bcf770bcd53d5 /apps/web/src | |
| parent | 7c83b8e70b2024d79f053bd40e6f633969c2c1f5 (diff) | |
| parent | 900deab065ef17941262f48524af786cac302945 (diff) | |
| download | opencut-62051de6c11dde40e2929c030e4418f87b137e42.tar.gz | |
Merge branch 'main' into implement-workflows
Diffstat (limited to 'apps/web/src')
36 files changed, 2026 insertions, 902 deletions
diff --git a/apps/web/src/app/(auth)/login/page.tsx b/apps/web/src/app/(auth)/login/page.tsx new file mode 100644 index 00000000..73c34e1e --- /dev/null +++ b/apps/web/src/app/(auth)/login/page.tsx @@ -0,0 +1,176 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { signIn } from "@opencut/auth/client"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Suspense, useState } from "react"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Separator } from "@/components/ui/separator"; +import Link from "next/link"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { ArrowLeft, Loader2 } from "lucide-react"; +import { GoogleIcon } from "@/components/icons"; + +function LoginForm() { + const router = useRouter(); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState<string | null>(null); + const [isEmailLoading, setIsEmailLoading] = useState(false); + const [isGoogleLoading, setIsGoogleLoading] = useState(false); + + const handleLogin = async () => { + setError(null); + setIsEmailLoading(true); + + const { error } = await signIn.email({ + email, + password, + }); + + if (error) { + setError(error.message || "An unexpected error occurred."); + setIsEmailLoading(false); + return; + } + + router.push("/editor"); + }; + + const handleGoogleLogin = async () => { + setError(null); + setIsGoogleLoading(true); + + try { + await signIn.social({ + provider: "google", + }); + router.push("/editor"); + } catch (error) { + setError("Failed to sign in with Google. Please try again."); + setIsGoogleLoading(false); + } + }; + + const isAnyLoading = isEmailLoading || isGoogleLoading; + + return ( + <div className="flex flex-col space-y-6"> + {error && ( + <Alert variant="destructive"> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error}</AlertDescription> + </Alert> + )} + + <Button + onClick={handleGoogleLogin} + variant="outline" + size="lg" + disabled={isAnyLoading} + > + {isGoogleLoading ? ( + <Loader2 className="animate-spin" /> + ) : ( + <GoogleIcon /> + )}{" "} + Continue with Google + </Button> + <div className="relative"> + <div className="absolute inset-0 flex items-center"> + <Separator className="w-full" /> + </div> + <div className="relative flex justify-center text-xs uppercase"> + <span className="bg-background px-2 text-muted-foreground"> + Or continue with + </span> + </div> + </div> + <div className="space-y-4"> + <div className="space-y-2"> + <Label htmlFor="email">Email</Label> + <Input + id="email" + type="email" + placeholder="m@example.com" + value={email} + onChange={(e) => setEmail(e.target.value)} + disabled={isAnyLoading} + className="h-11" + /> + </div> + <div className="space-y-2"> + <Label htmlFor="password">Password</Label> + <Input + id="password" + type="password" + value={password} + onChange={(e) => setPassword(e.target.value)} + disabled={isAnyLoading} + className="h-11" + /> + </div> + <Button + onClick={handleLogin} + disabled={isAnyLoading || !email || !password} + className="w-full h-11" + size="lg" + > + {isEmailLoading ? <Loader2 className="animate-spin" /> : "Sign in"} + </Button> + </div> + </div> + ); +} + +export default function LoginPage() { + const router = useRouter(); + + return ( + <div className="flex h-screen items-center justify-center relative"> + <Button + variant="text" + onClick={() => router.back()} + className="absolute top-6 left-6" + > + <ArrowLeft className="h-5 w-5" /> Back + </Button> + <Card className="w-[400px] shadow-lg border-0"> + <CardHeader className="text-center pb-4"> + <CardTitle className="text-2xl font-semibold">Welcome back</CardTitle> + <CardDescription className="text-base"> + Sign in to your account to continue + </CardDescription> + </CardHeader> + <CardContent className="pt-0"> + <Suspense + fallback={ + <div className="text-center"> + <Loader2 className="animate-spin" /> + </div> + } + > + <LoginForm /> + </Suspense> + <div className="mt-6 text-center text-sm"> + Don't have an account?{" "} + <Link + href="/signup" + className="font-medium text-primary underline-offset-4 hover:underline" + > + Sign up + </Link> + </div> + </CardContent> + </Card> + </div> + ); +} diff --git a/apps/web/src/app/(auth)/signup/page.tsx b/apps/web/src/app/(auth)/signup/page.tsx new file mode 100644 index 00000000..1c98b9e1 --- /dev/null +++ b/apps/web/src/app/(auth)/signup/page.tsx @@ -0,0 +1,201 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { signUp, signIn } from "@opencut/auth/client"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Suspense, useState } from "react"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Separator } from "@/components/ui/separator"; +import Link from "next/link"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { Loader2, ArrowLeft } from "lucide-react"; +import { GoogleIcon } from "@/components/icons"; + +function SignUpForm() { + const router = useRouter(); + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState<string | null>(null); + const [isEmailLoading, setIsEmailLoading] = useState(false); + const [isGoogleLoading, setIsGoogleLoading] = useState(false); + + const handleSignUp = async () => { + setError(null); + setIsEmailLoading(true); + + const { error } = await signUp.email({ + name, + email, + password, + }); + + if (error) { + setError(error.message || "An unexpected error occurred."); + setIsEmailLoading(false); + return; + } + + router.push("/login"); + }; + + const handleGoogleSignUp = async () => { + setError(null); + setIsGoogleLoading(true); + + try { + await signIn.social({ + provider: "google", + }); + + router.push("/editor"); + } catch (error) { + setError("Failed to sign up with Google. Please try again."); + setIsGoogleLoading(false); + } + }; + + const isAnyLoading = isEmailLoading || isGoogleLoading; + + return ( + <div className="flex flex-col space-y-6"> + {error && ( + <Alert variant="destructive"> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error}</AlertDescription> + </Alert> + )} + + <Button + onClick={handleGoogleSignUp} + variant="outline" + size="lg" + disabled={isAnyLoading} + > + {isGoogleLoading ? ( + <Loader2 className="animate-spin" /> + ) : ( + <GoogleIcon /> + )}{" "} + Continue with Google + </Button> + + <div className="relative"> + <div className="absolute inset-0 flex items-center"> + <Separator className="w-full" /> + </div> + <div className="relative flex justify-center text-xs uppercase"> + <span className="bg-background px-2 text-muted-foreground"> + Or continue with + </span> + </div> + </div> + + <div className="space-y-4"> + <div className="space-y-2"> + <Label htmlFor="name">Full Name</Label> + <Input + id="name" + type="text" + placeholder="John Doe" + value={name} + onChange={(e) => setName(e.target.value)} + disabled={isAnyLoading} + className="h-11" + /> + </div> + <div className="space-y-2"> + <Label htmlFor="email">Email</Label> + <Input + id="email" + type="email" + placeholder="m@example.com" + value={email} + onChange={(e) => setEmail(e.target.value)} + disabled={isAnyLoading} + className="h-11" + /> + </div> + <div className="space-y-2"> + <Label htmlFor="password">Password</Label> + <Input + id="password" + type="password" + placeholder="Create a strong password" + value={password} + onChange={(e) => setPassword(e.target.value)} + disabled={isAnyLoading} + className="h-11" + /> + </div> + <Button + onClick={handleSignUp} + disabled={isAnyLoading || !name || !email || !password} + className="w-full h-11" + size="lg" + > + {isEmailLoading ? ( + <Loader2 className="animate-spin" /> + ) : ( + "Create account" + )} + </Button> + </div> + </div> + ); +} + +export default function SignUpPage() { + const router = useRouter(); + + return ( + <div className="flex h-screen items-center justify-center relative"> + <Button + variant="text" + onClick={() => router.back()} + className="absolute top-6 left-6" + > + <ArrowLeft className="h-5 w-5" /> Back + </Button> + + <Card className="w-[400px] shadow-lg border-0"> + <CardHeader className="text-center pb-4"> + <CardTitle className="text-2xl font-semibold"> + Create your account + </CardTitle> + <CardDescription className="text-base"> + Get started with your free account today + </CardDescription> + </CardHeader> + <CardContent className="pt-0"> + <Suspense + fallback={ + <div className="text-center"> + <Loader2 className="animate-spin" /> + </div> + } + > + <SignUpForm /> + </Suspense> + <div className="mt-6 text-center text-sm"> + Already have an account?{" "} + <Link + href="/login" + className="font-medium text-primary underline-offset-4 hover:underline" + > + Sign in + </Link> + </div> + </CardContent> + </Card> + </div> + ); +} diff --git a/apps/web/src/app/api/auth/[...all]/route.ts b/apps/web/src/app/api/auth/[...all]/route.ts index 1fb57443..393fb7e7 100644 --- a/apps/web/src/app/api/auth/[...all]/route.ts +++ b/apps/web/src/app/api/auth/[...all]/route.ts @@ -1,4 +1,4 @@ -import { auth } from "@/lib/auth";
+import { auth } from "@opencut/auth/server";
import { toNextJsHandler } from "better-auth/next-js";
export const { POST, GET } = toNextJsHandler(auth);
\ No newline at end of file diff --git a/apps/web/src/app/api/waitlist/route.ts b/apps/web/src/app/api/waitlist/route.ts index f0b1c1fb..0632616b 100644 --- a/apps/web/src/app/api/waitlist/route.ts +++ b/apps/web/src/app/api/waitlist/route.ts @@ -1,6 +1,6 @@ import { NextRequest, NextResponse } from "next/server";
-import { db } from "@/lib/db";
-import { waitlist } from "@/lib/db/schema";
+import { db } from "@opencut/db";
+import { waitlist } from "@opencut/db/schema";
import { eq } from "drizzle-orm";
import { nanoid } from "nanoid";
import { waitlistRateLimit } from "@/lib/rate-limit";
diff --git a/apps/web/src/app/auth/login/page.tsx b/apps/web/src/app/auth/login/page.tsx deleted file mode 100644 index 5eadb85c..00000000 --- a/apps/web/src/app/auth/login/page.tsx +++ /dev/null @@ -1,98 +0,0 @@ -"use client"; - -import { useSearchParams, useRouter } from "next/navigation"; -import { authClient } from "@/lib/auth-client"; -import { Button } from "@/components/ui/button"; -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card"; -import { Suspense, useState } from "react"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import Link from "next/link"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; - -function LoginForm() { - const searchParams = useSearchParams(); - const router = useRouter(); - const redirectUrl = searchParams.get("redirect"); - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [error, setError] = useState<string | null>(null); - - const handleLogin = async () => { - setError(null); - const { error } = await authClient.signIn.email({ - email, - password, - }); - - if (error) { - setError(error.message || "An unexpected error occurred."); - return; - } - - router.push(redirectUrl || "/"); - }; - - return ( - <div className="flex flex-col space-y-4"> - {error && ( - <Alert variant="destructive"> - <AlertTitle>Error</AlertTitle> - <AlertDescription>{error}</AlertDescription> - </Alert> - )} - <div className="space-y-2"> - <Label htmlFor="email">Email</Label> - <Input - id="email" - type="email" - placeholder="m@example.com" - value={email} - onChange={(e) => setEmail(e.target.value)} - /> - </div> - <div className="space-y-2"> - <Label htmlFor="password">Password</Label> - <Input - id="password" - type="password" - value={password} - onChange={(e) => setPassword(e.target.value)} - /> - </div> - <Button onClick={handleLogin}>Login</Button> - </div> - ); -} - -export default function LoginPage() { - return ( - <div className="flex h-screen items-center justify-center"> - <Card className="w-[350px]"> - <CardHeader> - <CardTitle>Login</CardTitle> - <CardDescription> - Enter your email and password to login. - </CardDescription> - </CardHeader> - <CardContent> - <Suspense fallback={<div>Loading...</div>}> - <LoginForm /> - </Suspense> - <div className="mt-4 text-center text-sm"> - Don't have an account?{" "} - <Link href="/auth/signup" className="underline"> - Sign up - </Link> - </div> - </CardContent> - </Card> - </div> - ); -} diff --git a/apps/web/src/app/auth/signup/page.tsx b/apps/web/src/app/auth/signup/page.tsx deleted file mode 100644 index f328851c..00000000 --- a/apps/web/src/app/auth/signup/page.tsx +++ /dev/null @@ -1,108 +0,0 @@ -"use client"; - -import { useSearchParams, useRouter } from "next/navigation"; -import { authClient } from "@/lib/auth-client"; -import { Button } from "@/components/ui/button"; -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card"; -import { Suspense, useState } from "react"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import Link from "next/link"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; - -function SignUpForm() { - const searchParams = useSearchParams(); - const router = useRouter(); - const redirectUrl = searchParams.get("redirect"); - const [name, setName] = useState(""); - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [error, setError] = useState<string | null>(null); - - const handleSignUp = async () => { - setError(null); - const { error } = await authClient.signUp.email({ - name, - email, - password, - }); - - if (error) { - setError(error.message || "An unexpected error occurred."); - return; - } - - router.push(redirectUrl || "/"); - }; - - return ( - <div className="flex flex-col space-y-4"> - {error && ( - <Alert variant="destructive"> - <AlertTitle>Error</AlertTitle> - <AlertDescription>{error}</AlertDescription> - </Alert> - )} - <div className="space-y-2"> - <Label htmlFor="name">Name</Label> - <Input - id="name" - type="text" - placeholder="John Doe" - value={name} - onChange={(e) => setName(e.target.value)} - /> - </div> - <div className="space-y-2"> - <Label htmlFor="email">Email</Label> - <Input - id="email" - type="email" - placeholder="m@example.com" - value={email} - onChange={(e) => setEmail(e.target.value)} - /> - </div> - <div className="space-y-2"> - <Label htmlFor="password">Password</Label> - <Input - id="password" - type="password" - value={password} - onChange={(e) => setPassword(e.target.value)} - /> - </div> - <Button onClick={handleSignUp}>Sign Up</Button> - </div> - ); -} - -export default function SignUpPage() { - return ( - <div className="flex h-screen items-center justify-center"> - <Card className="w-[350px]"> - <CardHeader> - <CardTitle>Sign Up</CardTitle> - <CardDescription>Create an account to get started.</CardDescription> - </CardHeader> - <CardContent> - <Suspense fallback={<div>Loading...</div>}> - <SignUpForm /> - </Suspense> - <div className="mt-4 text-center text-sm"> - Already have an account?{" "} - <Link href="/auth/login" className="underline"> - Login - </Link> - </div> - </CardContent> - </Card> - </div> - ); -} diff --git a/apps/web/src/app/editor/editor.css b/apps/web/src/app/editor/editor.css new file mode 100644 index 00000000..f482c6de --- /dev/null +++ b/apps/web/src/app/editor/editor.css @@ -0,0 +1,4 @@ +/* Prevent scroll jumping on Mac devices when using the editor */ +body { + overflow: hidden; +}
\ No newline at end of file diff --git a/apps/web/src/app/editor/page.tsx b/apps/web/src/app/editor/page.tsx index 2f825a22..e0013937 100644 --- a/apps/web/src/app/editor/page.tsx +++ b/apps/web/src/app/editor/page.tsx @@ -1,13 +1,14 @@ "use client"; import { useEffect } from "react"; +import "./editor.css"; import { ResizablePanelGroup, ResizablePanel, ResizableHandle, } from "../../components/ui/resizable"; import { MediaPanel } from "../../components/editor/media-panel"; -import { PropertiesPanel } from "../../components/editor/properties-panel"; +// import { PropertiesPanel } from "../../components/editor/properties-panel"; import { Timeline } from "../../components/editor/timeline"; import { PreviewPanel } from "../../components/editor/preview-panel"; import { EditorHeader } from "@/components/editor-header"; @@ -42,59 +43,71 @@ export default function Editor() { return ( <EditorProvider> - <div className="h-screen w-screen flex flex-col bg-background"> + <div className="h-screen w-screen flex flex-col bg-background overflow-hidden"> <EditorHeader /> - <ResizablePanelGroup direction="vertical"> - <ResizablePanel - defaultSize={mainContent} - minSize={30} - onResize={setMainContent} - > - {/* Main content area */} - <ResizablePanelGroup direction="horizontal"> - {/* Tools Panel */} - <ResizablePanel - defaultSize={toolsPanel} - minSize={15} - onResize={setToolsPanel} - > - <MediaPanel /> - </ResizablePanel> + <div className="flex-1 min-h-0 min-w-0"> + <ResizablePanelGroup direction="vertical" className="h-full w-full"> + <ResizablePanel + defaultSize={mainContent} + minSize={30} + maxSize={85} + onResize={setMainContent} + className="min-h-0" + > + {/* Main content area */} + <ResizablePanelGroup direction="horizontal" className="h-full w-full"> + {/* Tools Panel */} + <ResizablePanel + defaultSize={toolsPanel} + minSize={15} + maxSize={40} + onResize={setToolsPanel} + className="min-w-0" + > + <MediaPanel /> + </ResizablePanel> - <ResizableHandle withHandle /> + <ResizableHandle withHandle /> - {/* Preview Area */} - <ResizablePanel - defaultSize={previewPanel} - onResize={setPreviewPanel} - > - <PreviewPanel /> - </ResizablePanel> + {/* Preview Area */} + <ResizablePanel + defaultSize={previewPanel} + minSize={30} + onResize={setPreviewPanel} + className="min-w-0 min-h-0 flex-1" + > + <PreviewPanel /> + </ResizablePanel> - <ResizableHandle withHandle /> + <ResizableHandle withHandle /> - {/* Properties Panel */} - <ResizablePanel - defaultSize={propertiesPanel} - minSize={15} - onResize={setPropertiesPanel} - > - <PropertiesPanel /> - </ResizablePanel> - </ResizablePanelGroup> - </ResizablePanel> + {/* Properties Panel - Hidden for now but ready */} + {/* <ResizablePanel + defaultSize={propertiesPanel} + minSize={15} + maxSize={40} + onResize={setPropertiesPanel} + className="min-w-0" + > + <PropertiesPanel /> + </ResizablePanel> */} + </ResizablePanelGroup> + </ResizablePanel> - <ResizableHandle withHandle /> + <ResizableHandle withHandle /> - {/* Timeline */} - <ResizablePanel - defaultSize={timeline} - minSize={15} - onResize={setTimeline} - > - <Timeline /> - </ResizablePanel> - </ResizablePanelGroup> + {/* Timeline */} + <ResizablePanel + defaultSize={timeline} + minSize={15} + maxSize={70} + onResize={setTimeline} + className="min-h-0" + > + <Timeline /> + </ResizablePanel> + </ResizablePanelGroup> + </div> </div> </EditorProvider> ); diff --git a/apps/web/src/app/favicon.ico b/apps/web/src/app/favicon.ico Binary files differindex 66b4ee0f..cb20127b 100644 --- a/apps/web/src/app/favicon.ico +++ b/apps/web/src/app/favicon.ico diff --git a/apps/web/src/components/auth-form.tsx b/apps/web/src/components/auth-form.tsx new file mode 100644 index 00000000..e0f8af2f --- /dev/null +++ b/apps/web/src/components/auth-form.tsx @@ -0,0 +1,398 @@ +"use client";
+
+import { useRouter } from "next/navigation";
+import { signUp, signIn } from "@opencut/auth/client";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { useState } from "react";
+import { Input } from "@/components/ui/input";
+import { Separator } from "@/components/ui/separator";
+import Link from "next/link";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { ArrowLeft, Loader2 } from "lucide-react";
+import { GoogleIcon } from "@/components/icons";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+
+// Zod schemas
+const loginSchema = z.object({
+ email: z.string().email("Please enter a valid email address"),
+ password: z.string().min(1, "Password is required"),
+});
+
+const signupSchema = z.object({
+ name: z.string().min(2, "Name must be at least 2 characters"),
+ email: z.string().email("Please enter a valid email address"),
+ password: z.string().min(8, "Password must be at least 8 characters"),
+});
+
+type LoginFormData = z.infer<typeof loginSchema>;
+type SignupFormData = z.infer<typeof signupSchema>;
+
+interface AuthFormProps {
+ mode: "login" | "signup";
+}
+
+const authConfig = {
+ login: {
+ title: "Welcome back",
+ description: "Sign in to your account to continue",
+ buttonText: "Sign in",
+ linkText: "Don't have an account?",
+ linkHref: "/signup",
+ linkLabel: "Sign up",
+ successRedirect: "/editor",
+ },
+ signup: {
+ title: "Create your account",
+ description: "Get started with your free account today",
+ buttonText: "Create account",
+ linkText: "Already have an account?",
+ linkHref: "/login",
+ linkLabel: "Sign in",
+ successRedirect: "/login",
+ },
+} as const;
+
+interface AuthFormContentProps {
+ error: string | null;
+ setError: (error: string | null) => void;
+ isGoogleLoading: boolean;
+ config: typeof authConfig.login | typeof authConfig.signup;
+ router: ReturnType<typeof useRouter>;
+}
+
+function LoginFormContent({
+ error,
+ setError,
+ isGoogleLoading,
+ config,
+ router,
+}: AuthFormContentProps) {
+ const form = useForm<LoginFormData>({
+ resolver: zodResolver(loginSchema),
+ defaultValues: { email: "", password: "" },
+ });
+
+ const { isSubmitting } = form.formState;
+ const isAnyLoading = isSubmitting || isGoogleLoading;
+
+ const onSubmit = async (data: LoginFormData) => {
+ setError(null);
+
+ try {
+ const { error } = await signIn.email({
+ email: data.email,
+ password: data.password,
+ });
+
+ if (error) {
+ setError(error.message || "An unexpected error occurred.");
+ return;
+ }
+
+ router.push(config.successRedirect);
+ } catch (error) {
+ setError("An unexpected error occurred. Please try again.");
+ }
+ };
+
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <FormControl>
+ <Input
+ type="email"
+ placeholder="m@example.com"
+ disabled={isAnyLoading}
+ className="h-11"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Password</FormLabel>
+ <FormControl>
+ <Input
+ type="password"
+ disabled={isAnyLoading}
+ className="h-11"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <Button
+ type="submit"
+ disabled={isAnyLoading}
+ className="w-full h-11"
+ size="lg"
+ >
+ {isSubmitting ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ config.buttonText
+ )}
+ </Button>
+ </form>
+ </Form>
+ );
+}
+
+function SignupFormContent({
+ error,
+ setError,
+ isGoogleLoading,
+ config,
+ router,
+}: AuthFormContentProps) {
+ const form = useForm<SignupFormData>({
+ resolver: zodResolver(signupSchema),
+ defaultValues: { email: "", password: "", name: "" },
+ });
+
+ const { isSubmitting } = form.formState;
+ const isAnyLoading = isSubmitting || isGoogleLoading;
+
+ const onSubmit = async (data: SignupFormData) => {
+ setError(null);
+
+ try {
+ const { error } = await signUp.email({
+ name: data.name,
+ email: data.email,
+ password: data.password,
+ });
+
+ if (error) {
+ setError(error.message || "An unexpected error occurred.");
+ return;
+ }
+
+ router.push(config.successRedirect);
+ } catch (error) {
+ setError("An unexpected error occurred. Please try again.");
+ }
+ };
+
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Full Name</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="John Doe"
+ disabled={isAnyLoading}
+ className="h-11"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <FormControl>
+ <Input
+ type="email"
+ placeholder="m@example.com"
+ disabled={isAnyLoading}
+ className="h-11"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Password</FormLabel>
+ <FormControl>
+ <Input
+ type="password"
+ placeholder="Create a strong password"
+ disabled={isAnyLoading}
+ className="h-11"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <Button
+ type="submit"
+ disabled={isAnyLoading}
+ className="w-full h-11"
+ size="lg"
+ >
+ {isSubmitting ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ config.buttonText
+ )}
+ </Button>
+ </form>
+ </Form>
+ );
+}
+
+export function AuthForm({ mode }: AuthFormProps) {
+ const router = useRouter();
+ const [error, setError] = useState<string | null>(null);
+ const [isGoogleLoading, setIsGoogleLoading] = useState(false);
+ const config = authConfig[mode];
+
+ const handleGoogleAuth = async () => {
+ setError(null);
+ setIsGoogleLoading(true);
+
+ try {
+ await signIn.social({
+ provider: "google",
+ });
+
+ router.push(config.successRedirect);
+ } catch (error) {
+ setError(
+ `Failed to ${mode === "login" ? "sign in" : "sign up"} with Google. Please try again.`
+ );
+ setIsGoogleLoading(false);
+ }
+ };
+
+ return (
+ <div className="flex h-screen items-center justify-center relative">
+ <Button
+ variant="text"
+ onClick={() => router.back()}
+ className="absolute top-6 left-6"
+ >
+ <ArrowLeft className="h-5 w-5" /> Back
+ </Button>
+
+ <Card className="w-[400px] shadow-lg border-0">
+ <CardHeader className="text-center pb-4">
+ <CardTitle className="text-2xl font-semibold">
+ {config.title}
+ </CardTitle>
+ <CardDescription className="text-base">
+ {config.description}
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <div className="flex flex-col space-y-6">
+ {error && (
+ <Alert variant="destructive">
+ <AlertTitle>Error</AlertTitle>
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+
+ <Button
+ onClick={handleGoogleAuth}
+ variant="outline"
+ size="lg"
+ disabled={isGoogleLoading}
+ >
+ {isGoogleLoading ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <GoogleIcon />
+ )}
+ Continue with Google
+ </Button>
+
+ <div className="relative">
+ <div className="absolute inset-0 flex items-center">
+ <Separator className="w-full" />
+ </div>
+ <div className="relative flex justify-center text-xs uppercase">
+ <span className="bg-background px-2 text-muted-foreground">
+ Or continue with
+ </span>
+ </div>
+ </div>
+
+ {mode === "login" ? (
+ <LoginFormContent
+ error={error}
+ setError={setError}
+ isGoogleLoading={isGoogleLoading}
+ config={config}
+ router={router}
+ />
+ ) : (
+ <SignupFormContent
+ error={error}
+ setError={setError}
+ isGoogleLoading={isGoogleLoading}
+ config={config}
+ router={router}
+ />
+ )}
+ </div>
+
+ <div className="mt-6 text-center text-sm">
+ {config.linkText}{" "}
+ <Link
+ href={config.linkHref}
+ className="font-medium text-primary underline-offset-4 hover:underline"
+ >
+ {config.linkLabel}
+ </Link>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor-provider.tsx b/apps/web/src/components/editor-provider.tsx index ab55c7d7..38255956 100644 --- a/apps/web/src/components/editor-provider.tsx +++ b/apps/web/src/components/editor-provider.tsx @@ -3,7 +3,6 @@ import { useEffect } from "react";
import { Loader2 } from "lucide-react";
import { useEditorStore } from "@/stores/editor-store";
-import { usePanelStore } from "@/stores/panel-store";
interface EditorProviderProps {
children: React.ReactNode;
@@ -11,19 +10,10 @@ interface EditorProviderProps { export function EditorProvider({ children }: EditorProviderProps) {
const { isInitializing, isPanelsReady, initializeApp } = useEditorStore();
- const { setInitialized } = usePanelStore();
useEffect(() => {
- const initialize = async () => {
- // Initialize the app
- await initializeApp();
-
- // Initialize panel store for future resize events
- setInitialized();
- };
-
- initialize();
- }, [initializeApp, setInitialized]);
+ initializeApp();
+ }, [initializeApp]);
// Show loading screen while initializing
if (isInitializing || !isPanelsReady) {
diff --git a/apps/web/src/components/editor/preview-panel.tsx b/apps/web/src/components/editor/preview-panel.tsx index 132d6c06..624a549e 100644 --- a/apps/web/src/components/editor/preview-panel.tsx +++ b/apps/web/src/components/editor/preview-panel.tsx @@ -3,109 +3,112 @@ import { useTimelineStore } from "@/stores/timeline-store";
import { useMediaStore } from "@/stores/media-store";
import { usePlaybackStore } from "@/stores/playback-store";
-import { ImageTimelineTreatment } from "@/components/ui/image-timeline-treatment";
import { VideoPlayer } from "@/components/ui/video-player";
import { Button } from "@/components/ui/button";
import { Play, Pause } from "lucide-react";
+import { useState, useRef } from "react";
+
+// Debug flag - set to false to hide active clips info
+const SHOW_DEBUG_INFO = process.env.NODE_ENV === 'development';
export function PreviewPanel() {
const { tracks } = useTimelineStore();
const { mediaItems } = useMediaStore();
const { isPlaying, toggle, currentTime } = usePlaybackStore();
+ const [canvasSize, setCanvasSize] = useState({ width: 1920, height: 1080 });
+ const [showDebug, setShowDebug] = useState(SHOW_DEBUG_INFO);
+ const previewRef = useRef<HTMLDivElement>(null);
+
+ // Get active clips at current time
+ const getActiveClips = () => {
+ const activeClips: Array<{
+ clip: any;
+ track: any;
+ mediaItem: any;
+ }> = [];
- // Find the active clip at the current playback time
- const getActiveClip = () => {
- for (const track of tracks) {
- for (const clip of track.clips) {
+ tracks.forEach((track) => {
+ track.clips.forEach((clip) => {
const clipStart = clip.startTime;
const clipEnd = clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd);
if (currentTime >= clipStart && currentTime < clipEnd) {
- return clip;
+ const mediaItem = clip.mediaId === "test"
+ ? { type: "test", name: clip.name, url: "", thumbnailUrl: "" }
+ : mediaItems.find((item) => item.id === clip.mediaId);
+
+ if (mediaItem || clip.mediaId === "test") {
+ activeClips.push({ clip, track, mediaItem });
+ }
}
- }
- }
- return null;
- };
+ });
+ });
- const activeClip = getActiveClip();
- const activeMediaItem = activeClip
- ? mediaItems.find((item) => item.id === activeClip.mediaId)
- : null;
+ return activeClips;
+ };
- const aspectRatio = activeMediaItem?.aspectRatio || 16 / 9;
+ const activeClips = getActiveClips();
+ const aspectRatio = canvasSize.width / canvasSize.height;
- const renderContent = () => {
- if (!activeClip) {
- return (
- <div className="absolute inset-0 flex items-center justify-center text-muted-foreground/50">
- {tracks.length === 0 ? "Drop media to start editing" : "No clip at current time"}
- </div>
- );
- }
+ // Render a clip
+ const renderClip = (clipData: any, index: number) => {
+ const { clip, mediaItem } = clipData;
- // Handle test clips without media items
- if (!activeMediaItem && activeClip.mediaId === "test") {
+ // Test clips
+ if (!mediaItem || clip.mediaId === "test") {
return (
- <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-blue-500/20 to-purple-500/20">
+ <div
+ key={clip.id}
+ className="absolute inset-0 bg-gradient-to-br from-blue-500/20 to-purple-500/20 flex items-center justify-center"
+ >
<div className="text-center">
- <div className="text-6xl mb-4">🎬</div>
- <p className="text-muted-foreground">{activeClip.name}</p>
- <p className="text-xs text-muted-foreground/70 mt-2">Test clip for playback</p>
+ <div className="text-2xl mb-2">🎬</div>
+ <p className="text-xs text-white">{clip.name}</p>
</div>
</div>
);
}
- if (!activeMediaItem) {
+ // Video clips
+ if (mediaItem.type === "video") {
return (
- <div className="absolute inset-0 flex items-center justify-center text-muted-foreground/50">
- Media not found
+ <div key={clip.id} className="absolute inset-0">
+ <VideoPlayer
+ src={mediaItem.url}
+ poster={mediaItem.thumbnailUrl}
+ clipStartTime={clip.startTime}
+ trimStart={clip.trimStart}
+ trimEnd={clip.trimEnd}
+ clipDuration={clip.duration}
+ />
</div>
);
}
- if (activeMediaItem.type === "video") {
+ // Image clips
+ if (mediaItem.type === "image") {
return (
- <VideoPlayer
- src={activeMediaItem.url}
- poster={activeMediaItem.thumbnailUrl}
- className="w-full h-full"
- clipStartTime={activeClip.startTime}
- trimStart={activeClip.trimStart}
- trimEnd={activeClip.trimEnd}
- clipDuration={activeClip.duration}
- key={`${activeClip.id}-${activeClip.trimStart}-${activeClip.trimEnd}`}
- />
- );
- }
-
- if (activeMediaItem.type === "image") {
- return (
- <ImageTimelineTreatment
- src={activeMediaItem.url}
- alt={activeMediaItem.name}
- targetAspectRatio={aspectRatio}
- className="w-full h-full"
- backgroundType="blur"
- />
+ <div key={clip.id} className="absolute inset-0">
+ <img
+ src={mediaItem.url}
+ alt={mediaItem.name}
+ className="w-full h-full object-cover"
+ draggable={false}
+ />
+ </div>
);
}
- if (activeMediaItem.type === "audio") {
+ // Audio clips (visual representation)
+ if (mediaItem.type === "audio") {
return (
- <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-green-500/20 to-emerald-500/20">
+ <div
+ key={clip.id}
+ className="absolute inset-0 bg-gradient-to-br from-green-500/20 to-emerald-500/20 flex items-center justify-center"
+ >
<div className="text-center">
- <div className="text-6xl mb-4">🎵</div>
- <p className="text-muted-foreground">{activeMediaItem.name}</p>
- <Button
- variant="outline"
- className="mt-4"
- onClick={toggle}
- >
- {isPlaying ? <Pause className="h-4 w-4 mr-2" /> : <Play className="h-4 w-4 mr-2" />}
- {isPlaying ? "Pause" : "Play"}
- </Button>
+ <div className="text-2xl mb-2">🎵</div>
+ <p className="text-xs text-white">{mediaItem.name}</p>
</div>
</div>
);
@@ -114,29 +117,95 @@ export function PreviewPanel() { return null;
};
+ // Canvas presets
+ const canvasPresets = [
+ { name: "16:9 HD", width: 1920, height: 1080 },
+ { name: "16:9 4K", width: 3840, height: 2160 },
+ { name: "9:16 Mobile", width: 1080, height: 1920 },
+ { name: "1:1 Square", width: 1080, height: 1080 },
+ { name: "4:3 Standard", width: 1440, height: 1080 },
+ ];
+
return (
- <div className="h-full flex flex-col items-center justify-center p-4 overflow-hidden">
- <div
- className="bg-black rounded-lg shadow-lg relative overflow-hidden flex-shrink-0"
- style={{
- aspectRatio: aspectRatio.toString(),
- width: aspectRatio > 1 ? "100%" : "auto",
- height: aspectRatio <= 1 ? "100%" : "auto",
- maxWidth: "100%",
- maxHeight: "100%",
- }}
- >
- {renderContent()}
+ <div className="h-full w-full flex flex-col min-h-0 min-w-0">
+ {/* Controls */}
+ <div className="border-b p-2 flex items-center gap-2 text-xs flex-shrink-0">
+ <span className="text-muted-foreground">Canvas:</span>
+ <select
+ value={`${canvasSize.width}x${canvasSize.height}`}
+ onChange={(e) => {
+ const preset = canvasPresets.find(p => `${p.width}x${p.height}` === e.target.value);
+ if (preset) setCanvasSize({ width: preset.width, height: preset.height });
+ }}
+ className="bg-background border rounded px-2 py-1 text-xs"
+ >
+ {canvasPresets.map(preset => (
+ <option key={preset.name} value={`${preset.width}x${preset.height}`}>
+ {preset.name} ({preset.width}×{preset.height})
+ </option>
+ ))}
+ </select>
+
+ {/* Debug Toggle - Only show in development */}
+ {SHOW_DEBUG_INFO && (
+ <Button
+ variant="text"
+ size="sm"
+ onClick={() => setShowDebug(!showDebug)}
+ className="text-xs"
+ >
+ Debug {showDebug ? 'ON' : 'OFF'}
+ </Button>
+ )}
+
+ <Button variant="outline" size="sm" onClick={toggle} className="ml-auto">
+ {isPlaying ? <Pause className="h-3 w-3 mr-1" /> : <Play className="h-3 w-3 mr-1" />}
+ {isPlaying ? "Pause" : "Play"}
+ </Button>
</div>
- {activeMediaItem && (
- <div className="mt-4 text-center">
- <p className="text-sm text-muted-foreground">
- {activeMediaItem.name}
- </p>
- <p className="text-xs text-muted-foreground/70">
- {aspectRatio.toFixed(2)} • {aspectRatio > 1 ? "Landscape" : aspectRatio < 1 ? "Portrait" : "Square"}
- </p>
+ {/* Preview Area */}
+ <div className="flex-1 flex items-center justify-center p-2 sm:p-4 bg-gray-900 min-h-0 min-w-0">
+ <div
+ ref={previewRef}
+ className="relative overflow-hidden rounded-sm max-w-full max-h-full bg-black border border-gray-600"
+ style={{
+ aspectRatio: aspectRatio.toString(),
+ width: "100%",
+ height: "100%",
+ }}
+ >
+ {activeClips.length === 0 ? (
+ <div className="absolute inset-0 flex items-center justify-center text-white/50">
+ {tracks.length === 0 ? "Drop media to start editing" : "No clips at current time"}
+ </div>
+ ) : (
+ activeClips.map((clipData, index) => renderClip(clipData, index))
+ )}
+ </div>
+ </div>
+
+ {/* Debug Info Panel - Conditionally rendered */}
+ {showDebug && (
+ <div className="border-t bg-background p-2 flex-shrink-0">
+ <div className="text-xs font-medium mb-1">Debug: Active Clips ({activeClips.length})</div>
+ <div className="flex gap-2 overflow-x-auto">
+ {activeClips.map((clipData, index) => (
+ <div
+ key={clipData.clip.id}
+ className="flex items-center gap-1 px-2 py-1 bg-muted rounded text-xs whitespace-nowrap"
+ >
+ <span className="w-4 h-4 bg-primary/20 rounded text-center text-xs leading-4">
+ {index + 1}
+ </span>
+ <span>{clipData.clip.name}</span>
+ <span className="text-muted-foreground">({clipData.mediaItem?.type || 'test'})</span>
+ </div>
+ ))}
+ {activeClips.length === 0 && (
+ <span className="text-muted-foreground">No active clips</span>
+ )}
+ </div>
</div>
)}
</div>
diff --git a/apps/web/src/components/editor/properties-panel.tsx b/apps/web/src/components/editor/properties-panel.tsx index af80f464..c784dab8 100644 --- a/apps/web/src/components/editor/properties-panel.tsx +++ b/apps/web/src/components/editor/properties-panel.tsx @@ -1,197 +1,217 @@ -"use client";
-
-import { Input } from "../ui/input";
-import { Label } from "../ui/label";
-import { Slider } from "../ui/slider";
-import { ScrollArea } from "../ui/scroll-area";
-import { Separator } from "../ui/separator";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "../ui/select";
-import { useTimelineStore } from "@/stores/timeline-store";
-import { useMediaStore } from "@/stores/media-store";
-import { ImageTimelineTreatment } from "@/components/ui/image-timeline-treatment";
-import { useState } from "react";
-
-export function PropertiesPanel() {
- const { tracks } = useTimelineStore();
- const { mediaItems } = useMediaStore();
- const [backgroundType, setBackgroundType] = useState<
- "blur" | "mirror" | "color"
- >("blur");
- const [backgroundColor, setBackgroundColor] = useState("#000000");
-
- // Get the first image clip for preview (simplified)
- const firstImageClip = tracks
- .flatMap((track) => track.clips)
- .find((clip) => {
- const mediaItem = mediaItems.find((item) => item.id === clip.mediaId);
- return mediaItem?.type === "image";
- });
-
- const firstImageItem = firstImageClip
- ? mediaItems.find((item) => item.id === firstImageClip.mediaId)
- : null;
-
- return (
- <ScrollArea className="h-full">
- <div className="space-y-6 p-5">
- {/* Image Treatment - only show if an image is selected */}
- {firstImageItem && (
- <>
- <div className="space-y-4">
- <h3 className="text-sm font-medium">Image Treatment</h3>
- <div className="space-y-4">
- {/* Preview */}
- <div className="space-y-2">
- <Label>Preview</Label>
- <div className="w-full aspect-video max-w-48">
- <ImageTimelineTreatment
- src={firstImageItem.url}
- alt={firstImageItem.name}
- targetAspectRatio={16 / 9}
- className="rounded-sm border"
- backgroundType={backgroundType}
- backgroundColor={backgroundColor}
- />
- </div>
- </div>
-
- {/* Background Type */}
- <div className="space-y-2">
- <Label htmlFor="bg-type">Background Type</Label>
- <Select
- value={backgroundType}
- onValueChange={(value: any) => setBackgroundType(value)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Select background type" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="blur">Blur</SelectItem>
- <SelectItem value="mirror">Mirror</SelectItem>
- <SelectItem value="color">Solid Color</SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- {/* Background Color - only show for color type */}
- {backgroundType === "color" && (
- <div className="space-y-2">
- <Label htmlFor="bg-color">Background Color</Label>
- <div className="flex gap-2">
- <Input
- id="bg-color"
- type="color"
- value={backgroundColor}
- onChange={(e) => setBackgroundColor(e.target.value)}
- className="w-16 h-10 p-1"
- />
- <Input
- value={backgroundColor}
- onChange={(e) => setBackgroundColor(e.target.value)}
- placeholder="#000000"
- className="flex-1"
- />
- </div>
- </div>
- )}
- </div>
- </div>
-
- <Separator />
- </>
- )}
-
- {/* Transform */}
- <div className="space-y-4">
- <h3 className="text-sm font-medium">Transform</h3>
- <div className="space-y-2">
- <div className="grid grid-cols-2 gap-2">
- <div className="space-y-1">
- <Label htmlFor="x">X Position</Label>
- <Input id="x" type="number" defaultValue="0" />
- </div>
- <div className="space-y-1">
- <Label htmlFor="y">Y Position</Label>
- <Input id="y" type="number" defaultValue="0" />
- </div>
- </div>
- <div className="space-y-1">
- <Label htmlFor="rotation">Rotation</Label>
- <Slider
- id="rotation"
- max={360}
- step={1}
- defaultValue={[0]}
- className="mt-2"
- />
- </div>
- </div>
- </div>
-
- <Separator />
-
- {/* Effects */}
- <div className="space-y-4">
- <h3 className="text-sm font-medium">Effects</h3>
- <div className="space-y-4">
- <div className="space-y-1">
- <Label htmlFor="opacity">Opacity</Label>
- <Slider
- id="opacity"
- max={100}
- step={1}
- defaultValue={[100]}
- className="mt-2"
- />
- </div>
- <div className="space-y-1">
- <Label htmlFor="blur">Blur</Label>
- <Slider
- id="blur"
- max={20}
- step={0.5}
- defaultValue={[0]}
- className="mt-2"
- />
- </div>
- </div>
- </div>
-
- <Separator />
-
- {/* Timing */}
- <div className="space-y-4">
- <h3 className="text-sm font-medium">Timing</h3>
- <div className="space-y-2">
- <div className="space-y-1">
- <Label htmlFor="duration">Duration (seconds)</Label>
- <Input
- id="duration"
- type="number"
- min="0"
- step="0.1"
- defaultValue="5"
- />
- </div>
- <div className="space-y-1">
- <Label htmlFor="delay">Delay (seconds)</Label>
- <Input
- id="delay"
- type="number"
- min="0"
- step="0.1"
- defaultValue="0"
- />
- </div>
- </div>
- </div>
- </div>
- </ScrollArea>
- );
-}
+"use client"; + +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { Slider } from "../ui/slider"; +import { ScrollArea } from "../ui/scroll-area"; +import { Separator } from "../ui/separator"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "../ui/select"; +import { useTimelineStore } from "@/stores/timeline-store"; +import { useMediaStore } from "@/stores/media-store"; +import { ImageTimelineTreatment } from "@/components/ui/image-timeline-treatment"; +import { useState } from "react"; +import { SpeedControl } from "./speed-control"; + +export function PropertiesPanel() { + const { tracks } = useTimelineStore(); + const { mediaItems } = useMediaStore(); + const [backgroundType, setBackgroundType] = useState< + "blur" | "mirror" | "color" + >("blur"); + const [backgroundColor, setBackgroundColor] = useState("#000000"); + + // Get the first video clip for preview (simplified) + const firstVideoClip = tracks + .flatMap((track) => track.clips) + .find((clip) => { + const mediaItem = mediaItems.find((item) => item.id === clip.mediaId); + return mediaItem?.type === "video"; + }); + + const firstVideoItem = firstVideoClip + ? mediaItems.find((item) => item.id === firstVideoClip.mediaId) + : null; + + const firstImageClip = tracks + .flatMap((track) => track.clips) + .find((clip) => { + const mediaItem = mediaItems.find((item) => item.id === clip.mediaId); + return mediaItem?.type === "image"; + }); + + const firstImageItem = firstImageClip + ? mediaItems.find((item) => item.id === firstImageClip.mediaId) + : null; + + return ( + <ScrollArea className="h-full"> + <div className="space-y-6 p-5"> + {/* Image Treatment - only show if an image is selected */} + {firstImageItem && ( + <> + <div className="space-y-4"> + <h3 className="text-sm font-medium">Image Treatment</h3> + <div className="space-y-4"> + {/* Preview */} + <div className="space-y-2"> + <Label>Preview</Label> + <div className="w-full aspect-video max-w-48"> + <ImageTimelineTreatment + src={firstImageItem.url} + alt={firstImageItem.name} + targetAspectRatio={16 / 9} + className="rounded-sm border" + backgroundType={backgroundType} + backgroundColor={backgroundColor} + /> + </div> + </div> + + {/* Background Type */} + <div className="space-y-2"> + <Label htmlFor="bg-type">Background Type</Label> + <Select + value={backgroundType} + onValueChange={(value: any) => setBackgroundType(value)} + > + <SelectTrigger> + <SelectValue placeholder="Select background type" /> + </SelectTrigger> + <SelectContent> + <SelectItem value="blur">Blur</SelectItem> + <SelectItem value="mirror">Mirror</SelectItem> + <SelectItem value="color">Solid Color</SelectItem> + </SelectContent> + </Select> + </div> + + {/* Background Color - only show for color type */} + {backgroundType === "color" && ( + <div className="space-y-2"> + <Label htmlFor="bg-color">Background Color</Label> + <div className="flex gap-2"> + <Input + id="bg-color" + type="color" + value={backgroundColor} + onChange={(e) => setBackgroundColor(e.target.value)} + className="w-16 h-10 p-1" + /> + <Input + value={backgroundColor} + onChange={(e) => setBackgroundColor(e.target.value)} + placeholder="#000000" + className="flex-1" + /> + </div> + </div> + )} + </div> + </div> + + <Separator /> + </> + )} + + {/* Video Controls - only show if a video is selected */} + {firstVideoItem && ( + <> + <SpeedControl /> + <Separator /> + </> + )} + + {/* Transform */} + <div className="space-y-4"> + <h3 className="text-sm font-medium">Transform</h3> + <div className="space-y-2"> + <div className="grid grid-cols-2 gap-2"> + <div className="space-y-1"> + <Label htmlFor="x">X Position</Label> + <Input id="x" type="number" defaultValue="0" /> + </div> + <div className="space-y-1"> + <Label htmlFor="y">Y Position</Label> + <Input id="y" type="number" defaultValue="0" /> + </div> + </div> + <div className="space-y-1"> + <Label htmlFor="rotation">Rotation</Label> + <Slider + id="rotation" + max={360} + step={1} + defaultValue={[0]} + className="mt-2" + /> + </div> + </div> + </div> + + <Separator /> + + {/* Effects */} + <div className="space-y-4"> + <h3 className="text-sm font-medium">Effects</h3> + <div className="space-y-4"> + <div className="space-y-1"> + <Label htmlFor="opacity">Opacity</Label> + <Slider + id="opacity" + max={100} + step={1} + defaultValue={[100]} + className="mt-2" + /> + </div> + <div className="space-y-1"> + <Label htmlFor="blur">Blur</Label> + <Slider + id="blur" + max={20} + step={0.5} + defaultValue={[0]} + className="mt-2" + /> + </div> + </div> + </div> + + <Separator /> + + {/* Timing */} + <div className="space-y-4"> + <h3 className="text-sm font-medium">Timing</h3> + <div className="space-y-2"> + <div className="space-y-1"> + <Label htmlFor="duration">Duration (seconds)</Label> + <Input + id="duration" + type="number" + min="0" + step="0.1" + defaultValue="5" + /> + </div> + <div className="space-y-1"> + <Label htmlFor="delay">Delay (seconds)</Label> + <Input + id="delay" + type="number" + min="0" + step="0.1" + defaultValue="0" + /> + </div> + </div> + </div> + </div> + </ScrollArea> + ); +} diff --git a/apps/web/src/components/editor/speed-control.tsx b/apps/web/src/components/editor/speed-control.tsx new file mode 100644 index 00000000..39281a9a --- /dev/null +++ b/apps/web/src/components/editor/speed-control.tsx @@ -0,0 +1,46 @@ +import { Slider } from "../ui/slider"; +import { Label } from "../ui/label"; +import { Button } from "../ui/button"; +import { usePlaybackStore } from "@/stores/playback-store"; + +const SPEED_PRESETS = [ + { label: "0.5x", value: 0.5 }, + { label: "1x", value: 1.0 }, + { label: "1.5x", value: 1.5 }, + { label: "2x", value: 2.0 }, +]; + +export function SpeedControl() { + const { speed, setSpeed } = usePlaybackStore(); + + return ( + <div className="space-y-4"> + <h3 className="text-sm font-medium">Playback Speed</h3> + <div className="space-y-4"> + <div className="flex gap-2"> + {SPEED_PRESETS.map((preset) => ( + <Button + key={preset.value} + variant={speed === preset.value ? "default" : "outline"} + className="flex-1" + onClick={() => setSpeed(preset.value)} + > + {preset.label} + </Button> + ))} + </div> + <div className="space-y-1"> + <Label>Custom ({speed.toFixed(1)}x)</Label> + <Slider + value={[speed]} + min={0.1} + max={2.0} + step={0.1} + onValueChange={(value) => setSpeed(value[0])} + className="mt-2" + /> + </div> + </div> + </div> + ); +}
\ No newline at end of file diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index 1d2df66d..9dec5bbc 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -27,21 +27,29 @@ import { useMediaStore } from "@/stores/media-store"; import { usePlaybackStore } from "@/stores/playback-store";
import { processMediaFiles } from "@/lib/media-processing";
import { toast } from "sonner";
-import { useState, useRef, useEffect } from "react";
+import { useState, useRef, useEffect, useCallback } from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "../ui/select";
export function Timeline() {
// Timeline shows all tracks (video, audio, effects) and their clips.
// You can drag media here to add it to your project.
// Clips can be trimmed, deleted, and moved.
- const { tracks, addTrack, addClipToTrack, removeTrack, toggleTrackMute, removeClipFromTrack, moveClipToTrack, getTotalDuration } =
+ const { tracks, addTrack, addClipToTrack, removeTrack, toggleTrackMute, removeClipFromTrack, moveClipToTrack, getTotalDuration, selectedClips, selectClip, deselectClip, clearSelectedClips, setSelectedClips, updateClipTrim, undo, redo } =
useTimelineStore();
const { mediaItems, addMediaItem } = useMediaStore();
- const { currentTime, duration, seek, setDuration, isPlaying, play, pause, toggle } = usePlaybackStore();
+ const { currentTime, duration, seek, setDuration, isPlaying, play, pause, toggle, setSpeed, speed } = usePlaybackStore();
const [isDragOver, setIsDragOver] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
const [zoomLevel, setZoomLevel] = useState(1);
const dragCounterRef = useRef(0);
const timelineRef = useRef<HTMLDivElement>(null);
+ const [isInTimeline, setIsInTimeline] = useState(false);
// Unified context menu state
const [contextMenu, setContextMenu] = useState<{
@@ -52,6 +60,20 @@ export function Timeline() { y: number;
} | null>(null);
+ // Marquee selection state
+ const [marquee, setMarquee] = useState<{
+ startX: number;
+ startY: number;
+ endX: number;
+ endY: number;
+ active: boolean;
+ additive: boolean;
+ } | null>(null);
+
+ // Playhead scrubbing state
+ const [isScrubbing, setIsScrubbing] = useState(false);
+ const [scrubTime, setScrubTime] = useState<number | null>(null);
+
// Update timeline duration when tracks change
useEffect(() => {
const totalDuration = getTotalDuration();
@@ -67,6 +89,133 @@ export function Timeline() { }
}, [contextMenu]);
+ // Keyboard event for deleting selected clips
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if ((e.key === "Delete" || e.key === "Backspace") && selectedClips.length > 0) {
+ selectedClips.forEach(({ trackId, clipId }) => {
+ removeClipFromTrack(trackId, clipId);
+ });
+ clearSelectedClips();
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [selectedClips, removeClipFromTrack, clearSelectedClips]);
+
+ // Keyboard event for undo (Cmd+Z)
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "z" && !e.shiftKey) {
+ e.preventDefault();
+ undo();
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [undo]);
+
+ // Keyboard event for redo (Cmd+Shift+Z or Cmd+Y)
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "z" && e.shiftKey) {
+ e.preventDefault();
+ redo();
+ } else if ((e.metaKey || e.ctrlKey) && e.key === "y") {
+ e.preventDefault();
+ redo();
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [redo]);
+
+ // Mouse down on timeline background to start marquee
+ const handleTimelineMouseDown = (e: React.MouseEvent) => {
+ if (e.target === e.currentTarget && e.button === 0) {
+ setMarquee({
+ startX: e.clientX,
+ startY: e.clientY,
+ endX: e.clientX,
+ endY: e.clientY,
+ active: true,
+ additive: e.metaKey || e.ctrlKey || e.shiftKey,
+ });
+ }
+ };
+
+ // Mouse move to update marquee
+ useEffect(() => {
+ if (!marquee || !marquee.active) return;
+ const handleMouseMove = (e: MouseEvent) => {
+ setMarquee((prev) => prev && { ...prev, endX: e.clientX, endY: e.clientY });
+ };
+ const handleMouseUp = (e: MouseEvent) => {
+ setMarquee((prev) => prev && { ...prev, endX: e.clientX, endY: e.clientY, active: false });
+ };
+ window.addEventListener("mousemove", handleMouseMove);
+ window.addEventListener("mouseup", handleMouseUp);
+ return () => {
+ window.removeEventListener("mousemove", handleMouseMove);
+ window.removeEventListener("mouseup", handleMouseUp);
+ };
+ }, [marquee]);
+
+ // On marquee end, select clips in box
+ useEffect(() => {
+ if (!marquee || marquee.active) return;
+ const timeline = timelineRef.current;
+ if (!timeline) return;
+ const rect = timeline.getBoundingClientRect();
+ const x1 = Math.min(marquee.startX, marquee.endX) - rect.left;
+ const x2 = Math.max(marquee.startX, marquee.endX) - rect.left;
+ const y1 = Math.min(marquee.startY, marquee.endY) - rect.top;
+ const y2 = Math.max(marquee.startY, marquee.endY) - rect.top;
+ // Validation: skip if too small
+ if (Math.abs(x2 - x1) < 5 || Math.abs(y2 - y1) < 5) {
+ setMarquee(null);
+ return;
+ }
+ // Clamp to timeline bounds
+ const clamp = (val: number, min: number, max: number) => Math.max(min, Math.min(max, val));
+ const bx1 = clamp(x1, 0, rect.width);
+ const bx2 = clamp(x2, 0, rect.width);
+ const by1 = clamp(y1, 0, rect.height);
+ const by2 = clamp(y2, 0, rect.height);
+ let newSelection: { trackId: string; clipId: string }[] = [];
+ tracks.forEach((track, trackIdx) => {
+ track.clips.forEach((clip) => {
+ const effectiveDuration = clip.duration - clip.trimStart - clip.trimEnd;
+ const clipWidth = Math.max(80, effectiveDuration * 50 * zoomLevel);
+ const clipLeft = clip.startTime * 50 * zoomLevel;
+ const clipTop = trackIdx * 60;
+ const clipBottom = clipTop + 60;
+ const clipRight = clipLeft + clipWidth;
+ if (
+ bx1 < clipRight &&
+ bx2 > clipLeft &&
+ by1 < clipBottom &&
+ by2 > clipTop
+ ) {
+ newSelection.push({ trackId: track.id, clipId: clip.id });
+ }
+ });
+ });
+ if (newSelection.length > 0) {
+ if (marquee.additive) {
+ const selectedSet = new Set(selectedClips.map((c) => c.trackId + ':' + c.clipId));
+ newSelection = [
+ ...selectedClips,
+ ...newSelection.filter((c) => !selectedSet.has(c.trackId + ':' + c.clipId)),
+ ];
+ }
+ setSelectedClips(newSelection);
+ } else if (!marquee.additive) {
+ clearSelectedClips();
+ }
+ setMarquee(null);
+ }, [marquee, tracks, zoomLevel, selectedClips, setSelectedClips, clearSelectedClips]);
+
const handleDragEnter = (e: React.DragEvent) => {
// When something is dragged over the timeline, show overlay
e.preventDefault();
@@ -173,25 +322,69 @@ export function Timeline() { }
};
- const handleTimelineClick = (e: React.MouseEvent) => {
- const timeline = timelineRef.current;
- if (!timeline || duration === 0) return;
-
- const rect = timeline.getBoundingClientRect();
- const x = e.clientX - rect.left;
- const timelineWidth = rect.width;
- const visibleDuration = duration / zoomLevel;
- const clickedTime = (x / timelineWidth) * visibleDuration;
+ const handleSeekToPosition = (e: React.MouseEvent) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const clickX = e.clientX - rect.left;
+ const clickedTime = clickX / (50 * zoomLevel);
+ const clampedTime = Math.max(0, Math.min(duration, clickedTime));
+
+ seek(clampedTime);
+ };
- seek(Math.max(0, Math.min(duration, clickedTime)));
+ const handleTimelineAreaClick = (e: React.MouseEvent) => {
+ if (e.target === e.currentTarget) {
+ clearSelectedClips();
+
+ // Calculate the clicked time position and seek to it
+ handleSeekToPosition(e);
+ }
};
const handleWheel = (e: React.WheelEvent) => {
- e.preventDefault();
- const delta = e.deltaY > 0 ? -0.05 : 0.05;
- setZoomLevel((prev) => Math.max(0.1, Math.min(10, prev + delta)));
+ // Only zoom if user is using pinch gesture (ctrlKey or metaKey is true)
+ if (e.ctrlKey || e.metaKey) {
+ e.preventDefault();
+ const delta = e.deltaY > 0 ? -0.05 : 0.05;
+ setZoomLevel((prev) => Math.max(0.1, Math.min(10, prev + delta)));
+ }
+ // Otherwise, allow normal scrolling
};
+ // --- Playhead Scrubbing Handlers ---
+ const handlePlayheadMouseDown = useCallback((e: React.MouseEvent) => {
+ e.preventDefault();
+ setIsScrubbing(true);
+ handleScrub(e);
+ }, [duration, zoomLevel]);
+
+ const handleScrub = useCallback((e: MouseEvent | React.MouseEvent) => {
+ const timeline = timelineRef.current;
+ if (!timeline) return;
+ const rect = timeline.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ const time = Math.max(0, Math.min(duration, x / (50 * zoomLevel)));
+ setScrubTime(time);
+ seek(time); // update video preview in real time
+ }, [duration, zoomLevel, seek]);
+
+ useEffect(() => {
+ if (!isScrubbing) return;
+ const onMouseMove = (e: MouseEvent) => handleScrub(e);
+ const onMouseUp = (e: MouseEvent) => {
+ setIsScrubbing(false);
+ if (scrubTime !== null) seek(scrubTime); // finalize seek
+ setScrubTime(null);
+ };
+ window.addEventListener("mousemove", onMouseMove);
+ window.addEventListener("mouseup", onMouseUp);
+ return () => {
+ window.removeEventListener("mousemove", onMouseMove);
+ window.removeEventListener("mouseup", onMouseUp);
+ };
+ }, [isScrubbing, scrubTime, seek, handleScrub]);
+
+ const playheadPosition = isScrubbing && scrubTime !== null ? scrubTime : currentTime;
+
const dragProps = {
onDragEnter: handleDragEnter,
onDragOver: handleDragOver,
@@ -199,10 +392,116 @@ export function Timeline() { onDrop: handleDrop,
};
+ // Action handlers for toolbar
+ const handleSplitSelected = () => {
+ if (selectedClips.length === 0) {
+ toast.error("No clips selected");
+ return;
+ }
+ selectedClips.forEach(({ trackId, clipId }) => {
+ const track = tracks.find(t => t.id === trackId);
+ const clip = track?.clips.find(c => c.id === clipId);
+ if (clip && track) {
+ const splitTime = currentTime;
+ const effectiveStart = clip.startTime;
+ const effectiveEnd = clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd);
+ if (splitTime > effectiveStart && splitTime < effectiveEnd) {
+ updateClipTrim(track.id, clip.id, clip.trimStart, clip.trimEnd + (effectiveEnd - splitTime));
+ addClipToTrack(track.id, {
+ mediaId: clip.mediaId,
+ name: clip.name + " (split)",
+ duration: clip.duration,
+ startTime: splitTime,
+ trimStart: clip.trimStart + (splitTime - effectiveStart),
+ trimEnd: clip.trimEnd,
+ });
+ }
+ }
+ });
+ toast.success("Split selected clip(s)");
+ };
+
+ const handleDuplicateSelected = () => {
+ if (selectedClips.length === 0) {
+ toast.error("No clips selected");
+ return;
+ }
+ selectedClips.forEach(({ trackId, clipId }) => {
+ const track = tracks.find(t => t.id === trackId);
+ const clip = track?.clips.find(c => c.id === clipId);
+ if (clip && track) {
+ addClipToTrack(track.id, {
+ mediaId: clip.mediaId,
+ name: clip.name + " (copy)",
+ duration: clip.duration,
+ startTime: clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd) + 0.1,
+ trimStart: clip.trimStart,
+ trimEnd: clip.trimEnd,
+ });
+ }
+ });
+ toast.success("Duplicated selected clip(s)");
+ };
+
+ const handleFreezeSelected = () => {
+ if (selectedClips.length === 0) {
+ toast.error("No clips selected");
+ return;
+ }
+ selectedClips.forEach(({ trackId, clipId }) => {
+ const track = tracks.find(t => t.id === trackId);
+ const clip = track?.clips.find(c => c.id === clipId);
+ if (clip && track) {
+ // Add a new freeze frame clip at the playhead
+ addClipToTrack(track.id, {
+ mediaId: clip.mediaId,
+ name: clip.name + " (freeze)",
+ duration: 1, // 1 second freeze frame
+ startTime: currentTime,
+ trimStart: 0,
+ trimEnd: clip.duration - 1,
+ });
+ }
+ });
+ toast.success("Freeze frame added for selected clip(s)");
+ };
+
+ const handleDeleteSelected = () => {
+ if (selectedClips.length === 0) {
+ toast.error("No clips selected");
+ return;
+ }
+ selectedClips.forEach(({ trackId, clipId }) => {
+ removeClipFromTrack(trackId, clipId);
+ });
+ clearSelectedClips();
+ toast.success("Deleted selected clip(s)");
+ };
+
+
+ // Prevent explorer zooming in/out when in timeline
+ useEffect(() => {
+ const preventZoom = (e: WheelEvent) => {
+ // if (isInTimeline && (e.ctrlKey || e.metaKey)) {
+ if (isInTimeline && (e.ctrlKey || e.metaKey) && timelineRef.current?.contains(e.target as Node)) {
+ e.preventDefault();
+ }
+ };
+
+ document.addEventListener('wheel', preventZoom, { passive: false });
+
+ return () => {
+ document.removeEventListener('wheel', preventZoom);
+ };
+ }, [isInTimeline]);
+
return (
<div
className={`h-full flex flex-col transition-colors duration-200 relative ${isDragOver ? "bg-accent/30 border-accent" : ""}`}
{...dragProps}
+ onMouseEnter={() => setIsInTimeline(true)}
+ onMouseLeave={() => setIsInTimeline(false)}
+ onWheel={handleWheel}
>
{/* Show overlay when dragging media over the timeline */}
{isDragOver && (
@@ -220,7 +519,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
<Button
- variant="ghost"
+ variant="text"
size="icon"
onClick={toggle}
className="mr-2"
@@ -271,7 +570,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon" onClick={handleSplitSelected}>
<Scissors className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -280,7 +579,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon">
<ArrowLeftToLine className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -289,7 +588,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon">
<ArrowRightToLine className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -298,7 +597,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon">
<SplitSquareHorizontal className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -307,7 +606,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon" onClick={handleDuplicateSelected}>
<Copy className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -316,7 +615,7 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon" onClick={handleFreezeSelected}>
<Snowflake className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -325,12 +624,35 @@ export function Timeline() { <Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon">
+ <Button variant="text" size="icon" onClick={handleDeleteSelected}>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Delete clip (Delete)</TooltipContent>
</Tooltip>
+
+ <div className="w-px h-6 bg-border mx-1" />
+
+ {/* Speed Control */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Select
+ value={speed.toFixed(1)}
+ onValueChange={(value) => setSpeed(parseFloat(value))}
+ >
+ <SelectTrigger className="w-[90px] h-8">
+ <SelectValue placeholder="1.0x" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="0.5">0.5x</SelectItem>
+ <SelectItem value="1.0">1.0x</SelectItem>
+ <SelectItem value="1.5">1.5x</SelectItem>
+ <SelectItem value="2.0">2.0x</SelectItem>
+ </SelectContent>
+ </Select>
+ </TooltipTrigger>
+ <TooltipContent>Playback Speed</TooltipContent>
+ </Tooltip>
</TooltipProvider>
</div>
@@ -352,10 +674,14 @@ export function Timeline() { <div className="flex-1 relative overflow-hidden">
<ScrollArea className="w-full">
<div
- className="relative h-12 bg-muted/30"
+ className="relative h-12 bg-muted/30 cursor-pointer"
style={{
width: `${Math.max(1000, duration * 50 * zoomLevel)}px`,
}}
+ onClick={(e) => {
+ // Calculate the clicked time position and seek to it
+ handleSeekToPosition(e);
+ }}
>
{/* Time markers */}
{(() => {
@@ -420,10 +746,11 @@ export function Timeline() { }).filter(Boolean);
})()}
- {/* Playhead in ruler */}
+ {/* Playhead in ruler (scrubbable) */}
<div
- className="absolute top-0 bottom-0 w-0.5 bg-red-500 pointer-events-none z-10"
- style={{ left: `${currentTime * 50 * zoomLevel}px` }}
+ className="absolute top-0 bottom-0 w-0.5 bg-red-500 pointer-events-auto z-10 cursor-ew-resize"
+ style={{ left: `${playheadPosition * 50 * zoomLevel}px` }}
+ onMouseDown={handlePlayheadMouseDown}
>
<div className="absolute top-1 left-1/2 transform -translate-x-1/2 w-3 h-3 bg-red-500 rounded-full border-2 border-white shadow-sm" />
</div>
@@ -452,25 +779,35 @@ export function Timeline() { <div
key={track.id}
className="h-[60px] flex items-center px-3 border-b border-muted/30 bg-background group"
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setContextMenu({
+ type: 'track',
+ trackId: track.id,
+ x: e.clientX,
+ y: e.clientY,
+ });
+ }}
>
- <div className="flex items-center gap-2 flex-1 min-w-0">
+ <div className="flex items-center flex-1 min-w-0">
<div
- className={`w-3 h-3 rounded-full flex-shrink-0 ${track.type === "video"
- ? "bg-blue-500"
- : track.type === "audio"
+ className={`w-3 h-3 rounded-full flex-shrink-0 ${
+ track.type === "video"
+ ? "bg-blue-500"
+ : track.type === "audio"
? "bg-green-500"
: "bg-purple-500"
- }`}
+ }`}
/>
- <span className="text-sm font-medium truncate">
+ <span className="ml-2 text-sm font-medium truncate">
{track.name}
</span>
- {track.muted && (
- <span className="ml-2 text-xs text-red-500 font-semibold">
- Muted
- </span>
- )}
</div>
+ {track.muted && (
+ <span className="ml-2 text-xs text-red-500 font-semibold flex-shrink-0">
+ Muted
+ </span>
+ )}
</div>
))}
</div>
@@ -478,18 +815,17 @@ export function Timeline() { </div>
{/* Timeline Tracks Content */}
- <div className="flex-1 relative">
- <ScrollArea className="h-full w-full">
+ <div className="flex-1 relative overflow-hidden">
+ <div className="w-full h-[600px] overflow-hidden flex" ref={timelineRef} style={{ position: 'relative' }}>
+ {/* Timeline grid and clips area (with left margin for sidebar) */}
<div
- ref={timelineRef}
- className="relative cursor-pointer select-none"
+ className="relative flex-1"
style={{
+ height: `${tracks.length * 60}px`,
width: `${Math.max(1000, duration * 50 * zoomLevel)}px`,
- minHeight:
- tracks.length > 0 ? `${tracks.length * 60}px` : "200px",
}}
- onClick={handleTimelineClick}
- onWheel={handleWheel}
+ onClick={handleTimelineAreaClick}
+ onMouseDown={handleTimelineMouseDown}
>
{tracks.length === 0 ? (
<div className="absolute inset-0 flex items-center justify-center">
@@ -528,22 +864,24 @@ export function Timeline() { zoomLevel={zoomLevel}
setContextMenu={setContextMenu}
/>
-
</div>
))}
- {/* Playhead for tracks area */}
- <div
- className="absolute top-0 w-0.5 bg-red-500 pointer-events-none z-20"
- style={{
- left: `${currentTime * 50 * zoomLevel}px`,
- height: `${tracks.length * 60}px`,
- }}
- />
+ {/* Playhead for tracks area (scrubbable) */}
+ {tracks.length > 0 && (
+ <div
+ className="absolute top-0 w-0.5 bg-red-500 pointer-events-auto z-20 cursor-ew-resize"
+ style={{
+ left: `${playheadPosition * 50 * zoomLevel}px`,
+ height: `${tracks.length * 60}px`,
+ }}
+ onMouseDown={handlePlayheadMouseDown}
+ />
+ )}
</>
)}
</div>
- </ScrollArea>
+ </div>
</div>
</div>
</div>
@@ -609,7 +947,7 @@ export function Timeline() { const effectiveEnd = clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd);
if (splitTime > effectiveStart && splitTime < effectiveEnd) {
- useTimelineStore.getState().updateClipTrim(
+ updateClipTrim(
track.id,
clip.id,
clip.trimStart,
@@ -699,6 +1037,9 @@ function TimelineTrackContent({ addClipToTrack,
removeClipFromTrack,
toggleTrackMute,
+ selectedClips,
+ selectClip,
+ deselectClip,
} = useTimelineStore();
const { currentTime } = usePlaybackStore();
const [isDropping, setIsDropping] = useState(false);
@@ -1260,12 +1601,32 @@ function TimelineTrackContent({ effectiveDuration * 50 * zoomLevel
);
const clipLeft = clip.startTime * 50 * zoomLevel;
-
+ const isSelected = selectedClips.some(
+ (c) => c.trackId === track.id && c.clipId === clip.id
+ );
return (
<div
key={clip.id}
- className={`timeline-clip absolute h-full rounded-sm border transition-all duration-200 ${getTrackColor(track.type)} flex items-center py-3 min-w-[80px] overflow-hidden group hover:shadow-lg`}
+ className={`timeline-clip absolute h-full rounded-sm border transition-all duration-200 ${getTrackColor(track.type)} flex items-center py-3 min-w-[80px] overflow-hidden group hover:shadow-lg ${isSelected ? "ring-2 ring-blue-500 z-10" : ""}`}
style={{ width: `${clipWidth}px`, left: `${clipLeft}px` }}
+ onClick={(e) => {
+ e.stopPropagation();
+ const isSelected = selectedClips.some(
+ (c) => c.trackId === track.id && c.clipId === clip.id
+ );
+
+ if (e.metaKey || e.ctrlKey || e.shiftKey) {
+ // Multi-selection mode: toggle the clip
+ selectClip(track.id, clip.id, true);
+ } else if (isSelected) {
+ // If clip is already selected, deselect it
+ deselectClip(track.id, clip.id);
+ } else {
+ // If clip is not selected, select it (replacing other selections)
+ selectClip(track.id, clip.id, false);
+ }
+ }}
+ tabIndex={0}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -1294,7 +1655,7 @@ function TimelineTrackContent({ {/* Clip options menu */}
<div className="absolute top-1 right-1 z-10">
<Button
- variant="ghost"
+ variant="text"
size="icon"
className="opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => setClipMenuOpen(clip.id)}
@@ -1334,24 +1695,20 @@ function TimelineTrackContent({ {/* Drop position indicator */}
{isDraggedOver && dropPosition !== null && (
<div
- className={`absolute top-0 bottom-0 w-1 pointer-events-none z-30 transition-all duration-75 ease-out ${wouldOverlap ? "bg-red-500" : "bg-blue-500"
- }`}
+ className={`absolute top-0 bottom-0 w-1 pointer-events-none z-30 transition-all duration-75 ease-out ${wouldOverlap ? "bg-red-500" : "bg-blue-500"}`}
style={{
left: `${dropPosition * 50 * zoomLevel}px`,
transform: "translateX(-50%)",
}}
>
<div
- className={`absolute -top-2 left-1/2 transform -translate-x-1/2 w-3 h-3 rounded-full border-2 border-white shadow-md ${wouldOverlap ? "bg-red-500" : "bg-blue-500"
- }`}
+ className={`absolute -top-2 left-1/2 transform -translate-x-1/2 w-3 h-3 rounded-full border-2 border-white shadow-md ${wouldOverlap ? "bg-red-500" : "bg-blue-500"}`}
/>
<div
- className={`absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-3 h-3 rounded-full border-2 border-white shadow-md ${wouldOverlap ? "bg-red-500" : "bg-blue-500"
- }`}
+ className={`absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-3 h-3 rounded-full border-2 border-white shadow-md ${wouldOverlap ? "bg-red-500" : "bg-blue-500"}`}
/>
<div
- className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-xs text-white px-1 py-0.5 rounded whitespace-nowrap ${wouldOverlap ? "bg-red-500" : "bg-blue-500"
- }`}
+ className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-xs text-white px-1 py-0.5 rounded whitespace-nowrap ${wouldOverlap ? "bg-red-500" : "bg-blue-500"}`}
>
{wouldOverlap ? "⚠️" : ""}
{dropPosition.toFixed(1)}s
@@ -1363,4 +1720,4 @@ function TimelineTrackContent({ </div>
</div>
);
-}
\ No newline at end of file +}
diff --git a/apps/web/src/components/header.tsx b/apps/web/src/components/header.tsx index 004863d9..8c3ce610 100644 --- a/apps/web/src/components/header.tsx +++ b/apps/web/src/components/header.tsx @@ -5,8 +5,28 @@ import Image from "next/image"; import { Button } from "./ui/button";
import { ArrowRight } from "lucide-react";
import { HeaderBase } from "./header-base";
+import { useSession } from "@opencut/auth/client";
+import { getStars } from "@/lib/fetchGhStars";
+import { Star } from "lucide-react";
+import { useEffect, useState } from "react";
export function Header() {
+ const { data: session } = useSession();
+ const [star, setStar] = useState<string>("");
+
+ useEffect(() => {
+ const fetchStars = async () => {
+ try {
+ const data = await getStars();
+ setStar(data);
+ } catch (err) {
+ console.error("Failed to fetch GitHub stars", err);
+ }
+ };
+
+ fetchStars();
+ }, []);
+
const leftContent = (
<Link href="/" className="flex items-center gap-3">
<Image src="/logo.png" alt="OpenCut Logo" width={24} height={24} />
@@ -17,11 +37,18 @@ export function Header() { const rightContent = (
<nav className="flex items-center">
<Link href="https://github.com/OpenCut-app/OpenCut" target="_blank">
- <Button variant="ghost" className="text-sm">
- GitHub
+ <Button
+ variant="text"
+ className="flex items-center text-sm text-muted-foreground hover:text-foreground"
+ >
+ <span className="hidden sm:inline">GitHub</span>
+ <span className="text-foreground flex items-center">
+ {star}+
+ <Star className="w-4 h-4 ml-1" />
+ </span>
</Button>
</Link>
- <Link href="/editor">
+ <Link href={session ? "/editor" : "/login"}>
<Button size="sm" className="text-sm ml-4">
Start editing
<ArrowRight className="h-4 w-4" />
diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsx new file mode 100644 index 00000000..5cc24157 --- /dev/null +++ b/apps/web/src/components/icons.tsx @@ -0,0 +1,22 @@ +export function GoogleIcon({ className }: { className?: string }) { + return ( + <svg className={className} viewBox="0 0 24 24"> + <path + fill="#4285F4" + d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" + /> + <path + fill="#34A853" + d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" + /> + <path + fill="#FBBC05" + d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" + /> + <path + fill="#EA4335" + d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" + /> + </svg> + ); +} diff --git a/apps/web/src/components/landing/hero.tsx b/apps/web/src/components/landing/hero.tsx index f2c70f5d..7b2586c3 100644 --- a/apps/web/src/components/landing/hero.tsx +++ b/apps/web/src/components/landing/hero.tsx @@ -5,18 +5,33 @@ import { Button } from "../ui/button"; import { Input } from "../ui/input";
import { ArrowRight } from "lucide-react";
import Link from "next/link";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useToast } from "@/hooks/use-toast";
+import { getStars } from "@/lib/fetchGhStars";
interface HeroProps {
signupCount: number;
}
export function Hero({ signupCount }: HeroProps) {
+ const [star, setStar] = useState<string>();
const [email, setEmail] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const { toast } = useToast();
+ useEffect(() => {
+ const fetchStars = async () => {
+ try {
+ const data = await getStars();
+ setStar(data);
+ } catch (err) {
+ console.error("Failed to fetch GitHub stars", err);
+ }
+ };
+
+ fetchStars();
+ }, []);
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -67,7 +82,7 @@ export function Hero({ signupCount }: HeroProps) { };
return (
- <div className="relative min-h-screen flex flex-col items-center justify-center text-center px-4">
+ <div className="relative min-h-[calc(100vh-4rem)] flex flex-col items-center justify-center text-center px-4">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
@@ -84,12 +99,12 @@ export function Hero({ signupCount }: HeroProps) { The open source
</h1>
<h1 className="text-5xl sm:text-7xl font-bold tracking-tighter mt-2">
- CapCut alternative.
+ video editor
</h1>
</motion.div>
<motion.p
- className="mt-12 text-lg sm:text-xl text-muted-foreground font-light tracking-wide max-w-xl mx-auto"
+ className="mt-10 text-lg sm:text-xl text-muted-foreground font-light tracking-wide max-w-xl mx-auto"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.4, duration: 0.8 }}
@@ -152,7 +167,7 @@ export function Hero({ signupCount }: HeroProps) { href="https://github.com/OpenCut-app/OpenCut"
className="text-foreground underline"
>
- GitHub
+ GitHub {star}+
</Link>
</motion.div>
</div>
diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx index f5863e20..d4406d5b 100644 --- a/apps/web/src/components/ui/button.tsx +++ b/apps/web/src/components/ui/button.tsx @@ -17,7 +17,7 @@ const buttonVariants = cva( "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", - ghost: "hover:bg-accent hover:text-accent-foreground", + text: "bg-transparent p-0 rounded-none hover:text-muted-foreground", // Instead of ghost (matches app better) link: "text-primary underline-offset-4 hover:underline", }, size: { diff --git a/apps/web/src/components/ui/calendar.tsx b/apps/web/src/components/ui/calendar.tsx index 2dca9b14..192643cb 100644 --- a/apps/web/src/components/ui/calendar.tsx +++ b/apps/web/src/components/ui/calendar.tsx @@ -43,7 +43,7 @@ function Calendar({ : "[&:has([aria-selected])]:rounded-md" ), day: cn( - buttonVariants({ variant: "ghost" }), + buttonVariants({ variant: "text" }), "h-8 w-8 p-0 font-normal aria-selected:opacity-100" ), day_range_start: "day-range-start", diff --git a/apps/web/src/components/ui/command.tsx b/apps/web/src/components/ui/command.tsx index 29f29cf2..11b27041 100644 --- a/apps/web/src/components/ui/command.tsx +++ b/apps/web/src/components/ui/command.tsx @@ -1,7 +1,7 @@ "use client"; import * as React from "react"; -import { type DialogProps } from "radix-ui"; +import { DialogProps } from "@radix-ui/react-dialog"; import { Command as CommandPrimitive } from "cmdk"; import { Search } from "lucide-react"; diff --git a/apps/web/src/components/ui/input.tsx b/apps/web/src/components/ui/input.tsx index 42f4c452..72314045 100644 --- a/apps/web/src/components/ui/input.tsx +++ b/apps/web/src/components/ui/input.tsx @@ -41,7 +41,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>( {showPasswordToggle && ( <Button type="button" - variant="ghost" + variant="text" size="icon" onClick={() => onShowPasswordChange?.(!showPassword)} className="absolute right-0 top-0 h-full px-3 text-muted-foreground hover:text-foreground" diff --git a/apps/web/src/components/ui/pagination.tsx b/apps/web/src/components/ui/pagination.tsx index 79fd268e..61766cec 100644 --- a/apps/web/src/components/ui/pagination.tsx +++ b/apps/web/src/components/ui/pagination.tsx @@ -49,7 +49,7 @@ const PaginationLink = ({ aria-current={isActive ? "page" : undefined} className={cn( buttonVariants({ - variant: isActive ? "outline" : "ghost", + variant: isActive ? "outline" : "text", size, }), className diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx index e69d8751..c1583503 100644 --- a/apps/web/src/components/ui/sidebar.tsx +++ b/apps/web/src/components/ui/sidebar.tsx @@ -269,7 +269,7 @@ const SidebarTrigger = React.forwardRef< <Button ref={ref} data-sidebar="trigger" - variant="ghost" + variant="text" size="icon" className={cn("h-8 w-8", className)} onClick={(event) => { diff --git a/apps/web/src/components/ui/video-player.tsx b/apps/web/src/components/ui/video-player.tsx index 0c4f8498..32a12916 100644 --- a/apps/web/src/components/ui/video-player.tsx +++ b/apps/web/src/components/ui/video-player.tsx @@ -1,8 +1,6 @@ "use client"; import { useRef, useEffect } from "react"; -import { Button } from "./button"; -import { Play, Pause, Volume2 } from "lucide-react"; import { usePlaybackStore } from "@/stores/playback-store"; interface VideoPlayerProps { @@ -25,113 +23,89 @@ export function VideoPlayer({ clipDuration }: VideoPlayerProps) { const videoRef = useRef<HTMLVideoElement>(null); - const { isPlaying, currentTime, volume, play, pause, setVolume } = usePlaybackStore(); + const { isPlaying, currentTime, volume, speed } = usePlaybackStore(); // Calculate if we're within this clip's timeline range const clipEndTime = clipStartTime + (clipDuration - trimStart - trimEnd); const isInClipRange = currentTime >= clipStartTime && currentTime < clipEndTime; - // Calculate the video's internal time based on timeline position - const videoTime = Math.max(trimStart, Math.min( - clipDuration - trimEnd, - currentTime - clipStartTime + trimStart - )); - + // Sync playback events useEffect(() => { const video = videoRef.current; - if (!video) return; + if (!video || !isInClipRange) return; const handleSeekEvent = (e: CustomEvent) => { - if (!isInClipRange) return; + // Always update video time, even if outside clip range const timelineTime = e.detail.time; - const newVideoTime = Math.max(trimStart, Math.min( + const videoTime = Math.max(trimStart, Math.min( clipDuration - trimEnd, timelineTime - clipStartTime + trimStart )); - video.currentTime = newVideoTime; + video.currentTime = videoTime; }; const handleUpdateEvent = (e: CustomEvent) => { - if (!isInClipRange) return; + // Always update video time, even if outside clip range const timelineTime = e.detail.time; - const targetVideoTime = Math.max(trimStart, Math.min( + const targetTime = Math.max(trimStart, Math.min( clipDuration - trimEnd, timelineTime - clipStartTime + trimStart )); - // Only sync if there's a significant difference - if (Math.abs(video.currentTime - targetVideoTime) > 0.2) { - video.currentTime = targetVideoTime; + if (Math.abs(video.currentTime - targetTime) > 0.5) { + video.currentTime = targetTime; } }; + const handleSpeed = (e: CustomEvent) => { + video.playbackRate = e.detail.speed; + }; + window.addEventListener("playback-seek", handleSeekEvent as EventListener); window.addEventListener("playback-update", handleUpdateEvent as EventListener); + window.addEventListener("playback-speed", handleSpeed as EventListener); return () => { window.removeEventListener("playback-seek", handleSeekEvent as EventListener); window.removeEventListener("playback-update", handleUpdateEvent as EventListener); + window.removeEventListener("playback-speed", handleSpeed as EventListener); }; }, [clipStartTime, trimStart, trimEnd, clipDuration, isInClipRange]); - // Sync video playback state - only play if in clip range + // Sync playback state useEffect(() => { const video = videoRef.current; if (!video) return; if (isPlaying && isInClipRange) { - video.play().catch(console.error); + video.play().catch(() => { }); } else { video.pause(); } }, [isPlaying, isInClipRange]); - // Sync volume + // Sync volume and speed useEffect(() => { const video = videoRef.current; if (!video) return; + video.volume = volume; - }, [volume]); + video.playbackRate = speed; + }, [volume, speed]); return ( - <div className={`relative group ${className}`}> - <video - ref={videoRef} - src={src} - poster={poster} - className="w-full h-full object-cover" - playsInline - preload="metadata" - /> - - <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none" /> - - <div className="absolute bottom-2 left-2 right-2 flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity"> - <Button - variant="ghost" - size="icon" - className="h-8 w-8 bg-black/50 text-white hover:bg-black/70" - onClick={isPlaying ? pause : play} - > - {isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />} - </Button> - - <div className="flex-1 h-1 bg-white/30 rounded-full overflow-hidden"> - <div - className="h-full bg-white transition-all duration-100" - style={{ width: `${(currentTime / usePlaybackStore.getState().duration) * 100}%` }} - /> - </div> - - <Button - variant="ghost" - size="icon" - className="h-8 w-8 bg-black/50 text-white hover:bg-black/70" - onClick={() => setVolume(volume > 0 ? 0 : 1)} - > - <Volume2 className="h-4 w-4" /> - </Button> - </div> - </div> + <video + ref={videoRef} + src={src} + poster={poster} + className={`w-full h-full object-cover ${className}`} + playsInline + preload="auto" + controls={false} + disablePictureInPicture + disableRemotePlayback + style={{ pointerEvents: 'none' }} + onContextMenu={(e) => e.preventDefault()} + /> ); }
\ No newline at end of file diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts deleted file mode 100644 index 7c467e7e..00000000 --- a/apps/web/src/lib/auth-client.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { createAuthClient } from "better-auth/react";
-export const authClient = createAuthClient({
- baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL!,
-});
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts deleted file mode 100644 index 4cfaa6f2..00000000 --- a/apps/web/src/lib/auth.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { betterAuth } from "better-auth";
-import { drizzleAdapter } from "better-auth/adapters/drizzle";
-import { db } from "./db";
-
-export const auth = betterAuth({
- database: drizzleAdapter(db, {
- provider: "pg",
- usePlural: true,
- }),
- secret: process.env.BETTER_AUTH_SECRET!,
- user: {
- deleteUser: {
- enabled: true,
- },
- },
- emailAndPassword: {
- enabled: true,
- },
- appName: "OpenCut",
- trustedOrigins: ["http://localhost:3000"],
-});
-
-export type Auth = typeof auth;
diff --git a/apps/web/src/lib/db/index.tsx b/apps/web/src/lib/db/index.tsx deleted file mode 100644 index b66c6e39..00000000 --- a/apps/web/src/lib/db/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { drizzle } from "drizzle-orm/node-postgres";
-import { Pool } from "pg";
-import * as schema from "./schema";
-
-const pool = new Pool({
- connectionString: process.env.DATABASE_URL,
- max: 3,
- idleTimeoutMillis: 10000,
- connectionTimeoutMillis: 15000,
- query_timeout: 20000,
- statement_timeout: 20000,
-});
-
-export const db = drizzle(pool, { schema });
diff --git a/apps/web/src/lib/db/schema.ts b/apps/web/src/lib/db/schema.ts deleted file mode 100644 index 7c38724a..00000000 --- a/apps/web/src/lib/db/schema.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";
-
-export const users = pgTable("users", {
- id: text("id").primaryKey(),
- name: text("name").notNull(),
- email: text("email").notNull().unique(),
- emailVerified: boolean("email_verified")
- .$defaultFn(() => false)
- .notNull(),
- image: text("image"),
- createdAt: timestamp("created_at")
- .$defaultFn(() => /* @__PURE__ */ new Date())
- .notNull(),
- updatedAt: timestamp("updated_at")
- .$defaultFn(() => /* @__PURE__ */ new Date())
- .notNull(),
-}).enableRLS();
-
-export const sessions = pgTable("sessions", {
- id: text("id").primaryKey(),
- expiresAt: timestamp("expires_at").notNull(),
- token: text("token").notNull().unique(),
- createdAt: timestamp("created_at").notNull(),
- updatedAt: timestamp("updated_at").notNull(),
- ipAddress: text("ip_address"),
- userAgent: text("user_agent"),
- userId: text("user_id")
- .notNull()
- .references(() => users.id, { onDelete: "cascade" }),
-}).enableRLS();
-
-export const accounts = pgTable("accounts", {
- id: text("id").primaryKey(),
- accountId: text("account_id").notNull(),
- providerId: text("provider_id").notNull(),
- userId: text("user_id")
- .notNull()
- .references(() => users.id, { onDelete: "cascade" }),
- accessToken: text("access_token"),
- refreshToken: text("refresh_token"),
- idToken: text("id_token"),
- accessTokenExpiresAt: timestamp("access_token_expires_at"),
- refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
- scope: text("scope"),
- password: text("password"),
- createdAt: timestamp("created_at").notNull(),
- updatedAt: timestamp("updated_at").notNull(),
-}).enableRLS();
-
-export const verifications = pgTable("verifications", {
- id: text("id").primaryKey(),
- identifier: text("identifier").notNull(),
- value: text("value").notNull(),
- expiresAt: timestamp("expires_at").notNull(),
- createdAt: timestamp("created_at").$defaultFn(
- () => /* @__PURE__ */ new Date()
- ),
- updatedAt: timestamp("updated_at").$defaultFn(
- () => /* @__PURE__ */ new Date()
- ),
-}).enableRLS();
-
-export const waitlist = pgTable("waitlist", {
- id: text("id").primaryKey(),
- email: text("email").notNull().unique(),
- createdAt: timestamp("created_at")
- .$defaultFn(() => /* @__PURE__ */ new Date())
- .notNull(),
-}).enableRLS();
diff --git a/apps/web/src/lib/fetchGhStars.ts b/apps/web/src/lib/fetchGhStars.ts new file mode 100644 index 00000000..e0236840 --- /dev/null +++ b/apps/web/src/lib/fetchGhStars.ts @@ -0,0 +1,29 @@ +export async function getStars(): Promise<string> { + try { + const res = await fetch( + "https://api.github.com/repos/OpenCut-app/OpenCut", + { + next: { revalidate: 3600 }, + } + ); + + if (!res.ok) { + throw new Error(`GitHub API error: ${res.status} ${res.statusText}`); + } + const data = await res.json(); + const count = data.stargazers_count; + + if (typeof count !== "number") { + throw new Error("Invalid stargazers_count from GitHub API"); + } + + if (count >= 1_000_000) + return (count / 1_000_000).toFixed(1).replace(/\.0$/, "") + "M"; + if (count >= 1_000) + return (count / 1_000).toFixed(1).replace(/\.0$/, "") + "k"; + return count.toString(); + } catch (error) { + console.error("Failed to fetch GitHub stars:", error); + return "1.5k"; + } +} diff --git a/apps/web/src/lib/ffmpeg-utils.ts b/apps/web/src/lib/ffmpeg-utils.ts index 56085a21..ae0c267b 100644 --- a/apps/web/src/lib/ffmpeg-utils.ts +++ b/apps/web/src/lib/ffmpeg-utils.ts @@ -102,26 +102,60 @@ export const getVideoInfo = async (videoFile: File): Promise<{ fps: number; }> => { const ffmpeg = await initFFmpeg(); - + const inputName = 'input.mp4'; - + // Write input file await ffmpeg.writeFile(inputName, new Uint8Array(await videoFile.arrayBuffer())); - - // Get video info - await ffmpeg.exec(['-i', inputName, '-f', 'null', '-']); - - // Note: In a real implementation, you'd parse the FFmpeg output - // For now, we'll return default values and enhance this later - + + // Capture FFmpeg stderr output with a one-time listener pattern + let ffmpegOutput = ''; + let listening = true; + const listener = (data: string) => { + if (listening) ffmpegOutput += data; + }; + ffmpeg.on('log', ({ message }) => listener(message)); + + // Run ffmpeg to get info (stderr will contain the info) + try { + await ffmpeg.exec(['-i', inputName, '-f', 'null', '-']); + } catch (error) { + listening = false; + await ffmpeg.deleteFile(inputName); + console.error('FFmpeg execution failed:', error); + throw new Error('Failed to extract video info. The file may be corrupted or in an unsupported format.'); + } + + // Disable listener after exec completes + listening = false; + // Cleanup await ffmpeg.deleteFile(inputName); - + + // Parse output for duration, resolution, and fps + // Example: Duration: 00:00:10.00, start: 0.000000, bitrate: 1234 kb/s + // Example: Stream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 30 fps, 30 tbr, 90k tbn, 60 tbc + + const durationMatch = ffmpegOutput.match(/Duration: (\d+):(\d+):([\d.]+)/); + let duration = 0; + if (durationMatch) { + const [, h, m, s] = durationMatch; + duration = parseInt(h) * 3600 + parseInt(m) * 60 + parseFloat(s); + } + + const videoStreamMatch = ffmpegOutput.match(/Video:.* (\d+)x(\d+)[^,]*, ([\d.]+) fps/); + let width = 0, height = 0, fps = 0; + if (videoStreamMatch) { + width = parseInt(videoStreamMatch[1]); + height = parseInt(videoStreamMatch[2]); + fps = parseFloat(videoStreamMatch[3]); + } + return { - duration: 10, // Placeholder - would parse from FFmpeg output - width: 1920, // Placeholder - height: 1080, // Placeholder - fps: 30 // Placeholder + duration, + width, + height, + fps }; }; @@ -194,4 +228,4 @@ export const extractAudio = async ( await ffmpeg.deleteFile(outputName); return blob; -};
\ No newline at end of file +};
\ No newline at end of file diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts index 7f096cd5..f2d3f590 100644 --- a/apps/web/src/middleware.ts +++ b/apps/web/src/middleware.ts @@ -7,7 +7,7 @@ export async function middleware(request: NextRequest) { const session = getSessionCookie(request);
if (path === "/editor" && !session && process.env.NODE_ENV === "production") {
- const loginUrl = new URL("/auth/login", request.url);
+ const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("redirect", request.url);
return NextResponse.redirect(loginUrl);
}
diff --git a/apps/web/src/stores/panel-store.ts b/apps/web/src/stores/panel-store.ts index ea2dacb9..7706417a 100644 --- a/apps/web/src/stores/panel-store.ts +++ b/apps/web/src/stores/panel-store.ts @@ -2,78 +2,40 @@ import { create } from "zustand"; import { persist } from "zustand/middleware";
interface PanelState {
- // Horizontal panel sizes
+ // Panel sizes as percentages
toolsPanel: number;
previewPanel: number;
propertiesPanel: number;
-
- // Vertical panel sizes
mainContent: number;
timeline: number;
- // Flag to prevent initial overwrites
- isInitialized: boolean;
-
// Actions
setToolsPanel: (size: number) => void;
setPreviewPanel: (size: number) => void;
setPropertiesPanel: (size: number) => void;
setMainContent: (size: number) => void;
setTimeline: (size: number) => void;
- setInitialized: () => void;
}
export const usePanelStore = create<PanelState>()(
persist(
- (set, get) => ({
- // Default sizes
- toolsPanel: 20,
- previewPanel: 60,
+ (set) => ({
+ // Default sizes - optimized for responsiveness
+ toolsPanel: 25,
+ previewPanel: 75,
propertiesPanel: 20,
- mainContent: 50,
- timeline: 50,
- isInitialized: false,
+ mainContent: 70,
+ timeline: 30,
// Actions
- setToolsPanel: (size) => {
- const state = get();
- if (!state.isInitialized) return;
- set({ toolsPanel: size });
- },
- setPreviewPanel: (size) => {
- const state = get();
- if (!state.isInitialized) return;
- set({ previewPanel: size });
- },
- setPropertiesPanel: (size) => {
- const state = get();
- if (!state.isInitialized) return;
- set({ propertiesPanel: size });
- },
- setMainContent: (size) => {
- const state = get();
- if (!state.isInitialized) return;
- set({ mainContent: size });
- },
- setTimeline: (size) => {
- const state = get();
- if (!state.isInitialized) return;
- set({ timeline: size });
- },
- setInitialized: () => {
- console.log("Panel store initialized for resize events");
- set({ isInitialized: true });
- },
+ setToolsPanel: (size) => set({ toolsPanel: size }),
+ setPreviewPanel: (size) => set({ previewPanel: size }),
+ setPropertiesPanel: (size) => set({ propertiesPanel: size }),
+ setMainContent: (size) => set({ mainContent: size }),
+ setTimeline: (size) => set({ timeline: size }),
}),
{
name: "panel-sizes",
- partialize: (state) => ({
- toolsPanel: state.toolsPanel,
- previewPanel: state.previewPanel,
- propertiesPanel: state.propertiesPanel,
- mainContent: state.mainContent,
- timeline: state.timeline,
- }),
}
)
);
diff --git a/apps/web/src/stores/playback-store.ts b/apps/web/src/stores/playback-store.ts index 3c0bfdec..a4794b7f 100644 --- a/apps/web/src/stores/playback-store.ts +++ b/apps/web/src/stores/playback-store.ts @@ -6,15 +6,20 @@ interface PlaybackStore extends PlaybackState, PlaybackControls { setCurrentTime: (time: number) => void; } -let playbackTimer: NodeJS.Timeout | null = null; +let playbackTimer: number | null = null; const startTimer = (store: any) => { - if (playbackTimer) clearInterval(playbackTimer); + if (playbackTimer) cancelAnimationFrame(playbackTimer); - playbackTimer = setInterval(() => { + // Use requestAnimationFrame for smoother updates + const updateTime = () => { const state = store(); if (state.isPlaying && state.currentTime < state.duration) { - const newTime = state.currentTime + 0.1; + const now = performance.now(); + const delta = (now - lastUpdate) / 1000; // Convert to seconds + lastUpdate = now; + + const newTime = state.currentTime + (delta * state.speed); if (newTime >= state.duration) { state.pause(); } else { @@ -23,12 +28,16 @@ const startTimer = (store: any) => { window.dispatchEvent(new CustomEvent('playback-update', { detail: { time: newTime } })); } } - }, 100); + playbackTimer = requestAnimationFrame(updateTime); + }; + + let lastUpdate = performance.now(); + playbackTimer = requestAnimationFrame(updateTime); }; const stopTimer = () => { if (playbackTimer) { - clearInterval(playbackTimer); + cancelAnimationFrame(playbackTimer); playbackTimer = null; } }; @@ -38,6 +47,7 @@ export const usePlaybackStore = create<PlaybackStore>((set, get) => ({ currentTime: 0, duration: 0, volume: 1, + speed: 1.0, play: () => { set({ isPlaying: true }); @@ -64,10 +74,20 @@ export const usePlaybackStore = create<PlaybackStore>((set, get) => ({ set({ currentTime: clampedTime }); // Notify video elements to seek - window.dispatchEvent(new CustomEvent('playback-seek', { detail: { time: clampedTime } })); + const event = new CustomEvent('playback-seek', { detail: { time: clampedTime } }); + window.dispatchEvent(event); }, setVolume: (volume: number) => set({ volume: Math.max(0, Math.min(1, volume)) }), + + setSpeed: (speed: number) => { + const newSpeed = Math.max(0.1, Math.min(2.0, speed)); + set({ speed: newSpeed }); + + const event = new CustomEvent('playback-speed', { detail: { speed: newSpeed } }); + window.dispatchEvent(event); + }, + setDuration: (duration: number) => set({ duration }), setCurrentTime: (time: number) => set({ currentTime: time }), }));
\ No newline at end of file diff --git a/apps/web/src/stores/timeline-store.ts b/apps/web/src/stores/timeline-store.ts index c569ae11..e1474bae 100644 --- a/apps/web/src/stores/timeline-store.ts +++ b/apps/web/src/stores/timeline-store.ts @@ -20,6 +20,15 @@ export interface TimelineTrack { interface TimelineStore {
tracks: TimelineTrack[];
+ history: TimelineTrack[][];
+ redoStack: TimelineTrack[][];
+
+ // Multi-selection
+ selectedClips: { trackId: string; clipId: string }[];
+ selectClip: (trackId: string, clipId: string, multi?: boolean) => void;
+ deselectClip: (trackId: string, clipId: string) => void;
+ clearSelectedClips: () => void;
+ setSelectedClips: (clips: { trackId: string; clipId: string }[]) => void;
// Actions
addTrack: (type: "video" | "audio" | "effects") => string;
@@ -46,12 +55,67 @@ interface TimelineStore { // Computed values
getTotalDuration: () => number;
+
+ // New actions
+ undo: () => void;
+ redo: () => void;
+ pushHistory: () => void;
}
export const useTimelineStore = create<TimelineStore>((set, get) => ({
tracks: [],
+ history: [],
+ redoStack: [],
+ selectedClips: [],
+
+ pushHistory: () => {
+ const { tracks, history, redoStack } = get();
+ // Deep copy tracks
+ set({
+ history: [...history, JSON.parse(JSON.stringify(tracks))],
+ redoStack: [] // Clear redo stack when new action is performed
+ });
+ },
+
+ undo: () => {
+ const { history, redoStack, tracks } = get();
+ if (history.length === 0) return;
+ const prev = history[history.length - 1];
+ set({
+ tracks: prev,
+ history: history.slice(0, -1),
+ redoStack: [...redoStack, JSON.parse(JSON.stringify(tracks))] // Add current state to redo stack
+ });
+ },
+
+ selectClip: (trackId, clipId, multi = false) => {
+ set((state) => {
+ const exists = state.selectedClips.some(
+ (c) => c.trackId === trackId && c.clipId === clipId
+ );
+ if (multi) {
+ // Toggle selection
+ return exists
+ ? { selectedClips: state.selectedClips.filter((c) => !(c.trackId === trackId && c.clipId === clipId)) }
+ : { selectedClips: [...state.selectedClips, { trackId, clipId }] };
+ } else {
+ return { selectedClips: [{ trackId, clipId }] };
+ }
+ });
+ },
+ deselectClip: (trackId, clipId) => {
+ set((state) => ({
+ selectedClips: state.selectedClips.filter((c) => !(c.trackId === trackId && c.clipId === clipId)),
+ }));
+ },
+ clearSelectedClips: () => {
+ set({ selectedClips: [] });
+ },
+
+ setSelectedClips: (clips) => set({ selectedClips: clips }),
addTrack: (type) => {
+ get().pushHistory();
const newTrack: TimelineTrack = {
id: crypto.randomUUID(),
name: `${type.charAt(0).toUpperCase() + type.slice(1)} Track`,
@@ -66,12 +130,14 @@ export const useTimelineStore = create<TimelineStore>((set, get) => ({ },
removeTrack: (trackId) => {
+ get().pushHistory();
set((state) => ({
tracks: state.tracks.filter((track) => track.id !== trackId),
}));
},
addClipToTrack: (trackId, clipData) => {
+ get().pushHistory();
const newClip: TimelineClip = {
...clipData,
id: crypto.randomUUID(),
@@ -90,19 +156,21 @@ export const useTimelineStore = create<TimelineStore>((set, get) => ({ },
removeClipFromTrack: (trackId, clipId) => {
+ get().pushHistory();
set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? {
- ...track,
- clips: track.clips.filter((clip) => clip.id !== clipId),
- }
- : track
- ),
+ tracks: state.tracks
+ .map((track) =>
+ track.id === trackId
+ ? { ...track, clips: track.clips.filter((clip) => clip.id !== clipId) }
+ : track
+ )
+ // Remove track if it becomes empty
+ .filter((track) => track.clips.length > 0),
}));
},
moveClipToTrack: (fromTrackId, toTrackId, clipId) => {
+ get().pushHistory();
set((state) => {
const fromTrack = state.tracks.find((track) => track.id === fromTrackId);
const clipToMove = fromTrack?.clips.find((clip) => clip.id === clipId);
@@ -110,25 +178,29 @@ export const useTimelineStore = create<TimelineStore>((set, get) => ({ if (!clipToMove) return state;
return {
- tracks: state.tracks.map((track) => {
- if (track.id === fromTrackId) {
- return {
- ...track,
- clips: track.clips.filter((clip) => clip.id !== clipId),
- };
- } else if (track.id === toTrackId) {
- return {
- ...track,
- clips: [...track.clips, clipToMove],
- };
- }
- return track;
- }),
+ tracks: state.tracks
+ .map((track) => {
+ if (track.id === fromTrackId) {
+ return {
+ ...track,
+ clips: track.clips.filter((clip) => clip.id !== clipId),
+ };
+ } else if (track.id === toTrackId) {
+ return {
+ ...track,
+ clips: [...track.clips, clipToMove],
+ };
+ }
+ return track;
+ })
+ // Remove track if it becomes empty
+ .filter((track) => track.clips.length > 0),
};
});
},
updateClipTrim: (trackId, clipId, trimStart, trimEnd) => {
+ get().pushHistory();
set((state) => ({
tracks: state.tracks.map((track) =>
track.id === trackId
@@ -144,6 +216,7 @@ export const useTimelineStore = create<TimelineStore>((set, get) => ({ },
updateClipStartTime: (trackId, clipId, startTime) => {
+ get().pushHistory();
set((state) => ({
tracks: state.tracks.map((track) =>
track.id === trackId
@@ -159,6 +232,7 @@ export const useTimelineStore = create<TimelineStore>((set, get) => ({ },
toggleTrackMute: (trackId) => {
+ get().pushHistory();
set((state) => ({
tracks: state.tracks.map((track) =>
track.id === trackId ? { ...track, muted: !track.muted } : track
@@ -180,4 +254,11 @@ export const useTimelineStore = create<TimelineStore>((set, get) => ({ return Math.max(...trackEndTimes, 0);
},
+
+ redo: () => {
+ const { redoStack } = get();
+ if (redoStack.length === 0) return;
+ const next = redoStack[redoStack.length - 1];
+ set({ tracks: next, redoStack: redoStack.slice(0, -1) });
+ },
}));
diff --git a/apps/web/src/types/playback.ts b/apps/web/src/types/playback.ts index 88113ef3..3fbd1a02 100644 --- a/apps/web/src/types/playback.ts +++ b/apps/web/src/types/playback.ts @@ -3,6 +3,7 @@ export interface PlaybackState { currentTime: number; duration: number; volume: number; + speed: number; } export interface PlaybackControls { @@ -10,5 +11,6 @@ export interface PlaybackControls { pause: () => void; seek: (time: number) => void; setVolume: (volume: number) => void; + setSpeed: (speed: number) => void; toggle: () => void; }
\ No newline at end of file |
