Spaces:
Running
Running
Download algospaced-ui/src/components/DesktopIcons.tsx from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/components/DesktopIcons.tsx
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/algospaced-ui/src/components/DesktopIcons.tsx
-
curl -L -o DesktopIcons.tsx https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/components/DesktopIcons.tsx
11.9 kB
| 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<string, { x: number; y: number }> => { | |
| const positions: Record<string, { x: number; y: number }> = {}; | |
| 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<string, { x: number; y: number }> | null, | |
| icons: DesktopIconItem[] | |
| ): Record<string, { x: number; y: number }> => { | |
| const defaultPositions = calculateDefaultPositions(icons); | |
| if (!saved || typeof saved !== 'object') { | |
| return defaultPositions; | |
| } | |
| const result: Record<string, { x: number; y: number }> = {}; | |
| const occupiedSpots = new Set<string>(); | |
| 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<DesktopIconsRef, DesktopIconsProps>(({ | |
| icons, | |
| isMobile: _isMobile = false, | |
| onContextMenu | |
| }, ref) => { | |
| const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => { | |
| 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<string | null>(null); | |
| const [draggingId, setDraggingId] = useState<string | null>(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<HTMLDivElement>, 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<HTMLDivElement>) => { | |
| 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<HTMLDivElement>, 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 ( | |
| <div | |
| className="absolute inset-0 pointer-events-none z-10 select-none overflow-hidden" | |
| onContextMenu={onContextMenu} | |
| > | |
| {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 ( | |
| <div | |
| key={icon.id} | |
| id={`desktop-icon-${icon.id}`} | |
| style={{ | |
| transform: `translate3d(${pos.x}px, ${pos.y}px, 0)`, | |
| touchAction: 'none', | |
| }} | |
| onPointerDown={(e) => 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 */} | |
| <div | |
| className={`w-16 h-16 bg-paper-white border-[3px] flex items-center justify-center transition-all ${ | |
| isSelected | |
| ? 'border-[#0ea5e9] bg-[#dbeafe] shadow-[4px_4px_0px_0px_#0ea5e9] ring-2 ring-[#0ea5e9]' | |
| : 'border-ink-black gadget-shadow group-hover:bg-secondary-container shadow-[inset_2px_2px_0px_rgba(255,255,255,0.8)]' | |
| } ${icon.iconImg ? 'p-1 overflow-hidden' : ''}`} | |
| > | |
| {icon.iconImg ? ( | |
| <img | |
| alt={typeof icon.label === 'string' ? icon.label : icon.id} | |
| className="w-full h-full object-cover pointer-events-none select-none" | |
| src={icon.iconImg} | |
| draggable={false} | |
| /> | |
| ) : ( | |
| <span | |
| className="material-symbols-outlined text-4xl select-none text-ink-black" | |
| style={{ fontVariationSettings: "'FILL' 1" }} | |
| > | |
| {icon.icon || 'apps'} | |
| </span> | |
| )} | |
| </div> | |
| {/* Label */} | |
| <span | |
| className={`font-icon-label text-[9px] px-1.5 py-1 border-[2px] text-center leading-tight uppercase transition-all select-none ${ | |
| isSelected | |
| ? 'bg-[#0ea5e9] text-white border-ink-black shadow-[2px_2px_0px_0px_#1E293B]' | |
| : 'bg-ink-black text-white border-ink-black' | |
| }`} | |
| style={{ | |
| boxShadow: isSelected | |
| ? '2px 2px 0px 0px #1E293B' | |
| : `2px 2px 0px 0px ${icon.badgeShadowColor || '#fde047'}` | |
| }} | |
| > | |
| {icon.label} | |
| </span> | |
| </div> | |
| ); | |
| })} | |
| </div> | |
| ); | |
| }); | |
| export default DesktopIcons; | |