import React, { useEffect, useState, useRef, useCallback } from "react"; // next import Image from "next/image"; import { useRouter } from "next/router"; // swr import useSWR from "swr"; // react-dropdown import { useDropzone } from "react-dropzone"; // headless ui import { Tab, Transition, Popover } from "@headlessui/react"; // services import fileService from "services/file.service"; // components import { Input, Spinner, PrimaryButton, SecondaryButton } from "components/ui"; // hooks import useWorkspaceDetails from "hooks/use-workspace-details"; import useOutsideClickDetector from "hooks/use-outside-click-detector"; const unsplashEnabled = process.env.NEXT_PUBLIC_UNSPLASH_ENABLED === "true" || process.env.NEXT_PUBLIC_UNSPLASH_ENABLED === "1"; const tabOptions = [ { key: "images", title: "Images", }, { key: "upload", title: "Upload", }, ]; type Props = { label: string | React.ReactNode; value: string | null; onChange: (data: string) => void; disabled?: boolean; }; export const ImagePickerPopover: React.FC = ({ label, value, onChange, disabled = false, }) => { const ref = useRef(null); const router = useRouter(); const { workspaceSlug } = router.query; const [image, setImage] = useState(null); const [isImageUploading, setIsImageUploading] = useState(false); const [isOpen, setIsOpen] = useState(false); const [searchParams, setSearchParams] = useState(""); const [formData, setFormData] = useState({ search: "", }); const { data: images } = useSWR(`UNSPLASH_IMAGES_${searchParams}`, () => fileService.getUnsplashImages(1, searchParams) ); const imagePickerRef = useRef(null); const { workspaceDetails } = useWorkspaceDetails(); const onDrop = useCallback((acceptedFiles: File[]) => { setImage(acceptedFiles[0]); }, []); const { getRootProps, getInputProps, isDragActive, fileRejections } = useDropzone({ onDrop, accept: { "image/*": [".png", ".jpg", ".jpeg", ".svg", ".webp"], }, maxSize: 5 * 1024 * 1024, }); 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 && workspaceDetails) fileService.deleteFile(workspaceDetails.id, oldValue); }) .catch((err) => { console.log(err); }); }; useEffect(() => { if (!images || value !== null) return; onChange(images[0].urls.regular); }, [value, onChange, images]); useOutsideClickDetector(imagePickerRef, () => setIsOpen(false)); if (!unsplashEnabled) return null; return ( setIsOpen((prev) => !prev)} disabled={disabled} > {label}
{tabOptions.map((tab) => ( `rounded py-1 px-4 text-center text-sm outline-none transition-colors ${ selected ? "bg-custom-primary text-white" : "text-custom-text-100" }` } > {tab.title} ))}
setFormData({ ...formData, search: e.target.value })} placeholder="Search for images" /> setSearchParams(formData.search)} size="sm"> Search
{images ? (
{images.map((image) => (
{image.alt_description} { setIsOpen(false); onChange(image.urls.regular); }} />
))}
) : (
)}
{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

{ setIsOpen(false); setImage(null); }} > Cancel {isImageUploading ? "Uploading..." : "Upload & Save"}
); };