All files / src/components/UploadFile FileUploadDesktopView.tsx

70% Statements 42/60
42.5% Branches 17/40
57.89% Functions 11/19
71.92% Lines 41/57

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 261 262 263 264 265 266 267 268 269 270 271 272                                    2x   2x                             2x                                                           19x 19x 19x       19x 19x 19x         19x         19x 19x   19x                         19x             19x         19x 3x 3x     19x 1x     19x 11x                     11x 11x       19x 7x         7x   7x 7x       19x 3x 3x 3x           19x 10x   7x       3x       19x   12x                                                                       4x                                                             11x                                                                
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Box, Stack } from "@mui/material";
import { useFileUploadContext } from "./FileUploadContext";
import { UploadCard } from "./FileUploadSnackbar";
import { FileUploadStatus, SnackbarFile } from "./types";
import {
  DndContext,
  DragMoveEvent,
  DragOverlay,
  DragStartEvent,
  MouseSensor,
  TouchSensor,
  useSensor,
  useSensors,
} from "@dnd-kit/core";
import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
 
//when released under this value, it will be deleted
const DRAG_TRESHOLD = 140;
 
const animatedStyle = {
  animation: "outAnimation 270ms ease-out",
  opacity: 0.1,
  "@keyframes outAnimation": {
    "0%": {
      transform: "translateX(0)",
      opacity: 1,
    },
    "100%": {
      transform: `translateX(${-DRAG_TRESHOLD}px)`,
      opacity: 0.1,
    },
  },
};
 
const bounceAnimation = {
  animation: "bounceInRight 0.75s ease",
  "@keyframes bounceInRight": {
    "0%": {
      opacity: 0,
      transform: "translateX(-100%)",
    },
    "25%": {
      transform: "translateX(12px)",
    },
    "50%": {
      transform: "translateX(-8px)",
    },
    "75%": {
      transform: "translateX(3px)",
    },
    "100%": {
      opacity: 1,
      transform: "translateX(0)",
    },
  },
};
 
enum AnimationEnum {
  FADE,
  BOUNCE,
}
 
export default function FileUploadDesktopView() {
  const { snackbarFiles, setSnackbarFiles, isEveryFileUploaded } =
    useFileUploadContext();
  const [expanded, setExpanded] = React.useState(false);
  const [draggedItem, setDraggedItem] = React.useState<SnackbarFile | null>(
    null,
  );
  const [currentAnimation, setCurrentAnimation] =
    React.useState<AnimationEnum | null>(AnimationEnum.BOUNCE);
  const [dragX, setDragX] = useState<number>(0); //DragOverlay does not have it's own transform, we need the actual item
  const mouseSensor = useSensor(MouseSensor, {
    activationConstraint: {
      distance: 5,
    },
  });
  const touchSensor = useSensor(TouchSensor, {
    activationConstraint: {
      distance: 5,
    },
  });
  const sensors = useSensors(mouseSensor, touchSensor);
  const closeTimeoutRef = useRef<NodeJS.Timeout | null>();
 
  const handleDragEnd = useCallback(
    (event: DragMoveEvent) => {
      if (event.delta.x < -DRAG_TRESHOLD || event.delta.x > DRAG_TRESHOLD) {
        setSnackbarFiles((prev) =>
          prev.filter((item) => item.identifier !== event.active.id && item.name !== event.active.id),
        );
      }
      setDraggedItem(null);
      setDragX(0);
    },
    [snackbarFiles],
  );
 
  const handleDragStart = (event: DragStartEvent) => {
    const item = snackbarFiles.find(
      (item) => item.identifier === event.active.id || item.name === event.active.id,
    );
    if (item) setDraggedItem(item);
  };
 
  const handleDragMove = (event: DragMoveEvent) => {
    //we will use this for the opacity effect
    setDragX(event.delta.x);
  };
 
  const handleMouseEnter = () => {
    closeTimeoutRef.current && clearTimeout(closeTimeoutRef.current);
    !currentAnimation && setExpanded(true);
  };
 
  const handleMouseLeave = () => {
    !currentAnimation && !draggedItem && setExpanded(false);
  };
 
  useEffect(() => {
    const timeoutID = setTimeout(() => {
      if (
        snackbarFiles.length > 0 &&
        isEveryFileUploaded &&
        !expanded &&
        !draggedItem
      ) {
        setCurrentAnimation(AnimationEnum.FADE);
      }
    }, 3000);
 
    return () => {
      clearTimeout(timeoutID);
    };
  }, [snackbarFiles, isEveryFileUploaded, expanded]);
 
  useEffect(() => {
    const closeTimeout = setTimeout(() => {
      if (expanded && !draggedItem) {
        setExpanded(false);
      }
    }, 3000);
    closeTimeoutRef.current = closeTimeout;
    
    return () => {
      clearTimeout(closeTimeout);
    }
  }, [draggedItem]);
 
  const handleAnimationEnd = () => {
    Eif (currentAnimation === AnimationEnum.BOUNCE) {
      setCurrentAnimation(null);
      return;
    }
    setSnackbarFiles([]);
    setCurrentAnimation(AnimationEnum.BOUNCE);
  };
 
  const animStyle = useMemo(() => {
    switch (currentAnimation) {
      case AnimationEnum.BOUNCE:
        return bounceAnimation;
      case AnimationEnum.FADE:
        return animatedStyle;
      default:
        return {};
    }
  }, [currentAnimation]);
 
  if (snackbarFiles.length < 1) return null;
 
  return (
    <DndContext
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragMove={handleDragMove}
      sensors={sensors}
    >
      <Box
        sx={{
          position: "fixed",
          zIndex: 1500,
          left: "80px",
          bottom: "0px",
          width: "400px",
        }}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        data-testid="snackbar-desktop-container"
      >
        {expanded || !!draggedItem ? ( //to avoid glitches, it's better to keep list expanded while dragging
          <Stack
            direction="column-reverse"
            alignItems="center"
            spacing={1}
            sx={{
              maxHeight: "100vh",
              overflowY: "auto",
              paddingTop: "30px",
              paddingBottom: "30px",
              paddingLeft: "15px",
              paddingRight: "55px",
              overflowX: "hidden",
            }}
            data-testid="snackbar-desktop-expanded-container"
          >
            {snackbarFiles.map((file: SnackbarFile) => {
              return (
                <UploadCard
                  key={file.id}
                  snackbarFile={file}
                  style={{
                    width: "100%",
                  }}
                  isDraggingEnabled={
                    file.status !== FileUploadStatus.IN_PROGRESS
                  }
                />
              );
            })}
          </Stack>
        ) : (
          <Stack
            direction="column-reverse"
            alignItems="center"
            spacing={-5.5}
            sx={{
              paddingBottom: "30px",
              paddingLeft: "15px",
              paddingRight: "55px",
              ...animStyle,
            }}
            data-testid="snackbar-desktop-collapsed-container"
            onAnimationEnd={handleAnimationEnd}
          >
            {snackbarFiles
              .slice(0, 3)
              .map((file: SnackbarFile, index: number) => {
                return (
                  <UploadCard
                    snackbarFile={file}
                    key={file.id}
                    progressVisibleOnCollapse={index === 0}
                    style={{
                      // In mockups, when stack is collapsed each next item is approximately 16px smaller than previous
                      width: `calc(100% - ${index * 16}px)`,
                    }}
                  />
                );
              })}
          </Stack>
        )}
      </Box>
      <DragOverlay zIndex={1501} modifiers={[restrictToHorizontalAxis]}>
        {draggedItem ? (
          <UploadCard
            key={draggedItem.id}
            snackbarFile={draggedItem}
            style={{
              width: "100%",
            }}
            dragX={dragX}
            isDraggingEnabled
            isOverlay
          />
        ) : null}
      </DragOverlay>
    </DndContext>
  );
}