All files / src/components/rooms RoomList.tsx

97.27% Statements 143/147
82.25% Branches 51/62
100% Functions 23/23
98.57% Lines 138/140

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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437                                                                                                92x 92x 92x 92x 92x 92x 92x     92x     92x 2x     2x 1x         92x 92x 92x   92x 6x 2x 2x     4x 4x   4x 4x       2x 2x 2x 2x   2x 2x   4x       92x 2x   2x 2x   2x 2x       1x 1x 1x 1x   1x 1x   2x       92x 4x                 1x     3x 3x 1x   2x 2x       92x 4x 4x 4x     92x 3x 3x 3x 3x       92x       6x 6x   4x 4x 4x   4x     4x     4x         92x 4x 4x 4x   4x 1x     1x     3x 3x 3x   3x                 2x 2x 1x             1x   2x 2x         92x         8x 8x 8x 8x 8x 8x       92x 1x 1x 1x 1x     92x         2x 2x         2x       92x         6x 6x         4x   2x 6x 6x   6x     2x 2x 2x     2x 2x 2x     2x 2x     4x   1x   1x       92x 3x               1x   2x 2x 1x   1x         92x 4x 4x                                 2x                                   88x                 8x                                       174x 174x                                                                     3x 3x                        
import { useState, type ChangeEvent, type DragEvent } from "react";
import {
	proApi,
	type Room,
	type RoomType,
	type Media,
	ApiError,
	getErrorMessage,
} from "../../lib/api";
import { Button } from "../ui/button";
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
	CardDescription,
} from "../ui/card";
import { Plus, ChevronRight, Home } from "lucide-react";
import { RoomCard } from "./RoomCard";
import { RoomFormModal } from "./RoomFormModal";
import { useConfirmDialog } from "../../hooks";
import { API_BASE_URL } from "../../lib/api/base";
 
type RoomListProps = {
	proId: string;
	projectId: string;
	rooms: Room[];
	roomTypes: RoomType[];
	roomMediaMap: Record<number, Media[]>;
	onRoomsChange: () => void;
	onRoomMediaChange: (roomId: number) => void;
	onSelectRoom: (room: Room) => void;
	selectedRoomId?: number;
	useRooms: boolean;
};
 
export function RoomList({
	proId,
	projectId,
	rooms,
	roomTypes,
	roomMediaMap,
	onRoomsChange,
	onRoomMediaChange,
	onSelectRoom,
	selectedRoomId: _selectedRoomId,
	useRooms,
}: RoomListProps) {
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	const [isAddModalOpen, setIsAddModalOpen] = useState(false);
	const [editingRoom, setEditingRoom] = useState<Room | null>(null);
	const [newRoomType, setNewRoomType] = useState("");
	const [newRoomName, setNewRoomName] = useState("");
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState("");
 
	// Upload state per room
	const [uploadingRoomId, setUploadingRoomId] = useState<number | null>(null);
 
	// Helper to trigger file input click
	const triggerFileInput = (roomId: number) => {
		const input = document.getElementById(
			`room-file-input-${roomId}`,
		) as HTMLInputElement;
		if (input) {
			input.click();
		}
	};
 
	// Drag reorder state
	const [draggedMediaId, setDraggedMediaId] = useState<number | null>(null);
	const [dragOverMediaId, setDragOverMediaId] = useState<number | null>(null);
	const [draggingInRoom, setDraggingInRoom] = useState<number | null>(null);
 
	const handleAddRoom = async () => {
		if (!newRoomType) {
			setError("Please select a room type");
			return;
		}
 
		setIsSubmitting(true);
		setError("");
 
		try {
			await proApi.createRoom(proId, projectId, {
				roomType: newRoomType,
				name: newRoomName || undefined,
			});
			setNewRoomType("");
			setNewRoomName("");
			setIsAddModalOpen(false);
			onRoomsChange();
		} catch (err) {
			console.error("Failed to create room:", err);
			setError(getErrorMessage(err));
		} finally {
			setIsSubmitting(false);
		}
	};
 
	const handleUpdateRoom = async () => {
		Iif (!editingRoom) return;
 
		setIsSubmitting(true);
		setError("");
 
		try {
			await proApi.updateRoom(proId, editingRoom.id, {
				roomType: newRoomType,
				name: newRoomName || undefined,
			});
			setEditingRoom(null);
			setNewRoomType("");
			setNewRoomName("");
			onRoomsChange();
		} catch (err) {
			console.error("Failed to update room:", err);
			setError(getErrorMessage(err));
		} finally {
			setIsSubmitting(false);
		}
	};
 
	const handleDeleteRoom = async (roomId: number) => {
		if (
			!(await confirm({
				title: "Delete room",
				description:
					"Delete this room? All media in this room will also be deleted.",
				confirmLabel: "Delete",
				variant: "destructive",
			}))
		) {
			return;
		}
 
		try {
			await proApi.deleteRoom(proId, roomId);
			onRoomsChange();
		} catch (err) {
			console.error("Failed to delete room:", err);
			setError(getErrorMessage(err));
		}
	};
 
	const startEditing = (room: Room) => {
		setEditingRoom(room);
		setNewRoomType(room.roomType);
		setNewRoomName(room.name || "");
	};
 
	const cancelEdit = () => {
		setEditingRoom(null);
		setNewRoomType("");
		setNewRoomName("");
		setError("");
	};
 
	// File upload handlers
	const handleFileSelect = async (
		roomId: number,
		e: ChangeEvent<HTMLInputElement>,
	) => {
		const files = e.target.files;
		if (!files || files.length === 0) return;
 
		setUploadingRoomId(roomId);
		for (let i = 0; i < files.length; i++) {
			await uploadFile(roomId, files[i]);
		}
		setUploadingRoomId(null);
 
		// Reset file input
		const fileInput = document.getElementById(
			`room-file-input-${roomId}`,
		) as HTMLInputElement;
		Iif (fileInput) {
			fileInput.value = "";
		}
	};
 
	const uploadFile = async (roomId: number, file: File) => {
		const imageTypes = ["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"];
		const videoTypes = ["video/mp4", "video/webm", "video/quicktime"];
		const allowedTypes = [...imageTypes, ...videoTypes];
 
		if (!allowedTypes.includes(file.type)) {
			setError(
				"Invalid file type. Allowed: JPEG, PNG, WebP, GIF, AVIF, MP4, WebM, MOV",
			);
			return;
		}
 
		try {
			const formData = new FormData();
			formData.append("file", file);
 
			const response = await fetch(
				`${API_BASE_URL}/api/pro/${proId}/rooms/${roomId}/upload-media`,
				{
					method: "POST",
					credentials: "include",
					body: formData,
				},
			);
 
			const data = await response.json();
			if (!response.ok || !data.success) {
				throw new ApiError(
					data.error?.code || "UPLOAD_ERROR",
					data.error?.message || "Failed to upload media",
					response.status,
				);
			}
 
			onRoomMediaChange(roomId);
		} catch (err) {
			console.error("Failed to upload media:", err);
			setError(getErrorMessage(err));
		}
	};
 
	// Media reorder handlers
	const handleMediaDragStart = (
		e: DragEvent<HTMLElement>,
		mediaId: number,
		roomId: number,
	) => {
		setDraggedMediaId(mediaId);
		setDraggingInRoom(roomId);
		e.dataTransfer.effectAllowed = "move";
		const target = e.currentTarget;
		setTimeout(() => {
			target.style.opacity = "0.5";
		}, 0);
	};
 
	const handleMediaDragEnd = (e: DragEvent<HTMLElement>) => {
		e.currentTarget.style.opacity = "1";
		setDraggedMediaId(null);
		setDragOverMediaId(null);
		setDraggingInRoom(null);
	};
 
	const handleMediaDragOver = (
		e: DragEvent<HTMLElement>,
		mediaId: number,
		roomId: number,
	) => {
		e.preventDefault();
		Eif (
			draggedMediaId === null ||
			draggedMediaId === mediaId ||
			draggingInRoom !== roomId
		)
			return;
		setDragOverMediaId(mediaId);
	};
 
	const handleMediaDrop = async (
		e: DragEvent<HTMLElement>,
		targetMediaId: number,
		roomId: number,
	) => {
		e.preventDefault();
		if (
			draggedMediaId === null ||
			draggedMediaId === targetMediaId ||
			draggingInRoom !== roomId
		)
			return;
 
		const roomMedia = roomMediaMap[roomId] || [];
		const draggedIndex = roomMedia.findIndex((m) => m.id === draggedMediaId);
		const targetIndex = roomMedia.findIndex((m) => m.id === targetMediaId);
 
		Iif (draggedIndex === -1 || targetIndex === -1) return;
 
		// Calculate new order
		const newMedia = [...roomMedia];
		const [draggedItem] = newMedia.splice(draggedIndex, 1);
		newMedia.splice(targetIndex, 0, draggedItem);
 
		// Reset drag state
		setDraggedMediaId(null);
		setDragOverMediaId(null);
		setDraggingInRoom(null);
 
		// Save to server
		try {
			await proApi.reorderMedia(
				proId,
				roomId,
				newMedia.map((m) => m.id),
			);
			onRoomMediaChange(roomId);
		} catch (err) {
			console.error("Failed to reorder media:", err);
		}
	};
 
	const handleDeleteMedia = async (mediaId: number, roomId: number) => {
		if (
			!(await confirm({
				title: "Delete image",
				description: "Delete this image?",
				confirmLabel: "Delete",
				variant: "destructive",
			}))
		)
			return;
 
		try {
			await proApi.deleteMedia(proId, mediaId);
			onRoomMediaChange(roomId);
		} catch (err) {
			console.error("Failed to delete media:", err);
		}
	};
 
	// Simple view for useRooms = false (show only default room)
	if (!useRooms) {
		const defaultRoom = rooms.find((r) => r.isDefault);
		return (
			<>
				<Card>
					<CardHeader className="pb-3">
						<CardTitle className="text-lg flex items-center gap-2">
							<Home className="h-5 w-5" />
							Project Media
						</CardTitle>
						<CardDescription>
							Manage images and videos for this project
						</CardDescription>
					</CardHeader>
					<CardContent>
						{defaultRoom ? (
							<Button
								variant="outline"
								className="w-full justify-between"
								onClick={() => onSelectRoom(defaultRoom)}
							>
								<span>View & Manage Media</span>
								<ChevronRight className="h-4 w-4" />
							</Button>
						) : (
							<p className="text-sm text-foreground-muted">
								No media room available
							</p>
						)}
					</CardContent>
				</Card>
				{confirmDialog}
			</>
		);
	}
 
	// Full room management view for useRooms = true - Card Layout
	return (
		<>
		<Card>
			<CardHeader className="pb-3">
				<div className="flex items-center justify-between">
					<div>
						<CardTitle className="text-lg">Rooms</CardTitle>
						<CardDescription>Organize your project by rooms</CardDescription>
					</div>
					<Button size="sm" onClick={() => setIsAddModalOpen(true)}>
						<Plus className="h-4 w-4 mr-1" />
						Add Room
					</Button>
				</div>
			</CardHeader>
			<CardContent>
				{error && (
					<div className="mb-4 p-3 text-sm text-error bg-error-light border border-error/20 rounded-lg">
						{error}
					</div>
				)}
 
				{rooms.length === 0 ? (
					<p className="text-sm text-foreground-muted text-center py-8">
						No rooms yet. Add rooms to organize your project media.
					</p>
				) : (
					<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
						{rooms.map((room) => {
							const roomMedia = roomMediaMap[room.id] || [];
							return (
								<RoomCard
									key={room.id}
									room={room}
									roomTypes={roomTypes}
									roomMedia={roomMedia}
									uploadingRoomId={uploadingRoomId}
									draggedMediaId={draggedMediaId}
									dragOverMediaId={dragOverMediaId}
									draggingInRoom={draggingInRoom}
									onEdit={startEditing}
									onDelete={handleDeleteRoom}
									onSelectRoom={onSelectRoom}
									onFileSelect={handleFileSelect}
									onMediaDragStart={handleMediaDragStart}
									onMediaDragEnd={handleMediaDragEnd}
									onMediaDragOver={handleMediaDragOver}
									onMediaDrop={handleMediaDrop}
									onDeleteMedia={handleDeleteMedia}
									triggerFileInput={triggerFileInput}
								/>
							);
						})}
					</div>
				)}
 
				{/* Add/Edit Room Modal */}
				<RoomFormModal
					isOpen={isAddModalOpen || editingRoom !== null}
					editingRoom={editingRoom}
					newRoomType={newRoomType}
					newRoomName={newRoomName}
					roomTypes={roomTypes}
					isSubmitting={isSubmitting}
					onClose={() => {
						setIsAddModalOpen(false);
						cancelEdit();
					}}
					onSubmit={editingRoom ? handleUpdateRoom : handleAddRoom}
					onRoomTypeChange={setNewRoomType}
					onRoomNameChange={setNewRoomName}
				/>
			</CardContent>
		</Card>
		{confirmDialog}
		</>
	);
}