Spaces:
Runtime error
Runtime error
File size: 21,881 Bytes
e008c35 04c347b e008c35 04c347b e008c35 f461769 e008c35 | 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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 | "use client";
import { DragEvent, useCallback, useRef, useState, useMemo, useEffect } from "react";
import dynamic from "next/dynamic";
import { RoomUploader } from "@/components/RoomUploader";
import { TopHeader } from "@/components/TopHeader";
import { FloatingToolbar } from "@/components/FloatingToolbar";
import { MaterialDrawer } from "@/components/MaterialDrawer";
import { ImageSlider } from "@/components/ImageSlider";
import { defaultControls, tileTextures, SURFACE_META, getSurfaceLabel } from "@/lib/tiles";
import { resizeImageFile } from "@/lib/image";
import type {
DetectionStatus,
MaskKind,
SegmentResponse,
SurfaceRenderMode,
SurfaceType,
VisualizerControls,
} from "@/lib/types";
const RoomCanvas = dynamic(
() => import("@/components/RoomCanvas").then((mod) => mod.RoomCanvas),
{
ssr: false,
loading: () => (
<div className="canvas-empty">
<div className="skeleton-pulse" style={{ width: "100%", height: "100%" }} />
</div>
),
}
);
export function VisualizerApp() {
const [roomImage, setRoomImage] = useState<string | null>(null);
const [segment, setSegment] = useState<SegmentResponse | null>(null);
// Surface management
const [selectedSurfaces, setSelectedSurfaces] = useState<string[]>([]);
const [appliedSurfaces, setAppliedSurfaces] = useState<string[]>([]);
const [surfaceTiles, setSurfaceTiles] = useState<Record<string, string>>({});
const [hiddenSurfaces, setHiddenSurfaces] = useState<string[]>([]);
// Hover states
const [hoveredSurface, setHoveredSurface] = useState<string | null>(null);
const [controls] = useState<VisualizerControls>({
...defaultControls,
opacity: 1.0,
});
const [renderMode] = useState<SurfaceRenderMode>("auto");
const [detectionStatus, setDetectionStatus] = useState<DetectionStatus>("idle");
const [detectionProgress, setDetectionProgress] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const [showComparison, setShowComparison] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
// Refs for file upload and canvas download
const fileInputRef = useRef<HTMLInputElement>(null);
const stageRefCallback = useRef<(() => string | null) | null>(null);
// ββ New State: Auto-hiding Sidebar Hotspots ββ
const [activeCategory, setActiveCategory] = useState<SurfaceType | null>(null);
const categoryTimerRef = useRef<NodeJS.Timeout | null>(null);
// Group segment mask keys by surface type
const surfaceCategories = useMemo(() => {
if (!segment || !segment.surface_types) return {};
const cats: Partial<Record<SurfaceType, string[]>> = {};
Object.entries(segment.surface_types).forEach(([key, type]) => {
const t = type as SurfaceType;
// We don't filter out doors here, since user wanted "option to delete cabin". We'll just list them all.
if (!cats[t]) cats[t] = [];
cats[t].push(key);
});
return cats;
}, [segment]);
const activateCategory = useCallback((category: SurfaceType) => {
setActiveCategory(category);
if (categoryTimerRef.current) clearTimeout(categoryTimerRef.current);
categoryTimerRef.current = setTimeout(() => {
setActiveCategory(null);
}, 4000); // 4 seconds auto-hide
}, []);
const handleHotspotInteract = useCallback(() => {
if (activeCategory && categoryTimerRef.current) {
clearTimeout(categoryTimerRef.current);
categoryTimerRef.current = setTimeout(() => {
setActiveCategory(null);
}, 4000);
}
}, [activeCategory]);
useEffect(() => {
return () => {
if (categoryTimerRef.current) clearTimeout(categoryTimerRef.current);
};
}, []);
// ββ New State: Dynamic Loading Messages ββ
const messageInitRef = useRef(false);
useEffect(() => {
if (detectionStatus !== "detecting") {
messageInitRef.current = false;
return;
}
const messages = [
"Uploading image...",
"Running Segment Anything Model...",
"Analyzing room semantics...",
"Generating surface masks...",
"Finalizing geometric boundaries...",
"Almost done... refining edges..."
];
let currentIndex = 0;
if (!messageInitRef.current) {
// We start with Uploading (set by segmentRoom), so next tick we skip to index 1
currentIndex = 1;
messageInitRef.current = true;
}
const interval = setInterval(() => {
setDetectionProgress(messages[currentIndex]);
currentIndex = (currentIndex + 1) % messages.length;
if (currentIndex === 0) currentIndex = 1;
}, 4500);
return () => clearInterval(interval);
}, [detectionStatus]);
const handleToggleSurface = useCallback((maskKey: string) => {
setSelectedSurfaces((prev) => {
if (prev.includes(maskKey)) {
return prev.filter((k) => k !== maskKey);
}
return [...prev, maskKey];
});
}, []);
const handleSelectAllOfType = useCallback((type: SurfaceType) => {
if (!segment) return;
const keysOfType = Object.keys(segment.masks).filter((key) => {
const t: SurfaceType = segment.surface_types?.[key] ?? (key.startsWith("wall") ? "wall" : key.startsWith("floor") ? "floor" : "wall");
return t === type;
});
setSelectedSurfaces((prev) => {
const set = new Set(prev);
keysOfType.forEach(k => set.add(k));
return Array.from(set);
});
}, [segment]);
const handleDeselectAllOfType = useCallback((type: SurfaceType) => {
if (!segment) return;
const keysOfType = Object.keys(segment.masks).filter((key) => {
const t: SurfaceType = segment.surface_types?.[key] ?? (key.startsWith("wall") ? "wall" : key.startsWith("floor") ? "floor" : "wall");
return t === type;
});
setSelectedSurfaces((prev) => prev.filter(k => !keysOfType.includes(k)));
}, [segment]);
const handleApplyTile = useCallback(
(tileId: string) => {
if (selectedSurfaces.length === 0) return;
setSurfaceTiles((prev) => {
const next = { ...prev };
for (const key of selectedSurfaces) {
next[key] = tileId;
}
return next;
});
// Add selected surfaces to applied list
setAppliedSurfaces((prev) => {
const set = new Set(prev);
for (const key of selectedSurfaces) {
set.add(key);
}
return Array.from(set);
});
},
[selectedSurfaces]
);
const handleCloseDrawer = useCallback(() => {
setSelectedSurfaces([]);
}, []);
const segmentRoom = useCallback(async (file: File, previewUrl: string) => {
setRoomImage(previewUrl);
setSegment(null);
setError(null);
setDetectionStatus("detecting");
setDetectionProgress("Uploading image...");
setSelectedSurfaces([]);
setAppliedSurfaces([]);
setSurfaceTiles({});
setHiddenSurfaces([]);
setShowComparison(false);
try {
const { resizedFile } = await resizeImageFile(file);
const formData = new FormData();
formData.append("image", resizedFile);
formData.append("target", "auto");
// The useEffect will handle cycling through the messages automatically
// setDetectionProgress("Detecting surfaces with AI... This may take a minute on first run.");
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 300_000);
const response = await fetch("/api/segment", {
method: "POST",
body: formData,
signal: controller.signal,
});
clearTimeout(timeout);
if (!response.ok) {
const text = await response.text();
let errorMsg: string;
try {
const data = JSON.parse(text);
errorMsg = data.error || `Server error (${response.status})`;
} catch {
errorMsg = text || `Server error (${response.status})`;
}
throw new Error(errorMsg);
}
const data = (await response.json()) as SegmentResponse;
setSegment(data);
// Initialize tile assignments with default tile for all detected surfaces
const keys = Object.keys(data.masks);
if (keys.length === 0) {
setError("No surfaces detected. Try a clearer room photo.");
setDetectionStatus("error");
return;
}
const initialTiles: Record<string, string> = {};
for (const k of keys) {
initialTiles[k] = tileTextures[0].id;
}
setSurfaceTiles(initialTiles);
setAppliedSurfaces([]); // Don't apply any masks by default so the user sees the original image
setDetectionStatus("complete");
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") {
setError("Detection timed out. Try a smaller image.");
} else {
setError(
err instanceof Error ? err.message : "Could not segment this room image."
);
}
setDetectionStatus("error");
}
}, []);
const loadDemoRoom = useCallback(async (demoPath: string) => {
const response = await fetch(demoPath);
const blob = await response.blob();
const filename = demoPath.split("/").pop() || "demo.png";
const file = new File([blob], filename, { type: "image/png" });
await segmentRoom(file, demoPath);
}, [segmentRoom]);
const handleNewUpload = useCallback(
async (file: File, previewUrl: string) => {
await segmentRoom(file, previewUrl);
},
[segmentRoom]
);
const handleReset = useCallback(() => {
setRoomImage(null);
setSegment(null);
setSelectedSurfaces([]);
setAppliedSurfaces([]);
setSurfaceTiles({});
setHiddenSurfaces([]);
setHoveredSurface(null);
setDetectionStatus("idle");
setError(null);
setShowComparison(false);
}, []);
const handleFileInputChange = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file || !file.type.startsWith("image/")) return;
const { resizedFile, previewUrl } = await resizeImageFile(file);
await segmentRoom(resizedFile, previewUrl);
e.target.value = "";
},
[segmentRoom]
);
const handleDragOver = useCallback((e: DragEvent) => {
e.preventDefault();
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: DragEvent) => {
e.preventDefault();
setIsDragOver(false);
}, []);
const handleDrop = useCallback(
async (e: DragEvent) => {
e.preventDefault();
setIsDragOver(false);
const file = e.dataTransfer.files[0];
if (!file || !file.type.startsWith("image/")) return;
const { resizedFile, previewUrl } = await resizeImageFile(file);
await segmentRoom(resizedFile, previewUrl);
},
[segmentRoom]
);
const handleDownload = useCallback(() => {
if (!stageRefCallback.current) return;
const dataUrl = stageRefCallback.current();
if (!dataUrl) return;
const link = document.createElement("a");
link.download = "room-visualizer.png";
link.href = dataUrl;
link.click();
}, []);
const isDetecting = detectionStatus === "detecting";
const drawerOpen = !!segment && !showComparison;
return (
<main className="app-shell">
{/* Hidden file input for header upload button */}
<input
ref={fileInputRef}
id="file-upload"
accept="image/png,image/jpeg,image/webp"
hidden
onChange={handleFileInputChange}
type="file"
/>
<TopHeader
viewMode={showComparison ? "before" : "after"}
onViewModeChange={(mode) => setShowComparison(mode === "before")}
onUploadClick={() => fileInputRef.current?.click()}
onDownloadClick={handleDownload}
onResetClick={handleReset}
canDownload={!!roomImage && !!segment}
hasRoom={!!roomImage}
/>
<section
className="stage-area"
onDragOver={!roomImage ? handleDragOver : undefined}
onDragLeave={!roomImage ? handleDragLeave : undefined}
onDrop={!roomImage ? handleDrop : undefined}
>
{roomImage ? (
<>
{/* ββ Surface Selection Sidebar ββ */}
{segment && !showComparison && (
<aside className="surface-sidebar">
<h3 className="sidebar-title">Detected Surfaces</h3>
{Object.entries(surfaceCategories).map(([type, keys]) => {
const surfaceType = type as SurfaceType;
const meta = SURFACE_META[surfaceType];
if (!meta) return null;
const areAllSelected = keys.every((k) => selectedSurfaces.includes(k));
const isSomeSelected = keys.some((k) => selectedSurfaces.includes(k));
return (
<button
key={surfaceType}
className={`sidebar-item ${activeCategory === surfaceType ? 'active' : ''} ${areAllSelected ? 'selected' : ''}`}
onClick={() => {
activateCategory(surfaceType);
if (areAllSelected) {
handleDeselectAllOfType(surfaceType);
} else {
handleSelectAllOfType(surfaceType);
}
}}
>
<div className={`custom-checkbox ${areAllSelected ? 'checked' : isSomeSelected ? 'indeterminate' : ''}`}>
{areAllSelected && (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
)}
{(!areAllSelected && isSomeSelected) && (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
)}
</div>
<span className="sidebar-label">{meta.label}</span>
</button>
);
})}
</aside>
)}
<div className="canvas-wrap">
<RoomCanvas
activeMasks={appliedSurfaces}
controls={controls}
imageSrc={roomImage}
segment={segment}
renderMode={renderMode}
showComparison={showComparison}
showMaskOverlay={false}
showSurfaceHandles={false}
surfaceTiles={surfaceTiles}
hoveredSurface={hoveredSurface}
hoveredTile={null}
onSurfaceHover={setHoveredSurface}
onSurfaceClick={handleToggleSurface}
onStageExport={(fn) => { stageRefCallback.current = fn; }}
>
{/* ββ Surface Hotspot Overlay ββ */}
{segment && segment.centroids && !showComparison && (
<div className="surface-hotspots-overlay">
{Object.keys(segment.masks).map((maskKey) => {
const centroid = segment.centroids?.[maskKey];
if (!centroid) return null;
const surfaceType: SurfaceType =
(segment.surface_types?.[maskKey] as SurfaceType) ??
(maskKey.startsWith("wall") ? "wall" : maskKey.startsWith("floor") ? "floor" : "wall");
if (hiddenSurfaces.includes(maskKey)) return null;
if (activeCategory && surfaceType !== activeCategory) return null;
// Removed: if (!activeCategory) return null; // hotspots should always be visible
const meta = SURFACE_META[surfaceType];
const label = getSurfaceLabel(maskKey, surfaceType);
const isSelected = selectedSurfaces.includes(maskKey);
const isHovered = hoveredSurface === maskKey;
return (
<div
key={maskKey}
role="button"
tabIndex={0}
className={`surface-hotspot${isSelected ? " selected" : ""}${isHovered ? " hovered" : ""}`}
style={{
left: `${centroid[0] * 100}%`,
top: `${centroid[1] * 100}%`,
// @ts-expect-error CSS custom property
"--hotspot-color": meta?.color ?? "#6c5ce7",
}}
onClick={() => { handleToggleSurface(maskKey); handleHotspotInteract(); }}
onMouseEnter={() => { setHoveredSurface(maskKey); handleHotspotInteract(); }}
onMouseLeave={() => setHoveredSurface(null)}
>
{isSelected && (
<svg className="surface-hotspot-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
)}
</div>
);
})}
</div>
)}
</RoomCanvas>
{!showComparison && (
<FloatingToolbar
onSplit={() => setShowComparison(true)}
isSplit={showComparison}
/>
)}
{/* Detecting overlay */}
{isDetecting && (
<div className="detecting-overlay">
<div className="detecting-content">
<span className="detecting-spinner" />
<span className="detecting-text">
{detectionProgress || "Detecting room surfaces..."}
</span>
<span className="detecting-subtext">
Analyzing your room photo
</span>
</div>
</div>
)}
{/* Error overlay on canvas */}
{error && detectionStatus === "error" && (
<div className="error-overlay">
<div className="error-content">
<span className="error-icon">β οΈ</span>
<span className="error-text">{error}</span>
<button className="secondary-button" onClick={handleReset}>
Try Again
</button>
</div>
</div>
)}
</div>
{/* Material Drawer β slides in from right */}
<MaterialDrawer
isOpen={drawerOpen}
segment={segment}
selectedSurfaces={selectedSurfaces}
surfaceTiles={surfaceTiles}
onApplyTile={handleApplyTile}
onClose={handleCloseDrawer}
onSelectAllOfType={handleSelectAllOfType}
onDeselectAllOfType={handleDeselectAllOfType}
/>
</>
) : (
<div className={`landing-container${isDragOver ? " drag-active" : ""}`}>
<div className="landing-hero">
<div className="landing-hero-content">
<h1 className="landing-title">Visualize materials.<br/>Transform your space.</h1>
<p className="landing-subtitle">
Upload a room photo and instantly try different materials and finishes in real time.
</p>
<RoomUploader
disabled={isDetecting}
isCompact={false}
isDragOver={isDragOver}
onDemo={loadDemoRoom}
onUpload={handleNewUpload}
/>
</div>
<div className="landing-hero-slider">
<ImageSlider
beforeImage="/demos/hero-before.png"
afterImage="/demos/hero-after.png"
/>
</div>
</div>
<div className="landing-how-it-works">
<div className="hiw-header">
<h2>How it Works</h2>
<p>Redesign any room in three simple steps.</p>
</div>
<div className="hiw-steps">
<div className="hiw-step">
<div className="hiw-number">1</div>
<div className="hiw-text">
<h4>Upload a Photo</h4>
<p>Take a picture of your room or choose one from your gallery.</p>
</div>
</div>
<div className="hiw-step">
<div className="hiw-number">2</div>
<div className="hiw-text">
<h4>Select Surfaces</h4>
<p>Our AI automatically detects walls, floors, and ceilings.</p>
</div>
</div>
<div className="hiw-step">
<div className="hiw-number">3</div>
<div className="hiw-text">
<h4>Apply Materials</h4>
<p>Instantly visualize new paint, tile, or hardwood floors.</p>
</div>
</div>
</div>
</div>
</div>
)}
</section>
</main>
);
}
|