# All files / components Desktop.tsx

97.19% Statements 173/178
75% Branches 21/28
62.5% Functions 5/8
97.19% Lines 173/178

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    1x
    1x
    1x
    1x
    1x
    1x

    1x

    1x
    1x
    1x

    1x
    5x
    5x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x

    8x
    8x
    7x

    8x
    8x

    8x

    8x
    8x
    3x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    8x

    8x
    7x

    7x
    7x

    7x
    3x
    1x
    1x
    1x
    1x
    3x

    7x
    1x
    1x
    8x
    8x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    8x

    8x

    8x

    8x
    8x
    2x
    2x
    2x
    8x

    8x
    2x
    2x
    8x

    8x
    8x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    8x

    8x
    8x

    8x

    8x
    8x
    8x

    8x
    8x
    8x
    8x

    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x

    8x
    8x
    8x
    8x
    8x

    8x
    8x
    8x
    8x
    8x

    8x
    8x
    8x

    8x
    8x
    3x

    3x
    3x
    3x
    3x

    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x

    3x

    8x
     "use client";

    import type React from "react";
    import { useState, useEffect, useMemo, useCallback, memo } from "react";
    import { motion, AnimatePresence } from "framer-motion";
    import DesktopIcon from "./DesktopIcon";
    import Window from "./Window";
    import styles from "./Desktop.module.css";
    import { desktopApps } from "@/data/apps";
    import { WindowState } from "@/app/page";
    import { publish, AwarenessEvent } from '@/lib/awareness';

    // ========================================
    // 🧠 Debug Mode (safe console logger)
    // ========================================
    const DEBUG =
      (typeof process !== "undefined" &&
        process.env.NODE_ENV !== "production") ||
      (typeof process !== "undefined" &&
        process.env.NEXT_PUBLIC_DEBUG === "true");

    const dlog = (...args: any[]) => {
      if (DEBUG) console.log("[Desktop]", ...args);
    };

    // ========================================
    // 🧩 Interfaces
    // ========================================
    interface DesktopProps {
      openWindow: (app: any) => void;
      openWindows?: any[];
      closeWindow: (id: string) => void;
      minimizeWindow: (id: string) => void;
      minimizedWindows?: string[];
      activeWindow: string | null;
      setActiveWindow: (id: string | null) => void;
      windowStates?: Record<string, WindowState>;
      setWindowState: (id: string, newState: Partial<WindowState>) => void;
    }

    // ========================================
    // ⚡ Memoized particle for performance
    // ========================================
    const Particle = memo(({ particle, index }: { particle: any; index: number }) => (
      <motion.div
        className={styles.particle}
        initial={{
          x: particle.x,
          y: particle.y,
          opacity: 0,
        }}
        animate={{
          x: [particle.x, particle.x + (Math.random() - 0.5) * 100],
          y: [particle.y, particle.y + (Math.random() - 0.5) * 100],
          opacity: [0, 0.6, 0],
        }}
        transition={{
          duration: 15 + Math.random() * 10,
          repeat: Number.POSITIVE_INFINITY,
          ease: "linear",
          delay: index * 0.5,
        }}
      />
    ));
    Particle.displayName = "Particle";

    // ========================================
    // 🧱 Desktop Component
    // ========================================
    export default function Desktop({
      openWindow,
      openWindows = [],
      closeWindow,
      minimizeWindow,
      minimizedWindows = [],
      activeWindow,
      setActiveWindow,
      windowStates = {},
      setWindowState,
    }: DesktopProps) {
      // 🧩 Safety
      const safeWindows = Array.isArray(openWindows) ? openWindows : [];
      const safeMinimized = Array.isArray(minimizedWindows)
        ? minimizedWindows
        : [];

      const [selectedIcon, setSelectedIcon] = useState<string | null>(null);
      const [windowZIndexes, setWindowZIndexes] = useState<
        Record<string, number>
      >({});

      // 🌀 Reduced background particles
      const particles = useMemo(
        () =>
          [...Array(8)].map((_, i) => ({
            id: i,
            x:
              Math.random() *
              (typeof window !== "undefined" ? window.innerWidth : 1000),
            y:
              Math.random() *
              (typeof window !== "undefined" ? window.innerHeight : 800),
          })),
        []
      );

      // 🧱 Initialize z-indexes safely
      useEffect(() => {
        if (!Array.isArray(safeWindows)) return;

        const newZIndexes: Record<string, number> = {};
        let hasNewWindows = false;

        safeWindows.forEach((window, index) => {
          if (window && window.id && !windowZIndexes[window.id]) {
            newZIndexes[window.id] = 100 + index;
            hasNewWindows = true;
            if (DEBUG) dlog(`🪟 Added z-index for ${window.id}`);
          }
        });

        if (hasNewWindows) {
          setWindowZIndexes((prev) => ({ ...prev, ...newZIndexes }));
        }
      }, [safeWindows, windowZIndexes]);
        useEffect(() => {
          publish({
            type: AwarenessEvent.DESKTOP_LOADED,
            payload: {
                timestamp: performance.now(),
                openWindows: safeWindows.length,
                activeWindow: activeWindow,
            }
        });
        }, []);

      // 🖱️ Desktop click logic
      const handleIconClick = useCallback((e: React.MouseEvent, app: any) => {
        e.stopPropagation();
        setSelectedIcon(app.id);
      }, []);

      const handleIconDoubleClick = useCallback(
        (app: any) => {
          dlog(`🚀 Opening app: ${app.id}`);
          openWindow(app);
        },
        [openWindow]
      );

      const handleDesktopClick = useCallback(() => {
        setSelectedIcon(null);
        setActiveWindow(null);
      }, [setActiveWindow]);

      // 🧭 Focus handler
      const focusWindow = useCallback(
        (id: string) => {
          setActiveWindow(id);
          setWindowZIndexes((prev) => {
            const maxZ = Math.max(...Object.values(prev), 100);
            return {
              ...prev,
              [id]: maxZ + 1,
            };
          });
          dlog(`🎯 Focused window: ${id}`);
          publish({
              type: AwarenessEvent.WINDOW_FOCUSED,
              payload: {
                  windowId: id,
                  timestamp: performance.now(),
              }
          });
        },
        [setActiveWindow]
      );

      return (
        <div className={`desktop ${styles.desktop}`} onClick={handleDesktopClick}>
          {/* Simplified background */}
          <div className={styles.backgroundLayer} />

          {/* Reduced particles */}
          <div className={styles.particles}>
            {particles.map((particle, index) => (
              <Particle key={particle.id} particle={particle} index={index} />
            ))}
          </div>

          {/* Desktop icons grid */}
          <div className={styles.desktopContent}>
            <div
              className={styles.iconsGrid}
              onClick={(e) => e.stopPropagation()}
            >
              {desktopApps.map((app, index) => (
                <motion.div
                  key={app.id}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{
                    duration: 0.3,
                    delay: index * 0.05,
                  }}
                >
                  <DesktopIcon
                    app={app}
                    isSelected={selectedIcon === app.id}
                    onClick={(e) => handleIconClick(e, app)}
                    onDoubleClick={() => handleIconDoubleClick(app)}
                  />
                </motion.div>
              ))}
            </div>

            {/* Welcome message */}
            <motion.div
              className={styles.welcomeMessage}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.5 }}
            >
              <h1>Welcome to Mohamed Gamal's Portfolio</h1>
              <p>Team Lead | Full Stack Engineer specializing in Laravel + Vue.js</p>
              <p>Double-click any icon to explore my work and experience</p>
            </motion.div>
          </div>

          {/* Windows rendering */}
          <AnimatePresence mode="popLayout">
            {safeWindows.map((window) => {
              if (!window || !window.id) return null;

              const windowWithOpenWindow = {
                ...window,
                openWindow,
              };

              return (
                <Window
                  key={window.id}
                  app={windowWithOpenWindow}
                  onClose={() => closeWindow(window.id)}
                  isActive={activeWindow === window.id}
                  onFocus={() => focusWindow(window.id)}
                  onMinimize={() => minimizeWindow(window.id)}
                  zIndex={windowZIndexes[window.id] || 100}
                  initialPosition={windowStates?.[window.id]?.position}
                  initialSize={windowStates?.[window.id]?.size}
                  isMaximized={windowStates?.[window.id]?.isMaximized}
                  setWindowState={setWindowState}
                />
              );
            })}
          </AnimatePresence>
        </div>
      );
    }