All files / src/pages projects.tsx

98.66% Statements 74/75
83.67% Branches 41/49
100% Functions 26/26
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276                                                          45x 45x 45x 45x 45x 45x 45x 45x 32x       45x     45x 45x 45x 45x   45x 6x     45x 3x     3x 3x 3x 1x     3x     45x 2x 2x     45x 2x 1x     45x 2x 1x     45x 2x 1x     45x 2x 1x     45x 1x       45x 34x 34x 34x       45x 33x 33x 35x   33x 1x 1x   1x         45x           45x 2x                                   43x                         1x             1x                                                       1x                                       1x 1x                                               31x                           3x                                 1x                  
import { useState, useMemo } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import type { Project } from "../lib/api";
import { usePro } from "../lib/pro-context";
import { Plus, Search, FolderKanban, LayoutGrid, List, FileEdit, Globe, Archive, ArrowUpDown, Clapperboard } from "lucide-react";
import { StickyPageHeader } from "../components/ui/sticky-page-header";
import { FacetedFilter } from "../components/ui/faceted-filter";
import { ProjectCreationWizard } from "../components/projects/ProjectCreationWizard";
import { ProjectListItem } from "../components/projects/ProjectListItem";
import { ProjectCard } from "../components/projects/ProjectCard";
import { ProjectEmptyState } from "../components/projects/ProjectEmptyState";
import { useConfirmDialog } from "../hooks";
import { queryKeys } from "../lib/query-keys";
import {
	useProjects,
} from "../hooks/queries/useProjectQueries";
import {
	useDeleteProject,
	usePublishProject,
	useArchiveProject,
	useUnarchiveProject,
} from "../hooks/mutations/useProjectMutations";
import { Skeleton } from "../components/ui/skeleton";
import { useSortable } from "../hooks/useSortable";
 
export function ProjectsPage() {
	const { proId, isLoading: proLoading } = usePro();
	const navigate = useNavigate();
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	const [searchQuery, setSearchQuery] = useState("");
	const [statusFilter, setStatusFilter] = useState<Set<string>>(() => new Set(["draft", "published"]));
	const [wizardOpen, setWizardOpen] = useState(false);
	const [viewMode, setViewMode] = useState<"grid" | "list">(() => {
		try { return (localStorage.getItem("projects-view-mode") as "grid" | "list") || "grid"; } catch { return "grid"; }
	});
 
	// Use TanStack Query hooks
	const { data: projects = [], isLoading } = useProjects(proId);
 
	// Mutations
	const deleteProjectMutation = useDeleteProject(proId ?? "");
	const publishProjectMutation = usePublishProject(proId ?? "");
	const archiveProjectMutation = useArchiveProject(proId ?? "");
	const unarchiveProjectMutation = useUnarchiveProject(proId ?? "");
 
	const openCreateModal = () => {
		setWizardOpen(true);
	};
 
	const handleWizardComplete = (projectId: string) => {
		setWizardOpen(false);
		// Invalidate immediately, then again after a short delay to catch
		// the async cover image denormalization (runs in waitUntil on the API)
		Eif (proId) {
			queryClient.invalidateQueries({ queryKey: queryKeys.projects.list(proId) });
			setTimeout(() => {
				queryClient.invalidateQueries({ queryKey: queryKeys.projects.list(proId) });
			}, 1500);
		}
		navigate({ to: "/projects/$projectId", params: { projectId } });
	};
 
	const handleViewModeChange = (mode: "grid" | "list") => {
		setViewMode(mode);
		try { localStorage.setItem("projects-view-mode", mode); } catch {}
	};
 
	const handleDelete = async (projectId: string) => {
		if (!(await confirm({ title: "Delete project", description: "Are you sure you want to delete this project?", confirmLabel: "Delete", variant: "destructive" }))) return;
		deleteProjectMutation.mutate(projectId);
	};
 
	const handlePublish = async (projectId: string) => {
		if (!(await confirm({ title: "Publish project", description: "This will make the project visible on the marketplace. Continue?", confirmLabel: "Publish" }))) return;
		publishProjectMutation.mutate(projectId);
	};
 
	const handleArchive = async (projectId: string) => {
		if (!(await confirm({ title: "Archive project", description: "This will hide the project from the marketplace. You can move it back to draft later.", confirmLabel: "Archive" }))) return;
		archiveProjectMutation.mutate(projectId);
	};
 
	const handleUnarchive = async (projectId: string) => {
		if (!(await confirm({ title: "Move to draft", description: "This will move the project back to draft status. You can publish it again later.", confirmLabel: "Move to Draft" }))) return;
		unarchiveProjectMutation.mutate(projectId);
	};
 
	const openPhotoManagement = (project: Project) => {
		navigate({ to: "/projects/$projectId", params: { projectId: project.id }, search: { tab: "photos" } });
	};
 
	// Status counts for filter badges
	const statusCounts = useMemo(() => ({
		draft: projects.filter((p) => p.status === "draft").length,
		published: projects.filter((p) => p.status === "published").length,
		archived: projects.filter((p) => p.status === "archived").length,
	}), [projects]);
 
	// Client-side status + search filter
	const filteredProjects = useMemo(() => {
		let result = projects;
		Eif (statusFilter.size > 0) {
			result = result.filter((p) => statusFilter.has(p.status));
		}
		if (!searchQuery.trim()) return result;
		const q = searchQuery.toLowerCase();
		return result.filter(
			(p) =>
				p.title?.toLowerCase().includes(q) ||
				p.description?.toLowerCase().includes(q),
		);
	}, [projects, statusFilter, searchQuery]);
 
	const { sorted: sortedProjects, sortKey, sortOrder, setSort } = useSortable(
		filteredProjects,
		"dateCreated" as keyof Project,
		"desc",
	);
 
	if (proLoading || isLoading) {
		return (
			<div className="space-y-6">
				<div className="flex items-center justify-between">
					<div className="space-y-2">
						<Skeleton className="h-8 w-32" />
						<Skeleton className="h-4 w-64" />
					</div>
					<Skeleton className="h-10 w-32" />
				</div>
				<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
					<Skeleton className="h-64 w-full" />
					<Skeleton className="h-64 w-full" />
					<Skeleton className="h-64 w-full" />
				</div>
			</div>
		);
	}
 
	return (
		<>
			<div className="space-y-6">
				<StickyPageHeader>
					<div className="flex items-center justify-between w-full">
						<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2">
							<FolderKanban className="h-6 w-6" />
							Projects
						</h1>
						<div className="flex items-center gap-2">
							<div className="hidden sm:inline-flex items-center h-9 rounded-lg bg-background-muted p-0.5">
								<button
									type="button"
									onClick={() => handleViewModeChange("grid")}
									className={`inline-flex items-center justify-center rounded-md px-2.5 h-8 transition-all ${viewMode === "grid" ? "bg-background-elevated shadow-sm text-foreground-default" : "text-foreground-muted hover:text-foreground-default"}`}
								>
									<LayoutGrid className="h-4 w-4" />
								</button>
								<button
									type="button"
									onClick={() => handleViewModeChange("list")}
									className={`inline-flex items-center justify-center rounded-md px-2.5 h-8 transition-all ${viewMode === "list" ? "bg-background-elevated shadow-sm text-foreground-default" : "text-foreground-muted hover:text-foreground-default"}`}
								>
									<List className="h-4 w-4" />
								</button>
							</div>
							<Button asChild size="sm" variant="outline" className="whitespace-nowrap hidden sm:inline-flex">
								<Link to="/social-studio/create">
									<Clapperboard className="h-4 w-4" />
									New Reel
								</Link>
							</Button>
							<Button size="sm" onClick={openCreateModal}>
								<Plus className="h-4 w-4" />
								Add Project
							</Button>
						</div>
					</div>
				</StickyPageHeader>
 
				{/* Search & Faceted Filters */}
				{projects.length > 0 && (
					<div className="space-y-2 sm:space-y-0 sm:flex sm:flex-wrap sm:items-center sm:gap-2">
						<div className="relative w-full sm:min-w-0 sm:flex-1 sm:basis-40 sm:max-w-sm">
							<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
							<Input
								placeholder="Filter projects..."
								value={searchQuery}
								onChange={(e) => setSearchQuery(e.target.value)}
								className="pl-10"
							/>
						</div>
						<div className="flex items-center gap-2">
							<FacetedFilter
								title="Status"
								options={[
									{ value: "draft", label: "Draft", icon: <FileEdit className="h-4 w-4" />, count: statusCounts.draft },
									{ value: "published", label: "Published", icon: <Globe className="h-4 w-4" />, count: statusCounts.published },
									{ value: "archived", label: "Archived", icon: <Archive className="h-4 w-4" />, count: statusCounts.archived },
								]}
								selected={statusFilter}
								onChange={setStatusFilter}
							/>
							<div className="relative shrink-0">
								<ArrowUpDown className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-foreground-subtle pointer-events-none" />
								<select
									value={`${sortKey as string}-${sortOrder}`}
									onChange={(e) => {
										const [key, order] = e.target.value.split("-");
										setSort(key as keyof Project, order as "asc" | "desc");
									}}
									className="h-9 rounded-md border border-dashed border-border-default bg-transparent pl-8 pr-3 text-sm font-medium cursor-pointer hover:bg-background-muted transition-colors focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500 appearance-none"
								>
									<option value="dateCreated-desc">Newest</option>
									<option value="dateCreated-asc">Oldest</option>
									<option value="title-asc">A → Z</option>
									<option value="title-desc">Z → A</option>
								</select>
							</div>
						</div>
					</div>
				)}
 
				{/* Projects Grid */}
				{sortedProjects.length === 0 && projects.length > 0 ? (
					<div className="py-12 text-center text-foreground-muted">
						No projects match your {searchQuery.trim() ? "search" : "filter"}.
					</div>
				) : sortedProjects.length === 0 ? (
					<ProjectEmptyState onCreateProject={openCreateModal} />
				) : viewMode === "grid" ? (
					<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
						{sortedProjects.map((project) => (
							<ProjectCard
								key={project.id}
								project={project}
								onDelete={handleDelete}
								onManagePhotos={openPhotoManagement}
								onPublish={handlePublish}
								onArchive={handleArchive}
								onUnarchive={handleUnarchive}
							/>
						))}
					</div>
				) : (
					<div className="space-y-2">
						{sortedProjects.map((project) => (
							<ProjectListItem
								key={project.id}
								project={project}
								onDelete={handleDelete}
								onManagePhotos={openPhotoManagement}
								onPublish={handlePublish}
								onArchive={handleArchive}
								onUnarchive={handleUnarchive}
							/>
						))}
					</div>
				)}
			</div>
 
			{/* Creation Wizard */}
			<ProjectCreationWizard
				isOpen={wizardOpen}
				onClose={() => setWizardOpen(false)}
				onComplete={handleWizardComplete}
				proId={proId ?? ""}
			/>
 
			{confirmDialog}
		</>
	);
}