"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: () => (
), } ); export function VisualizerApp() { const [roomImage, setRoomImage] = useState(null); const [segment, setSegment] = useState(null); // Surface management const [selectedSurfaces, setSelectedSurfaces] = useState([]); const [appliedSurfaces, setAppliedSurfaces] = useState([]); const [surfaceTiles, setSurfaceTiles] = useState>({}); const [hiddenSurfaces, setHiddenSurfaces] = useState([]); // Hover states const [hoveredSurface, setHoveredSurface] = useState(null); const [controls] = useState({ ...defaultControls, opacity: 1.0, }); const [renderMode] = useState("auto"); const [detectionStatus, setDetectionStatus] = useState("idle"); const [detectionProgress, setDetectionProgress] = useState(""); const [error, setError] = useState(null); const [showComparison, setShowComparison] = useState(false); const [isDragOver, setIsDragOver] = useState(false); // Refs for file upload and canvas download const fileInputRef = useRef(null); const stageRefCallback = useRef<(() => string | null) | null>(null); // ── New State: Auto-hiding Sidebar Hotspots ── const [activeCategory, setActiveCategory] = useState(null); const categoryTimerRef = useRef(null); // Group segment mask keys by surface type const surfaceCategories = useMemo(() => { if (!segment || !segment.surface_types) return {}; const cats: Partial> = {}; 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 = {}; 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) => { 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 (
{/* Hidden file input for header upload button */} setShowComparison(mode === "before")} onUploadClick={() => fileInputRef.current?.click()} onDownloadClick={handleDownload} onResetClick={handleReset} canDownload={!!roomImage && !!segment} hasRoom={!!roomImage} />
{roomImage ? ( <> {/* ── Surface Selection Sidebar ── */} {segment && !showComparison && ( )}
{ stageRefCallback.current = fn; }} > {/* ── Surface Hotspot Overlay ── */} {segment && segment.centroids && !showComparison && (
{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 (
{ handleToggleSurface(maskKey); handleHotspotInteract(); }} onMouseEnter={() => { setHoveredSurface(maskKey); handleHotspotInteract(); }} onMouseLeave={() => setHoveredSurface(null)} > {isSelected && ( )}
); })}
)}
{!showComparison && ( setShowComparison(true)} isSplit={showComparison} /> )} {/* Detecting overlay */} {isDetecting && (
{detectionProgress || "Detecting room surfaces..."} Analyzing your room photo
)} {/* Error overlay on canvas */} {error && detectionStatus === "error" && (
⚠️ {error}
)}
{/* Material Drawer — slides in from right */} ) : (

Visualize materials.
Transform your space.

Upload a room photo and instantly try different materials and finishes in real time.

How it Works

Redesign any room in three simple steps.

1

Upload a Photo

Take a picture of your room or choose one from your gallery.

2

Select Surfaces

Our AI automatically detects walls, floors, and ceilings.

3

Apply Materials

Instantly visualize new paint, tile, or hardwood floors.

)}
); }