tile-room-visualizer / components /VisualizerApp.tsx
richuj's picture
style(ui): update loading text to remove AI reference
f461769
Raw History Blame Contribute Delete
21.9 kB
"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>
);
}