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(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(null),[size,setSize]=useState({width:innerWidth,height:innerHeight}),[view,setView]=useState(()=>homeView(innerWidth,innerHeight)); const viewport=useRef(null),zoomBehavior=useRef|null>(null),viewRef=useRef(view),searchRef=useRef(null),savedView=useRef(null); const [basketIds,setBasketIds]=useState(()=>{try{return decodeBasket(localStorage.getItem(BASKET_KEY));}catch{return [];}}),[basketOpen,setBasketOpen]=useState(false); const pendingInspection=useRef(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().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
{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`}}>
{menu==='datasets'&&
{Object.entries(catalogue?.meta.counts??{}).map(([repo,count])=>)}
}
setQuery(e.target.value)} spellCheck={false}/>{query?:/}{menu==='filters'&&

Show objects with interactive joints.

}
{menu==='about'&&} {!catalogue&&!error&&
Making room for objects…
} {error&&

The catalogue is taking a moment.

{error}

} {catalogue&&filtered.length===0&&

No objects here yet.

Try another word or clear your filters.

} {selected&&selectedPosition&&setBasketIds(ids=>toggleBasket(ids,selected.id))} onClose={()=>setSelected(null)}/>} {basketOpen&&setBasketOpen(false)} onRemove={id=>setBasketIds(ids=>ids.filter(value=>value!==id))} onClear={()=>setBasketIds([])} onInspect={inspectFromBasket}/>}
; }