All files / src/components/ui/imageinput index.tsx

52.02% Statements 77/148
71.42% Branches 5/7
16.66% Functions 1/6
52.02% Lines 77/148

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 1491x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 22x 22x     22x 22x 51x 51x 51x 51x 51x 51x 22x 22x 22x     22x 22x 51x 51x 51x                                                                       51x 51x     51x 51x                   51x 51x                                 51x 51x           51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x  
import React, { useEffect, useRef, useState } from 'react';
 
import { IMAGE_CONFIG } from '@/lib/constants/image';
import { validateImage } from '@/lib/validateImage';
 
export type ImageRecord = Record<string, File | null>;
 
export interface ImageInputProps {
  value?: ImageRecord;
  children: (
    images: ImageRecord,
    onRemoveImageClick: (url: string) => void,
    onFileSelectClick: () => void,
  ) => React.ReactNode;
  onChange?: (images: ImageRecord) => void;
  maxFiles?: number;
  accept?: string;
  multiple?: boolean;
  mode?: 'replace' | 'append';
  initialImages?: string[];
}
 
export const ImageInput = ({
  value,
  children,
  onChange,
  maxFiles = 1,
  accept = IMAGE_CONFIG.allowedTypes.join(','),
  multiple = false,
  mode = 'replace',
  initialImages = [],
}: ImageInputProps) => {
  const [internalImages, setInternalImages] = useState<ImageRecord>(() => {
    // initialImages 처리
    return initialImages.reduce((acc, url) => {
      acc[url] = null;
      return acc;
    }, {} as ImageRecord);
  });
  const inputRef = useRef<HTMLInputElement>(null);
 
  const isControlled = value !== undefined && onChange !== undefined;
  const images = isControlled ? value : internalImages;
 
  useEffect(() => {
    return () => {
      Object.keys(images).forEach((url) => {
        if (url.startsWith('blob:')) {
          URL.revokeObjectURL(url);
        }
      });
    };
  }, [images]);
 
  const addImages = (files: File[]) => {
    const newImages: ImageRecord = {};

    // 선택된 파일들에 대해 blob URL 생성
    files.forEach((file) => {
      const url = URL.createObjectURL(file);
      newImages[url] = file;
    });

    // append 모드면 이미지 계속 쌓임
    // replace 모드면 이미지 교체
    const nextImages = mode === 'append' ? { ...images, ...newImages } : newImages;

    // 전체 이미지
    const entries = Object.entries(nextImages);

    // 최대 선택가능한 이미지 갯수만 적용
    const limitedEntries = entries.slice(0, maxFiles);

    // 최대 갯수 초과한 이미지들에 대해 revoke URL 적용
    const removedEntries = entries.slice(maxFiles);

    removedEntries.forEach(([url]) => {
      if (url.startsWith('blob:')) {
        URL.revokeObjectURL(url);
      }
    });

    // 최대 선택가능한 이미지 갯수에 대해서만 상태 업데이트
    const limitedImages = limitedEntries.slice(0, maxFiles).reduce((acc, [url, file]) => {
      acc[url] = file;
      return acc;
    }, {} as ImageRecord);

    updateImages(limitedImages);
  };
 
  const onFileSelectClick = () => {
    inputRef.current?.click();
  };
 
  const onRemoveImageClick = (url: string) => {
    if (url.startsWith('blob:')) {
      URL.revokeObjectURL(url);
    }

    const newImages = { ...images };
    delete newImages[url];

    updateImages(newImages);
  };
 
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);

    for (const file of files) {
      const validation = await validateImage(file);
      if (!validation.valid) {
        // toast.error(validation.error);
        alert(validation.error);
        e.target.value = '';
        return;
      }
    }

    // 검증통과 하면 이미지 추가
    addImages(files);
    e.target.value = '';
  };
 
  const updateImages = (newImages: ImageRecord) => {
    if (!isControlled) {
      setInternalImages(newImages);
    }
    onChange?.(newImages);
  };
 
  return (
    <>
      <input
        ref={inputRef}
        style={{ display: 'none' }}
        accept={accept}
        multiple={multiple}
        tabIndex={-1}
        type='file'
        onChange={handleFileChange}
      />
 
      {/* eslint-disable-next-line react-hooks/refs */}
      {children(images, onRemoveImageClick, onFileSelectClick)}
    </>
  );
};