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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | 3x 3x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 1009x 80x 80x 53x 53x 53x 1009x 1009x 1009x 1009x 1009x 75x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1009x 9x 9x 1009x 167x 2x 2x 2x 2x 1009x 58x 54x 1009x 85x 85x 61x 61x 3x 3x 58x 58x 58x 57x 56x 57x 56x 56x 1x 57x 24x 22x 22x 22x 22x 22x 22x 22x 22x 24x 22x 2x 2x 2x 2x 1x 1009x 7x 7x 7x 7x 1009x 7x 3x 3x 3x 3x 4x 2x 2x 2x 2x 1009x 1005x 1009x 980x 796x 184x 1009x 1005x 184x 145x 821x 1009x 1009x 1009x 718x 718x 1x 1009x 2x 1003x | import { useState, useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, X } from "lucide-react";
import {
validateProjectTitle,
projectTitleErrorMessage,
normalizeProjectTitle,
} from "@interioring/utils/validation/project-title";
import { notify } from "../../lib/notify";
import { Button } from "../ui/button";
import { OnboardingProgress } from "../onboarding/OnboardingProgress";
import { useDialogAccessibility } from "../../hooks";
import { useIsMobile } from "../../hooks/useIsMobile";
import {
proApi,
getErrorMessage,
} from "../../lib/api";
import {
useCreateProject,
useUpdateProject,
} from "../../hooks/mutations/useProjectMutations";
import { useRoomTypes } from "../../hooks/queries/useTaxonomyQueries";
import { queryKeys } from "../../lib/query-keys";
import { BasicInfoSection } from "./form-sections";
import { RoomPhotosStep } from "./RoomPhotosStep.subcomponent";
import { RoomSummaryStep } from "./RoomSummaryStep.subcomponent";
import { useRoomUpload } from "./use-room-upload.hook";
interface ProjectCreationWizardProps {
isOpen: boolean;
onClose: () => void;
onComplete: (projectId: string) => void;
proId: string;
}
interface RoomState {
roomType: string;
name: string;
areaSqft: string;
styleTags: string[];
budgetSpent: string;
materials: string[];
roomId?: number;
photoCount: number;
}
const STEP_TITLES = ["Project Info", "Add Room & Photos", "Room Summary"];
const TOTAL_STEPS = 3;
export function ProjectCreationWizard({
isOpen,
onClose,
onComplete,
proId,
}: ProjectCreationWizardProps) {
const queryClient = useQueryClient();
// Step navigation
const [currentStep, setCurrentStep] = useState(1);
const [createdProjectId, setCreatedProjectId] = useState<string | null>(null);
// Tracks whether the user completed the wizard via Finish
// (regression #585 — discard orphaned draft projects on close).
const finishedRef = useRef(false);
const createdProjectIdRef = useRef<string | null>(null);
// Step 1 - Basic Info
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [titleErrorMessage, setTitleErrorMessage] = useState<string | null>(null);
// Rooms tracking
const [rooms, setRooms] = useState<RoomState[]>([]);
const [currentRoomIndex, setCurrentRoomIndex] = useState(0);
// Current room being edited (Step 2)
const [roomType, setRoomType] = useState("");
const [roomName, setRoomName] = useState("");
// Taxonomy data (cached via React Query)
const { data: roomTypes = [] } = useRoomTypes();
// Room upload logic via hook
const { fileInputRef, isDragOver, isUploading, roomMedia, setRoomMedia, loadRoomMedia,
handleFileSelect, handleDragOver, handleDragLeave, handleDrop, handleSetCover, resetRoomMedia,
} = useRoomUpload({ proId, roomType, roomName, createdProjectId, rooms, currentRoomIndex, setRooms, setCurrentRoomIndex });
// Mutations
const createProjectMutation = useCreateProject(proId);
const updateProjectMutation = useUpdateProject(proId, createdProjectId || "");
const isSubmitting =
createProjectMutation.isPending ||
updateProjectMutation.isPending ||
isUploading;
// Discard orphaned draft on close/unmount (#585)
const discardPendingDraft = () => {
const pendingProjectId = createdProjectIdRef.current;
if (pendingProjectId && !finishedRef.current) {
createdProjectIdRef.current = null;
void proApi
.deleteProject(proId, pendingProjectId)
.catch(() => {})
.finally(() => { queryClient.invalidateQueries({ queryKey: queryKeys.projects.list(proId) }); });
}
};
const handleClose = () => { discardPendingDraft(); onClose(); };
// biome-ignore lint/correctness/useExhaustiveDependencies: cleanup on unmount only
useEffect(() => { return () => { discardPendingDraft(); }; /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, []);
// Accessibility
const { dialogRef, handleFocusTrap } = useDialogAccessibility(handleClose);
const isMobile = useIsMobile();
// Reset all form state when modal opens/closes
// biome-ignore lint/correctness/useExhaustiveDependencies: reset on open/close only
useEffect(() => {
if (!isOpen) {
setCurrentStep(1);
setCreatedProjectId(null);
createdProjectIdRef.current = null;
finishedRef.current = false;
setTitle("");
setDescription("");
setTitleErrorMessage(null);
setRooms([]);
setCurrentRoomIndex(0);
resetRoomForm();
resetRoomMedia();
}
}, [isOpen]);
const resetRoomForm = () => {
setRoomType("");
setRoomName("");
};
// Re-populate room form when navigating back to step 2
// biome-ignore lint/correctness/useExhaustiveDependencies: only re-populate on step/index change
useEffect(() => {
if (currentStep === 2 && rooms[currentRoomIndex]?.roomId) {
const room = rooms[currentRoomIndex];
setRoomType(room.roomType);
setRoomName(room.name || "");
// Load existing media for this room
loadRoomMedia(rooms[currentRoomIndex].roomId as number);
}
}, [currentStep, currentRoomIndex]);
// Get room type display name
const getRoomTypeName = (code: string) => {
const rt = roomTypes.find((t) => t.code === code);
return rt?.displayName || code;
};
// Navigation logic
const handleNext = async () => {
try {
if (currentStep === 1) {
const titleError = validateProjectTitle(title);
if (titleError) {
setTitleErrorMessage(projectTitleErrorMessage(titleError));
return;
}
const normalizedTitle = normalizeProjectTitle(title);
// Create project (or reuse if already created from a failed attempt)
let projectId = createdProjectId;
if (!projectId) {
const result = await createProjectMutation.mutateAsync({
title: normalizedTitle,
description: description || null,
useRooms: true,
});
projectId = result?.id || null;
if (projectId) {
setCreatedProjectId(projectId);
createdProjectIdRef.current = projectId;
}
} else {
// Project exists from prior attempt — just update title/description
await proApi.updateProject(proId, projectId, {
title: normalizedTitle,
description: description || null,
useRooms: true,
});
}
setCurrentStep(2);
} else if (currentStep === 2) {
// Create or update room, then save photo count and go to summary
Iif (!createdProjectId) return;
const roomData: { roomType: string; name?: string } = { roomType };
Iif (roomName) roomData.name = roomName;
const existingRoom = rooms[currentRoomIndex];
if (existingRoom?.roomId) {
// Update existing room (user navigated back)
await proApi.updateRoom(proId, existingRoom.roomId, roomData);
setRooms((prev) =>
prev.map((r, i) =>
i === currentRoomIndex
? { ...r, roomType, name: roomName, photoCount: roomMedia.length }
: r,
),
);
} else E{
// Create new room
const response = await proApi.createRoom(proId, createdProjectId, roomData);
const createdRoom = response.data;
if (createdRoom) {
const newRoom: RoomState = {
roomType,
name: roomName,
areaSqft: "",
styleTags: [],
budgetSpent: "",
materials: [],
roomId: createdRoom.id,
photoCount: roomMedia.length,
};
const newIndex = rooms.length;
setRooms((prev) => [...prev, newRoom]);
setCurrentRoomIndex(newIndex);
}
}
setCurrentStep(3);
E} else if (currentStep === 3) {
// Finish — navigate to project detail
Eif (createdProjectId) {
finishedRef.current = true;
onComplete(createdProjectId);
}
}
} catch (err) {
notify.error(getErrorMessage(err));
}
};
const handleAddAnotherRoom = () => {
resetRoomForm();
setRoomMedia([]);
setCurrentRoomIndex(rooms.length);
setCurrentStep(2);
};
const handleBack = () => {
if (currentStep === 2 && rooms.length > 0) {
// Going back from room setup when rooms exist — sync photo count
// from the live roomMedia state before returning to summary
const existingRoom = rooms[currentRoomIndex];
Iif (existingRoom?.roomId) {
setRooms((prev) =>
prev.map((r, i) =>
i === currentRoomIndex
? { ...r, photoCount: roomMedia.length }
: r,
),
);
} else {
// Abandoned an unsaved "Add Another Room" slot — restore the
// index to the last saved room so the next step-2 visit (e.g.
// via Back from step 3) repopulates correctly. Without this,
// currentRoomIndex stays pointing at an empty slot and the
// existing rooms become unreachable for editing (issue #615).
setCurrentRoomIndex(rooms.length - 1);
}
setCurrentStep(3);
} else if (currentStep === 3 && rooms.length > 0) {
// Step 3 → 2 means "edit last saved room". Clamp a stale index
// (e.g. left over from an abandoned Add Another) so the repopulate
// effect can load the correct room.
Iif (currentRoomIndex >= rooms.length) {
setCurrentRoomIndex(rooms.length - 1);
}
setCurrentStep(2);
E} else if (currentStep > 1) {
setCurrentStep(currentStep - 1);
}
};
if (!isOpen) return null;
// Step 1 button stays enabled once anything is typed so handleNext can
// validate and surface a specific error message (e.g. for "======").
// A fully-empty title still disables the button, matching the prior UX.
const isNextDisabled =
(currentStep === 1 && !title.trim()) ||
(currentStep === 2 && (!roomType || roomMedia.length === 0)) ||
isSubmitting;
// Button labels
const getNextButtonLabel = () => {
switch (currentStep) {
case 1:
return "Create & Continue";
case 2:
return "Save Room";
case 3:
return "Finish";
default:
return "Next";
}
};
// Step title
const getStepTitle = () => {
if (currentStep === 2) {
// When the current index points at a saved room, the user is
// editing it (arrived via Back from step 3). Otherwise they're
// adding a new room.
if (rooms[currentRoomIndex]?.roomId) return "Edit Room";
return rooms.length === 0 ? "Add Room & Photos" : "Add Another Room";
}
return STEP_TITLES[currentStep - 1];
};
// ─── Shared UI pieces ───────────────────────────────────────────────
const progressHeader = (
<>
<OnboardingProgress
currentStep={currentStep}
totalSteps={TOTAL_STEPS}
/>
<p className="text-sm text-foreground-muted mt-2">
Step {currentStep}: {getStepTitle()}
</p>
</>
);
const footerContent = (
<div className="flex items-center gap-3">
{currentStep > 1 && (
<Button
type="button"
variant="outline"
onClick={handleBack}
disabled={isSubmitting}
>
Back
</Button>
)}
<div className="flex-1" />
{currentStep !== 3 && (
<Button
type="button"
onClick={handleNext}
isLoading={isSubmitting}
disabled={isNextDisabled}
>
{getNextButtonLabel()}
</Button>
)}
{currentStep === 3 && (
<Button
type="button"
onClick={handleNext}
isLoading={isSubmitting}
disabled={rooms.length === 0}
>
Finish
</Button>
)}
</div>
);
const stepContent = (
<>
{/* Step 1: Project Info */}
{currentStep === 1 && (
<div className="space-y-1">
<BasicInfoSection
title={title}
description={description}
onTitleChange={(v) => {
setTitle(v);
if (titleErrorMessage && validateProjectTitle(v) === null) {
setTitleErrorMessage(null);
}
}}
onDescriptionChange={setDescription}
titleError={titleErrorMessage}
/>
</div>
)}
{/* Step 2: Add Room + Photos (merged) */}
{currentStep === 2 && (
<RoomPhotosStep
roomType={roomType}
roomName={roomName}
roomMedia={roomMedia}
isDragOver={isDragOver}
isUploading={isUploading}
roomTypes={roomTypes}
fileInputRef={fileInputRef}
onRoomTypeChange={setRoomType}
onRoomNameChange={setRoomName}
onFileSelect={handleFileSelect}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onSetCover={handleSetCover}
/>
)}
{/* Step 3: Room Summary / Add Another */}
{currentStep === 3 && (
<RoomSummaryStep
rooms={rooms}
getRoomTypeName={getRoomTypeName}
onAddAnotherRoom={handleAddAnotherRoom}
/>
)}
</>
);
// ─── Mobile: full-screen page (matches DrawerDialog pattern) ────────
if (isMobile) {
return (
<div className="fixed inset-0 z-[60] flex flex-col bg-background-base animate-page-in">
{/* Header */}
<div className="flex h-14 items-center gap-3 border-b border-border-default bg-background-elevated px-4 flex-shrink-0">
<button
type="button"
onClick={handleClose}
className="p-2 -ml-2 text-foreground-muted hover:text-foreground-default rounded-md"
aria-label="Go back"
>
<ArrowLeft className="h-5 w-5" />
</button>
<h2 className="text-lg font-semibold text-foreground-default">
New Project
</h2>
</div>
{/* Progress */}
<div className="px-4 pt-3 pb-1 bg-background-base flex-shrink-0">
{progressHeader}
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-4">
{stepContent}
</div>
{/* Footer */}
<div className="flex-shrink-0 px-4 py-4 border-t border-border-default bg-background-elevated">
{footerContent}
</div>
</div>
);
}
// ─── Desktop: dialog overlay ────────────────────────────────────────
return (
<div
className="fixed inset-0 z-50 flex flex-col items-center justify-center p-4"
tabIndex={-1}
>
{/* Backdrop */}
<button
type="button"
aria-label="Close modal"
className="fixed inset-0 bg-black/50 cursor-default"
onClick={handleClose}
tabIndex={-1}
/>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby="project-wizard-dialog-title"
onKeyDown={handleFocusTrap}
className="relative flex flex-col bg-background-elevated w-full max-w-3xl mx-auto max-h-[90vh] rounded-lg shadow-xl"
>
{/* Header */}
<div className="bg-background-elevated border-b px-6 py-4 z-10 rounded-t-lg flex-shrink-0">
<div className="flex items-center justify-between mb-3">
<h2
id="project-wizard-dialog-title"
className="text-lg font-semibold"
>
New Project
</h2>
<button
type="button"
onClick={handleClose}
aria-label="Close"
className="text-foreground-subtle hover:text-foreground-muted"
>
<X className="h-5 w-5" />
</button>
</div>
{progressHeader}
</div>
{/* Scrollable content */}
<div className="flex-1 overflow-y-auto p-6">
{stepContent}
</div>
{/* Footer */}
<div className="bg-background-elevated border-t px-6 py-4 rounded-b-lg flex-shrink-0">
{footerContent}
</div>
</div>
</div>
);
}
|