import React, { useEffect, useState } from "react"; import CollectionSelection from "@/components/InputSelect/CollectionSelection"; import TagSelection from "@/components/InputSelect/TagSelection"; import TextInput from "@/components/TextInput"; import unescapeString from "@/lib/client/unescapeString"; import { useRouter } from "next/router"; import Modal from "../Modal"; import { useTranslation } from "next-i18next"; import { useCollections } from "@/hooks/store/collections"; import { useAddLink } from "@/hooks/store/links"; import toast from "react-hot-toast"; import { PostLinkSchemaType } from "@/lib/shared/schemaValidation"; type Props = { onClose: Function; }; export default function NewLinkModal({ onClose }: Props) { const { t } = useTranslation(); const initial = { name: "", url: "", description: "", type: "url", tags: [], collection: { id: undefined, name: "", }, } as PostLinkSchemaType; const [link, setLink] = useState(initial); const addLink = useAddLink(); const [submitLoader, setSubmitLoader] = useState(false); const [optionsExpanded, setOptionsExpanded] = useState(false); const router = useRouter(); const { data: collections = [] } = useCollections(); const setCollection = (e: any) => { if (e?.__isNew__) e.value = undefined; setLink({ ...link, collection: { id: e?.value, name: e?.label }, }); }; const setTags = (e: any) => { const tagNames = e.map((e: any) => ({ name: e.label })); setLink({ ...link, tags: tagNames }); }; useEffect(() => { if (router.pathname.startsWith("/collections/") && router.query.id) { const currentCollection = collections.find( (e) => e.id == Number(router.query.id) ); if (currentCollection && currentCollection.ownerId) setLink({ ...initial, collection: { id: currentCollection.id, name: currentCollection.name, }, }); } else setLink({ ...initial, collection: { name: "Unorganized" }, }); }, []); const submit = async () => { if (!submitLoader) { setSubmitLoader(true); const load = toast.loading(t("creating_link")); await addLink.mutateAsync(link, { onSettled: (data, error) => { toast.dismiss(load); if (error) { toast.error(t(error.message)); } else { onClose(); toast.success(t("link_created")); } }, }); setSubmitLoader(false); } }; return (

{t("create_new_link")}

{t("link")}

setLink({ ...link, url: e.target.value })} placeholder={t("link_url_placeholder")} className="bg-base-200" />

{t("collection")}

{link.collection?.name && ( )}
{optionsExpanded && (

{t("name")}

setLink({ ...link, name: e.target.value })} placeholder={t("link_name_placeholder")} className="bg-base-200" />

{t("tags")}

({ label: e.name, value: e.id, }))} />

{t("description")}