handle thumbnails (manual)
This commit is contained in:
@@ -7,6 +7,7 @@ import { useEffect, useState } from 'react'
|
|||||||
import { ViewerCameraControls } from './viewer-camera-controls'
|
import { ViewerCameraControls } from './viewer-camera-controls'
|
||||||
import { ViewerOverlay } from './viewer-overlay'
|
import { ViewerOverlay } from './viewer-overlay'
|
||||||
import { ViewerZoneSystem } from './viewer-zone-system'
|
import { ViewerZoneSystem } from './viewer-zone-system'
|
||||||
|
import { ThumbnailGenerator } from './thumbnail-generator'
|
||||||
import { getPropertyModelPublic, incrementPropertyViews } from '@/features/community/lib/properties/actions'
|
import { getPropertyModelPublic, incrementPropertyViews } from '@/features/community/lib/properties/actions'
|
||||||
|
|
||||||
export default function ViewerPage() {
|
export default function ViewerPage() {
|
||||||
@@ -14,6 +15,7 @@ export default function ViewerPage() {
|
|||||||
const id = params.id as string
|
const id = params.id as string
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [propertyId, setPropertyId] = useState<string | null>(null)
|
||||||
const setScene = useScene((state) => state.setScene)
|
const setScene = useScene((state) => state.setScene)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -35,7 +37,8 @@ export default function ViewerPage() {
|
|||||||
const result = await getPropertyModelPublic(id)
|
const result = await getPropertyModelPublic(id)
|
||||||
|
|
||||||
if (result.success && result.data) {
|
if (result.success && result.data) {
|
||||||
const { model } = result.data
|
const { property, model } = result.data
|
||||||
|
setPropertyId(property.id)
|
||||||
|
|
||||||
if (model?.scene_graph) {
|
if (model?.scene_graph) {
|
||||||
const { nodes, rootNodeIds } = model.scene_graph
|
const { nodes, rootNodeIds } = model.scene_graph
|
||||||
@@ -84,6 +87,8 @@ export default function ViewerPage() {
|
|||||||
<ViewerCameraControls />
|
<ViewerCameraControls />
|
||||||
{/* Custom Zone System */}
|
{/* Custom Zone System */}
|
||||||
<ViewerZoneSystem />
|
<ViewerZoneSystem />
|
||||||
|
{/* Thumbnail Generator */}
|
||||||
|
<ThumbnailGenerator propertyId={propertyId || undefined} />
|
||||||
</Viewer>
|
</Viewer>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { emitter } from '@pascal-app/core'
|
||||||
|
import { useThree } from '@react-three/fiber'
|
||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import * as THREE from 'three'
|
||||||
|
import { uploadPropertyThumbnail } from '@/features/community/lib/properties/actions'
|
||||||
|
|
||||||
|
const THUMBNAIL_WIDTH = 1920
|
||||||
|
const THUMBNAIL_HEIGHT = 1080
|
||||||
|
|
||||||
|
interface ThumbnailGeneratorProps {
|
||||||
|
propertyId?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ThumbnailGenerator = ({ propertyId: propPropertyId }: ThumbnailGeneratorProps) => {
|
||||||
|
const gl = useThree((state) => state.gl)
|
||||||
|
const scene = useThree((state) => state.scene)
|
||||||
|
const camera = useThree((state) => state.camera)
|
||||||
|
const isGenerating = useRef(false)
|
||||||
|
|
||||||
|
// Use prop propertyId (from URL)
|
||||||
|
const fallbackPropertyId = propPropertyId
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleGenerateThumbnail = async (event: { propertyId: string }) => {
|
||||||
|
if (isGenerating.current) {
|
||||||
|
console.log('⏸️ Thumbnail generation already in progress')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prioritize prop propertyId over event propertyId (URL has priority over session)
|
||||||
|
const propertyId = fallbackPropertyId || event.propertyId
|
||||||
|
|
||||||
|
if (!propertyId) {
|
||||||
|
console.error('❌ No property ID provided')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
isGenerating.current = true
|
||||||
|
console.log('📸 Generating thumbnail for property:', propertyId)
|
||||||
|
console.log('📝 Property ID from URL/prop:', fallbackPropertyId)
|
||||||
|
console.log('📝 Property ID from event:', event.propertyId)
|
||||||
|
console.log('✅ Using property ID:', propertyId, fallbackPropertyId ? '(from URL)' : '(from event)')
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Save current renderer state
|
||||||
|
const currentSize = gl.getSize(new THREE.Vector2())
|
||||||
|
const currentPixelRatio = gl.getPixelRatio()
|
||||||
|
|
||||||
|
// Temporarily resize renderer to thumbnail size
|
||||||
|
gl.setPixelRatio(1)
|
||||||
|
gl.setSize(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)
|
||||||
|
|
||||||
|
// Update camera aspect ratio if it's a perspective camera
|
||||||
|
if (camera instanceof THREE.PerspectiveCamera) {
|
||||||
|
camera.aspect = THUMBNAIL_WIDTH / THUMBNAIL_HEIGHT
|
||||||
|
camera.updateProjectionMatrix()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render the scene
|
||||||
|
gl.render(scene, camera)
|
||||||
|
|
||||||
|
// Wait a frame to ensure render is complete
|
||||||
|
await new Promise((resolve) => requestAnimationFrame(resolve))
|
||||||
|
|
||||||
|
// Capture canvas as blob
|
||||||
|
const canvas = gl.domElement
|
||||||
|
canvas.toBlob(async (blob) => {
|
||||||
|
if (blob) {
|
||||||
|
// Upload to Supabase Storage
|
||||||
|
console.log('☁️ Uploading thumbnail to storage...')
|
||||||
|
const result = await uploadPropertyThumbnail(propertyId, blob)
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
console.log('✅ Thumbnail uploaded successfully!')
|
||||||
|
console.log('🔗 URL:', result.data.thumbnail_url)
|
||||||
|
} else {
|
||||||
|
console.error('❌ Failed to upload thumbnail:', result.error)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('❌ Failed to create blob from canvas')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore renderer size and camera
|
||||||
|
gl.setPixelRatio(currentPixelRatio)
|
||||||
|
gl.setSize(currentSize.x, currentSize.y)
|
||||||
|
|
||||||
|
if (camera instanceof THREE.PerspectiveCamera) {
|
||||||
|
camera.aspect = currentSize.x / currentSize.y
|
||||||
|
camera.updateProjectionMatrix()
|
||||||
|
}
|
||||||
|
|
||||||
|
isGenerating.current = false
|
||||||
|
}, 'image/png')
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Failed to generate thumbnail:', error)
|
||||||
|
|
||||||
|
// Make sure to restore size even on error
|
||||||
|
const currentSize = gl.getSize(new THREE.Vector2())
|
||||||
|
const currentPixelRatio = gl.getPixelRatio()
|
||||||
|
gl.setPixelRatio(currentPixelRatio)
|
||||||
|
gl.setSize(currentSize.x, currentSize.y)
|
||||||
|
|
||||||
|
if (camera instanceof THREE.PerspectiveCamera) {
|
||||||
|
camera.aspect = currentSize.x / currentSize.y
|
||||||
|
camera.updateProjectionMatrix()
|
||||||
|
}
|
||||||
|
|
||||||
|
isGenerating.current = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
emitter.on('camera-controls:generate-thumbnail', handleGenerateThumbnail)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
emitter.off('camera-controls:generate-thumbnail', handleGenerateThumbnail)
|
||||||
|
}
|
||||||
|
}, [gl, scene, camera, fallbackPropertyId])
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
@@ -52,7 +52,6 @@ export const CustomCameraControls = () => {
|
|||||||
}, [cameraMode])
|
}, [cameraMode])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log('ohla')
|
|
||||||
const keyState = {
|
const keyState = {
|
||||||
shiftRight: false,
|
shiftRight: false,
|
||||||
shiftLeft: false,
|
shiftLeft: false,
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import { ExportManager } from './export-manager'
|
|||||||
import { Grid } from './grid'
|
import { Grid } from './grid'
|
||||||
import { SelectionManager } from './selection-manager'
|
import { SelectionManager } from './selection-manager'
|
||||||
import { initSFXBus } from '@/lib/sfx-bus'
|
import { initSFXBus } from '@/lib/sfx-bus'
|
||||||
|
import { ThumbnailGenerator } from '@/app/viewer/[id]/thumbnail-generator'
|
||||||
|
|
||||||
// Load default scene initially (will be replaced when property loads)
|
// Load default scene initially (will be replaced when property loads)
|
||||||
useScene.getState().loadScene()
|
useScene.getState().loadScene()
|
||||||
@@ -73,6 +74,7 @@ export default function Editor({ propertyId }: EditorProps) {
|
|||||||
<Grid cellColor="#aaa" sectionColor="#ccc" fadeDistance={500} />
|
<Grid cellColor="#aaa" sectionColor="#ccc" fadeDistance={500} />
|
||||||
<ToolManager />
|
<ToolManager />
|
||||||
<CustomCameraControls />
|
<CustomCameraControls />
|
||||||
|
<ThumbnailGenerator propertyId={propertyId} />
|
||||||
</Viewer>
|
</Viewer>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { useScene } from "@pascal-app/core";
|
import { emitter, useScene } from "@pascal-app/core";
|
||||||
import { useViewer } from "@pascal-app/viewer";
|
import { useViewer } from "@pascal-app/viewer";
|
||||||
import { Download, Save, Trash2, Upload } from "lucide-react";
|
import { Camera, Download, Save, Trash2, Upload } from "lucide-react";
|
||||||
import { useRef } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { Button } from "@/components/ui/primitives/button";
|
import { Button } from "@/components/ui/primitives/button";
|
||||||
import useEditor from "@/store/use-editor";
|
import useEditor from "@/store/use-editor";
|
||||||
import { AudioSettingsDialog } from "./audio-settings-dialog";
|
import { AudioSettingsDialog } from "./audio-settings-dialog";
|
||||||
|
import { usePropertyStore } from "@/features/community/lib/properties/store";
|
||||||
|
|
||||||
export function SettingsPanel() {
|
export function SettingsPanel() {
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -15,6 +16,11 @@ export function SettingsPanel() {
|
|||||||
const resetSelection = useViewer((state) => state.resetSelection);
|
const resetSelection = useViewer((state) => state.resetSelection);
|
||||||
const exportScene = useViewer((state) => state.exportScene);
|
const exportScene = useViewer((state) => state.exportScene);
|
||||||
const setPhase = useEditor((state) => state.setPhase);
|
const setPhase = useEditor((state) => state.setPhase);
|
||||||
|
const activeProperty = usePropertyStore((state) => state.activeProperty);
|
||||||
|
const [isGeneratingThumbnail, setIsGeneratingThumbnail] = useState(false);
|
||||||
|
|
||||||
|
const propertyId = activeProperty?.id;
|
||||||
|
const isLocalProperty = false; // Store only contains cloud properties
|
||||||
|
|
||||||
const handleExport = async () => {
|
const handleExport = async () => {
|
||||||
if (exportScene) {
|
if (exportScene) {
|
||||||
@@ -64,6 +70,19 @@ export function SettingsPanel() {
|
|||||||
setPhase("site");
|
setPhase("site");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleGenerateThumbnail = () => {
|
||||||
|
if (!propertyId) {
|
||||||
|
console.error('❌ No property ID found');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log('🎯 Generate thumbnail clicked for property:', propertyId);
|
||||||
|
setIsGeneratingThumbnail(true);
|
||||||
|
emitter.emit('camera-controls:generate-thumbnail', { propertyId });
|
||||||
|
console.log('📤 Event emitted with property ID:', propertyId);
|
||||||
|
// Reset loading state after a delay (thumbnail generation is async)
|
||||||
|
setTimeout(() => setIsGeneratingThumbnail(false), 3000);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6 p-3">
|
<div className="flex flex-col gap-6 p-3">
|
||||||
{/* Export Section */}
|
{/* Export Section */}
|
||||||
@@ -81,6 +100,24 @@ export function SettingsPanel() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Thumbnail Section (only for cloud properties) */}
|
||||||
|
{propertyId && !isLocalProperty && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="font-medium text-muted-foreground text-xs uppercase">
|
||||||
|
Thumbnail
|
||||||
|
</label>
|
||||||
|
<Button
|
||||||
|
className="w-full justify-start gap-2"
|
||||||
|
onClick={handleGenerateThumbnail}
|
||||||
|
variant="outline"
|
||||||
|
disabled={isGeneratingThumbnail}
|
||||||
|
>
|
||||||
|
<Camera className="size-4" />
|
||||||
|
{isGeneratingThumbnail ? 'Generating...' : 'Generate Thumbnail'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Save/Load Section */}
|
{/* Save/Load Section */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="font-medium text-muted-foreground text-xs uppercase">
|
<label className="font-medium text-muted-foreground text-xs uppercase">
|
||||||
|
|||||||
@@ -65,6 +65,40 @@ export async function getUserProperties(): Promise<ActionResult<Property[]>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a specific property by ID for the current user
|
||||||
|
*/
|
||||||
|
export async function getPropertyById(propertyId: string): Promise<ActionResult<Property | null>> {
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return { success: false, error: 'Not authenticated', data: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
const supabase = await createServerSupabaseClient()
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('properties')
|
||||||
|
.select(`*, address:properties_addresses(*)`)
|
||||||
|
.eq('id', propertyId)
|
||||||
|
.eq('owner_id', session.user.id)
|
||||||
|
.single<Property>()
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return { success: false, error: error.message, data: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, data: data as Property }
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Failed to fetch property',
|
||||||
|
data: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the active property for the current session
|
* Get the active property for the current session
|
||||||
*/
|
*/
|
||||||
@@ -891,3 +925,84 @@ export async function togglePropertyLike(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upload a thumbnail image to Supabase Storage and update the property
|
||||||
|
*/
|
||||||
|
export async function uploadPropertyThumbnail(
|
||||||
|
propertyId: string,
|
||||||
|
blob: Blob
|
||||||
|
): Promise<{ success: true; data: { thumbnail_url: string } } | { success: false; error: string }> {
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return { success: false, error: 'Not authenticated' }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file size (max 10MB)
|
||||||
|
const MAX_SIZE = 10 * 1024 * 1024
|
||||||
|
if (blob.size > MAX_SIZE) {
|
||||||
|
return { success: false, error: `Image too large (${(blob.size / 1024 / 1024).toFixed(1)}MB). Maximum size is 10MB.` }
|
||||||
|
}
|
||||||
|
|
||||||
|
const supabase = await createServerSupabaseClient()
|
||||||
|
|
||||||
|
// Verify the user owns this property
|
||||||
|
const { data: property, error: propertyError } = await supabase
|
||||||
|
.from('properties')
|
||||||
|
.select('owner_id')
|
||||||
|
.eq('id', propertyId)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (propertyError || !property) {
|
||||||
|
return { success: false, error: 'Property not found' }
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((property as any).owner_id !== session.user.id) {
|
||||||
|
return { success: false, error: 'Not authorized to update this property' }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a unique filename
|
||||||
|
const timestamp = Date.now()
|
||||||
|
const filename = `${propertyId}/${timestamp}.png`
|
||||||
|
|
||||||
|
// Upload to Supabase Storage
|
||||||
|
const { data: uploadData, error: uploadError } = await supabase.storage
|
||||||
|
.from('property-thumbnails')
|
||||||
|
.upload(filename, blob, {
|
||||||
|
contentType: 'image/png',
|
||||||
|
upsert: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (uploadError) {
|
||||||
|
return { success: false, error: `Upload failed: ${uploadError.message}` }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the public URL
|
||||||
|
const { data: urlData } = supabase.storage
|
||||||
|
.from('property-thumbnails')
|
||||||
|
.getPublicUrl(uploadData.path)
|
||||||
|
|
||||||
|
const thumbnailUrl = urlData.publicUrl
|
||||||
|
|
||||||
|
// Update the property with the new thumbnail URL
|
||||||
|
const { error: updateError } = await (supabase
|
||||||
|
.from('properties') as any)
|
||||||
|
.update({ thumbnail_url: thumbnailUrl })
|
||||||
|
.eq('id', propertyId)
|
||||||
|
|
||||||
|
if (updateError) {
|
||||||
|
return { success: false, error: `Failed to update property: ${updateError.message}` }
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: { thumbnail_url: thumbnailUrl },
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Failed to upload thumbnail',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,234 +0,0 @@
|
|||||||
'use client'
|
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
||||||
import {
|
|
||||||
getActiveProperty,
|
|
||||||
getUserProperties,
|
|
||||||
setActiveProperty as setActivePropertyAction,
|
|
||||||
} from './actions'
|
|
||||||
import type { Property } from './types'
|
|
||||||
|
|
||||||
interface UsePropertiesReturn {
|
|
||||||
properties: Property[]
|
|
||||||
isLoading: boolean
|
|
||||||
error: string | null
|
|
||||||
refetch: () => Promise<void>
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to fetch and manage user properties
|
|
||||||
*/
|
|
||||||
export function useProperties(): UsePropertiesReturn {
|
|
||||||
const [properties, setProperties] = useState<Property[]>([])
|
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
|
||||||
|
|
||||||
const fetchProperties = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true)
|
|
||||||
setError(null)
|
|
||||||
|
|
||||||
const result = await getUserProperties()
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
setProperties(result.data || [])
|
|
||||||
} else {
|
|
||||||
setError(result.error || 'Failed to fetch properties')
|
|
||||||
setProperties([])
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
|
|
||||||
setProperties([])
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchProperties()
|
|
||||||
}, [fetchProperties])
|
|
||||||
|
|
||||||
return {
|
|
||||||
properties,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
refetch: fetchProperties,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to fetch a single property by ID
|
|
||||||
*/
|
|
||||||
export function useProperty(propertyId: string | undefined) {
|
|
||||||
const [property, setProperty] = useState<Property | null>(null)
|
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!propertyId) {
|
|
||||||
setProperty(null)
|
|
||||||
setIsLoading(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const fetchProperty = async () => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true)
|
|
||||||
setError(null)
|
|
||||||
|
|
||||||
const result = await getUserProperties()
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
const found = result.data?.find((p) => p.id === propertyId)
|
|
||||||
if (found) {
|
|
||||||
setProperty(found)
|
|
||||||
} else {
|
|
||||||
setError('Property not found')
|
|
||||||
setProperty(null)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setError(result.error || 'Failed to fetch property')
|
|
||||||
setProperty(null)
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
|
|
||||||
setProperty(null)
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchProperty()
|
|
||||||
}, [propertyId])
|
|
||||||
|
|
||||||
return {
|
|
||||||
property,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to manage the active property for the current session
|
|
||||||
*/
|
|
||||||
export function useActiveProperty() {
|
|
||||||
const [activeProperty, setActivePropertyState] = useState<Property | null>(null)
|
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
|
||||||
const [isPending, setIsPending] = useState(false)
|
|
||||||
const isInitialFetchRef = useRef(true)
|
|
||||||
|
|
||||||
const fetchActiveProperty = useCallback(async (allowAutoSelect = false) => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true)
|
|
||||||
setError(null)
|
|
||||||
|
|
||||||
const result = await getActiveProperty()
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
setActivePropertyState(result.data || null)
|
|
||||||
|
|
||||||
// If no active property is set, automatically set the first property as active
|
|
||||||
// Only do this on initial mount to avoid interfering with property selection/creation
|
|
||||||
if (!result.data && allowAutoSelect) {
|
|
||||||
console.log('[useActiveProperty] No active property, checking if we should auto-select')
|
|
||||||
const propertiesResult = await getUserProperties()
|
|
||||||
|
|
||||||
if (
|
|
||||||
propertiesResult.success &&
|
|
||||||
propertiesResult.data &&
|
|
||||||
propertiesResult.data.length > 0
|
|
||||||
) {
|
|
||||||
console.log('[useActiveProperty] Found properties, auto-selecting first one')
|
|
||||||
const firstProperty = propertiesResult.data[0]
|
|
||||||
if (firstProperty) {
|
|
||||||
const setActiveResult = await setActivePropertyAction(firstProperty.id)
|
|
||||||
|
|
||||||
if (setActiveResult.success) {
|
|
||||||
console.log('[useActiveProperty] Auto-selected property:', firstProperty.name)
|
|
||||||
setActivePropertyState(firstProperty)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (!result.data && !allowAutoSelect) {
|
|
||||||
console.log('[useActiveProperty] No active property but auto-select is disabled')
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setError(result.error || 'Failed to fetch active property')
|
|
||||||
setActivePropertyState(null)
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred')
|
|
||||||
setActivePropertyState(null)
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const changeActiveProperty = useCallback(
|
|
||||||
async (propertyId: string | null) => {
|
|
||||||
try {
|
|
||||||
setIsPending(true)
|
|
||||||
setIsLoading(true)
|
|
||||||
const result = await setActivePropertyAction(propertyId)
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
if (propertyId) {
|
|
||||||
// Fetch the property data and set it immediately
|
|
||||||
console.log('[useActiveProperty] Fetching property data for ID:', propertyId)
|
|
||||||
const propertiesResult = await getUserProperties()
|
|
||||||
|
|
||||||
if (propertiesResult.success && propertiesResult.data) {
|
|
||||||
const selectedProperty = propertiesResult.data.find(p => p.id === propertyId)
|
|
||||||
if (selectedProperty) {
|
|
||||||
console.log('[useActiveProperty] Found property, setting as active:', selectedProperty.name)
|
|
||||||
console.log('[useActiveProperty] Current isLoading state:', isLoading)
|
|
||||||
setActivePropertyState(selectedProperty)
|
|
||||||
setIsLoading(false)
|
|
||||||
console.log('[useActiveProperty] Set isLoading to false')
|
|
||||||
} else {
|
|
||||||
console.error('[useActiveProperty] Property not found in user properties')
|
|
||||||
// Fall back to refetch
|
|
||||||
await fetchActiveProperty(false)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.error('[useActiveProperty] Failed to fetch properties')
|
|
||||||
// Fall back to refetch
|
|
||||||
await fetchActiveProperty(false)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setActivePropertyState(null)
|
|
||||||
setIsLoading(false)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.error(result.error || 'Failed to update active property')
|
|
||||||
setIsLoading(false)
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err instanceof Error ? err.message : 'An unexpected error occurred')
|
|
||||||
setIsLoading(false)
|
|
||||||
} finally {
|
|
||||||
setIsPending(false)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[fetchActiveProperty],
|
|
||||||
)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Only allow auto-select on the initial mount
|
|
||||||
const allowAutoSelect = isInitialFetchRef.current
|
|
||||||
if (isInitialFetchRef.current) {
|
|
||||||
isInitialFetchRef.current = false
|
|
||||||
}
|
|
||||||
fetchActiveProperty(allowAutoSelect)
|
|
||||||
}, [fetchActiveProperty])
|
|
||||||
|
|
||||||
return {
|
|
||||||
activeProperty,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
setActiveProperty: changeActiveProperty,
|
|
||||||
isPending,
|
|
||||||
refetch: fetchActiveProperty,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@ import type { Property } from './types'
|
|||||||
import {
|
import {
|
||||||
getActiveProperty,
|
getActiveProperty,
|
||||||
getUserProperties,
|
getUserProperties,
|
||||||
setActiveProperty as setActivePropertyAction,
|
getPropertyById,
|
||||||
} from './actions'
|
} from './actions'
|
||||||
|
|
||||||
interface PropertyStore {
|
interface PropertyStore {
|
||||||
@@ -65,44 +65,16 @@ export const usePropertyStore = create<PropertyStore>((set, get) => ({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Set active property
|
// Set active property by fetching it directly by ID (URL-based, no session update)
|
||||||
setActiveProperty: async (propertyId: string) => {
|
setActiveProperty: async (propertyId: string) => {
|
||||||
set({ isLoading: true })
|
set({ isLoading: true })
|
||||||
|
|
||||||
// Update database
|
const result = await getPropertyById(propertyId)
|
||||||
const result = await setActivePropertyAction(propertyId)
|
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success && result.data) {
|
||||||
// Fetch properties to get the full property object
|
set({ activeProperty: result.data, isLoading: false, error: null })
|
||||||
const propertiesResult = await getUserProperties()
|
|
||||||
|
|
||||||
if (propertiesResult.success && propertiesResult.data) {
|
|
||||||
const selectedProperty = propertiesResult.data.find(p => p.id === propertyId)
|
|
||||||
|
|
||||||
if (selectedProperty) {
|
|
||||||
set({
|
|
||||||
activeProperty: selectedProperty,
|
|
||||||
properties: propertiesResult.data,
|
|
||||||
isLoading: false,
|
|
||||||
error: null
|
|
||||||
})
|
|
||||||
} else {
|
} else {
|
||||||
set({
|
set({ isLoading: false, error: result.error || 'Property not found' })
|
||||||
isLoading: false,
|
|
||||||
error: 'Property not found'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
set({
|
|
||||||
isLoading: false,
|
|
||||||
error: 'Failed to fetch properties'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
set({
|
|
||||||
isLoading: false,
|
|
||||||
error: result.error || 'Failed to set active property'
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -54,12 +54,17 @@ export interface CameraControlEvent {
|
|||||||
nodeId: AnyNode['id']
|
nodeId: AnyNode['id']
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ThumbnailGenerateEvent {
|
||||||
|
propertyId: string
|
||||||
|
}
|
||||||
|
|
||||||
type CameraControlEvents = {
|
type CameraControlEvents = {
|
||||||
'camera-controls:view': CameraControlEvent
|
'camera-controls:view': CameraControlEvent
|
||||||
'camera-controls:capture': CameraControlEvent
|
'camera-controls:capture': CameraControlEvent
|
||||||
'camera-controls:top-view': undefined
|
'camera-controls:top-view': undefined
|
||||||
'camera-controls:orbit-cw': undefined
|
'camera-controls:orbit-cw': undefined
|
||||||
'camera-controls:orbit-ccw': undefined
|
'camera-controls:orbit-ccw': undefined
|
||||||
|
'camera-controls:generate-thumbnail': ThumbnailGenerateEvent
|
||||||
}
|
}
|
||||||
|
|
||||||
type EditorEvents = GridEvents &
|
type EditorEvents = GridEvents &
|
||||||
|
|||||||
Reference in New Issue
Block a user