refactor(dashboard): centralize access guards and split interactive pages into client components

This commit is contained in:
Yusuf İpek
2026-02-25 16:42:47 +03:00
parent a2b07b3e19
commit 6eea327083
29 changed files with 4859 additions and 4539 deletions
@@ -1,11 +1,17 @@
'use client';
import { useParams } from 'next/navigation';
import { MembersManagementPage } from '@/components/members-management-page';
import { requireProjectAccessOrRedirect } from '@/lib/route-access';
export default function ProjectMembersPage() {
const params = useParams();
const projectId = params.projectId as string;
interface ProjectMembersPageProps {
params: Promise<{ projectId: string }>;
}
export default async function ProjectMembersPage({ params }: ProjectMembersPageProps) {
const { projectId } = await params;
await requireProjectAccessOrRedirect({
projectId,
intent: 'manage',
});
return (
<MembersManagementPage
@@ -20,7 +26,6 @@ export default function ProjectMembersPage() {
<strong>Commentator</strong> - can view and comment only.
</>
}
forbiddenRedirect="/dashboard"
/>
);
}
@@ -93,6 +93,9 @@ export default async function ProjectPage({ params, searchParams }: ProjectPageP
}
if (!isOwner && !isMember && !isPublic && !isWorkspaceMember) {
if (!session?.user?.id) {
redirect('/login');
}
redirect('/dashboard');
}
@@ -1,513 +1,17 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Loader2, Globe, Lock, UserPlus, Trash2, AlertTriangle, Settings, Save, Tag, Plus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
type Visibility = 'PRIVATE' | 'INVITE' | 'PUBLIC';
const visibilityOptions: { value: Visibility; label: string; description: string; icon: React.ReactNode }[] = [
{
value: 'PRIVATE',
label: 'Private',
description: 'Only you can access this project',
icon: <Lock className="h-5 w-5" />,
},
{
value: 'INVITE',
label: 'Invite Only',
description: 'Share with specific people via email',
icon: <UserPlus className="h-5 w-5" />,
},
{
value: 'PUBLIC',
label: 'Public',
description: 'Anyone with the link can view',
icon: <Globe className="h-5 w-5" />,
},
];
import { requireProjectAccessOrRedirect } from '@/lib/route-access';
import ProjectSettingsPageClient from './project-settings-page-client';
interface ProjectSettingsPageProps {
params: Promise<{ projectId: string }>;
params: Promise<{ projectId: string }>;
}
interface CommentTag {
id: string;
name: string;
color: string;
position: number;
}
export default async function ProjectSettingsPage({ params }: ProjectSettingsPageProps) {
const { projectId } = await params;
export default function ProjectSettingsPage({ params }: ProjectSettingsPageProps) {
const router = useRouter();
const [projectId, setProjectId] = useState<string>('');
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [deleteConfirmation, setDeleteConfirmation] = useState('');
const [formData, setFormData] = useState({
name: '',
description: '',
visibility: 'PRIVATE' as Visibility,
});
await requireProjectAccessOrRedirect({
projectId,
intent: 'manage',
});
// Tag management state
const [tags, setTags] = useState<CommentTag[]>([]);
const [newTagName, setNewTagName] = useState('');
const [newTagColor, setNewTagColor] = useState('#3B82F6');
const [isAddingTag, setIsAddingTag] = useState(false);
const [editingTagId, setEditingTagId] = useState<string | null>(null);
const [editTagName, setEditTagName] = useState('');
const [editTagColor, setEditTagColor] = useState('');
useEffect(() => {
params.then(({ projectId: id }) => {
setProjectId(id);
// Fetch project data
fetch(`/api/projects/${id}`)
.then((res) => res.json())
.then((data) => {
if (data.error) {
setError(data.error);
} else {
const project = data.data;
setFormData({
name: project.name || '',
description: project.description || '',
visibility: project.visibility || 'PRIVATE',
});
}
})
.catch(() => setError('Failed to load project'))
.finally(() => setIsLoading(false));
// Fetch tags
fetch(`/api/projects/${id}/tags`)
.then((res) => res.json())
.then((data) => {
if (Array.isArray(data.data)) {
setTags(data.data);
}
})
.catch(() => { /* Silent fail - tags are optional */ });
});
}, [params]);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
setError('');
setSuccess('');
try {
const response = await fetch(`/api/projects/${projectId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
const data = await response.json();
if (!response.ok) {
setError(data.error || 'Failed to update project');
return;
}
setSuccess('Project settings saved successfully');
setTimeout(() => setSuccess(''), 3000);
} catch {
setError('Something went wrong. Please try again.');
} finally {
setIsSaving(false);
}
};
const handleAddTag = async () => {
if (!newTagName.trim()) return;
setIsAddingTag(true);
try {
const res = await fetch(`/api/projects/${projectId}/tags`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newTagName.trim(), color: newTagColor }),
});
if (res.ok) {
const data = await res.json();
const newTag = data.data;
setTags([...tags, newTag]);
setNewTagName('');
setNewTagColor('#3B82F6');
}
} catch {
// Silent fail
} finally {
setIsAddingTag(false);
}
};
const handleUpdateTag = async (tagId: string) => {
if (!editTagName.trim()) return;
try {
const res = await fetch(`/api/projects/${projectId}/tags/${tagId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: editTagName.trim(), color: editTagColor }),
});
if (res.ok) {
const data = await res.json();
const updated = data.data;
setTags(tags.map((t) => (t.id === tagId ? updated : t)));
setEditingTagId(null);
}
} catch {
// Silent fail
}
};
const handleDeleteTag = async (tagId: string) => {
try {
const res = await fetch(`/api/projects/${projectId}/tags/${tagId}`, {
method: 'DELETE',
});
if (res.ok) {
setTags(tags.filter((t) => t.id !== tagId));
}
} catch {
// Silent fail
}
};
const handleDelete = async () => {
if (deleteConfirmation !== formData.name) {
setError('Project name does not match');
return;
}
setIsDeleting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}`, {
method: 'DELETE',
});
if (!response.ok) {
const data = await response.json();
setError(data.error || 'Failed to delete project');
return;
}
router.push('/dashboard');
} catch {
setError('Something went wrong. Please try again.');
} finally {
setIsDeleting(false);
}
};
if (isLoading) {
return (
<div className="min-h-[calc(100vh-4rem)] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="min-h-[calc(100vh-4rem)] flex items-start justify-center py-12 px-4">
<div className="w-full max-w-xl">
<div className="mb-8">
<Link
href={`/projects/${projectId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Project
</Link>
</div>
<div className="space-y-6">
{/* General Settings */}
<Card className="border-border/50 shadow-lg">
<CardHeader className="text-center pb-2">
<div className="mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4">
<Settings className="h-7 w-7 text-primary" />
</div>
<CardTitle className="text-2xl">Project Settings</CardTitle>
<CardDescription className="text-base">
Update your project details and access settings
</CardDescription>
</CardHeader>
<CardContent className="pt-6">
<form onSubmit={handleSave} className="space-y-6">
<div className="space-y-2">
<Label htmlFor="name" className="text-sm font-medium">
Project Name
</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
required
disabled={isSaving}
className="h-11"
/>
</div>
<div className="space-y-2">
<Label htmlFor="description" className="text-sm font-medium">
Description
</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
rows={3}
disabled={isSaving}
className="resize-none"
/>
</div>
<div className="space-y-3">
<Label className="text-sm font-medium">Who can access?</Label>
<div className="grid gap-3">
{visibilityOptions.map((option) => (
<button
key={option.value}
type="button"
onClick={() => setFormData(prev => ({ ...prev, visibility: option.value }))}
disabled={isSaving}
className={`w-full flex items-center gap-4 p-4 rounded-xl border-2 text-left transition-all ${formData.visibility === option.value
? 'border-primary bg-primary/5 ring-1 ring-primary/20'
: 'border-border hover:border-border/80 hover:bg-accent/50'
}`}
>
<div className={`shrink-0 w-10 h-10 rounded-lg flex items-center justify-center ${formData.visibility === option.value
? 'bg-primary text-primary-foreground'
: 'bg-muted text-muted-foreground'
}`}>
{option.icon}
</div>
<div className="flex-1 min-w-0">
<div className="font-medium">{option.label}</div>
<div className="text-sm text-muted-foreground">
{option.description}
</div>
</div>
<div className={`shrink-0 w-5 h-5 rounded-full border-2 flex items-center justify-center ${formData.visibility === option.value
? 'border-primary bg-primary'
: 'border-muted-foreground/30'
}`}>
{formData.visibility === option.value && (
<div className="w-2 h-2 rounded-full bg-primary-foreground" />
)}
</div>
</button>
))}
</div>
</div>
{error && (
<div className="p-4 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error}
</div>
)}
{success && (
<div className="p-4 rounded-lg bg-green-500/10 border border-green-500/20 text-green-500 text-sm flex items-center gap-2">
<Save className="h-4 w-4" />
{success}
</div>
)}
<Button type="submit" disabled={isSaving || !formData.name.trim()} className="h-11">
{isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save Changes
</Button>
</form>
</CardContent>
</Card>
{/* Comment Tags */}
<Card id="comment-tags" className="border-border/50 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Tag className="h-5 w-5" />
Comment Tags
</CardTitle>
<CardDescription>
Customize tags for categorizing comments on videos
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Existing tags */}
<div className="space-y-2">
{tags.map((tag) => (
<div key={tag.id} className="flex flex-wrap items-center gap-2 p-2 rounded-lg border bg-card">
{editingTagId === tag.id ? (
<>
<input
type="color"
value={editTagColor}
onChange={(e) => setEditTagColor(e.target.value)}
className="w-8 h-8 rounded cursor-pointer border-0"
/>
<Input
value={editTagName}
onChange={(e) => setEditTagName(e.target.value)}
className="flex-1 h-8"
onKeyDown={(e) => e.key === 'Enter' && handleUpdateTag(tag.id)}
/>
<Button size="sm" variant="ghost" onClick={() => handleUpdateTag(tag.id)}>
<Save className="h-4 w-4" />
</Button>
<Button size="sm" variant="ghost" onClick={() => setEditingTagId(null)}>
<X className="h-4 w-4" />
</Button>
</>
) : (
<>
<div
className="w-6 h-6 rounded-full shrink-0"
style={{ backgroundColor: tag.color }}
/>
<span className="flex-1 text-sm font-medium">{tag.name}</span>
<Button
size="sm"
variant="ghost"
onClick={() => {
setEditingTagId(tag.id);
setEditTagName(tag.name);
setEditTagColor(tag.color);
}}
>
Edit
</Button>
<Button
size="sm"
variant="ghost"
className="text-destructive hover:text-destructive"
onClick={() => handleDeleteTag(tag.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</>
)}
</div>
))}
</div>
{/* Add new tag */}
<div className="flex flex-wrap items-center gap-2 pt-2 border-t">
<input
type="color"
value={newTagColor}
onChange={(e) => setNewTagColor(e.target.value)}
className="w-8 h-8 rounded cursor-pointer border-0"
/>
<Input
placeholder="New tag name..."
value={newTagName}
onChange={(e) => setNewTagName(e.target.value)}
className="flex-1 h-8"
onKeyDown={(e) => e.key === 'Enter' && handleAddTag()}
/>
<Button size="sm" onClick={handleAddTag} disabled={!newTagName.trim() || isAddingTag}>
{isAddingTag ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* Danger Zone */}
<Card className="border-destructive/30 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg text-destructive flex items-center gap-2">
<AlertTriangle className="h-5 w-5" />
Danger Zone
</CardTitle>
<CardDescription>
Irreversible actions that will permanently affect your project
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between p-4 rounded-xl border border-destructive/20 bg-destructive/5">
<div>
<h4 className="font-medium">Delete this project</h4>
<p className="text-sm text-muted-foreground">
This action cannot be undone
</p>
</div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive" size="sm">
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete &quot;{formData.name}&quot;?</AlertDialogTitle>
<AlertDialogDescription asChild>
<div className="space-y-4">
<p>
This will permanently delete this project and all of its
videos, versions, and comments. This action cannot be undone.
</p>
<div className="space-y-2">
<Label htmlFor="delete-confirm">
Type <strong className="text-foreground">{formData.name}</strong> to confirm
</Label>
<Input
id="delete-confirm"
value={deleteConfirmation}
onChange={(e) => setDeleteConfirmation(e.target.value)}
placeholder="Project name"
className="h-11"
/>
</div>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setDeleteConfirmation('')}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={deleteConfirmation !== formData.name || isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Delete Project
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
);
return <ProjectSettingsPageClient projectId={projectId} />;
}
@@ -0,0 +1,509 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Loader2, Globe, Lock, UserPlus, Trash2, AlertTriangle, Settings, Save, Tag, Plus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
type Visibility = 'PRIVATE' | 'INVITE' | 'PUBLIC';
const visibilityOptions: { value: Visibility; label: string; description: string; icon: React.ReactNode }[] = [
{
value: 'PRIVATE',
label: 'Private',
description: 'Only you can access this project',
icon: <Lock className="h-5 w-5" />,
},
{
value: 'INVITE',
label: 'Invite Only',
description: 'Share with specific people via email',
icon: <UserPlus className="h-5 w-5" />,
},
{
value: 'PUBLIC',
label: 'Public',
description: 'Anyone with the link can view',
icon: <Globe className="h-5 w-5" />,
},
];
interface ProjectSettingsPageProps {
projectId: string;
}
interface CommentTag {
id: string;
name: string;
color: string;
position: number;
}
export default function ProjectSettingsPageClient({ projectId }: ProjectSettingsPageProps) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [deleteConfirmation, setDeleteConfirmation] = useState('');
const [formData, setFormData] = useState({
name: '',
description: '',
visibility: 'PRIVATE' as Visibility,
});
// Tag management state
const [tags, setTags] = useState<CommentTag[]>([]);
const [newTagName, setNewTagName] = useState('');
const [newTagColor, setNewTagColor] = useState('#3B82F6');
const [isAddingTag, setIsAddingTag] = useState(false);
const [editingTagId, setEditingTagId] = useState<string | null>(null);
const [editTagName, setEditTagName] = useState('');
const [editTagColor, setEditTagColor] = useState('');
useEffect(() => {
// Fetch project data
fetch(`/api/projects/${projectId}`)
.then((res) => res.json())
.then((data) => {
if (data.error) {
setError(data.error);
} else {
const project = data.data;
setFormData({
name: project.name || '',
description: project.description || '',
visibility: project.visibility || 'PRIVATE',
});
}
})
.catch(() => setError('Failed to load project'))
.finally(() => setIsLoading(false));
// Fetch tags
fetch(`/api/projects/${projectId}/tags`)
.then((res) => res.json())
.then((data) => {
if (Array.isArray(data.data)) {
setTags(data.data);
}
})
.catch(() => { /* Silent fail - tags are optional */ });
}, [projectId]);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
setError('');
setSuccess('');
try {
const response = await fetch(`/api/projects/${projectId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
const data = await response.json();
if (!response.ok) {
setError(data.error || 'Failed to update project');
return;
}
setSuccess('Project settings saved successfully');
setTimeout(() => setSuccess(''), 3000);
} catch {
setError('Something went wrong. Please try again.');
} finally {
setIsSaving(false);
}
};
const handleAddTag = async () => {
if (!newTagName.trim()) return;
setIsAddingTag(true);
try {
const res = await fetch(`/api/projects/${projectId}/tags`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newTagName.trim(), color: newTagColor }),
});
if (res.ok) {
const data = await res.json();
const newTag = data.data;
setTags([...tags, newTag]);
setNewTagName('');
setNewTagColor('#3B82F6');
}
} catch {
// Silent fail
} finally {
setIsAddingTag(false);
}
};
const handleUpdateTag = async (tagId: string) => {
if (!editTagName.trim()) return;
try {
const res = await fetch(`/api/projects/${projectId}/tags/${tagId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: editTagName.trim(), color: editTagColor }),
});
if (res.ok) {
const data = await res.json();
const updated = data.data;
setTags(tags.map((t) => (t.id === tagId ? updated : t)));
setEditingTagId(null);
}
} catch {
// Silent fail
}
};
const handleDeleteTag = async (tagId: string) => {
try {
const res = await fetch(`/api/projects/${projectId}/tags/${tagId}`, {
method: 'DELETE',
});
if (res.ok) {
setTags(tags.filter((t) => t.id !== tagId));
}
} catch {
// Silent fail
}
};
const handleDelete = async () => {
if (deleteConfirmation !== formData.name) {
setError('Project name does not match');
return;
}
setIsDeleting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}`, {
method: 'DELETE',
});
if (!response.ok) {
const data = await response.json();
setError(data.error || 'Failed to delete project');
return;
}
router.push('/dashboard');
} catch {
setError('Something went wrong. Please try again.');
} finally {
setIsDeleting(false);
}
};
if (isLoading) {
return (
<div className="min-h-[calc(100vh-4rem)] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="min-h-[calc(100vh-4rem)] flex items-start justify-center py-12 px-4">
<div className="w-full max-w-xl">
<div className="mb-8">
<Link
href={`/projects/${projectId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Project
</Link>
</div>
<div className="space-y-6">
{/* General Settings */}
<Card className="border-border/50 shadow-lg">
<CardHeader className="text-center pb-2">
<div className="mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4">
<Settings className="h-7 w-7 text-primary" />
</div>
<CardTitle className="text-2xl">Project Settings</CardTitle>
<CardDescription className="text-base">
Update your project details and access settings
</CardDescription>
</CardHeader>
<CardContent className="pt-6">
<form onSubmit={handleSave} className="space-y-6">
<div className="space-y-2">
<Label htmlFor="name" className="text-sm font-medium">
Project Name
</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
required
disabled={isSaving}
className="h-11"
/>
</div>
<div className="space-y-2">
<Label htmlFor="description" className="text-sm font-medium">
Description
</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
rows={3}
disabled={isSaving}
className="resize-none"
/>
</div>
<div className="space-y-3">
<Label className="text-sm font-medium">Who can access?</Label>
<div className="grid gap-3">
{visibilityOptions.map((option) => (
<button
key={option.value}
type="button"
onClick={() => setFormData(prev => ({ ...prev, visibility: option.value }))}
disabled={isSaving}
className={`w-full flex items-center gap-4 p-4 rounded-xl border-2 text-left transition-all ${formData.visibility === option.value
? 'border-primary bg-primary/5 ring-1 ring-primary/20'
: 'border-border hover:border-border/80 hover:bg-accent/50'
}`}
>
<div className={`shrink-0 w-10 h-10 rounded-lg flex items-center justify-center ${formData.visibility === option.value
? 'bg-primary text-primary-foreground'
: 'bg-muted text-muted-foreground'
}`}>
{option.icon}
</div>
<div className="flex-1 min-w-0">
<div className="font-medium">{option.label}</div>
<div className="text-sm text-muted-foreground">
{option.description}
</div>
</div>
<div className={`shrink-0 w-5 h-5 rounded-full border-2 flex items-center justify-center ${formData.visibility === option.value
? 'border-primary bg-primary'
: 'border-muted-foreground/30'
}`}>
{formData.visibility === option.value && (
<div className="w-2 h-2 rounded-full bg-primary-foreground" />
)}
</div>
</button>
))}
</div>
</div>
{error && (
<div className="p-4 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error}
</div>
)}
{success && (
<div className="p-4 rounded-lg bg-green-500/10 border border-green-500/20 text-green-500 text-sm flex items-center gap-2">
<Save className="h-4 w-4" />
{success}
</div>
)}
<Button type="submit" disabled={isSaving || !formData.name.trim()} className="h-11">
{isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save Changes
</Button>
</form>
</CardContent>
</Card>
{/* Comment Tags */}
<Card id="comment-tags" className="border-border/50 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Tag className="h-5 w-5" />
Comment Tags
</CardTitle>
<CardDescription>
Customize tags for categorizing comments on videos
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Existing tags */}
<div className="space-y-2">
{tags.map((tag) => (
<div key={tag.id} className="flex flex-wrap items-center gap-2 p-2 rounded-lg border bg-card">
{editingTagId === tag.id ? (
<>
<input
type="color"
value={editTagColor}
onChange={(e) => setEditTagColor(e.target.value)}
className="w-8 h-8 rounded cursor-pointer border-0"
/>
<Input
value={editTagName}
onChange={(e) => setEditTagName(e.target.value)}
className="flex-1 h-8"
onKeyDown={(e) => e.key === 'Enter' && handleUpdateTag(tag.id)}
/>
<Button size="sm" variant="ghost" onClick={() => handleUpdateTag(tag.id)}>
<Save className="h-4 w-4" />
</Button>
<Button size="sm" variant="ghost" onClick={() => setEditingTagId(null)}>
<X className="h-4 w-4" />
</Button>
</>
) : (
<>
<div
className="w-6 h-6 rounded-full shrink-0"
style={{ backgroundColor: tag.color }}
/>
<span className="flex-1 text-sm font-medium">{tag.name}</span>
<Button
size="sm"
variant="ghost"
onClick={() => {
setEditingTagId(tag.id);
setEditTagName(tag.name);
setEditTagColor(tag.color);
}}
>
Edit
</Button>
<Button
size="sm"
variant="ghost"
className="text-destructive hover:text-destructive"
onClick={() => handleDeleteTag(tag.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</>
)}
</div>
))}
</div>
{/* Add new tag */}
<div className="flex flex-wrap items-center gap-2 pt-2 border-t">
<input
type="color"
value={newTagColor}
onChange={(e) => setNewTagColor(e.target.value)}
className="w-8 h-8 rounded cursor-pointer border-0"
/>
<Input
placeholder="New tag name..."
value={newTagName}
onChange={(e) => setNewTagName(e.target.value)}
className="flex-1 h-8"
onKeyDown={(e) => e.key === 'Enter' && handleAddTag()}
/>
<Button size="sm" onClick={handleAddTag} disabled={!newTagName.trim() || isAddingTag}>
{isAddingTag ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* Danger Zone */}
<Card className="border-destructive/30 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg text-destructive flex items-center gap-2">
<AlertTriangle className="h-5 w-5" />
Danger Zone
</CardTitle>
<CardDescription>
Irreversible actions that will permanently affect your project
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between p-4 rounded-xl border border-destructive/20 bg-destructive/5">
<div>
<h4 className="font-medium">Delete this project</h4>
<p className="text-sm text-muted-foreground">
This action cannot be undone
</p>
</div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive" size="sm">
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete &quot;{formData.name}&quot;?</AlertDialogTitle>
<AlertDialogDescription asChild>
<div className="space-y-4">
<p>
This will permanently delete this project and all of its
videos, versions, and comments. This action cannot be undone.
</p>
<div className="space-y-2">
<Label htmlFor="delete-confirm">
Type <strong className="text-foreground">{formData.name}</strong> to confirm
</Label>
<Input
id="delete-confirm"
value={deleteConfirmation}
onChange={(e) => setDeleteConfirmation(e.target.value)}
placeholder="Project name"
className="h-11"
/>
</div>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setDeleteConfirmation('')}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={deleteConfirmation !== formData.name || isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Delete Project
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
@@ -1,337 +1,17 @@
'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { ArrowLeft, Copy, Check, Loader2, UserPlus, Share2, Globe, Lock, Mail, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
interface ProjectMember {
id: string;
role: string;
user: {
id: string;
name: string | null;
email: string | null;
};
}
import { requireProjectAccessOrRedirect } from '@/lib/route-access';
import ProjectSharePageClient from './project-share-page-client';
interface ProjectSharePageProps {
params: Promise<{ projectId: string }>;
params: Promise<{ projectId: string }>;
}
export default function ProjectSharePage({ params }: ProjectSharePageProps) {
const [projectId, setProjectId] = useState<string>('');
const [projectName, setProjectName] = useState('');
const [projectVisibility, setProjectVisibility] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [members, setMembers] = useState<ProjectMember[]>([]);
const [copied, setCopied] = useState(false);
const [error, setError] = useState('');
const [inviteEmail, setInviteEmail] = useState('');
const [isInviting, setIsInviting] = useState(false);
const [inviteSuccess, setInviteSuccess] = useState('');
export default async function ProjectSharePage({ params }: ProjectSharePageProps) {
const { projectId } = await params;
useEffect(() => {
params.then(({ projectId: id }) => {
setProjectId(id);
fetch(`/api/projects/${id}`)
.then((res) => res.json())
.then((data) => {
if (data.error) {
setError(data.error);
} else {
const project = data.data;
setProjectName(project.name || '');
setProjectVisibility(project.visibility || 'PRIVATE');
setMembers(project.members || []);
}
})
.catch(() => setError('Failed to load project'))
.finally(() => setIsLoading(false));
});
}, [params]);
await requireProjectAccessOrRedirect({
projectId,
intent: 'manage',
});
const copyToClipboard = async (text: string) => {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const getDirectLink = () => {
if (typeof window !== 'undefined') {
return `${window.location.origin}/projects/${projectId}`;
}
return `/projects/${projectId}`;
};
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault();
if (!inviteEmail.trim()) return;
setIsInviting(true);
setError('');
setInviteSuccess('');
try {
// TODO: Implement invite API
await new Promise(resolve => setTimeout(resolve, 500));
setInviteSuccess(`Invitation sent to ${inviteEmail}`);
setInviteEmail('');
setTimeout(() => setInviteSuccess(''), 3000);
} catch {
setError('Failed to send invitation');
} finally {
setIsInviting(false);
}
};
const VisibilityIcon = () => {
switch (projectVisibility) {
case 'PUBLIC':
return <Globe className="h-5 w-5" />;
case 'INVITE':
return <UserPlus className="h-5 w-5" />;
default:
return <Lock className="h-5 w-5" />;
}
};
const getVisibilityColor = () => {
switch (projectVisibility) {
case 'PUBLIC':
return 'bg-green-500/10 text-green-500';
case 'INVITE':
return 'bg-blue-500/10 text-blue-500';
default:
return 'bg-orange-500/10 text-orange-500';
}
};
const getVisibilityLabel = () => {
switch (projectVisibility) {
case 'PUBLIC':
return { title: 'Public', description: 'Anyone with the link can view this project' };
case 'INVITE':
return { title: 'Invite Only', description: 'Only people you invite can access' };
default:
return { title: 'Private', description: 'Only you can access this project' };
}
};
if (isLoading) {
return (
<div className="min-h-[calc(100vh-4rem)] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
const visibilityInfo = getVisibilityLabel();
return (
<div className="min-h-[calc(100vh-4rem)] flex items-start justify-center py-12 px-4">
<div className="w-full max-w-xl">
<div className="mb-8">
<Link
href={`/projects/${projectId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Project
</Link>
</div>
<div className="space-y-6">
{/* Header Card */}
<Card className="border-border/50 shadow-lg">
<CardHeader className="text-center pb-2">
<div className="mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4">
<Share2 className="h-7 w-7 text-primary" />
</div>
<CardTitle className="text-2xl">Share Project</CardTitle>
<CardDescription className="text-base">
Share &quot;{projectName}&quot; with your team or clients
</CardDescription>
</CardHeader>
<CardContent className="pt-4">
{/* Visibility Status */}
<div className={`flex items-center gap-3 p-4 rounded-xl ${getVisibilityColor()}`}>
<div className="w-10 h-10 rounded-lg bg-current/10 flex items-center justify-center">
<VisibilityIcon />
</div>
<div className="flex-1">
<div className="font-medium">{visibilityInfo.title}</div>
<div className="text-sm opacity-80">{visibilityInfo.description}</div>
</div>
<Link href={`/projects/${projectId}/settings`}>
<Button variant="ghost" size="sm" className="text-current hover:bg-current/10">
Change
</Button>
</Link>
</div>
</CardContent>
</Card>
{/* Invite People - Only show for INVITE visibility */}
{projectVisibility === 'INVITE' && (
<Card className="border-border/50 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Mail className="h-5 w-5 text-primary" />
Invite People
</CardTitle>
<CardDescription>
Send email invitations to specific people
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<form onSubmit={handleInvite} className="flex gap-2">
<Input
type="email"
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
placeholder="[email protected]"
className="h-11 flex-1"
disabled={isInviting}
/>
<Button type="submit" disabled={isInviting || !inviteEmail.trim()} className="h-11">
{isInviting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<UserPlus className="h-4 w-4 mr-2" />
Invite
</>
)}
</Button>
</form>
{inviteSuccess && (
<div className="p-3 rounded-lg bg-green-500/10 border border-green-500/20 text-green-500 text-sm">
{inviteSuccess}
</div>
)}
{/* Current Members */}
{members.length > 0 && (
<div className="space-y-2 pt-2">
<Label className="text-sm text-muted-foreground">Project Members</Label>
<div className="space-y-2">
{members.map((member) => (
<div
key={member.id}
className="flex items-center justify-between p-3 rounded-xl border bg-card"
>
<div className="flex items-center gap-3">
<Avatar className="h-9 w-9">
<AvatarFallback className="text-xs">
{member.user.name?.charAt(0) || member.user.email?.charAt(0) || '?'}
</AvatarFallback>
</Avatar>
<div>
<div className="font-medium text-sm">
{member.user.name || 'Unknown'}
</div>
<div className="text-xs text-muted-foreground">
{member.user.email}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs capitalize">
{member.role.toLowerCase()}
</Badge>
<Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive">
<X className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
</div>
)}
{members.length === 0 && (
<div className="text-center py-6 text-muted-foreground">
<UserPlus className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No members yet</p>
<p className="text-xs opacity-70">Invite people to collaborate on this project</p>
</div>
)}
</CardContent>
</Card>
)}
{/* Public Link - Only show for PUBLIC visibility */}
{projectVisibility === 'PUBLIC' && (
<Card className="border-border/50 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Globe className="h-5 w-5 text-primary" />
Public Link
</CardTitle>
<CardDescription>
Share this link with anyone
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Input
value={getDirectLink()}
readOnly
className="font-mono text-sm h-11 bg-muted/50"
/>
<Button
variant={copied ? 'default' : 'outline'}
size="icon"
className="h-11 w-11 shrink-0"
onClick={() => copyToClipboard(getDirectLink())}
>
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</CardContent>
</Card>
)}
{/* Private notice */}
{projectVisibility === 'PRIVATE' && (
<Card className="border-border/50 shadow-lg">
<CardContent className="py-8">
<div className="text-center">
<div className="w-16 h-16 rounded-full bg-muted/50 flex items-center justify-center mx-auto mb-4">
<Lock className="h-8 w-8 text-muted-foreground/50" />
</div>
<h3 className="font-medium mb-1">This project is private</h3>
<p className="text-sm text-muted-foreground mb-4">
Only you can access this project. Change visibility to share with others.
</p>
<Button asChild variant="outline">
<Link href={`/projects/${projectId}/settings`}>
Change Visibility
</Link>
</Button>
</div>
</CardContent>
</Card>
)}
{error && (
<div className="p-4 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error}
</div>
)}
</div>
</div>
</div>
);
return <ProjectSharePageClient projectId={projectId} />;
}
@@ -0,0 +1,333 @@
'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { ArrowLeft, Copy, Check, Loader2, UserPlus, Share2, Globe, Lock, Mail, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
interface ProjectMember {
id: string;
role: string;
user: {
id: string;
name: string | null;
email: string | null;
};
}
interface ProjectSharePageProps {
projectId: string;
}
export default function ProjectSharePageClient({ projectId }: ProjectSharePageProps) {
const [projectName, setProjectName] = useState('');
const [projectVisibility, setProjectVisibility] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [members, setMembers] = useState<ProjectMember[]>([]);
const [copied, setCopied] = useState(false);
const [error, setError] = useState('');
const [inviteEmail, setInviteEmail] = useState('');
const [isInviting, setIsInviting] = useState(false);
const [inviteSuccess, setInviteSuccess] = useState('');
useEffect(() => {
fetch(`/api/projects/${projectId}`)
.then((res) => res.json())
.then((data) => {
if (data.error) {
setError(data.error);
} else {
const project = data.data;
setProjectName(project.name || '');
setProjectVisibility(project.visibility || 'PRIVATE');
setMembers(project.members || []);
}
})
.catch(() => setError('Failed to load project'))
.finally(() => setIsLoading(false));
}, [projectId]);
const copyToClipboard = async (text: string) => {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const getDirectLink = () => {
if (typeof window !== 'undefined') {
return `${window.location.origin}/projects/${projectId}`;
}
return `/projects/${projectId}`;
};
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault();
if (!inviteEmail.trim()) return;
setIsInviting(true);
setError('');
setInviteSuccess('');
try {
// TODO: Implement invite API
await new Promise(resolve => setTimeout(resolve, 500));
setInviteSuccess(`Invitation sent to ${inviteEmail}`);
setInviteEmail('');
setTimeout(() => setInviteSuccess(''), 3000);
} catch {
setError('Failed to send invitation');
} finally {
setIsInviting(false);
}
};
const VisibilityIcon = () => {
switch (projectVisibility) {
case 'PUBLIC':
return <Globe className="h-5 w-5" />;
case 'INVITE':
return <UserPlus className="h-5 w-5" />;
default:
return <Lock className="h-5 w-5" />;
}
};
const getVisibilityColor = () => {
switch (projectVisibility) {
case 'PUBLIC':
return 'bg-green-500/10 text-green-500';
case 'INVITE':
return 'bg-blue-500/10 text-blue-500';
default:
return 'bg-orange-500/10 text-orange-500';
}
};
const getVisibilityLabel = () => {
switch (projectVisibility) {
case 'PUBLIC':
return { title: 'Public', description: 'Anyone with the link can view this project' };
case 'INVITE':
return { title: 'Invite Only', description: 'Only people you invite can access' };
default:
return { title: 'Private', description: 'Only you can access this project' };
}
};
if (isLoading) {
return (
<div className="min-h-[calc(100vh-4rem)] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
const visibilityInfo = getVisibilityLabel();
return (
<div className="min-h-[calc(100vh-4rem)] flex items-start justify-center py-12 px-4">
<div className="w-full max-w-xl">
<div className="mb-8">
<Link
href={`/projects/${projectId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Project
</Link>
</div>
<div className="space-y-6">
{/* Header Card */}
<Card className="border-border/50 shadow-lg">
<CardHeader className="text-center pb-2">
<div className="mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4">
<Share2 className="h-7 w-7 text-primary" />
</div>
<CardTitle className="text-2xl">Share Project</CardTitle>
<CardDescription className="text-base">
Share &quot;{projectName}&quot; with your team or clients
</CardDescription>
</CardHeader>
<CardContent className="pt-4">
{/* Visibility Status */}
<div className={`flex items-center gap-3 p-4 rounded-xl ${getVisibilityColor()}`}>
<div className="w-10 h-10 rounded-lg bg-current/10 flex items-center justify-center">
<VisibilityIcon />
</div>
<div className="flex-1">
<div className="font-medium">{visibilityInfo.title}</div>
<div className="text-sm opacity-80">{visibilityInfo.description}</div>
</div>
<Link href={`/projects/${projectId}/settings`}>
<Button variant="ghost" size="sm" className="text-current hover:bg-current/10">
Change
</Button>
</Link>
</div>
</CardContent>
</Card>
{/* Invite People - Only show for INVITE visibility */}
{projectVisibility === 'INVITE' && (
<Card className="border-border/50 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Mail className="h-5 w-5 text-primary" />
Invite People
</CardTitle>
<CardDescription>
Send email invitations to specific people
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<form onSubmit={handleInvite} className="flex gap-2">
<Input
type="email"
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
placeholder="[email protected]"
className="h-11 flex-1"
disabled={isInviting}
/>
<Button type="submit" disabled={isInviting || !inviteEmail.trim()} className="h-11">
{isInviting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<UserPlus className="h-4 w-4 mr-2" />
Invite
</>
)}
</Button>
</form>
{inviteSuccess && (
<div className="p-3 rounded-lg bg-green-500/10 border border-green-500/20 text-green-500 text-sm">
{inviteSuccess}
</div>
)}
{/* Current Members */}
{members.length > 0 && (
<div className="space-y-2 pt-2">
<Label className="text-sm text-muted-foreground">Project Members</Label>
<div className="space-y-2">
{members.map((member) => (
<div
key={member.id}
className="flex items-center justify-between p-3 rounded-xl border bg-card"
>
<div className="flex items-center gap-3">
<Avatar className="h-9 w-9">
<AvatarFallback className="text-xs">
{member.user.name?.charAt(0) || member.user.email?.charAt(0) || '?'}
</AvatarFallback>
</Avatar>
<div>
<div className="font-medium text-sm">
{member.user.name || 'Unknown'}
</div>
<div className="text-xs text-muted-foreground">
{member.user.email}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs capitalize">
{member.role.toLowerCase()}
</Badge>
<Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive">
<X className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
</div>
)}
{members.length === 0 && (
<div className="text-center py-6 text-muted-foreground">
<UserPlus className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No members yet</p>
<p className="text-xs opacity-70">Invite people to collaborate on this project</p>
</div>
)}
</CardContent>
</Card>
)}
{/* Public Link - Only show for PUBLIC visibility */}
{projectVisibility === 'PUBLIC' && (
<Card className="border-border/50 shadow-lg">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Globe className="h-5 w-5 text-primary" />
Public Link
</CardTitle>
<CardDescription>
Share this link with anyone
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Input
value={getDirectLink()}
readOnly
className="font-mono text-sm h-11 bg-muted/50"
/>
<Button
variant={copied ? 'default' : 'outline'}
size="icon"
className="h-11 w-11 shrink-0"
onClick={() => copyToClipboard(getDirectLink())}
>
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</CardContent>
</Card>
)}
{/* Private notice */}
{projectVisibility === 'PRIVATE' && (
<Card className="border-border/50 shadow-lg">
<CardContent className="py-8">
<div className="text-center">
<div className="w-16 h-16 rounded-full bg-muted/50 flex items-center justify-center mx-auto mb-4">
<Lock className="h-8 w-8 text-muted-foreground/50" />
</div>
<h3 className="font-medium mb-1">This project is private</h3>
<p className="text-sm text-muted-foreground mb-4">
Only you can access this project. Change visibility to share with others.
</p>
<Button asChild variant="outline">
<Link href={`/projects/${projectId}/settings`}>
Change Visibility
</Link>
</Button>
</div>
</CardContent>
</Card>
)}
{error && (
<div className="p-4 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error}
</div>
)}
</div>
</div>
</div>
);
}
File diff suppressed because it is too large Load Diff
@@ -1,18 +1,22 @@
'use client';
import { useParams } from 'next/navigation';
import { VideoPageContent } from '@/components/video-page-content';
import { auth } from '@/lib/auth';
import { requireVideoProjectAccessOrRedirect } from '@/lib/route-access';
export default function VideoPage() {
const params = useParams();
const projectId = params.projectId as string;
const videoId = params.videoId as string;
interface VideoPageProps {
params: Promise<{ projectId: string; videoId: string }>;
}
return (
<VideoPageContent
mode="dashboard"
videoId={videoId}
projectId={projectId}
/>
);
export default async function VideoPage({ params }: VideoPageProps) {
const { projectId, videoId } = await params;
const session = await auth();
await requireVideoProjectAccessOrRedirect({
projectId,
videoId,
userId: session?.user?.id,
intent: 'view',
allowPublicView: true,
});
return <VideoPageContent mode="dashboard" videoId={videoId} projectId={projectId} />;
}
@@ -1,332 +1,18 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Check, Copy, Link2, Loader2, RefreshCcw, ShieldOff, Lock, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
type RouteParams = Promise<{ projectId: string; videoId: string }>;
import { requireVideoProjectAccessOrRedirect } from '@/lib/route-access';
import VideoSharePageClient from './video-share-page-client';
interface VideoSharePageProps {
params: RouteParams;
params: Promise<{ projectId: string; videoId: string }>;
}
interface ShareLinkData {
id: string;
token: string;
allowGuests: boolean;
allowDownloads: boolean;
hasPassword: boolean;
}
export default async function VideoSharePage({ params }: VideoSharePageProps) {
const { projectId, videoId } = await params;
interface ShareResponse {
data: {
link: ShareLinkData | null;
shareUrl: string | null;
};
error?: string;
}
await requireVideoProjectAccessOrRedirect({
projectId,
videoId,
intent: 'manage',
});
export default function VideoSharePage({ params }: VideoSharePageProps) {
const [projectId, setProjectId] = useState('');
const [videoId, setVideoId] = useState('');
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [copied, setCopied] = useState(false);
const [error, setError] = useState('');
const [shareUrl, setShareUrl] = useState<string | null>(null);
const [hasPassword, setHasPassword] = useState(false);
const [password, setPassword] = useState('');
const [allowDownloads, setAllowDownloads] = useState(false);
useEffect(() => {
params.then(({ projectId: nextProjectId, videoId: nextVideoId }) => {
setProjectId(nextProjectId);
setVideoId(nextVideoId);
});
}, [params]);
useEffect(() => {
if (!projectId || !videoId) return;
async function loadShareLink() {
setLoading(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, { cache: 'no-store' });
const payload = (await response.json()) as ShareResponse;
if (!response.ok || payload.error) {
setError(payload.error || 'Failed to load share link');
setShareUrl(null);
return;
}
setShareUrl(payload.data.shareUrl);
setHasPassword(!!payload.data.link?.hasPassword);
setAllowDownloads(!!payload.data.link?.allowDownloads);
} catch {
setError('Failed to load share link');
setShareUrl(null);
setHasPassword(false);
setAllowDownloads(false);
} finally {
setLoading(false);
}
}
loadShareLink();
}, [projectId, videoId]);
const copyLink = async () => {
if (!shareUrl) return;
await navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const createShareLink = async () => {
if (!projectId || !videoId) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ allowGuests: true, allowDownloads }),
});
const payload = (await response.json()) as ShareResponse;
if (!response.ok || payload.error) {
setError(payload.error || 'Failed to create share link');
return;
}
setShareUrl(payload.data.shareUrl);
setHasPassword(!!payload.data.link?.hasPassword);
setAllowDownloads(!!payload.data.link?.allowDownloads);
setPassword('');
} catch {
setError('Failed to create share link');
} finally {
setSubmitting(false);
}
};
const revokeShareLink = async () => {
if (!projectId || !videoId) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'DELETE',
});
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: string } | null;
setError(payload?.error || 'Failed to revoke share link');
return;
}
setShareUrl(null);
setHasPassword(false);
setAllowDownloads(false);
setPassword('');
} catch {
setError('Failed to revoke share link');
} finally {
setSubmitting(false);
}
};
const updateSecuritySettings = async (clearPassword = false) => {
if (!projectId || !videoId || !shareUrl) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...(clearPassword ? { clearPassword: true } : {}),
...(!clearPassword ? { password } : {}),
}),
});
const payload = (await response.json().catch(() => null)) as ShareResponse | { error?: string } | null;
if (!response.ok || ('error' in (payload || {}) && payload?.error)) {
setError((payload as { error?: string } | null)?.error || 'Failed to update link security');
return;
}
const data = (payload as ShareResponse).data;
setShareUrl(data.shareUrl);
setHasPassword(!!data.link?.hasPassword);
setAllowDownloads(!!data.link?.allowDownloads);
setPassword('');
} catch {
setError('Failed to update link security');
} finally {
setSubmitting(false);
}
};
const updateDownloadSetting = async (nextAllowDownloads: boolean) => {
if (!projectId || !videoId || !shareUrl) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ allowDownloads: nextAllowDownloads }),
});
const payload = (await response.json().catch(() => null)) as ShareResponse | { error?: string } | null;
if (!response.ok || ('error' in (payload || {}) && payload?.error)) {
setError((payload as { error?: string } | null)?.error || 'Failed to update download setting');
return;
}
const data = (payload as ShareResponse).data;
setShareUrl(data.shareUrl);
setAllowDownloads(!!data.link?.allowDownloads);
setHasPassword(!!data.link?.hasPassword);
} catch {
setError('Failed to update download setting');
} finally {
setSubmitting(false);
}
};
return (
<div className="min-h-[calc(100vh-4rem)] flex items-start justify-center py-12 px-4">
<div className="w-full max-w-xl space-y-6">
<Link
href={`/projects/${projectId}/videos/${videoId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Video
</Link>
<Card className="border-border/50 shadow-lg">
<CardHeader>
<CardTitle className="text-2xl">Share Video For Review</CardTitle>
<CardDescription>
Create a private link so reviewers can watch and comment on this single video.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{loading ? (
<div className="flex items-center text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Loading link settings...
</div>
) : shareUrl ? (
<div className="space-y-3">
<div className="flex gap-2">
<Input value={shareUrl} readOnly className="font-mono text-sm h-11 bg-muted/50" />
<Button
variant={copied ? 'default' : 'outline'}
size="icon"
className="h-11 w-11 shrink-0"
onClick={copyLink}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
<div className="flex gap-2">
<Button onClick={createShareLink} disabled={submitting} variant="outline">
{submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <RefreshCcw className="h-4 w-4 mr-2" />}
Regenerate Link
</Button>
<Button onClick={revokeShareLink} disabled={submitting} variant="destructive">
{submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <ShieldOff className="h-4 w-4 mr-2" />}
Revoke Link
</Button>
</div>
<div className="rounded-lg border p-3 space-y-2">
<div>
<p className="text-sm font-medium">Video download</p>
<p className="text-xs text-muted-foreground">Allow viewers with this link to download</p>
</div>
<div className="flex gap-2">
<Button
variant={allowDownloads ? 'default' : 'outline'}
disabled={submitting || allowDownloads}
onClick={() => updateDownloadSetting(true)}
>
Allow Download
</Button>
<Button
variant={!allowDownloads ? 'default' : 'outline'}
disabled={submitting || !allowDownloads}
onClick={() => updateDownloadSetting(false)}
>
Block Download
</Button>
</div>
</div>
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center gap-2 text-sm font-medium">
{hasPassword ? <ShieldCheck className="h-4 w-4 text-green-600" /> : <Lock className="h-4 w-4" />}
Link password
</div>
<div className="flex gap-2">
<Input
type="password"
placeholder={hasPassword ? 'Enter new password to replace current one' : 'Set a password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={submitting}
/>
<Button
onClick={() => updateSecuritySettings(false)}
disabled={submitting || !password.trim()}
variant="outline"
>
Save
</Button>
{hasPassword && (
<Button
onClick={() => updateSecuritySettings(true)}
disabled={submitting}
variant="outline"
>
Remove
</Button>
)}
</div>
</div>
</div>
) : (
<Button onClick={createShareLink} disabled={submitting}>
{submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Link2 className="h-4 w-4 mr-2" />}
Create Review Link
</Button>
)}
<p className="text-xs text-muted-foreground">
This link allows guests to leave comments without an account. You can optionally protect it with a password.
</p>
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
</CardContent>
</Card>
</div>
</div>
);
return <VideoSharePageClient projectId={projectId} videoId={videoId} />;
}
@@ -0,0 +1,322 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Check, Copy, Link2, Loader2, RefreshCcw, ShieldOff, Lock, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
interface VideoSharePageProps {
projectId: string;
videoId: string;
}
interface ShareLinkData {
id: string;
token: string;
allowGuests: boolean;
allowDownloads: boolean;
hasPassword: boolean;
}
interface ShareResponse {
data: {
link: ShareLinkData | null;
shareUrl: string | null;
};
error?: string;
}
export default function VideoSharePageClient({ projectId, videoId }: VideoSharePageProps) {
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [copied, setCopied] = useState(false);
const [error, setError] = useState('');
const [shareUrl, setShareUrl] = useState<string | null>(null);
const [hasPassword, setHasPassword] = useState(false);
const [password, setPassword] = useState('');
const [allowDownloads, setAllowDownloads] = useState(false);
useEffect(() => {
if (!projectId || !videoId) return;
async function loadShareLink() {
setLoading(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, { cache: 'no-store' });
const payload = (await response.json()) as ShareResponse;
if (!response.ok || payload.error) {
setError(payload.error || 'Failed to load share link');
setShareUrl(null);
return;
}
setShareUrl(payload.data.shareUrl);
setHasPassword(!!payload.data.link?.hasPassword);
setAllowDownloads(!!payload.data.link?.allowDownloads);
} catch {
setError('Failed to load share link');
setShareUrl(null);
setHasPassword(false);
setAllowDownloads(false);
} finally {
setLoading(false);
}
}
loadShareLink();
}, [projectId, videoId]);
const copyLink = async () => {
if (!shareUrl) return;
await navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const createShareLink = async () => {
if (!projectId || !videoId) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ allowGuests: true, allowDownloads }),
});
const payload = (await response.json()) as ShareResponse;
if (!response.ok || payload.error) {
setError(payload.error || 'Failed to create share link');
return;
}
setShareUrl(payload.data.shareUrl);
setHasPassword(!!payload.data.link?.hasPassword);
setAllowDownloads(!!payload.data.link?.allowDownloads);
setPassword('');
} catch {
setError('Failed to create share link');
} finally {
setSubmitting(false);
}
};
const revokeShareLink = async () => {
if (!projectId || !videoId) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'DELETE',
});
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: string } | null;
setError(payload?.error || 'Failed to revoke share link');
return;
}
setShareUrl(null);
setHasPassword(false);
setAllowDownloads(false);
setPassword('');
} catch {
setError('Failed to revoke share link');
} finally {
setSubmitting(false);
}
};
const updateSecuritySettings = async (clearPassword = false) => {
if (!projectId || !videoId || !shareUrl) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...(clearPassword ? { clearPassword: true } : {}),
...(!clearPassword ? { password } : {}),
}),
});
const payload = (await response.json().catch(() => null)) as ShareResponse | { error?: string } | null;
if (!response.ok || ('error' in (payload || {}) && payload?.error)) {
setError((payload as { error?: string } | null)?.error || 'Failed to update link security');
return;
}
const data = (payload as ShareResponse).data;
setShareUrl(data.shareUrl);
setHasPassword(!!data.link?.hasPassword);
setAllowDownloads(!!data.link?.allowDownloads);
setPassword('');
} catch {
setError('Failed to update link security');
} finally {
setSubmitting(false);
}
};
const updateDownloadSetting = async (nextAllowDownloads: boolean) => {
if (!projectId || !videoId || !shareUrl) return;
setSubmitting(true);
setError('');
try {
const response = await fetch(`/api/projects/${projectId}/videos/${videoId}/share`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ allowDownloads: nextAllowDownloads }),
});
const payload = (await response.json().catch(() => null)) as ShareResponse | { error?: string } | null;
if (!response.ok || ('error' in (payload || {}) && payload?.error)) {
setError((payload as { error?: string } | null)?.error || 'Failed to update download setting');
return;
}
const data = (payload as ShareResponse).data;
setShareUrl(data.shareUrl);
setAllowDownloads(!!data.link?.allowDownloads);
setHasPassword(!!data.link?.hasPassword);
} catch {
setError('Failed to update download setting');
} finally {
setSubmitting(false);
}
};
return (
<div className="min-h-[calc(100vh-4rem)] flex items-start justify-center py-12 px-4">
<div className="w-full max-w-xl space-y-6">
<Link
href={`/projects/${projectId}/videos/${videoId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Video
</Link>
<Card className="border-border/50 shadow-lg">
<CardHeader>
<CardTitle className="text-2xl">Share Video For Review</CardTitle>
<CardDescription>
Create a private link so reviewers can watch and comment on this single video.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{loading ? (
<div className="flex items-center text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Loading link settings...
</div>
) : shareUrl ? (
<div className="space-y-3">
<div className="flex gap-2">
<Input value={shareUrl} readOnly className="font-mono text-sm h-11 bg-muted/50" />
<Button
variant={copied ? 'default' : 'outline'}
size="icon"
className="h-11 w-11 shrink-0"
onClick={copyLink}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
<div className="flex gap-2">
<Button onClick={createShareLink} disabled={submitting} variant="outline">
{submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <RefreshCcw className="h-4 w-4 mr-2" />}
Regenerate Link
</Button>
<Button onClick={revokeShareLink} disabled={submitting} variant="destructive">
{submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <ShieldOff className="h-4 w-4 mr-2" />}
Revoke Link
</Button>
</div>
<div className="rounded-lg border p-3 space-y-2">
<div>
<p className="text-sm font-medium">Video download</p>
<p className="text-xs text-muted-foreground">Allow viewers with this link to download</p>
</div>
<div className="flex gap-2">
<Button
variant={allowDownloads ? 'default' : 'outline'}
disabled={submitting || allowDownloads}
onClick={() => updateDownloadSetting(true)}
>
Allow Download
</Button>
<Button
variant={!allowDownloads ? 'default' : 'outline'}
disabled={submitting || !allowDownloads}
onClick={() => updateDownloadSetting(false)}
>
Block Download
</Button>
</div>
</div>
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center gap-2 text-sm font-medium">
{hasPassword ? <ShieldCheck className="h-4 w-4 text-green-600" /> : <Lock className="h-4 w-4" />}
Link password
</div>
<div className="flex gap-2">
<Input
type="password"
placeholder={hasPassword ? 'Enter new password to replace current one' : 'Set a password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={submitting}
/>
<Button
onClick={() => updateSecuritySettings(false)}
disabled={submitting || !password.trim()}
variant="outline"
>
Save
</Button>
{hasPassword && (
<Button
onClick={() => updateSecuritySettings(true)}
disabled={submitting}
variant="outline"
>
Remove
</Button>
)}
</div>
</div>
</div>
) : (
<Button onClick={createShareLink} disabled={submitting}>
{submitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Link2 className="h-4 w-4 mr-2" />}
Create Review Link
</Button>
)}
<p className="text-xs text-muted-foreground">
This link allows guests to leave comments without an account. You can optionally protect it with a password.
</p>
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
</CardContent>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,531 @@
'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { ArrowLeft, Loader2, Link as LinkIcon, AlertCircle, CheckCircle2, UploadCloud, FileVideo } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { parseVideoUrl, fetchVideoMetadata, getThumbnailUrl, type VideoSource } from '@/lib/video-providers';
import * as tus from 'tus-js-client';
export default function NewVideoPageClient({ projectId }: { projectId: string }) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [isFetchingMeta, setIsFetchingMeta] = useState(false);
// URL Mode State
const [videoUrl, setVideoUrl] = useState('');
const [videoSource, setVideoSource] = useState<VideoSource | null>(null);
const [urlError, setUrlError] = useState('');
// Upload Mode State
const [uploadMode, setUploadMode] = useState<'url' | 'file'>('url');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadStatus, setUploadStatus] = useState('');
const [pendingBunnyVideoId, setPendingBunnyVideoId] = useState<string | null>(null);
const [pendingBunnyUploadToken, setPendingBunnyUploadToken] = useState<string | null>(null);
const pendingBunnyVideoIdRef = useRef<string | null>(null);
const pendingBunnyUploadTokenRef = useRef<string | null>(null);
const activeTusUploadRef = useRef<tus.Upload | null>(null);
const [submitError, setSubmitError] = useState('');
const [formData, setFormData] = useState({
title: '',
description: '',
});
const isUploadingFile = isLoading && uploadMode === 'file';
const leaveWarningMessage = 'A video upload is in progress. Leaving this page will interrupt it. Do you want to leave?';
useEffect(() => {
pendingBunnyVideoIdRef.current = pendingBunnyVideoId;
}, [pendingBunnyVideoId]);
useEffect(() => {
pendingBunnyUploadTokenRef.current = pendingBunnyUploadToken;
}, [pendingBunnyUploadToken]);
const cleanupPendingBunnyVideo = useCallback(async (videoId: string, uploadToken: string, keepalive = false) => {
try {
await fetch(`/api/projects/${projectId}/videos/bunny-init`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ videoId, uploadToken }),
keepalive,
});
} catch (error) {
console.error('Failed to cleanup pending Bunny upload:', error);
} finally {
if (pendingBunnyVideoIdRef.current === videoId) {
pendingBunnyVideoIdRef.current = null;
setPendingBunnyVideoId(null);
}
if (pendingBunnyUploadTokenRef.current === uploadToken) {
pendingBunnyUploadTokenRef.current = null;
setPendingBunnyUploadToken(null);
}
}
}, [projectId]);
const abortAndCleanupPendingUpload = useCallback((keepalive = false) => {
const pendingVideoId = pendingBunnyVideoIdRef.current;
const pendingUploadToken = pendingBunnyUploadTokenRef.current;
if (!pendingVideoId || !pendingUploadToken) return;
if (activeTusUploadRef.current) {
try {
activeTusUploadRef.current.abort(true);
} catch {
// Ignore abort failures; we'll still attempt cleanup.
} finally {
activeTusUploadRef.current = null;
}
}
void cleanupPendingBunnyVideo(pendingVideoId, pendingUploadToken, keepalive);
}, [cleanupPendingBunnyVideo]);
useEffect(() => {
if (!isUploadingFile) return;
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = '';
};
const handlePageHide = () => {
abortAndCleanupPendingUpload(true);
};
const handlePopState = () => {
const shouldLeave = window.confirm(leaveWarningMessage);
if (!shouldLeave) {
window.history.pushState(null, '', window.location.href);
return;
}
abortAndCleanupPendingUpload(true);
};
window.history.pushState(null, '', window.location.href);
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('pagehide', handlePageHide);
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('pagehide', handlePageHide);
window.removeEventListener('popstate', handlePopState);
};
}, [abortAndCleanupPendingUpload, isUploadingFile]);
// Auto-fetch metadata when a valid video source is detected
useEffect(() => {
if (!videoSource) return;
let cancelled = false;
setIsFetchingMeta(true);
fetchVideoMetadata(videoSource).then((meta) => {
if (cancelled || !meta) {
setIsFetchingMeta(false);
return;
}
if (!formData.title) {
setFormData((prev) => ({ ...prev, title: meta.title }));
}
setVideoSource((prev) => (prev ? { ...prev, metadata: meta } : prev));
setIsFetchingMeta(false);
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [videoSource?.videoId, videoSource?.providerId]);
const handleUrlChange = (url: string) => {
setVideoUrl(url);
setUrlError('');
setSubmitError('');
if (!url.trim()) {
setVideoSource(null);
return;
}
const source = parseVideoUrl(url);
if (source) {
setVideoSource(source);
} else {
setVideoSource(null);
if (url.length > 10) {
setUrlError('Could not recognize this video URL. Currently supported: YouTube, Vimeo');
}
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
if (!file.type.startsWith('video/')) {
setSubmitError('Please select a valid video file.');
return;
}
setSelectedFile(file);
setSubmitError('');
if (!formData.title) {
// Strip extension from filename for default title
const nameWithoutExt = file.name.replace(/\.[^/.]+$/, '');
setFormData((prev) => ({ ...prev, title: nameWithoutExt }));
}
}
};
const uploadToBunny = async (
file: File
): Promise<{ videoId: string; libraryId: string; providerId: string; url: string; uploadToken: string }> => {
// 1. Initialize Bunny Stream upload (creates video & gets signature)
setUploadStatus('Initializing upload...');
const initRes = await fetch(`/api/projects/${projectId}/videos/bunny-init`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: formData.title || file.name })
});
if (!initRes.ok) {
const data = await initRes.json();
throw new Error(data.error || 'Failed to initialize upload');
}
const { data: { videoId, libraryId, signature, expirationTime, uploadToken } } = await initRes.json();
setPendingBunnyVideoId(videoId);
setPendingBunnyUploadToken(uploadToken);
pendingBunnyVideoIdRef.current = videoId;
pendingBunnyUploadTokenRef.current = uploadToken;
// 2. Upload via TUS
return new Promise((resolve, reject) => {
setUploadStatus('Uploading video...');
const upload = new tus.Upload(file, {
endpoint: 'https://video.bunnycdn.com/tusupload',
retryDelays: [0, 3000, 5000, 10000, 20000],
headers: {
AuthorizationSignature: signature,
AuthorizationExpire: expirationTime.toString(),
VideoId: videoId,
LibraryId: libraryId,
},
metadata: {
filetype: file.type,
title: formData.title || file.name,
},
onError: (error) => {
activeTusUploadRef.current = null;
reject(new Error('Upload failed: ' + error.message));
},
onProgress: (bytesUploaded, bytesTotal) => {
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(1);
setUploadProgress(Number(percentage));
setUploadStatus(`Uploading... ${percentage}%`);
},
onSuccess: () => {
activeTusUploadRef.current = null;
setUploadStatus('Processing video...');
resolve({
videoId,
libraryId,
providerId: 'bunny',
url: `https://iframe.mediadelivery.net/embed/${libraryId}/${videoId}`,
uploadToken,
});
},
});
activeTusUploadRef.current = upload;
upload.start();
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setSubmitError('');
setUploadStatus('');
setUploadProgress(0);
try {
let uploadedBunnyVideoId: string | null = null;
let uploadedBunnyUploadToken: string | null = null;
let finalTitle = formData.title.trim();
const finalDescription = formData.description.trim() || null;
let finalVideoUrl = '';
let finalProviderId = '';
let finalVideoId = '';
let finalThumbnailUrl: string | null = null;
let finalDuration: number | null = null;
if (uploadMode === 'url') {
if (!videoSource) {
setUrlError('Please enter a valid video URL');
setIsLoading(false);
return;
}
finalTitle = finalTitle || videoSource.metadata?.title || 'Untitled Video';
finalVideoUrl = videoSource.originalUrl;
finalProviderId = videoSource.providerId;
finalVideoId = videoSource.videoId;
finalThumbnailUrl = getThumbnailUrl(videoSource, 'large');
finalDuration = videoSource.metadata?.duration || null;
} else {
if (!selectedFile) {
setSubmitError('Please select a video file to upload');
setIsLoading(false);
return;
}
finalTitle = finalTitle || selectedFile.name;
// Handle TUS Upload
const bunnyData = await uploadToBunny(selectedFile);
uploadedBunnyVideoId = bunnyData.videoId;
uploadedBunnyUploadToken = bunnyData.uploadToken;
finalVideoUrl = bunnyData.url;
finalProviderId = bunnyData.providerId;
finalVideoId = bunnyData.videoId;
// Bunny will generate thumbnails automatically after processing.
// We'll just provide the standard CDN thumbnail URL format as fallback.
finalThumbnailUrl = `https://vz-thumbnail.b-cdn.net/${bunnyData.videoId}/thumbnail.jpg`;
}
// Final POST to our database
const response = await fetch(`/api/projects/${projectId}/videos`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: finalTitle,
description: finalDescription,
videoUrl: finalVideoUrl,
providerId: finalProviderId,
videoId: finalVideoId,
thumbnailUrl: finalThumbnailUrl,
duration: finalDuration,
uploadToken: uploadedBunnyUploadToken,
}),
});
if (!response.ok) {
const data = await response.json();
setSubmitError(data.error || 'Failed to add video');
if (uploadedBunnyVideoId && uploadedBunnyUploadToken) {
await cleanupPendingBunnyVideo(uploadedBunnyVideoId, uploadedBunnyUploadToken);
}
return;
}
pendingBunnyVideoIdRef.current = null;
pendingBunnyUploadTokenRef.current = null;
setPendingBunnyVideoId(null);
setPendingBunnyUploadToken(null);
router.push(`/projects/${projectId}`);
} catch (error: unknown) {
console.error('Failed to add video:', error);
setSubmitError(error instanceof Error ? error.message : 'An unexpected error occurred');
if (pendingBunnyVideoIdRef.current && pendingBunnyUploadTokenRef.current) {
await cleanupPendingBunnyVideo(pendingBunnyVideoIdRef.current, pendingBunnyUploadTokenRef.current);
}
} finally {
activeTusUploadRef.current = null;
setIsLoading(false);
}
};
const thumbnailUrl = videoSource ? getThumbnailUrl(videoSource, 'large') : null;
return (
<div className="container max-w-2xl mx-auto py-8">
<div className="mb-6">
<Link
href={`/projects/${projectId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
onClick={(event) => {
if (!isUploadingFile) return;
const shouldLeave = window.confirm(leaveWarningMessage);
if (!shouldLeave) {
event.preventDefault();
return;
}
abortAndCleanupPendingUpload(true);
}}
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Project
</Link>
</div>
<Card>
<CardHeader>
<CardTitle>Add Video</CardTitle>
<CardDescription>
Paste a video link or upload a file directly to add it to your project. Currently supports YouTube.
</CardDescription>
</CardHeader>
<CardContent>
<Tabs value={uploadMode} onValueChange={(v) => !isLoading && setUploadMode(v as 'url' | 'file')} className="mb-6">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="url" disabled={isLoading}>Paste URL</TabsTrigger>
<TabsTrigger value="file" disabled={isLoading}>Direct Upload</TabsTrigger>
</TabsList>
</Tabs>
<form onSubmit={handleSubmit} className="space-y-6">
{uploadMode === 'url' ? (
<div className="space-y-2">
<Label htmlFor="url">Video URL</Label>
<div className="relative">
<LinkIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
id="url"
placeholder="https://youtube.com/watch?v=..."
value={videoUrl}
onChange={(e) => handleUrlChange(e.target.value)}
className="pl-10"
required
disabled={isLoading}
/>
</div>
{urlError && (
<p className="text-sm text-destructive flex items-center gap-1">
<AlertCircle className="h-4 w-4" />
{urlError}
</p>
)}
{videoSource && (
<p className="text-sm text-green-600 flex items-center gap-1">
<CheckCircle2 className="h-4 w-4" />
{videoSource.providerId.charAt(0).toUpperCase() + videoSource.providerId.slice(1)} video detected
{isFetchingMeta && ' — fetching metadata...'}
</p>
)}
</div>
) : (
<div className="space-y-2">
<Label htmlFor="file">Video File</Label>
<div className="flex items-center justify-center w-full">
<label htmlFor="file" className={`flex flex-col items-center justify-center w-full h-40 border-2 border-dashed rounded-lg cursor-pointer bg-muted/30 hover:bg-muted/50 transition-colors ${selectedFile ? 'border-primary' : 'border-border'}`}>
<div className="flex flex-col items-center justify-center pt-5 pb-6">
{selectedFile ? (
<>
<FileVideo className="w-10 h-10 mb-3 text-primary" />
<p className="mb-2 text-sm text-foreground font-medium">{selectedFile.name}</p>
<p className="text-xs text-muted-foreground">
{(selectedFile.size / (1024 * 1024)).toFixed(2)} MB
</p>
</>
) : (
<>
<UploadCloud className="w-10 h-10 mb-3 text-muted-foreground" />
<p className="mb-2 text-sm text-muted-foreground">
<span className="font-semibold">Click to upload</span> or drag and drop
</p>
<p className="text-xs text-muted-foreground">MP4, WebM, or OGG</p>
</>
)}
</div>
<input id="file" type="file" accept="video/*" className="hidden" onChange={handleFileChange} disabled={isLoading} />
</label>
</div>
</div>
)}
{/* Video Preview (Only for URL mode) */}
{uploadMode === 'url' && thumbnailUrl && videoSource && (
<div className="space-y-2">
<Label>Preview</Label>
<div className="relative aspect-video rounded-lg overflow-hidden bg-muted">
<Image
src={thumbnailUrl}
alt="Video thumbnail"
fill
sizes="(max-width: 768px) 100vw, 600px"
className="object-cover"
/>
</div>
</div>
)}
{/* Title */}
<div className="space-y-2">
<Label htmlFor="title">Title</Label>
<Input
id="title"
placeholder={isFetchingMeta ? 'Fetching title...' : 'Video title (will auto-fill from video if empty)'}
value={formData.title}
onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
disabled={isLoading}
/>
<p className="text-xs text-muted-foreground">
Leave empty to use the original video title
</p>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="description">Description (optional)</Label>
<Textarea
id="description"
placeholder="Add context about this video..."
value={formData.description}
onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
rows={3}
disabled={isLoading}
/>
</div>
{submitError && (
<p className="text-sm text-destructive flex items-center gap-1">
<AlertCircle className="h-4 w-4" />
{submitError}
</p>
)}
{uploadStatus && (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">{uploadStatus}</p>
{uploadProgress > 0 && uploadProgress < 100 && (
<div className="w-full bg-secondary rounded-full h-2">
<div className="bg-primary h-2 rounded-full transition-all" style={{ width: `${uploadProgress}%` }}></div>
</div>
)}
{isUploadingFile && (
<p className="text-xs text-amber-500">
Do not close, refresh, or navigate away while the upload is in progress.
</p>
)}
</div>
)}
<div className="flex flex-wrap gap-3">
<Button type="submit" disabled={isLoading || (uploadMode === 'url' && !videoSource) || (uploadMode === 'file' && !selectedFile)}>
{isLoading && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Add Video
</Button>
<Button type="button" variant="outline" onClick={() => router.back()} disabled={isLoading}>
Cancel
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
@@ -1,533 +1,17 @@
'use client';
import { requireProjectAccessOrRedirect } from '@/lib/route-access';
import NewVideoPageClient from './new-video-page-client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { ArrowLeft, Loader2, Link as LinkIcon, AlertCircle, CheckCircle2, UploadCloud, FileVideo } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { parseVideoUrl, fetchVideoMetadata, getThumbnailUrl, type VideoSource } from '@/lib/video-providers';
import * as tus from 'tus-js-client';
interface NewVideoPageProps {
params: Promise<{ projectId: string }>;
}
export default function NewVideoPage() {
const router = useRouter();
const params = useParams();
const projectId = params.projectId as string;
export default async function NewVideoPage({ params }: NewVideoPageProps) {
const { projectId } = await params;
const [isLoading, setIsLoading] = useState(false);
const [isFetchingMeta, setIsFetchingMeta] = useState(false);
// URL Mode State
const [videoUrl, setVideoUrl] = useState('');
const [videoSource, setVideoSource] = useState<VideoSource | null>(null);
const [urlError, setUrlError] = useState('');
// Upload Mode State
const [uploadMode, setUploadMode] = useState<'url' | 'file'>('url');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadStatus, setUploadStatus] = useState('');
const [pendingBunnyVideoId, setPendingBunnyVideoId] = useState<string | null>(null);
const [pendingBunnyUploadToken, setPendingBunnyUploadToken] = useState<string | null>(null);
const pendingBunnyVideoIdRef = useRef<string | null>(null);
const pendingBunnyUploadTokenRef = useRef<string | null>(null);
const activeTusUploadRef = useRef<tus.Upload | null>(null);
const [submitError, setSubmitError] = useState('');
const [formData, setFormData] = useState({
title: '',
description: '',
await requireProjectAccessOrRedirect({
projectId,
intent: 'manage',
});
const isUploadingFile = isLoading && uploadMode === 'file';
const leaveWarningMessage = 'A video upload is in progress. Leaving this page will interrupt it. Do you want to leave?';
useEffect(() => {
pendingBunnyVideoIdRef.current = pendingBunnyVideoId;
}, [pendingBunnyVideoId]);
useEffect(() => {
pendingBunnyUploadTokenRef.current = pendingBunnyUploadToken;
}, [pendingBunnyUploadToken]);
const cleanupPendingBunnyVideo = useCallback(async (videoId: string, uploadToken: string, keepalive = false) => {
try {
await fetch(`/api/projects/${projectId}/videos/bunny-init`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ videoId, uploadToken }),
keepalive,
});
} catch (error) {
console.error('Failed to cleanup pending Bunny upload:', error);
} finally {
if (pendingBunnyVideoIdRef.current === videoId) {
pendingBunnyVideoIdRef.current = null;
setPendingBunnyVideoId(null);
}
if (pendingBunnyUploadTokenRef.current === uploadToken) {
pendingBunnyUploadTokenRef.current = null;
setPendingBunnyUploadToken(null);
}
}
}, [projectId]);
const abortAndCleanupPendingUpload = useCallback((keepalive = false) => {
const pendingVideoId = pendingBunnyVideoIdRef.current;
const pendingUploadToken = pendingBunnyUploadTokenRef.current;
if (!pendingVideoId || !pendingUploadToken) return;
if (activeTusUploadRef.current) {
try {
activeTusUploadRef.current.abort(true);
} catch {
// Ignore abort failures; we'll still attempt cleanup.
} finally {
activeTusUploadRef.current = null;
}
}
void cleanupPendingBunnyVideo(pendingVideoId, pendingUploadToken, keepalive);
}, [cleanupPendingBunnyVideo]);
useEffect(() => {
if (!isUploadingFile) return;
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = '';
};
const handlePageHide = () => {
abortAndCleanupPendingUpload(true);
};
const handlePopState = () => {
const shouldLeave = window.confirm(leaveWarningMessage);
if (!shouldLeave) {
window.history.pushState(null, '', window.location.href);
return;
}
abortAndCleanupPendingUpload(true);
};
window.history.pushState(null, '', window.location.href);
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('pagehide', handlePageHide);
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('pagehide', handlePageHide);
window.removeEventListener('popstate', handlePopState);
};
}, [abortAndCleanupPendingUpload, isUploadingFile]);
// Auto-fetch metadata when a valid video source is detected
useEffect(() => {
if (!videoSource) return;
let cancelled = false;
setIsFetchingMeta(true);
fetchVideoMetadata(videoSource).then((meta) => {
if (cancelled || !meta) {
setIsFetchingMeta(false);
return;
}
if (!formData.title) {
setFormData((prev) => ({ ...prev, title: meta.title }));
}
setVideoSource((prev) => (prev ? { ...prev, metadata: meta } : prev));
setIsFetchingMeta(false);
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [videoSource?.videoId, videoSource?.providerId]);
const handleUrlChange = (url: string) => {
setVideoUrl(url);
setUrlError('');
setSubmitError('');
if (!url.trim()) {
setVideoSource(null);
return;
}
const source = parseVideoUrl(url);
if (source) {
setVideoSource(source);
} else {
setVideoSource(null);
if (url.length > 10) {
setUrlError('Could not recognize this video URL. Currently supported: YouTube, Vimeo');
}
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
if (!file.type.startsWith('video/')) {
setSubmitError('Please select a valid video file.');
return;
}
setSelectedFile(file);
setSubmitError('');
if (!formData.title) {
// Strip extension from filename for default title
const nameWithoutExt = file.name.replace(/\.[^/.]+$/, '');
setFormData((prev) => ({ ...prev, title: nameWithoutExt }));
}
}
};
const uploadToBunny = async (
file: File
): Promise<{ videoId: string; libraryId: string; providerId: string; url: string; uploadToken: string }> => {
// 1. Initialize Bunny Stream upload (creates video & gets signature)
setUploadStatus('Initializing upload...');
const initRes = await fetch(`/api/projects/${projectId}/videos/bunny-init`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: formData.title || file.name })
});
if (!initRes.ok) {
const data = await initRes.json();
throw new Error(data.error || 'Failed to initialize upload');
}
const { data: { videoId, libraryId, signature, expirationTime, uploadToken } } = await initRes.json();
setPendingBunnyVideoId(videoId);
setPendingBunnyUploadToken(uploadToken);
pendingBunnyVideoIdRef.current = videoId;
pendingBunnyUploadTokenRef.current = uploadToken;
// 2. Upload via TUS
return new Promise((resolve, reject) => {
setUploadStatus('Uploading video...');
const upload = new tus.Upload(file, {
endpoint: 'https://video.bunnycdn.com/tusupload',
retryDelays: [0, 3000, 5000, 10000, 20000],
headers: {
AuthorizationSignature: signature,
AuthorizationExpire: expirationTime.toString(),
VideoId: videoId,
LibraryId: libraryId,
},
metadata: {
filetype: file.type,
title: formData.title || file.name,
},
onError: (error) => {
activeTusUploadRef.current = null;
reject(new Error('Upload failed: ' + error.message));
},
onProgress: (bytesUploaded, bytesTotal) => {
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(1);
setUploadProgress(Number(percentage));
setUploadStatus(`Uploading... ${percentage}%`);
},
onSuccess: () => {
activeTusUploadRef.current = null;
setUploadStatus('Processing video...');
resolve({
videoId,
libraryId,
providerId: 'bunny',
url: `https://iframe.mediadelivery.net/embed/${libraryId}/${videoId}`,
uploadToken,
});
},
});
activeTusUploadRef.current = upload;
upload.start();
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setSubmitError('');
setUploadStatus('');
setUploadProgress(0);
try {
let uploadedBunnyVideoId: string | null = null;
let uploadedBunnyUploadToken: string | null = null;
let finalTitle = formData.title.trim();
const finalDescription = formData.description.trim() || null;
let finalVideoUrl = '';
let finalProviderId = '';
let finalVideoId = '';
let finalThumbnailUrl: string | null = null;
let finalDuration: number | null = null;
if (uploadMode === 'url') {
if (!videoSource) {
setUrlError('Please enter a valid video URL');
setIsLoading(false);
return;
}
finalTitle = finalTitle || videoSource.metadata?.title || 'Untitled Video';
finalVideoUrl = videoSource.originalUrl;
finalProviderId = videoSource.providerId;
finalVideoId = videoSource.videoId;
finalThumbnailUrl = getThumbnailUrl(videoSource, 'large');
finalDuration = videoSource.metadata?.duration || null;
} else {
if (!selectedFile) {
setSubmitError('Please select a video file to upload');
setIsLoading(false);
return;
}
finalTitle = finalTitle || selectedFile.name;
// Handle TUS Upload
const bunnyData = await uploadToBunny(selectedFile);
uploadedBunnyVideoId = bunnyData.videoId;
uploadedBunnyUploadToken = bunnyData.uploadToken;
finalVideoUrl = bunnyData.url;
finalProviderId = bunnyData.providerId;
finalVideoId = bunnyData.videoId;
// Bunny will generate thumbnails automatically after processing.
// We'll just provide the standard CDN thumbnail URL format as fallback.
finalThumbnailUrl = `https://vz-thumbnail.b-cdn.net/${bunnyData.videoId}/thumbnail.jpg`;
}
// Final POST to our database
const response = await fetch(`/api/projects/${projectId}/videos`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: finalTitle,
description: finalDescription,
videoUrl: finalVideoUrl,
providerId: finalProviderId,
videoId: finalVideoId,
thumbnailUrl: finalThumbnailUrl,
duration: finalDuration,
uploadToken: uploadedBunnyUploadToken,
}),
});
if (!response.ok) {
const data = await response.json();
setSubmitError(data.error || 'Failed to add video');
if (uploadedBunnyVideoId && uploadedBunnyUploadToken) {
await cleanupPendingBunnyVideo(uploadedBunnyVideoId, uploadedBunnyUploadToken);
}
return;
}
pendingBunnyVideoIdRef.current = null;
pendingBunnyUploadTokenRef.current = null;
setPendingBunnyVideoId(null);
setPendingBunnyUploadToken(null);
router.push(`/projects/${projectId}`);
} catch (error: unknown) {
console.error('Failed to add video:', error);
setSubmitError(error instanceof Error ? error.message : 'An unexpected error occurred');
if (pendingBunnyVideoIdRef.current && pendingBunnyUploadTokenRef.current) {
await cleanupPendingBunnyVideo(pendingBunnyVideoIdRef.current, pendingBunnyUploadTokenRef.current);
}
} finally {
activeTusUploadRef.current = null;
setIsLoading(false);
}
};
const thumbnailUrl = videoSource ? getThumbnailUrl(videoSource, 'large') : null;
return (
<div className="container max-w-2xl mx-auto py-8">
<div className="mb-6">
<Link
href={`/projects/${projectId}`}
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
onClick={(event) => {
if (!isUploadingFile) return;
const shouldLeave = window.confirm(leaveWarningMessage);
if (!shouldLeave) {
event.preventDefault();
return;
}
abortAndCleanupPendingUpload(true);
}}
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to Project
</Link>
</div>
<Card>
<CardHeader>
<CardTitle>Add Video</CardTitle>
<CardDescription>
Paste a video link or upload a file directly to add it to your project. Currently supports YouTube.
</CardDescription>
</CardHeader>
<CardContent>
<Tabs value={uploadMode} onValueChange={(v) => !isLoading && setUploadMode(v as 'url' | 'file')} className="mb-6">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="url" disabled={isLoading}>Paste URL</TabsTrigger>
<TabsTrigger value="file" disabled={isLoading}>Direct Upload</TabsTrigger>
</TabsList>
</Tabs>
<form onSubmit={handleSubmit} className="space-y-6">
{uploadMode === 'url' ? (
<div className="space-y-2">
<Label htmlFor="url">Video URL</Label>
<div className="relative">
<LinkIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
id="url"
placeholder="https://youtube.com/watch?v=..."
value={videoUrl}
onChange={(e) => handleUrlChange(e.target.value)}
className="pl-10"
required
disabled={isLoading}
/>
</div>
{urlError && (
<p className="text-sm text-destructive flex items-center gap-1">
<AlertCircle className="h-4 w-4" />
{urlError}
</p>
)}
{videoSource && (
<p className="text-sm text-green-600 flex items-center gap-1">
<CheckCircle2 className="h-4 w-4" />
{videoSource.providerId.charAt(0).toUpperCase() + videoSource.providerId.slice(1)} video detected
{isFetchingMeta && ' — fetching metadata...'}
</p>
)}
</div>
) : (
<div className="space-y-2">
<Label htmlFor="file">Video File</Label>
<div className="flex items-center justify-center w-full">
<label htmlFor="file" className={`flex flex-col items-center justify-center w-full h-40 border-2 border-dashed rounded-lg cursor-pointer bg-muted/30 hover:bg-muted/50 transition-colors ${selectedFile ? 'border-primary' : 'border-border'}`}>
<div className="flex flex-col items-center justify-center pt-5 pb-6">
{selectedFile ? (
<>
<FileVideo className="w-10 h-10 mb-3 text-primary" />
<p className="mb-2 text-sm text-foreground font-medium">{selectedFile.name}</p>
<p className="text-xs text-muted-foreground">
{(selectedFile.size / (1024 * 1024)).toFixed(2)} MB
</p>
</>
) : (
<>
<UploadCloud className="w-10 h-10 mb-3 text-muted-foreground" />
<p className="mb-2 text-sm text-muted-foreground">
<span className="font-semibold">Click to upload</span> or drag and drop
</p>
<p className="text-xs text-muted-foreground">MP4, WebM, or OGG</p>
</>
)}
</div>
<input id="file" type="file" accept="video/*" className="hidden" onChange={handleFileChange} disabled={isLoading} />
</label>
</div>
</div>
)}
{/* Video Preview (Only for URL mode) */}
{uploadMode === 'url' && thumbnailUrl && videoSource && (
<div className="space-y-2">
<Label>Preview</Label>
<div className="relative aspect-video rounded-lg overflow-hidden bg-muted">
<Image
src={thumbnailUrl}
alt="Video thumbnail"
fill
sizes="(max-width: 768px) 100vw, 600px"
className="object-cover"
/>
</div>
</div>
)}
{/* Title */}
<div className="space-y-2">
<Label htmlFor="title">Title</Label>
<Input
id="title"
placeholder={isFetchingMeta ? 'Fetching title...' : 'Video title (will auto-fill from video if empty)'}
value={formData.title}
onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
disabled={isLoading}
/>
<p className="text-xs text-muted-foreground">
Leave empty to use the original video title
</p>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="description">Description (optional)</Label>
<Textarea
id="description"
placeholder="Add context about this video..."
value={formData.description}
onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
rows={3}
disabled={isLoading}
/>
</div>
{submitError && (
<p className="text-sm text-destructive flex items-center gap-1">
<AlertCircle className="h-4 w-4" />
{submitError}
</p>
)}
{uploadStatus && (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">{uploadStatus}</p>
{uploadProgress > 0 && uploadProgress < 100 && (
<div className="w-full bg-secondary rounded-full h-2">
<div className="bg-primary h-2 rounded-full transition-all" style={{ width: `${uploadProgress}%` }}></div>
</div>
)}
{isUploadingFile && (
<p className="text-xs text-amber-500">
Do not close, refresh, or navigate away while the upload is in progress.
</p>
)}
</div>
)}
<div className="flex flex-wrap gap-3">
<Button type="submit" disabled={isLoading || (uploadMode === 'url' && !videoSource) || (uploadMode === 'file' && !selectedFile)}>
{isLoading && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Add Video
</Button>
<Button type="button" variant="outline" onClick={() => router.back()} disabled={isLoading}>
Cancel
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
return <NewVideoPageClient projectId={projectId} />;
}