import {useEffect,useRef,useState} from 'react'; import {X,Info,Download,Copy,Check,ArrowUpRight,Film,Box,RotateCw,ShoppingBag,Code2} from 'lucide-react'; import type {Asset} from './types'; import type {createEngine,Joint} from './viewer-engine'; import AssetImage from './AssetImage'; import MotionControls from './MotionControls'; import ObjectInfo from './ObjectInfo'; import VisualControls,{type ViewMode,type InspectionInfo} from './VisualControls'; import CodePanel from './CodePanel'; import SelectionIndicator from './SelectionIndicator'; import {homeProgress} from './vendor/kinematics.js'; import {downloadCommand} from './download'; import {viewerFrame,selectionInFocus} from './spatial'; import {formatFileSize} from './file-size'; import {inspectionLayout} from './inspection-layout'; type Props={asset:Asset;moving?:boolean;x:number;y:number;scale:number;objectSize:number;width:number;height:number;inBasket:boolean;onToggleBasket:()=>void;onClose:()=>void}; export default function ObjectViewer({asset,moving=false,x,y,scale,objectSize,width,height,inBasket,onToggleBasket,onClose}:Props){ const interaction=useRef(null),host=useRef(null),video=useRef(null),engine=useRef|null>(null); const inspectorContent=useRef(null),codeTrigger=useRef(null),jointsRef=useRef([]); const movingRef=useRef(moving);movingRef.current=moving; const values=useRef>({}),selectedRef=useRef([]); const [status,setStatus]=useState('Preparing 3D…'),[error,setError]=useState(''),[ready,setReady]=useState(false); const [joints,setJoints]=useState([]),[selected,setSelected]=useState([]),[positions,setPositions]=useState>({}),[fixedPart,setFixedPart]=useState(false),[playing,setPlaying]=useState(false),[highlighted,setHighlighted]=useState(!asset.motion); const [panel,setPanel]=useState<'info'|'download'|'code'|null>(null),[copied,setCopied]=useState(false),[copyError,setCopyError]=useState(false),[mode,setMode]=useState<'3d'|'video'>('3d'),[retry,setRetry]=useState(0),[allowLarge,setAllowLarge]=useState(false); const [code,setCode]=useState(''),[codeError,setCodeError]=useState(''),[motionWarning,setMotionWarning]=useState(''); const [viewMode,setViewMode]=useState('materials'),[explode,setExplode]=useState(0),[part,setPart]=useState(''),[hovered,setHovered]=useState(''); const [inspection,setInspection]=useState(null),[viewBusy,setViewBusy]=useState(false),[viewError,setViewError]=useState(''); useEffect(()=>{if(panel!=='code'||!asset.program)return;const abort=new AbortController();setCode('');setCodeError('');fetch(asset.program,{signal:abort.signal}).then(r=>{if(!r.ok)throw Error('Program unavailable.');return r.text();}).then(setCode).catch(e=>{if(e.name!=='AbortError')setCodeError(e.message);});return()=>abort.abort();},[panel,asset.program]); const large=!!asset.bytes&&asset.bytes>50*1024*1024&&!allowLarge; const {dimension,left,top,inView}=viewerFrame(x,y,scale,width,height,objectSize); const showControls=inView&&selectionInFocus(x,y,width,height); const layout=inspectionLayout(width,height),codeOpen=panel==='code'; useEffect(()=>{if(inspectorContent.current)inspectorContent.current.scrollTop=0;},[asset.id,panel,mode]); useEffect(()=>{ if(mode!=='3d'||!asset.model||large)return; let cancelled=false,start=0;setReady(false);setError('');setMotionWarning('');setJoints([]);setSelected([]);selectedRef.current=[];setFixedPart(false);setPlaying(false);setHighlighted(!asset.motion);setStatus('Preparing 3D…'); setInspection(null);setViewMode('materials');setExplode(0);setPart('');setHovered('');setViewBusy(false);setViewError(''); // Center first: rapidly changing selection can cancel before allocating a renderer. const begin=()=>{ if(cancelled)return; if(movingRef.current){start=requestAnimationFrame(begin);return;} start=requestAnimationFrame(()=>{ if(movingRef.current){begin();return;} import('./viewer-engine').then(({createEngine})=>{ if(cancelled||!host.current)return; try{ engine.current=createEngine(host.current,{url:asset.model!,compact:asset.compact,sha256:asset.sha256,motion:asset.motion,motionSha256:asset.motionSha256},value=>{if(!cancelled)setStatus(value);},(items,info={})=>{ if(cancelled)return; setInspection((info.inspection as InspectionInfo|undefined)??null); setMotionWarning(((info.warnings as {code:string;message:string}[]|undefined)??[]).filter(w=>w.code==='motion').map(w=>w.message).join(' '));jointsRef.current=items;setJoints(items);selectedRef.current=items.slice(0,1).map(j=>j.id);setSelected(selectedRef.current); values.current=Object.fromEntries(items.map(j=>[j.id,homeProgress(j)])); setPositions({...values.current});setReady(true); },failure=>{if(!cancelled){setReady(false);setPlaying(false);setJoints([]);setError(failure.message);setStatus('');}},(id,value)=>{ if(cancelled)return;values.current[id]=value;setPositions(current=>({...current,[id]:value})); },(kind,item)=>{ if(cancelled)return; if(kind==='hover'){setHovered(item?.name??'');return;} setPart(item?.id??'');if(!item)setFixedPart(false); if(item&&item.jointId!==undefined){ engine.current?.play(false);setPlaying(false); const next=jointsRef.current.find(j=>j.id===item.jointId); setFixedPart(!next); // A picked driver joins the group; a fixed part clears playback explicitly. const ids=next?[...new Set([...selectedRef.current,next.id])]:[]; selectedRef.current=ids;setSelected(ids);engine.current?.setPlaybackSelection(ids); } },interaction.current??undefined); }catch(failure){if(!cancelled){setError(String(failure));setStatus('');}} }).catch(failure=>{if(!cancelled){setError(String(failure));setStatus('');}}); }); };start=requestAnimationFrame(begin); return()=>{cancelled=true;cancelAnimationFrame(start);engine.current?.dispose();engine.current=null;}; },[asset.id,mode,retry,large]); useEffect(()=>{ engine.current?.setVisible(inView); if(!showControls){engine.current?.play(false);setPlaying(false);video.current?.pause();} },[inView,showControls,ready,mode]); const hasMovement=mode==='3d'&&ready&&joints.length>0; const command=downloadCommand(asset); const copy=async()=>{try{await navigator.clipboard.writeText(command);setCopied(true);setCopyError(false);}catch{setCopied(false);setCopyError(true);}}; const chooseMovements=(ids:string[])=>{ selectedRef.current=ids;setSelected(ids);setFixedPart(false); if(!ids.length)setPlaying(false); engine.current?.setPlaybackSelection(ids); engine.current?.selectPart('');setPart(''); }; const setPosition=(id:string,value:number)=>{setPlaying(false);engine.current?.setJoint(id,value);}; const chooseView=(next:ViewMode)=>{ const current=engine.current;if(!current||viewBusy)return; setViewBusy(true);setViewError(''); // Let the busy state paint before the first edge geometry is prepared. requestAnimationFrame(()=>setTimeout(()=>{ if(engine.current!==current)return; try{current.setMode(next);setViewMode(next);}catch{current.setMode('materials');setViewMode('materials');setViewError('Mesh view unavailable for this object. Materials remain available.');} finally{setViewBusy(false);} },0)); }; const resetAppearance=()=>{engine.current?.resetAppearance();setViewMode('materials');setExplode(0);setPart('');setHovered('');setViewError('');}; const indicator=error?'error':ready?'ready':large||!asset.model?'idle':'loading'; return <>
{mode==='3d'&&<>
{!ready&&}{inView&&}} {mode==='video'&&asset.video&&
{showControls&&
{asset.name}{asset.author}USDA{asset.bytes!=null?` · ${formatFileSize(asset.bytes)}`:''}
{asset.program&&}
{mode==='video'?{error||'Recorded motion · all parts'}:!asset.model?Image preview · 3D unavailable for this object:large?:error?<>3D unavailable · Showing source image:ready?<>{motionWarning?'3D ready · Movement unavailable — see information':'3D ready · Drag to rotate'}:<>{moving?'Centering object…':status}} {asset.video&&}
{!panel&&mode==='3d'&&ready&&inspection&&<>{setExplode(value);engine.current?.explode(value);}} onPart={id=>engine.current?.selectPart(id)} onReset={resetAppearance}/> {viewError&&

{viewError}

}} {!panel&&hasMovement&&{engine.current?.play(!playing);setPlaying(!playing);}} onReset={()=>{engine.current?.resetMovements();setPlaying(false);}} onHighlight={()=>{engine.current?.setHighlight(!highlighted);setHighlighted(!highlighted);}}/>} {panel==='info'&&} {panel==='download'&&

Take this object with you.

Download the original USDA, its Python program and attribution together from your basket.

{copyError&&

Clipboard unavailable. Open the command below and copy it manually.

}Browse source files
Show command{command}
Source version: {asset.revision.slice(0,8)}
}
} {showControls&&codeOpen&&asset.program&&
{setPanel(null);requestAnimationFrame(()=>codeTrigger.current?.focus({preventScroll:true}));}}/>
} ; }