import useCollectionStore from "@/store/collections";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import Link from "next/link";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
type Props = {
links: boolean;
};
const CollectionSelection = ({ links }: Props) => {
const { collections } = useCollectionStore();
const [active, setActive] = useState("");
const router = useRouter();
useEffect(() => {
setActive(router.asPath);
}, [router, collections]);
return (
{collections[0] ? (
collections
.sort((a, b) => a.name.localeCompare(b.name))
.filter((e) => e.parentId === null)
.map((e, i) => (
))
) : (
You Have No Collections...
)}
);
};
export default CollectionSelection;
const CollectionItem = ({
collection,
active,
collections,
}: {
collection: CollectionIncludingMembersAndLinkCount;
active: string;
collections: CollectionIncludingMembersAndLinkCount[];
}) => {
const hasChildren = collections.some((e) => e.parentId === collection.id);
const router = useRouter();
// Check if the current collection or any of its subcollections is active
const isActiveOrParentOfActive = React.useMemo(() => {
const isActive = active === `/collections/${collection.id}`;
if (isActive) return true;
const checkIfParentOfActive = (parentId: number): boolean => {
return collections.some((e) => {
if (e.id === parseInt(active.split("/collections/")[1])) {
if (e.parentId === parentId) return true;
if (e.parentId) return checkIfParentOfActive(e.parentId);
}
return false;
});
};
return checkIfParentOfActive(collection.id as number);
}, [active, collection.id, collections]);
const [isOpen, setIsOpen] = useState(isActiveOrParentOfActive);
useEffect(() => {
setIsOpen(isActiveOrParentOfActive);
}, [isActiveOrParentOfActive]);
return hasChildren ? (
<>
{collection.name}
{collection.isPublic ? (
) : undefined}
{collection._count?.links}
{isOpen && hasChildren && (
{collections
.filter((e) => e.parentId === collection.id)
.map((subCollection) => (
))}
)}
>
) : (
{collection.name}
{collection.isPublic ? (
) : undefined}
{collection._count?.links}
);
};