import { useState, useEffect, useRef, useImperativeHandle, forwardRef, type ReactNode, type PointerEvent as ReactPointerEvent, type MouseEvent as ReactMouseEvent } from 'react'; export interface DesktopIconItem { id: string; label: ReactNode; icon?: string; iconImg?: string; badgeShadowColor?: string; action: () => void; hidden?: boolean; } export interface DesktopIconsRef { autoArrange: () => void; resetLayout: () => void; } interface DesktopIconsProps { icons: DesktopIconItem[]; isMobile?: boolean; onContextMenu?: (e: ReactMouseEvent) => void; } const STORAGE_KEY = 'algospaced_desktop_icon_positions_v2'; const ICON_WIDTH = 96; const ICON_HEIGHT = 105; const START_X = 24; const START_Y = 60; const SPACING_Y = 112; const SPACING_X = 108; const calculateDefaultPositions = (icons: DesktopIconItem[]): Record => { const positions: Record = {}; const visibleIcons = icons.filter(i => !i.hidden); const maxY = typeof window !== 'undefined' ? window.innerHeight - 100 : 700; let currentX = START_X; let currentY = START_Y; visibleIcons.forEach((icon) => { if (currentY + ICON_HEIGHT > maxY && currentY > START_Y) { currentX += SPACING_X; currentY = START_Y; } positions[icon.id] = { x: currentX, y: currentY }; currentY += SPACING_Y; }); return positions; }; const sanitizePositions = ( saved: Record | null, icons: DesktopIconItem[] ): Record => { const defaultPositions = calculateDefaultPositions(icons); if (!saved || typeof saved !== 'object') { return defaultPositions; } const result: Record = {}; const occupiedSpots = new Set(); const spotKey = (x: number, y: number) => `${Math.round(x / 50)},${Math.round(y / 50)}`; // Place queue first to guarantee top-left placement const orderedIcons = [...icons].sort((a, b) => { if (a.id === 'queue') return -1; if (b.id === 'queue') return 1; return 0; }); orderedIcons.forEach((icon) => { const p = saved[icon.id]; if (p && Number.isFinite(p.x) && Number.isFinite(p.y)) { const key = spotKey(p.x, p.y); if (!occupiedSpots.has(key)) { result[icon.id] = { x: Math.max(8, p.x), y: Math.max(48, p.y) }; occupiedSpots.add(key); return; } } // If missing or colliding, use default position or find next open slot const def = defaultPositions[icon.id] || { x: START_X, y: START_Y }; let finalX = def.x; let finalY = def.y; while (occupiedSpots.has(spotKey(finalX, finalY))) { finalY += SPACING_Y; if (typeof window !== 'undefined' && finalY + ICON_HEIGHT > window.innerHeight - 100) { finalX += SPACING_X; finalY = START_Y; } } result[icon.id] = { x: finalX, y: finalY }; occupiedSpots.add(spotKey(finalX, finalY)); }); return result; }; const DesktopIcons = forwardRef(({ icons, isMobile: _isMobile = false, onContextMenu }, ref) => { const [positions, setPositions] = useState>(() => { try { const saved = localStorage.getItem(STORAGE_KEY); if (saved) { const parsed = JSON.parse(saved); if (parsed && typeof parsed === 'object') { return sanitizePositions(parsed, icons); } } } catch (e) { console.error('Error loading icon positions:', e); } return calculateDefaultPositions(icons); }); const [selectedIconId, setSelectedIconId] = useState(null); const [draggingId, setDraggingId] = useState(null); const dragInfoRef = useRef<{ startX: number; startY: number; initialIconX: number; initialIconY: number; hasMoved: boolean; pointerId: number | null; }>({ startX: 0, startY: 0, initialIconX: 0, initialIconY: 0, hasMoved: false, pointerId: null }); // Keep positions within screen bounds on window resize or initial icon additions useEffect(() => { const handleResize = () => { setPositions(prev => { const next = sanitizePositions(prev, icons); let changed = false; const maxX = Math.max(100, window.innerWidth - ICON_WIDTH); const maxY = Math.max(100, window.innerHeight - 120); icons.forEach(icon => { const raw = next[icon.id]; if (raw) { const clampedX = Math.max(8, Math.min(raw.x, maxX)); const clampedY = Math.max(48, Math.min(raw.y, maxY)); if (clampedX !== raw.x || clampedY !== raw.y) { next[icon.id] = { x: clampedX, y: clampedY }; changed = true; } } }); if (changed || JSON.stringify(next) !== JSON.stringify(prev)) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch (_) {} } return next; }); }; handleResize(); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, [icons]); // Imperative actions for Desktop Context Menu useImperativeHandle(ref, () => ({ autoArrange: () => { const newPos = calculateDefaultPositions(icons); setPositions(newPos); try { localStorage.setItem(STORAGE_KEY, JSON.stringify(newPos)); } catch (_) {} }, resetLayout: () => { localStorage.removeItem(STORAGE_KEY); localStorage.removeItem('algospaced_desktop_icon_positions_v1'); const newPos = calculateDefaultPositions(icons); setPositions(newPos); } })); // Deselect icon when clicking empty desktop area useEffect(() => { const handleGlobalClick = (e: MouseEvent) => { const target = e.target as HTMLElement; if (!target.closest('.desktop-icon-unit')) { setSelectedIconId(null); } }; window.addEventListener('pointerdown', handleGlobalClick); return () => window.removeEventListener('pointerdown', handleGlobalClick); }, []); const handlePointerDown = (e: ReactPointerEvent, icon: DesktopIconItem) => { // Only handle primary button / touches if (e.button !== 0 && e.pointerType === 'mouse') return; e.stopPropagation(); const defaultPos = calculateDefaultPositions(icons)[icon.id] || { x: START_X, y: START_Y }; const rawPos = positions[icon.id]; const currentPos = rawPos && Number.isFinite(rawPos.x) && Number.isFinite(rawPos.y) ? rawPos : defaultPos; dragInfoRef.current = { startX: e.clientX, startY: e.clientY, initialIconX: currentPos.x, initialIconY: currentPos.y, hasMoved: false, pointerId: e.pointerId }; setDraggingId(icon.id); try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); } catch (_) {} }; const handlePointerMove = (e: ReactPointerEvent) => { if (!draggingId) return; const { startX, startY, initialIconX, initialIconY, hasMoved } = dragInfoRef.current; const deltaX = e.clientX - startX; const deltaY = e.clientY - startY; if (!hasMoved && Math.hypot(deltaX, deltaY) > 6) { dragInfoRef.current.hasMoved = true; } if (dragInfoRef.current.hasMoved) { const maxX = Math.max(100, window.innerWidth - ICON_WIDTH); const maxY = Math.max(100, window.innerHeight - 110); const newX = Math.max(8, Math.min(initialIconX + deltaX, maxX)); const newY = Math.max(48, Math.min(initialIconY + deltaY, maxY)); setPositions(prev => ({ ...prev, [draggingId]: { x: newX, y: newY } })); } }; const handlePointerUp = (e: ReactPointerEvent, icon: DesktopIconItem) => { if (draggingId !== icon.id) return; try { (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId); } catch (_) {} const { hasMoved } = dragInfoRef.current; if (hasMoved) { // Drag ended, save positions to localStorage try { localStorage.setItem(STORAGE_KEY, JSON.stringify(positions)); } catch (_) {} } else { // It was a click / tap: select and immediately execute action setSelectedIconId(icon.id); icon.action(); } setDraggingId(null); }; const handleDoubleClick = (icon: DesktopIconItem) => { icon.action(); }; const visibleIcons = icons.filter(i => !i.hidden); return (
{visibleIcons.map((icon) => { const defaultPositions = calculateDefaultPositions(icons); const rawPos = positions[icon.id]; const pos = rawPos && Number.isFinite(rawPos.x) && Number.isFinite(rawPos.y) ? rawPos : defaultPositions[icon.id] || { x: START_X, y: START_Y }; const isSelected = selectedIconId === icon.id; const isDragging = draggingId === icon.id; return (
handlePointerDown(e, icon)} onPointerMove={handlePointerMove} onPointerUp={(e) => handlePointerUp(e, icon)} onPointerCancel={(e) => handlePointerUp(e, icon)} onDoubleClick={() => handleDoubleClick(icon)} className={`desktop-icon-unit absolute top-0 left-0 w-[96px] flex flex-col items-center justify-center gap-1.5 p-2 pointer-events-auto cursor-grab active:cursor-grabbing group transition-transform duration-75 ${ isDragging ? 'z-30 scale-105 opacity-90' : 'z-10' }`} > {/* Retro Icon Container */}
{icon.iconImg ? ( {typeof ) : ( {icon.icon || 'apps'} )}
{/* Label */} {icon.label}
); })}
); }); export default DesktopIcons;