All files / src/shared/FilePreview GiveFilePreviewModal.tsx

84.69% Statements 83/98
72.04% Branches 67/93
85.18% Functions 23/27
87.64% Lines 78/89

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 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526                                                                  4x             4x                                 4x 4x 4x 4x 4x   4x             4x                     51x 51x   51x 51x 51x 51x         51x 51x 51x 51x       51x 51x                                                             51x             51x                     51x   51x 51x                                             51x 2x 2x     51x 3x 1x 1x 1x   2x 2x                 51x 2x 2x       2x         2x       51x 51x 22x 22x     19x     19x     19x     51x 51x 68x 68x         51x                                               1x                             51x               2x           2x             2x               3x                   51x           1x                 1x               227x   227x                               51x                                                                                     61x                                                 35x                 4x 35x                     4x 35x                   4x                         4x                 4x 39x                   31x                                     4x                 155x                      
import { Box, Divider, Stack } from "@mui/material";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { styled, useAppTheme } from "@theme/v2/Provider";
import {
  ArrowLeftIcon,
  ArrowRightIcon,
  CircleIcon,
  DownloadSimpleIcon,
  MagnifyingGlassIcon,
  MinusIcon,
  PlusIcon,
  TrashIcon,
  XIcon,
} from "@phosphor-icons/react";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import useImagePreviewer from "@common/FilePreview/hooks/useImagePreviewer";
import { TDocument } from "@common/FilePreview/types";
import { FILE_PREVIEW_MODAL_V2 } from "modals/modal_names";
import { CustomTheme } from "@theme/v2/palette.interface";
import useDocumentListV2 from "./hooks/useDocumentListV2";
import {
  deleteDocument,
  downloadBase64Document,
  downloadDocument,
} from "@hooks/common/documents/utils";
import { useQueryClient } from "react-query";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "features/Merchants/MerchantSidePanel/constants";
import usePdfPreviewerV2 from "./hooks/usePdfPreviewerV2";
import GiveText from "@shared/Text/GiveText";
import { useTransition, animated } from "@react-spring/web";
import { useState, useMemo, useRef, useEffect } from "react";
 
const transitionConfig = {
  mass: 1,
  tension: 210,
  friction: 20,
  clamp: true,
  precision: 0.01,
};
const numDotsToShow = 5;
 
type Props = {
  file: TDocument;
  documentList: TDocument[];
  isDeleteHidden?: boolean;
  entityId: number;
  handleLocalDelete?: (
    index: number,
    name?: string,
    onDeleteCb?: () => void,
  ) => void;
  isBase64?: boolean;
  isMedia?: boolean;
  isPdfAsImage?: boolean;
};
 
const MEDIA_LIBRARY_ACTION_HEIGHT_PX = 64;
const MEDIA_LIBRARY_ACTION_HEIGHT = `${MEDIA_LIBRARY_ACTION_HEIGHT_PX}px`;
const MEDIA_LIBRARY_FOOTER_HEIGHT_PX = 74;
const OUTSIDE_MODAL_VERTICAL_SPACE_PX = 50 * 2;
const ACTION_BORDER_FIX_PX = 0.8;
 
const PREVIEW_MODAL_CONTENT_HEIGHT = `calc(
  100vh
  - ${OUTSIDE_MODAL_VERTICAL_SPACE_PX}px
  - ${MEDIA_LIBRARY_ACTION_HEIGHT_PX + ACTION_BORDER_FIX_PX}px
  - ${MEDIA_LIBRARY_FOOTER_HEIGHT_PX}px
)`;
 
const GiveFilePreviewModal = NiceModal.create(
  ({
    file,
    documentList,
    isDeleteHidden = false,
    entityId,
    handleLocalDelete,
    isBase64 = false,
    isMedia = false,
    isPdfAsImage = false,
  }: Props) => {
    const queryClient = useQueryClient();
    const theme = useAppTheme();
    const [currentDocumentList, setCurrentDocumentList] =
      useState(documentList);
    const [currentFileData, setCurrentFileData] = useState(file);
    const { visible, remove: removeModal } = useModal(FILE_PREVIEW_MODAL_V2);
    const { currentFile, currentIndex, navigation } = useDocumentListV2(
      currentDocumentList, // ← Use state instead of prop
      currentFileData, // ← Use state instead of prop
      removeModal,
    );
    const { name } = currentFile || {};
    const { changeFile, showNext, showPrev } = navigation || {};
    const hasMultipleFiles = documentList?.length > 1;
    const isPdf = ["pdf", "application/pdf", ".pdf"].includes(
      currentFile?.type || "",
    );
 
    const isLocalFile = currentFile?.isUploaded === false;
    const handleRefetchFiles = async () => {
      await queryClient.refetchQueries([
        MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_FILES,
        entityId,
      ]);
 
      const freshList = queryClient.getQueryData<TDocument[]>([
        MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_FILES,
        entityId,
      ]);
 
      // Safely check if result is an array then Update the local state with fresh data
      if (Array.isArray(freshList)) {
        setCurrentDocumentList(freshList);
 
        const updatedCurrentFile = freshList.find(
          (doc: TDocument) => doc.id === currentFileData.id,
        );
 
        if (updatedCurrentFile) {
          setCurrentFileData(updatedCurrentFile);
        }
      }
    };
 
    const {
      Previewer,
      onZoom: onPdfZoom,
      toolbar,
      toggleSearch,
      isSearchActive,
    } = usePdfPreviewerV2({
      file: currentFile as TDocument,
      customDocumentWrapperStyles: pdfPreviewStyles,
      handleRefetchFiles,
    });
 
    const { Previewer: ImagePreviewer, onZoom: onImageZoom } =
      useImagePreviewer({
        file: currentFile as TDocument,
        customImageStyle: {
          maxWidth: isPdfAsImage ? "60%" : "100%",
          maxHeight: "100%",
          display: "block",
          margin: "auto",
          transformOrigin: "center center",
        },
      });
 
    const previewer = isPdf ? Previewer : ImagePreviewer;
 
    const [direction, setDirection] = useState("next");
    const transitions = useTransition(previewer, {
      key: currentIndex,
      from: {
        opacity: 0.8,
        transform: `translateX(${direction === "next" ? "100%" : "-100%"})`,
        width: "100%",
        height: isPdfAsImage ? "auto" : "100%", // important
      },
      enter: {
        opacity: 1,
        transform: "translateX(0%)",
        width: "100%",
        height: isPdfAsImage ? "auto" : "100%",
      },
      leave: {
        opacity: 0.8,
        transform: `translateX(${direction === "next" ? "-100%" : "100%"})`,
        width: "100%",
        height: isPdfAsImage ? "auto" : "100%",
      },
      config: transitionConfig,
    });
 
    const handleSlide = (dir: "next" | "prev") => {
      setDirection(dir);
      changeFile(dir);
    };
 
    const handleDeleteDocument = (file: TDocument | null) => {
      if (handleLocalDelete && file) {
        handleLocalDelete(file.id, file?.name, () => handleSlide("next"));
        Eif (!hasMultipleFiles) removeModal();
        return;
      }
      Eif (file && entityId) {
        deleteDocument(entityId, { id: file.id, fileName: file.name }, () => {
          queryClient.invalidateQueries(
            MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_FILES,
          );
          if (!hasMultipleFiles) removeModal();
        });
      }
    };
 
    const handleDownloadDocument = (file: TDocument | null) => {
      Eif (file) {
        const payload = {
          fileName: file.name,
          fileURL: file.URL,
        };
        Iif (isBase64) {
          downloadBase64Document({
            ...payload,
            label: file?.type,
          });
        } else downloadDocument(payload, false, true);
      }
    };
 
    const totalDocs = documentList.length;
    const minIndex = useMemo(() => {
      const numVisible = Math.min(numDotsToShow, totalDocs);
      if (totalDocs <= numVisible) return 0;
 
      // If we are near the end, lock the window so the last visible dot is the last doc
      Iif (currentIndex >= totalDocs - 1) return totalDocs - numVisible;
 
      // If we are at the second-last of the visible window, shift window forward
      Iif (currentIndex >= numVisible - 1) return currentIndex - numVisible + 2;
 
      // Otherwise, start from 0
      return 0;
    }, [currentIndex, totalDocs, numDotsToShow]);
 
    const numVisible = Math.min(numDotsToShow, totalDocs);
    const visibleDots = useMemo(() => {
      return Array.from({ length: numVisible }, (_, i) => minIndex + i).filter(
        (i) => i < totalDocs,
      );
    }, [minIndex, totalDocs, numVisible]);
 
    const CustomHeader = (
      <Stack
        direction="row"
        gap="16px"
        alignItems="center"
        padding="16px 20px"
        sx={{
          justifyContent: "space-between",
          borderBottom: `1px solid ${theme.palette.border?.primary}`,
          ...(isMedia && { height: MEDIA_LIBRARY_ACTION_HEIGHT }),
        }}
      >
        <GiveText
          variant="bodyS"
          color="secondary"
          flex={1}
          data-testid="preview-title"
        >
          {name}
        </GiveText>
        <Stack direction="row" gap="12px" alignItems="center">
          {isPdf && (
            <GiveIconButton
              bgColor="solidWhite"
              Icon={MagnifyingGlassIcon}
              onClick={() => toggleSearch?.(!isSearchActive)}
              data-testid="search-btn"
            />
          )}
          <GiveIconButton
            bgColor="solidWhite"
            Icon={XIcon}
            onClick={removeModal}
            data-testid="close-preview-button"
          />
        </Stack>
      </Stack>
    );
 
    const CustomFooter = (
      <Stack
        direction="row"
        gap="16px"
        alignItems="center"
        justifyContent="center"
      >
        <GiveIconButton
          Icon={MinusIcon}
          onClick={() => (isPdf ? onPdfZoom("out") : onImageZoom("out"))}
          bgColor="solidWhite"
          data-testid="zoom-out-btn"
        />
        <GiveIconButton
          Icon={PlusIcon}
          onClick={() => (isPdf ? onPdfZoom("in") : onImageZoom("in"))}
          bgColor="solidWhite"
          data-testid="zoom-in-btn"
        />
        <Divider orientation="vertical" flexItem />
        <GiveIconButton
          Icon={DownloadSimpleIcon}
          onClick={() => handleDownloadDocument(currentFile)}
          bgColor="solidWhite"
          data-testid="download-btn"
        />
        {(!isDeleteHidden || isLocalFile) && (
          <GiveIconButton
            Icon={TrashIcon}
            color={theme.palette.primitive?.error[50]}
            onClick={() => handleDeleteDocument(currentFile)}
            bgColor="solidWhite"
            data-testid="delete-btn"
          />
        )}
        {isPdf && toolbar.primary.content}
      </Stack>
    );
 
    const ControlComponents = (
      <>
        {showPrev && (
          <StyledGiveIconButton
            Icon={ArrowLeftIcon}
            bgColor="solidWhite"
            left="16px"
            onClick={() => handleSlide("prev")}
            data-testid="arrow-button-left"
          />
        )}
        {showNext && (
          <StyledGiveIconButton
            Icon={ArrowRightIcon}
            bgColor="solidWhite"
            right="16px"
            onClick={() => handleSlide("next")}
            data-testid="arrow-button-right"
          />
        )}
 
        <NavContainer data-testid="nav-dots">
          {visibleDots.map((index, i, arr) => {
            const isEdge =
              (i === 0 && minIndex > 0) ||
              (i === arr.length - 1 && minIndex + arr.length < totalDocs);
            return (
              <NavDot
                theme={theme}
                key={index}
                selected={index === currentIndex}
                weight="fill"
                isEdge={isEdge}
                data-testid="nav-dot"
                data-index={index}
              />
            );
          })}
        </NavContainer>
      </>
    );
 
    return (
      <GiveBaseModal
        open={visible}
        title={name}
        width="1040px"
        height="100%"
        onClose={removeModal}
        closeIconProps={{
          ["data-testid" as string]: "close-preview-button",
          bgColor: "solidWhite",
        }}
        customContentPadding="0"
        sx={{
          zIndex: 10000,
          "& .MuiDialog-paper": {
            position: "relative",
            ...(isMedia && {
              my: "90px",
              height: "100vh",
              "& .MuiDialogActions-root": {
                height: MEDIA_LIBRARY_ACTION_HEIGHT,
              },
            }),
          },
        }}
        customHeader={CustomHeader}
        customFooter={CustomFooter}
        customDialogStyle={customDialogStyles}
      >
        <Container data-testid="file-preview-modal">
          <FilePreviewWrapper
            data-testid="previewer"
            sx={{
              maxHeight: PREVIEW_MODAL_CONTENT_HEIGHT,
              overflowY: "auto",
              overflowX: "hidden",
              display: "flex",
              justifyContent: "center",
              alignItems: "flex-start", // top align tall images
            }}
          >
            <AnimatedWrapper>
              {transitions((style, item) => (
                <animated.div
                  style={{
                    ...(style as any),
                    display: "flex",
                    justifyContent: "center",
                    alignItems: isPdf ? "stretch" : "center",
                    width: "100%",
                    height: "100%",
                    overflow: isPdf ? "hidden" : "visible",
                  }}
                >
                  {item}
                </animated.div>
              ))}
            </AnimatedWrapper>
          </FilePreviewWrapper>
        </Container>
        {hasMultipleFiles && ControlComponents}
      </GiveBaseModal>
    );
  },
);
 
export default GiveFilePreviewModal;
 
const Container = styled(Box)(() => ({
  position: "relative",
  width: "100%",
  height: "100%",
  display: "flex",
  flexDirection: "column",
  paddingBottom: "74px", // Account for fixed footer height
}));
 
const FilePreviewWrapper = styled(Box)<{ isPdfAsImage?: boolean }>(
  ({ isPdfAsImage }) => ({
    width: "100%",
    margin: "0 auto",
    overflowY: isPdfAsImage ? "auto" : "hidden", // scroll for tall images
    overflowX: "hidden",
    flex: isPdfAsImage ? "0 0 auto" : "1 1 auto", // allow content to grow
    display: "flex",
    justifyContent: "center",
  }),
);
 
const AnimatedWrapper = styled("div")<{ isPdfAsImage?: boolean }>(
  ({ isPdfAsImage }) => ({
    position: "relative",
    width: "100%",
    height: isPdfAsImage ? "auto" : "100%",
    display: "flex",
    alignItems: isPdfAsImage ? "flex-start" : "center",
    justifyContent: "center",
    overflow: isPdfAsImage ? "visible" : "hidden",
  }),
);
const pdfPreviewStyles = {
  width: "100%",
  height: "100%",
  display: "flex",
  flexDirection: "column",
  "& .react-pdf__Page__canvas": {
    margin: "0 auto",
  },
  "& .react-pdf__Page:first-of-type": {
    marginTop: "0px",
  },
};
 
const customDialogStyles = {
  "& .MuiDialog-paper": {
    "& .MuiDialogContent-root": {
      height: "60vh",
      padding: "0px !important",
    },
  },
};
 
const StyledGiveIconButton = styled(GiveIconButton)(
  ({ right, left }: { right?: string; left?: string }) => ({
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    zIndex: 10,
    right: right,
    left: left,
  }),
);
 
const NavContainer = styled(Stack)(({ theme }) => ({
  flexDirection: "row",
  gap: "5px",
  alignItems: "center",
  position: "absolute",
  bottom: "88px",
  left: "50%",
  transform: "translateX(-50%)",
  zIndex: 1,
  backgroundColor: theme.palette.surface?.["primary-transparent"],
  borderRadius: "30px",
  padding: "8px",
  backdropFilter: "blur(15px)",
  WebkitBackdropFilter: "blur(15px)",
  flexWrap: "nowrap",
  width: "auto",
  justifyContent: "center",
}));
 
const NavDot = styled(CircleIcon)(
  ({
    theme,
    selected,
    isEdge,
  }: {
    theme: CustomTheme;
    selected: boolean;
    isEdge?: boolean;
  }) => ({
    width: "8px",
    height: "8px",
    color: theme.palette.background.dimmedWhite,
    opacity: selected ? 1 : 0.5,
    padding: 0,
    borderRadius: "50%",
    transform: isEdge ? "scale(0.6)" : "scale(1)",
    transition: "transform 0.3s ease, opacity 0.3s ease",
  }),
);