import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { styles } from "./styles"; import { Options } from "./types"; import CreatableSelect from "react-select/creatable"; import Select from "react-select"; import { useCollections } from "@/hooks/store/collections"; type Props = { onChange: any; showDefaultValue?: boolean; defaultValue?: | { label: string; value?: number; } | undefined; creatable?: boolean; }; export default function CollectionSelection({ onChange, defaultValue, showDefaultValue = true, creatable = true, }: Props) { const { data: collections = [] } = useCollections(); const router = useRouter(); const [options, setOptions] = useState([]); const collectionId = Number(router.query.id); const activeCollection = collections.find((e) => { return e.id === collectionId; }); if (activeCollection && !defaultValue) { defaultValue = { value: activeCollection?.id, label: activeCollection?.name, }; } useEffect(() => { const formatedCollections = collections.map((e) => { return { value: e.id, label: e.name, ownerId: e.ownerId, count: e._count, parentId: e.parentId, }; }); setOptions(formatedCollections); }, [collections]); const getParentNames = (parentId: number): string[] => { const parentNames = []; const parent = collections.find((e) => e.id === parentId); if (parent) { parentNames.push(parent.name); if (parent.parentId) { parentNames.push(...getParentNames(parent.parentId)); } } // Have the top level parent at beginning return parentNames.reverse(); }; const customOption = ({ data, innerProps }: any) => { return (
{data.label} {data.count?.links}
{getParentNames(data?.parentId).length > 0 ? ( <> {getParentNames(data.parentId).join(" > ")} {">"} {data.label} ) : ( data.label )}
); }; if (creatable) { return ( ); } else { return (