File size: 11,905 Bytes
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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;