ZIP Space Deployer
Deploy ZIP — 2026-10-27 22:06 UTC
7539b2e
Raw History Blame Contribute Delete
15.2 kB
import {useEffect,useMemo,useRef,useState,useCallback} from 'react';
import {select} from 'd3-selection';
import {zoom,zoomIdentity,type ZoomBehavior} from 'd3-zoom';
import {Box,Search,ChevronDown,X,Plus,Minus,Maximize,SlidersHorizontal,ArrowUpRight,RotateCw,Info,Check,ShoppingBag} from 'lucide-react';
import type {Asset,Catalogue,View} from './types';
import {placeAssets,createVisibilityWindow,homeView} from './spatial';
import CanvasObjects from './CanvasObjects';
import ObjectViewer from './ObjectViewer';
import Basket from './Basket';
import ThemeToggle from './ThemeToggle';
import {BASKET_KEY,decodeBasket,toggleBasket} from './basket';
import {createSearch} from './search';
import {applyPreviewIndex} from './preview-index';
import './styles.css';
export default function App(){
const [catalogue,setCatalogue]=useState<Catalogue|null>(null),[error,setError]=useState(''),[retry,setRetry]=useState(0);
const [query,setQuery]=useState(''),[dataset,setDataset]=useState(''),[movingOnly,setMovingOnly]=useState(false),[menu,setMenu]=useState<'datasets'|'filters'|'about'|null>(null);
const [selected,setSelected]=useState<Asset|null>(null),[size,setSize]=useState({width:innerWidth,height:innerHeight}),[view,setView]=useState<View>(()=>homeView(innerWidth,innerHeight));
const viewport=useRef<HTMLDivElement>(null),zoomBehavior=useRef<ZoomBehavior<HTMLDivElement,unknown>|null>(null),viewRef=useRef(view),searchRef=useRef<HTMLInputElement>(null),savedView=useRef<View|null>(null);
const [basketIds,setBasketIds]=useState<string[]>(()=>{try{return decodeBasket(localStorage.getItem(BASKET_KEY));}catch{return [];}}),[basketOpen,setBasketOpen]=useState(false);
const pendingInspection=useRef<Asset|null>(null),panFrame=useRef(0);
const [centering,setCentering]=useState(false);
const basketAssets=useMemo(()=>{const byId=new Map(catalogue?.assets.map(asset=>[asset.id,asset]));return basketIds.flatMap(id=>byId.get(id)?[byId.get(id)!]:[]);},[catalogue,basketIds]);
useEffect(()=>{try{localStorage.setItem(BASKET_KEY,JSON.stringify(basketIds));}catch{/* Storage can be unavailable in private browsing. */}},[basketIds]);
useEffect(()=>{if(catalogue){const known=new Set(catalogue.assets.map(asset=>asset.id));setBasketIds(ids=>{const next=ids.filter(id=>known.has(id));return next.length===ids.length?ids:next;});}},[catalogue]);
const filtering=!!query.trim()||!!dataset||movingOnly;
const search=useMemo(()=>createSearch(catalogue?.assets??[]),[catalogue]);
const filtered=useMemo(()=>search(query,dataset,movingOnly),[search,query,dataset,movingOnly]);
const placed=useMemo(()=>placeAssets(filtered),[filtered]);
const visibility=useMemo(()=>createVisibilityWindow(placed,size.width,size.height),[placed,size.width,size.height]);
const visible=visibility(view);
const selectedPosition=selected?placed.find(p=>p.asset.id===selected.id):null;
const stopPan=useCallback(()=>{cancelAnimationFrame(panFrame.current);panFrame.current=0;setCentering(false);},[]);
const applyView=useCallback((next:View)=>{if(viewport.current&&zoomBehavior.current)select(viewport.current).call(zoomBehavior.current.transform,zoomIdentity.translate(next.x,next.y).scale(next.k));},[]);
const moveTo=useCallback((next:View)=>{stopPan();applyView(next);},[stopPan,applyView]);
const slideTo=useCallback((target:View)=>{
stopPan();
const from={...viewRef.current},next={...target,k:from.k};
if(matchMedia('(prefers-reduced-motion: reduce)').matches||Math.hypot(next.x-from.x,next.y-from.y)<1){applyView(next);return;}
setCentering(true);
const started=performance.now();
const frame=(now:number)=>{
const progress=Math.min(1,Math.max(0,(now-started)/320));
const eased=progress<.5?4*progress**3:1-(-2*progress+2)**3/2;
// One shared view keeps the grid, thumbnails, live 3D and controls aligned.
applyView({x:from.x+(next.x-from.x)*eased,y:from.y+(next.y-from.y)*eased,k:from.k});
panFrame.current=progress<1?requestAnimationFrame(frame):0;
if(progress===1)setCentering(false);
};
panFrame.current=requestAnimationFrame(frame);
},[stopPan,applyView]);
const changeZoom=useCallback((factor:number)=>{stopPan();if(viewport.current&&zoomBehavior.current)select(viewport.current).call(zoomBehavior.current.scaleBy,factor);},[stopPan]);
useEffect(()=>{
const abort=new AbortController();setError('');
const catalogue=fetch(import.meta.env.BASE_URL+'catalogue.json',{signal:abort.signal}).then(r=>{if(!r.ok)throw Error('The catalogue could not be loaded.');return r.json();});
const previews=fetch(import.meta.env.BASE_URL+'preview-index.json',{signal:abort.signal}).then(r=>r.ok?r.json():null).catch(()=>null);
Promise.all([catalogue,previews]).then(([data,index])=>{if(!abort.signal.aborted)setCatalogue(applyPreviewIndex(data,index));}).catch(e=>{if(e.name!=='AbortError')setError(e.message);});
return()=>abort.abort();
},[retry]);
useEffect(()=>{
const el=viewport.current;if(!el)return;let frame=0;
const behavior=zoom<HTMLDivElement,unknown>().scaleExtent([0.35,2.4]).clickDistance(5).filter(event=>{const target=event.target as HTMLElement;if(target.closest('[data-ui]')||target.closest('.viewer-host'))return false;return event.type==='wheel'||(!event.ctrlKey&&!event.button);}).on('start',event=>{if(event.sourceEvent)stopPan();}).on('zoom',event=>{viewRef.current={x:event.transform.x,y:event.transform.y,k:event.transform.k};cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>setView(viewRef.current));});
zoomBehavior.current=behavior;select(el).call(behavior).on('dblclick.zoom',null);moveTo(viewRef.current);
const observer=new ResizeObserver(()=>{stopPan();const rect=el.getBoundingClientRect();setSize({width:rect.width,height:rect.height});});observer.observe(el);
return()=>{stopPan();cancelAnimationFrame(frame);select(el).on('.zoom',null);observer.disconnect();};
},[moveTo,stopPan]);
const wasFiltering=useRef(false);
useEffect(()=>{if(filtering&&!wasFiltering.current)savedView.current={...viewRef.current};if(!filtering&&wasFiltering.current&&savedView.current){moveTo(savedView.current);savedView.current=null;}else if(filtering)moveTo(homeView(size.width,size.height));wasFiltering.current=filtering;setSelected(null);},[query,dataset,movingOnly,filtering,moveTo]);
useEffect(()=>{const handler=(event:KeyboardEvent)=>{if(basketOpen||(event.target as HTMLElement).closest('[role=dialog]'))return;if(event.key==='Escape'){setMenu(null);setSelected(null);searchRef.current?.blur();return;}if(event.ctrlKey||event.metaKey||(event.target as HTMLElement).closest('input,textarea,select,button,a,[contenteditable=true]'))return;if(event.key==='/'){event.preventDefault();searchRef.current?.focus();}if(event.key==='0')moveTo(homeView(size.width,size.height));if(['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key)){event.preventDefault();const v=viewRef.current;moveTo({...v,x:v.x+(event.key==='ArrowLeft'?120:event.key==='ArrowRight'?-120:0),y:v.y+(event.key==='ArrowUp'?120:event.key==='ArrowDown'?-120:0)});}if(event.key==='+'||event.key==='=')changeZoom(1.2);if(event.key==='-')changeZoom(1/1.2);};window.addEventListener('keydown',handler);return()=>window.removeEventListener('keydown',handler);},[moveTo,changeZoom,size,basketOpen]);
const placedRef=useRef(placed),sizeRef=useRef(size);placedRef.current=placed;sizeRef.current=size;
const selectAsset=useCallback((asset:Asset)=>{setSelected(asset);setMenu(null);const position=placedRef.current.find(p=>p.asset.id===asset.id);if(position){const k=viewRef.current.k;slideTo({x:sizeRef.current.width/2-position.x*k,y:sizeRef.current.height/2-position.y*k,k});}},[slideTo]);
useEffect(()=>{if(pendingInspection.current&&placed.some(p=>p.asset.id===pendingInspection.current?.id)){selectAsset(pendingInspection.current);pendingInspection.current=null;}},[placed,selectAsset]);
const inspectFromBasket=(asset:Asset)=>{setBasketOpen(false);if(placed.some(p=>p.asset.id===asset.id))selectAsset(asset);else{pendingInspection.current=asset;setQuery('');setDataset('');setMovingOnly(false);}};
const reset=()=>{setQuery('');setDataset('');setMovingOnly(false);setSelected(null);setMenu(null);};
const selectedX=selectedPosition?selectedPosition.x*view.k+view.x:0,selectedY=selectedPosition?selectedPosition.y*view.k+view.y:0;
return <main className="app-shell">
<div ref={viewport} className="viewport" aria-label="Object exploration canvas" onClick={e=>{if(e.target===viewport.current){setSelected(null);setMenu(null);}}} style={{backgroundPosition:`${view.x}px ${view.y}px`,backgroundSize:`${36*view.k}px ${36*view.k}px`}}>
<div className="world" style={{transform:`translate(${view.x}px,${view.y}px) scale(${view.k})`}}><CanvasObjects items={visible} selectedId={selected?.id} onInspect={selectAsset}/></div>
</div>
<header className="topbar" data-ui>
<button className="wordmark" aria-label="SimReady Assets Explorer — return to overview" onClick={()=>{savedView.current=null;wasFiltering.current=false;reset();moveTo(homeView(size.width,size.height));}}><Box size={25} strokeWidth={1.55}/><span className="brand-name"><strong>SimReady</strong><small>Assets Explorer</small></span></button>
<div className="dataset-selector"><button className={`quiet-button ${dataset?'active':''}`} onClick={()=>setMenu(menu==='datasets'?null:'datasets')} aria-expanded={menu==='datasets'}>{dataset?dataset.split('/')[0]:'All datasets'}<ChevronDown size={14}/></button>{menu==='datasets'&&<div className="popover dataset-menu"><button className={!dataset?'chosen':''} onClick={()=>{setDataset('');setMenu(null);}}>All datasets<span>{catalogue?.meta.assetCount.toLocaleString()}</span></button>{Object.entries(catalogue?.meta.counts??{}).map(([repo,count])=><button key={repo} className={dataset===repo?'chosen':''} onClick={()=>{setDataset(repo);setMenu(null);}}><span>{repo}</span><small>{count.toLocaleString()}</small></button>)}</div>}</div>
<div className="search-wrap"><Search size={18}/><input ref={searchRef} aria-label="Search objects" placeholder="Find an object…" value={query} onChange={e=>setQuery(e.target.value)} spellCheck={false}/>{query?<button className="icon-button" aria-label="Clear search" onClick={()=>setQuery('')}><X size={16}/></button>:<kbd>/</kbd>}<span className="divider"/><button className={`icon-button ${movingOnly?'active':''}`} aria-label="Search filters" aria-expanded={menu==='filters'} onClick={()=>setMenu(menu==='filters'?null:'filters')}><SlidersHorizontal size={17}/></button>{menu==='filters'&&<div className="popover filter-menu"><button onClick={()=>setMovingOnly(!movingOnly)} aria-pressed={movingOnly}><span>Objects with movement</span><span className={`toggle ${movingOnly?'on':''}`}>{movingOnly&&<Check size={12}/>}</span></button><p>Show objects with interactive joints.</p></div>}</div>
<div className="topbar-actions"><button className={`basket-button ${basketIds.length?'has-objects':''}`} aria-label={`Open basket, ${basketIds.length} objects`} aria-haspopup="dialog" onClick={()=>{setMenu(null);setBasketOpen(true);}}><ShoppingBag size={18}/>{!!basketIds.length&&<span>{basketIds.length}</span>}</button><button className="icon-button about-button" aria-label="About this explorer" onClick={()=>setMenu(menu==='about'?null:'about')}><Info size={18}/></button></div>
</header>
{menu==='about'&&<aside className="popover about-panel" data-ui><button className="close-panel icon-button" aria-label="Close information" onClick={()=>setMenu(null)}><X size={16}/></button><Box size={26}/><h2>Objects, ready to explore.</h2><p>Explore OpenUSD assets from NVIDIA SimReady Assets and contributing creators. Find an object, inspect it in 3D, and try its available movements.</p><p className="interface-credit">Interface by <a href="https://huggingface.co/fffiloni" target="_blank" rel="noreferrer">Sylvain Filoni / fffiloni<ArrowUpRight size={13}/></a></p><p className="subtle">Original assets by NVIDIA and contributing creators. Interactive previews use technology adapted from SimReady Central.</p><a href="https://huggingface.co/datasets/nvidia/simready-assets" target="_blank" rel="noreferrer">NVIDIA SimReady Assets<ArrowUpRight size={14}/></a><a href="https://huggingface.co/spaces/nvidia/simready-central" target="_blank" rel="noreferrer">Explore SimReady Central<ArrowUpRight size={14}/></a><a href="https://huggingface.co/collections/cfahlgren1/openusd-datasets" target="_blank" rel="noreferrer">OpenUSD dataset collection<ArrowUpRight size={14}/></a><small>{catalogue?.meta.assetCount.toLocaleString()} indexed objects · {catalogue?.meta.datasetCount} datasets</small></aside>}
{!catalogue&&!error&&<div className="center-status" role="status"><span className="loading-orbit"/>Making room for objects…</div>}
{error&&<div className="empty-state" role="alert"><Box size={34}/><h2>The catalogue is taking a moment.</h2><p>{error}</p><button className="quiet-button" onClick={()=>setRetry(x=>x+1)}><RotateCw size={15}/>Try again</button></div>}
{catalogue&&filtered.length===0&&<div className="empty-state"><Search size={32}/><h2>No objects here yet.</h2><p>Try another word or clear your filters.</p><button className="quiet-button" onClick={reset}>Show all objects</button></div>}
{selected&&selectedPosition&&<ObjectViewer key={selected.id} asset={selected} moving={centering} objectSize={selectedPosition.size} x={selectedX} y={selectedY} scale={view.k} width={size.width} height={size.height} inBasket={basketIds.includes(selected.id)} onToggleBasket={()=>setBasketIds(ids=>toggleBasket(ids,selected.id))} onClose={()=>setSelected(null)}/>}
{basketOpen&&<Basket assets={basketAssets} onClose={()=>setBasketOpen(false)} onRemove={id=>setBasketIds(ids=>ids.filter(value=>value!==id))} onClear={()=>setBasketIds([])} onInspect={inspectFromBasket}/>}
<footer className="bottom-bar" data-ui><div className="canvas-hint"><span className="desktop-hint">Drag to explore · Scroll to zoom</span><span className="mobile-hint">Drag to explore · Pinch to zoom</span>{catalogue&&<span className="object-count" role="status">{filtered.length.toLocaleString()} {filtering?'matches':'objects'}{filtering&&<button onClick={reset} aria-label="Clear all filters"><X size={13}/></button>}</span>}<a className="creator-credit" href="https://huggingface.co/fffiloni" target="_blank" rel="noreferrer" aria-label="Interface by fffiloni">Interface by fffiloni<ArrowUpRight size={11}/></a></div><div className="view-tools"><ThemeToggle/><div className="zoom-control"><button aria-label="Zoom out" onClick={()=>changeZoom(1/1.2)}><Minus size={16}/></button><button className="zoom-value" aria-label="Reset view" onClick={()=>moveTo(homeView(size.width,size.height))}>{Math.round(view.k*100)}%</button><button aria-label="Zoom in" onClick={()=>changeZoom(1.2)}><Plus size={16}/></button></div><button className="icon-button fit-button" aria-label="Return to overview" onClick={()=>{setSelected(null);moveTo(homeView(size.width,size.height));}}><Maximize size={17}/></button></div></footer>
</main>;
}