All files / src/components/blogs CoverImageModal.tsx

96.05% Statements 73/76
90% Branches 27/30
90.47% Functions 19/21
98.57% Lines 69/70

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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320                2x 2x                                               56x 56x 56x 56x     56x 56x 56x 56x             56x 4x 2x   4x 4x 4x     56x 4x 4x     56x 7x 7x     56x 1x 1x   1x 1x       56x 5x 5x 5x 5x       56x 2x 2x 2x 1x 1x       56x 1x       56x 1x 1x 1x       56x 3x 3x 3x     3x 1x 1x 1x 1x   2x 1x 1x 1x 1x 1x       1x   3x       56x   55x                                                                           1x     2x                                                   1x                                       15x       1x                                                                   1x                                                                                                                      
import { useState, useCallback, lazy, Suspense } from "react";
import { createPortal } from "react-dom";
import { notify } from "../../lib/notify";
import { X, Upload, Search, Image as ImageIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "../ui/tabs";
 
const ImageCropper = lazy(() =>
	import("./ImageCropper").then((m) => ({ default: m.ImageCropper })),
);
import { proApi } from "../../lib/api";
import type { PexelsPhoto } from "../../lib/api/blog-images";
import { usePexelsSearch } from "../../hooks/queries/useBlogImageQueries";
 
interface CoverImageModalProps {
	isOpen: boolean;
	proId: string;
	blogId: string;
	onClose: () => void;
	onCoverSet: (imageUrl: string) => void;
	/** Override default upload function (used by admin mode) */
	onUploadCover?: (file: File) => Promise<string>;
}
 
export function CoverImageModal({
	isOpen,
	proId,
	blogId,
	onClose,
	onCoverSet,
	onUploadCover,
}: CoverImageModalProps) {
	const [step, setStep] = useState<"select" | "crop">("select");
	const [selectedImageSrc, setSelectedImageSrc] = useState("");
	const [uploading, setUploading] = useState(false);
	const [activeTab, setActiveTab] = useState("upload");
 
	// Pexels search state
	const [pexelsQuery, setPexelsQuery] = useState("");
	const [pexelsSearchTerm, setPexelsSearchTerm] = useState("");
	const [pexelsPage, setPexelsPage] = useState(1);
	const { data: pexelsData, isLoading: pexelsLoading } = usePexelsSearch(
		proId,
		pexelsSearchTerm,
		pexelsPage,
	);
 
 
	const resetState = useCallback(() => {
		if (selectedImageSrc.startsWith("blob:")) {
			URL.revokeObjectURL(selectedImageSrc);
		}
		setStep("select");
		setSelectedImageSrc("");
		setUploading(false);
	}, [selectedImageSrc]);
 
	const handleClose = () => {
		resetState();
		onClose();
	};
 
	const goToCrop = (src: string) => {
		setSelectedImageSrc(src);
		setStep("crop");
	};
 
	const handleBackToSelect = () => {
		Eif (selectedImageSrc.startsWith("blob:")) {
			URL.revokeObjectURL(selectedImageSrc);
		}
		setSelectedImageSrc("");
		setStep("select");
	};
 
	// Upload tab: file select
	const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		Iif (!file) return;
		const objectUrl = URL.createObjectURL(file);
		goToCrop(objectUrl);
	};
 
	// Drop handler
	const handleDrop = (e: React.DragEvent) => {
		e.preventDefault();
		const file = e.dataTransfer.files?.[0];
		if (!file?.type.startsWith("image/")) return;
		const objectUrl = URL.createObjectURL(file);
		goToCrop(objectUrl);
	};
 
	// Pexels: select photo
	const handlePexelsSelect = (photo: PexelsPhoto) => {
		goToCrop(photo.src.large);
	};
 
	// Pexels search submit
	const handlePexelsSearch = (e: React.FormEvent) => {
		e.preventDefault();
		setPexelsSearchTerm(pexelsQuery.trim());
		setPexelsPage(1);
	};
 
	// Crop complete: upload and notify parent
	const handleCropComplete = async (croppedBlob: Blob) => {
		setUploading(true);
		try {
			const file = new File([croppedBlob], "cover.jpg", {
				type: "image/jpeg",
			});
			if (onUploadCover) {
				const imageUrl = await onUploadCover(file);
				onCoverSet(imageUrl);
				notify.success("Cover image updated!");
				handleClose();
			} else {
				const result = await proApi.uploadBlogCover(proId, blogId, file);
				Eif (result.data) {
					const imageUrl = (result.data as { imageUrl: string }).imageUrl;
					onCoverSet(imageUrl);
					notify.success("Cover image updated!");
					handleClose();
				}
			}
		} catch {
			notify.error("Failed to upload cover image. Please try again.");
		} finally {
			setUploading(false);
		}
	};
 
	if (!isOpen) return null;
 
	return createPortal(
		<div
			role="dialog"
			aria-label="Cover Image"
			className="fixed inset-0 z-[100] flex items-center justify-center"
		>
			<button
				type="button"
				aria-label="Close modal"
				className="fixed inset-0 bg-black/50 cursor-default"
				onClick={handleClose}
			/>
			<div className="relative bg-background-elevated rounded-lg shadow-xl w-full max-w-3xl p-6 m-4 max-h-[90vh] overflow-y-auto">
				<div className="flex items-center justify-between mb-4">
					<h2 className="text-lg font-semibold">
						{step === "crop" ? "Crop Cover Image" : "Choose Cover Image"}
					</h2>
					<button
						type="button"
						onClick={handleClose}
						className="text-foreground-subtle hover:text-foreground-muted"
					>
						<X className="h-5 w-5" />
					</button>
				</div>
 
				{step === "select" ? (
					<Tabs value={activeTab} onValueChange={setActiveTab}>
						<TabsList className="grid w-full grid-cols-2">
							<TabsTrigger value="upload">Upload</TabsTrigger>
							<TabsTrigger value="pexels">Stock Photos</TabsTrigger>
						</TabsList>
 
						{/* Upload Tab */}
						<TabsContent value="upload" className="mt-4">
							<button
								type="button"
								className="w-full border-2 border-dashed border-default rounded-lg p-12 text-center hover:border-primary-500 transition-colors cursor-pointer"
								onDragOver={(e) => e.preventDefault()}
								onDrop={handleDrop}
								onClick={() =>
									document.getElementById("cover-file-input")?.click()
								}
							>
								<Upload className="h-10 w-10 mx-auto mb-3 text-foreground-subtle" />
								<p className="text-foreground-muted font-medium">
									Drop an image here or click to browse
								</p>
								<p className="text-sm text-foreground-subtle mt-1">
									JPG, PNG or WebP. Recommended: 1200x675 (16:9)
								</p>
								<input
									id="cover-file-input"
									type="file"
									accept="image/*"
									className="hidden"
									onChange={handleFileSelect}
								/>
							</button>
						</TabsContent>
 
						{/* Stock Photos Tab */}
						<TabsContent value="pexels" className="mt-4">
							<form onSubmit={handlePexelsSearch} className="flex gap-2 mb-4">
								<Input
									placeholder="Search free photos..."
									value={pexelsQuery}
									onChange={(e) => setPexelsQuery(e.target.value)}
									className="flex-1"
								/>
								<Button type="submit" disabled={!pexelsQuery.trim()}>
									<Search className="h-4 w-4 mr-1" />
									Search
								</Button>
							</form>
 
							{pexelsLoading ? (
								<div className="text-center py-12">
									<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500 mx-auto" />
									<p className="mt-2 text-sm text-foreground-muted">
										Searching photos...
									</p>
								</div>
							) : pexelsData && pexelsData.photos.length > 0 ? (
								<>
									<div className="grid grid-cols-3 gap-3 max-h-80 overflow-y-auto">
										{pexelsData.photos.map((photo) => (
											<button
												key={photo.id}
												type="button"
												className="group relative aspect-video bg-background-subtle rounded-lg overflow-hidden border border-default hover:border-primary-500 cursor-pointer transition-all"
												onClick={() => handlePexelsSelect(photo)}
											>
												<img
													src={photo.src.medium}
													alt={photo.alt}
													className="w-full h-full object-cover"
													loading="lazy"
												/>
												<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-2">
													<p className="text-foreground-inverse text-xs truncate">
														{photo.photographer}
													</p>
												</div>
											</button>
										))}
									</div>
									{pexelsData.total_results > pexelsData.per_page && (
										<div className="flex justify-center gap-2 mt-4">
											<Button
												variant="outline"
												size="sm"
												disabled={pexelsPage <= 1}
												onClick={() =>
													setPexelsPage((p) => Math.max(1, p - 1))
												}
											>
												Previous
											</Button>
											<Button
												variant="outline"
												size="sm"
												disabled={
													!pexelsData.next_page
												}
												onClick={() => setPexelsPage((p) => p + 1)}
											>
												Next
											</Button>
										</div>
									)}
								</>
							) : pexelsSearchTerm ? (
								<div className="text-center py-12 text-foreground-muted">
									<ImageIcon className="h-12 w-12 mx-auto mb-3 text-foreground-subtle" />
									<p>No photos found for "{pexelsSearchTerm}"</p>
									<p className="text-sm mt-1">Try a different search term.</p>
								</div>
							) : (
								<div className="text-center py-12 text-foreground-muted">
									<ImageIcon className="h-12 w-12 mx-auto mb-3 text-foreground-subtle" />
									<p>Search for free stock photos from Pexels</p>
									<p className="text-sm mt-1">
										Try "modern living room" or "kitchen design"
									</p>
								</div>
							)}
						</TabsContent>
 
					</Tabs>
				) : (
					/* Crop Step */
					<div>
						{uploading ? (
							<div className="text-center py-12">
								<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500 mx-auto" />
								<p className="mt-2 text-sm text-foreground-muted">
									Uploading cover image...
								</p>
							</div>
						) : (
							<Suspense
									fallback={
										<div className="text-center py-12">
											<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500 mx-auto" />
											<p className="mt-2 text-sm text-foreground-muted">Loading cropper...</p>
										</div>
									}
								>
									<ImageCropper
										imageSrc={selectedImageSrc}
										aspectRatio={16 / 9}
										onComplete={handleCropComplete}
										onCancel={handleBackToSelect}
									/>
								</Suspense>
						)}
					</div>
				)}
			</div>
		</div>,
		document.body,
	);
}