import React, { useEffect, useState, useRef, useCallback } from "react"; import { observer } from "mobx-react-lite"; import Image from "next/image"; import { useRouter } from "next/router"; import { useDropzone } from "react-dropzone"; import { Control, Controller } from "react-hook-form"; import useSWR from "swr"; import { Tab, Popover } from "@headlessui/react"; // hooks import { Button, Input, Loader } from "@plane/ui"; import { MAX_FILE_SIZE } from "constants/common"; import { useApplication, useWorkspace } from "hooks/store"; import { useDropdownKeyDown } from "hooks/use-dropdown-key-down"; // services import useOutsideClickDetector from "hooks/use-outside-click-detector"; import { FileService } from "services/file.service"; // hooks // components // constants const tabOptions = [ { key: "unsplash", title: "Unsplash", }, { key: "images", title: "Images", }, { key: "upload", title: "Upload", }, ]; type Props = { label: string | React.ReactNode; value: string | null; control: Control; onChange: (data: string) => void; disabled?: boolean; tabIndex?: number; }; // services const fileService = new FileService(); export const ImagePickerPopover: React.FC = observer((props) => { const { label, value, control, onChange, disabled = false, tabIndex } = props; // states const [image, setImage] = useState(null); const [isImageUploading, setIsImageUploading] = useState(false); const [isOpen, setIsOpen] = useState(false); const [searchParams, setSearchParams] = useState(""); const [formData, setFormData] = useState({ search: "", }); // refs const ref = useRef(null); // router const router = useRouter(); const { workspaceSlug } = router.query; // store hooks const { config: { envConfig }, } = useApplication(); const { currentWorkspace } = useWorkspace(); const { data: unsplashImages, error: unsplashError } = useSWR( `UNSPLASH_IMAGES_${searchParams}`, () => fileService.getUnsplashImages(searchParams), { revalidateOnFocus: false, revalidateOnReconnect: false, } ); const { data: projectCoverImages } = useSWR(`PROJECT_COVER_IMAGES`, () => fileService.getProjectCoverImages(), { revalidateOnFocus: false, revalidateOnReconnect: false, }); const imagePickerRef = useRef(null); const onDrop = useCallback((acceptedFiles: File[]) => { setImage(acceptedFiles[0]); }, []); const { getRootProps, getInputProps, isDragActive, fileRejections } = useDropzone({ onDrop, accept: { "image/*": [".png", ".jpg", ".jpeg", ".svg", ".webp"], }, maxSize: envConfig?.file_size_limit ?? MAX_FILE_SIZE, }); const handleSubmit = async () => { setIsImageUploading(true); if (!image || !workspaceSlug) return; const formData = new FormData(); formData.append("asset", image); formData.append("attributes", JSON.stringify({})); fileService .uploadFile(workspaceSlug.toString(), formData) .then((res) => { const oldValue = value; const isUnsplashImage = oldValue?.split("/")[2] === "images.unsplash.com"; const imageUrl = res.asset; onChange(imageUrl); setIsImageUploading(false); setImage(null); setIsOpen(false); if (isUnsplashImage) return; if (oldValue && currentWorkspace) fileService.deleteFile(currentWorkspace.id, oldValue); }) .catch((err) => { console.error(err); }); }; useEffect(() => { if (!unsplashImages || value !== null) return; onChange(unsplashImages[0].urls.regular); }, [value, onChange, unsplashImages]); const handleClose = () => { if (isOpen) setIsOpen(false); }; const toggleDropdown = () => { setIsOpen((prevIsOpen) => !prevIsOpen); }; const handleKeyDown = useDropdownKeyDown(toggleDropdown, handleClose); const handleOnClick = (e: React.MouseEvent) => { e.stopPropagation(); e.preventDefault(); toggleDropdown(); }; useOutsideClickDetector(ref, handleClose); return ( {label} {isOpen && (
{tabOptions.map((tab) => { if (!unsplashImages && unsplashError && tab.key === "unsplash") return null; if (projectCoverImages && projectCoverImages.length === 0 && tab.key === "images") return null; return ( `rounded px-4 py-1 text-center text-sm outline-none transition-colors ${ selected ? "bg-custom-primary text-white" : "text-custom-text-100" }` } > {tab.title} ); })} {(unsplashImages || !unsplashError) && (
( setFormData({ ...formData, search: e.target.value })} ref={ref} placeholder="Search for images" className="w-full text-sm" /> )} />
{unsplashImages ? ( unsplashImages.length > 0 ? (
{unsplashImages.map((image) => (
{ setIsOpen(false); onChange(image.urls.regular); }} > {image.alt_description}
))}
) : (

No images found.

) ) : ( )}
)} {(!projectCoverImages || projectCoverImages.length !== 0) && ( {projectCoverImages ? ( projectCoverImages.length > 0 ? (
{projectCoverImages.map((image, index) => (
{ setIsOpen(false); onChange(image); }} > {`Default
))}
) : (

No images found.

) ) : ( )}
)}
{image !== null || (value && value !== "") ? ( <> image ) : (
{isDragActive ? "Drop image here to upload" : "Drag & drop image here"}
)}
{fileRejections.length > 0 && (

{fileRejections[0].errors[0].code === "file-too-large" ? "The image size cannot exceed 5 MB." : "Please upload a file in a valid format."}

)}

File formats supported- .jpeg, .jpg, .png, .webp, .svg

)}
); });