improved typesafety

This commit is contained in:
Daniel 2023-05-27 07:41:29 +03:30
parent 7f3d93517d
commit f26ffa7323
12 changed files with 321 additions and 535 deletions

View File

@ -11,7 +11,7 @@ import {
faEllipsis, faEllipsis,
} from "@fortawesome/free-solid-svg-icons"; } from "@fortawesome/free-solid-svg-icons";
import Link from "next/link"; import Link from "next/link";
import { ExtendedCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import ImageWithFallback from "./ImageWithFallback"; import ImageWithFallback from "./ImageWithFallback";
import Dropdown from "./Dropdown"; import Dropdown from "./Dropdown";
@ -20,9 +20,15 @@ import Modal from "@/components/Modal";
import EditCollection from "@/components/Modal/EditCollection"; import EditCollection from "@/components/Modal/EditCollection";
import DeleteCollection from "@/components/Modal/DeleteCollection"; import DeleteCollection from "@/components/Modal/DeleteCollection";
export default function ({ collection }: { collection: ExtendedCollection }) { export default function ({
collection,
}: {
collection: CollectionIncludingMembers;
}) {
const { links } = useLinkStore(); const { links } = useLinkStore();
const formattedDate = new Date(collection.createdAt).toLocaleString("en-US", { const formattedDate = new Date(
collection.createdAt as unknown as string
).toLocaleString("en-US", {
year: "numeric", year: "numeric",
month: "short", month: "short",
day: "numeric", day: "numeric",
@ -61,7 +67,7 @@ export default function ({ collection }: { collection: ExtendedCollection }) {
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<div className="text-sky-400 flex items-center w-full"> <div className="text-sky-400 flex items-center w-full">
{collection.members {collection.members
.sort((a, b) => a.userId - b.userId) .sort((a, b) => (a.user.id as number) - (b.user.id as number))
.map((e, i) => { .map((e, i) => {
return ( return (
<ImageWithFallback <ImageWithFallback
@ -125,7 +131,7 @@ export default function ({ collection }: { collection: ExtendedCollection }) {
<Modal toggleModal={toggleEditCollectionModal}> <Modal toggleModal={toggleEditCollectionModal}>
<EditCollection <EditCollection
toggleCollectionModal={toggleEditCollectionModal} toggleCollectionModal={toggleEditCollectionModal}
collection={collection} activeCollection={collection}
/> />
</Modal> </Modal>
) : null} ) : null}

View File

@ -6,16 +6,15 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faChevronRight } from "@fortawesome/free-solid-svg-icons"; import { faChevronRight } from "@fortawesome/free-solid-svg-icons";
import Link from "next/link"; import Link from "next/link";
import { ExtendedCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
export default function ({ collection }: { collection: ExtendedCollection }) { export default function ({
collection,
}: {
collection: CollectionIncludingMembers;
}) {
const { links } = useLinkStore(); const { links } = useLinkStore();
const formattedDate = new Date(collection.createdAt).toLocaleString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
});
return ( return (
<Link <Link
@ -51,7 +50,6 @@ export default function ({ collection }: { collection: ExtendedCollection }) {
})} })}
</div> </div>
<div className="flex gap-2 items-baseline"> <div className="flex gap-2 items-baseline">
<p className="text-sky-300 font-bold text-sm">{formattedDate}</p>
<p className="text-sky-500 font-bold"> <p className="text-sky-500 font-bold">
{links.filter((e) => e.collectionId === collection.id).length} Links {links.filter((e) => e.collectionId === collection.id).length} Links
</p> </p>

View File

@ -3,7 +3,7 @@
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. // You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { import {
faClose, faClose,
@ -12,7 +12,7 @@ import {
faUserPlus, faUserPlus,
} from "@fortawesome/free-solid-svg-icons"; } from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections"; import useCollectionStore from "@/store/collections";
import { ExtendedCollection, NewCollection } from "@/types/global"; import { CollectionIncludingMembers, Member } from "@/types/global";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import RequiredBadge from "../RequiredBadge"; import RequiredBadge from "../RequiredBadge";
import addMemberToCollection from "@/lib/client/addMemberToCollection"; import addMemberToCollection from "@/lib/client/addMemberToCollection";
@ -23,33 +23,52 @@ type Props = {
}; };
export default function AddCollection({ toggleCollectionModal }: Props) { export default function AddCollection({ toggleCollectionModal }: Props) {
const [newCollection, setNewCollection] = useState<NewCollection>({ const session = useSession();
const [collection, setCollection] = useState<CollectionIncludingMembers>({
name: "", name: "",
description: "", description: "",
ownerId: session.data?.user.id as number,
members: [], members: [],
}); });
const [memberEmail, setMemberEmail] = useState(""); const [member, setMember] = useState<Member>({
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: "",
email: "",
},
});
const { addCollection } = useCollectionStore(); const { addCollection } = useCollectionStore();
const session = useSession();
const submit = async () => { const submit = async () => {
console.log(newCollection); if (!collection) return null;
const response = await addCollection(newCollection as NewCollection); const response = await addCollection(collection);
if (response) toggleCollectionModal(); if (response) toggleCollectionModal();
}; };
const setMemberState = (newMember: any) => { const setMemberState = (newMember: Member) => {
setNewCollection({ if (!collection) return null;
...newCollection,
members: [...newCollection.members, newMember], setCollection({
...collection,
members: [...collection.members, newMember],
}); });
setMemberEmail(""); setMember({
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: "",
email: "",
},
});
}; };
return ( return (
@ -63,9 +82,9 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
<RequiredBadge /> <RequiredBadge />
</p> </p>
<input <input
value={newCollection.name} value={collection.name}
onChange={(e) => onChange={(e) =>
setNewCollection({ ...newCollection, name: e.target.value }) setCollection({ ...collection, name: e.target.value })
} }
type="text" type="text"
placeholder="e.g. Example Collection" placeholder="e.g. Example Collection"
@ -76,10 +95,10 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
<div className="w-full"> <div className="w-full">
<p className="text-sm font-bold text-sky-300 mb-2">Description</p> <p className="text-sm font-bold text-sky-300 mb-2">Description</p>
<input <input
value={newCollection.description} value={collection.description}
onChange={(e) => onChange={(e) =>
setNewCollection({ setCollection({
...newCollection, ...collection,
description: e.target.value, description: e.target.value,
}) })
} }
@ -95,9 +114,12 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
<p className="text-sm font-bold text-sky-300">Members</p> <p className="text-sm font-bold text-sky-300">Members</p>
<div className="relative"> <div className="relative">
<input <input
value={memberEmail} value={member.user.email}
onChange={(e) => { onChange={(e) => {
setMemberEmail(e.target.value); setMember({
...member,
user: { ...member.user, email: e.target.value },
});
}} }}
type="text" type="text"
placeholder="Email" placeholder="Email"
@ -108,10 +130,9 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
onClick={() => onClick={() =>
addMemberToCollection( addMemberToCollection(
session.data?.user.email as string, session.data?.user.email as string,
memberEmail, member.user.email as string,
newCollection as unknown as ExtendedCollection, collection,
setMemberState, setMemberState
"ADD"
) )
} }
className="absolute flex items-center justify-center right-2 top-2 bottom-2 bg-sky-500 hover:bg-sky-400 duration-100 text-white w-9 rounded-md cursor-pointer" className="absolute flex items-center justify-center right-2 top-2 bottom-2 bg-sky-500 hover:bg-sky-400 duration-100 text-white w-9 rounded-md cursor-pointer"
@ -120,14 +141,14 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
</div> </div>
</div> </div>
{newCollection.members[0] ? ( {collection?.members[0]?.user ? (
<>
<p className="text-center text-gray-500 text-xs sm:text-sm"> <p className="text-center text-gray-500 text-xs sm:text-sm">
(All Members have <b>Read</b> access to this collection.) (All Members have <b>Read</b> access to this collection.)
</p> </p>
) : null}
<div className="h-36 overflow-auto flex flex-col gap-3 rounded-md shadow-inner"> <div className="h-36 overflow-auto flex flex-col gap-3 rounded-md shadow-inner">
{newCollection.members.map((e, i) => { {collection.members.map((e, i) => {
return ( return (
<div <div
key={i} key={i}
@ -138,13 +159,13 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
className="absolute right-2 top-2 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer" className="absolute right-2 top-2 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer"
title="Remove Member" title="Remove Member"
onClick={() => { onClick={() => {
const updatedMembers = newCollection.members.filter( const updatedMembers = collection.members.filter(
(member) => { (member) => {
return member.email !== e.email; return member.user.email !== e.user.email;
} }
); );
setNewCollection({ setCollection({
...newCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -152,8 +173,7 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<ImageWithFallback <ImageWithFallback
key={i} key={i}
// @ts-ignore src={`/api/avatar/${e.userId}`}
src={`/api/avatar/${e.id}`}
className="h-10 w-10 shadow rounded-full border-[3px] border-sky-100" className="h-10 w-10 shadow rounded-full border-[3px] border-sky-100"
> >
<div className="text-white bg-sky-500 h-10 w-10 shadow rounded-full border-[3px] border-sky-100 flex items-center justify-center"> <div className="text-white bg-sky-500 h-10 w-10 shadow rounded-full border-[3px] border-sky-100 flex items-center justify-center">
@ -161,13 +181,17 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
</div> </div>
</ImageWithFallback> </ImageWithFallback>
<div> <div>
<p className="text-sm font-bold text-sky-500">{e.name}</p> <p className="text-sm font-bold text-sky-500">
<p className="text-sky-900">{e.email}</p> {e.user.name}
</p>
<p className="text-sky-900">{e.user.email}</p>
</div> </div>
</div> </div>
<div className="flex sm:block items-center gap-5"> <div className="flex sm:block items-center gap-5">
<div> <div>
<p className="font-bold text-sm text-gray-500">Permissions</p> <p className="font-bold text-sm text-gray-500">
Permissions
</p>
<p className="text-xs text-gray-400 mb-2"> <p className="text-xs text-gray-400 mb-2">
(Click to toggle.) (Click to toggle.)
</p> </p>
@ -181,16 +205,16 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
className="peer sr-only" className="peer sr-only"
checked={e.canCreate} checked={e.canCreate}
onChange={() => { onChange={() => {
const updatedMembers = newCollection.members.map( const updatedMembers = collection.members.map(
(member) => { (member) => {
if (member.email === e.email) { if (member.user.email === e.user.email) {
return { ...member, canCreate: !e.canCreate }; return { ...member, canCreate: !e.canCreate };
} }
return member; return member;
} }
); );
setNewCollection({ setCollection({
...newCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -207,16 +231,16 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
className="peer sr-only" className="peer sr-only"
checked={e.canUpdate} checked={e.canUpdate}
onChange={() => { onChange={() => {
const updatedMembers = newCollection.members.map( const updatedMembers = collection.members.map(
(member) => { (member) => {
if (member.email === e.email) { if (member.user.email === e.user.email) {
return { ...member, canUpdate: !e.canUpdate }; return { ...member, canUpdate: !e.canUpdate };
} }
return member; return member;
} }
); );
setNewCollection({ setCollection({
...newCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -233,16 +257,16 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
className="peer sr-only" className="peer sr-only"
checked={e.canDelete} checked={e.canDelete}
onChange={() => { onChange={() => {
const updatedMembers = newCollection.members.map( const updatedMembers = collection.members.map(
(member) => { (member) => {
if (member.email === e.email) { if (member.user.email === e.user.email) {
return { ...member, canDelete: !e.canDelete }; return { ...member, canDelete: !e.canDelete };
} }
return member; return member;
} }
); );
setNewCollection({ setCollection({
...newCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -257,6 +281,8 @@ export default function AddCollection({ toggleCollectionModal }: Props) {
); );
})} })}
</div> </div>
</>
) : null}
<div <div
className="mx-auto mt-2 bg-sky-500 text-white flex items-center gap-2 py-2 px-5 rounded-md select-none font-bold cursor-pointer duration-100 hover:bg-sky-400" className="mx-auto mt-2 bg-sky-500 text-white flex items-center gap-2 py-2 px-5 rounded-md select-none font-bold cursor-pointer duration-100 hover:bg-sky-400"

View File

@ -6,13 +6,13 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlus, faTrashCan } from "@fortawesome/free-solid-svg-icons"; import { faPlus, faTrashCan } from "@fortawesome/free-solid-svg-icons";
import { ExtendedCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import useCollectionStore from "@/store/collections"; import useCollectionStore from "@/store/collections";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
type Props = { type Props = {
toggleDeleteCollectionModal: Function; toggleDeleteCollectionModal: Function;
collection: ExtendedCollection; collection: CollectionIncludingMembers;
}; };
export default function AddCollection({ export default function AddCollection({
@ -26,6 +26,8 @@ export default function AddCollection({
const router = useRouter(); const router = useRouter();
const submit = async () => { const submit = async () => {
if (!collection.id) return null;
const response = await removeCollection(collection.id); const response = await removeCollection(collection.id);
if (response) { if (response) {
toggleDeleteCollectionModal(); toggleDeleteCollectionModal();

View File

@ -8,13 +8,12 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { import {
faClose, faClose,
faPenToSquare, faPenToSquare,
faPlus,
faTrashCan, faTrashCan,
faUser, faUser,
faUserPlus, faUserPlus,
} from "@fortawesome/free-solid-svg-icons"; } from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections"; import useCollectionStore from "@/store/collections";
import { ExtendedCollection } from "@/types/global"; import { CollectionIncludingMembers, Member } from "@/types/global";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import DeleteCollection from "@/components/Modal/DeleteCollection"; import DeleteCollection from "@/components/Modal/DeleteCollection";
@ -25,17 +24,25 @@ import Checkbox from "../Checkbox";
type Props = { type Props = {
toggleCollectionModal: Function; toggleCollectionModal: Function;
collection: ExtendedCollection; activeCollection: CollectionIncludingMembers;
}; };
export default function EditCollection({ export default function EditCollection({
toggleCollectionModal, toggleCollectionModal,
collection, activeCollection,
}: Props) { }: Props) {
const [activeCollection, setActiveCollection] = const [collection, setCollection] =
useState<ExtendedCollection>(collection); useState<CollectionIncludingMembers>(activeCollection);
const [memberEmail, setMemberEmail] = useState(""); const [member, setMember] = useState<Member>({
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: "",
email: "",
},
});
const { updateCollection } = useCollectionStore(); const { updateCollection } = useCollectionStore();
@ -47,21 +54,29 @@ export default function EditCollection({
const session = useSession(); const session = useSession();
const setMemberState = (newMember: any) => { const setMemberState = (newMember: Member) => {
setActiveCollection({ if (!collection) return null;
...activeCollection,
members: [...activeCollection.members, newMember], setCollection({
...collection,
members: [...collection.members, newMember],
}); });
setMemberEmail(""); setMember({
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: "",
email: "",
},
});
}; };
const submit = async () => { const submit = async () => {
console.log(activeCollection); if (!collection) return null;
const response = await updateCollection( const response = await updateCollection(collection);
activeCollection as ExtendedCollection
);
if (response) toggleCollectionModal(); if (response) toggleCollectionModal();
}; };
@ -77,9 +92,9 @@ export default function EditCollection({
<RequiredBadge /> <RequiredBadge />
</p> </p>
<input <input
value={activeCollection.name} value={collection.name}
onChange={(e) => onChange={(e) =>
setActiveCollection({ ...activeCollection, name: e.target.value }) setCollection({ ...collection, name: e.target.value })
} }
type="text" type="text"
placeholder="e.g. Example Collection" placeholder="e.g. Example Collection"
@ -90,10 +105,10 @@ export default function EditCollection({
<div className="w-full"> <div className="w-full">
<p className="text-sm font-bold text-sky-300 mb-2">Description</p> <p className="text-sm font-bold text-sky-300 mb-2">Description</p>
<input <input
value={activeCollection.description} value={collection.description}
onChange={(e) => onChange={(e) =>
setActiveCollection({ setCollection({
...activeCollection, ...collection,
description: e.target.value, description: e.target.value,
}) })
} }
@ -127,9 +142,12 @@ export default function EditCollection({
<div className="relative"> <div className="relative">
<input <input
value={memberEmail} value={member.user.email}
onChange={(e) => { onChange={(e) => {
setMemberEmail(e.target.value); setMember({
...member,
user: { ...member.user, email: e.target.value },
});
}} }}
type="text" type="text"
placeholder="Email" placeholder="Email"
@ -140,10 +158,9 @@ export default function EditCollection({
onClick={() => onClick={() =>
addMemberToCollection( addMemberToCollection(
session.data?.user.email as string, session.data?.user.email as string,
memberEmail, member.user.email,
activeCollection, collection,
setMemberState, setMemberState
"UPDATE"
) )
} }
className="absolute flex items-center justify-center right-2 top-2 bottom-2 bg-sky-500 hover:bg-sky-400 duration-100 text-white w-9 rounded-md cursor-pointer" className="absolute flex items-center justify-center right-2 top-2 bottom-2 bg-sky-500 hover:bg-sky-400 duration-100 text-white w-9 rounded-md cursor-pointer"
@ -151,14 +168,14 @@ export default function EditCollection({
<FontAwesomeIcon icon={faUserPlus} className="w-6 h-6" /> <FontAwesomeIcon icon={faUserPlus} className="w-6 h-6" />
</div> </div>
</div> </div>
{activeCollection.members[0] ? ( {collection.members[0] ? (
<p className="text-center text-gray-500 text-xs sm:text-sm"> <p className="text-center text-gray-500 text-xs sm:text-sm">
(All Members have <b>Read</b> access to this collection.) (All Members have <b>Read</b> access to this collection.)
</p> </p>
) : null} ) : null}
<div className="h-36 overflow-auto flex flex-col gap-3 rounded-md shadow-inner"> <div className="h-36 overflow-auto flex flex-col gap-3 rounded-md shadow-inner">
{activeCollection.members.map((e, i) => { {collection.members.map((e, i) => {
return ( return (
<div <div
key={i} key={i}
@ -169,13 +186,11 @@ export default function EditCollection({
className="absolute right-2 top-2 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer" className="absolute right-2 top-2 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer"
title="Remove Member" title="Remove Member"
onClick={() => { onClick={() => {
const updatedMembers = activeCollection.members.filter( const updatedMembers = collection.members.filter((member) => {
(member) => {
return member.user.email !== e.user.email; return member.user.email !== e.user.email;
} });
); setCollection({
setActiveCollection({ ...collection,
...activeCollection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -213,7 +228,7 @@ export default function EditCollection({
className="peer sr-only" className="peer sr-only"
checked={e.canCreate} checked={e.canCreate}
onChange={() => { onChange={() => {
const updatedMembers = activeCollection.members.map( const updatedMembers = collection.members.map(
(member) => { (member) => {
if (member.user.email === e.user.email) { if (member.user.email === e.user.email) {
return { ...member, canCreate: !e.canCreate }; return { ...member, canCreate: !e.canCreate };
@ -221,8 +236,8 @@ export default function EditCollection({
return member; return member;
} }
); );
setActiveCollection({ setCollection({
...activeCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -239,7 +254,7 @@ export default function EditCollection({
className="peer sr-only" className="peer sr-only"
checked={e.canUpdate} checked={e.canUpdate}
onChange={() => { onChange={() => {
const updatedMembers = activeCollection.members.map( const updatedMembers = collection.members.map(
(member) => { (member) => {
if (member.user.email === e.user.email) { if (member.user.email === e.user.email) {
return { ...member, canUpdate: !e.canUpdate }; return { ...member, canUpdate: !e.canUpdate };
@ -247,8 +262,8 @@ export default function EditCollection({
return member; return member;
} }
); );
setActiveCollection({ setCollection({
...activeCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -265,7 +280,7 @@ export default function EditCollection({
className="peer sr-only" className="peer sr-only"
checked={e.canDelete} checked={e.canDelete}
onChange={() => { onChange={() => {
const updatedMembers = activeCollection.members.map( const updatedMembers = collection.members.map(
(member) => { (member) => {
if (member.user.email === e.user.email) { if (member.user.email === e.user.email) {
return { ...member, canDelete: !e.canDelete }; return { ...member, canDelete: !e.canDelete };
@ -273,8 +288,8 @@ export default function EditCollection({
return member; return member;
} }
); );
setActiveCollection({ setCollection({
...activeCollection, ...collection,
members: updatedMembers, members: updatedMembers,
}); });
}} }}
@ -320,7 +335,7 @@ export default function EditCollection({
{deleteCollectionModal ? ( {deleteCollectionModal ? (
<Modal toggleModal={toggleDeleteCollectionModal}> <Modal toggleModal={toggleDeleteCollectionModal}>
<DeleteCollection <DeleteCollection
collection={activeCollection} collection={collection}
toggleDeleteCollectionModal={toggleDeleteCollectionModal} toggleDeleteCollectionModal={toggleDeleteCollectionModal}
/> />
</Modal> </Modal>

View File

@ -1,265 +0,0 @@
// Copyright (C) 2022-present Daniel31x13 <daniel31x13@gmail.com>
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faClose, faPlus, faUser } from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import { ExtendedCollection, NewCollection } from "@/types/global";
import { useSession } from "next-auth/react";
import RequiredBadge from "../RequiredBadge";
import addMemberToCollection from "@/lib/client/addMemberToCollection";
import ImageWithFallback from "../ImageWithFallback";
type Props = {
toggleCollectionModal: Function;
};
export default function AddCollection({ toggleCollectionModal }: Props) {
const [newCollection, setNewCollection] = useState<NewCollection>({
name: "",
description: "",
members: [],
});
const [memberEmail, setMemberEmail] = useState("");
const { addCollection } = useCollectionStore();
const session = useSession();
const submit = async () => {
console.log(newCollection);
const response = await addCollection(newCollection as NewCollection);
if (response) toggleCollectionModal();
};
const setMemberState = (newMember: any) => {
setNewCollection({
...newCollection,
members: [...newCollection.members, newMember],
});
setMemberEmail("");
};
return (
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
<p className="text-xl text-sky-500 mb-2 text-center">New Collection</p>
<div className="flex flex-col sm:flex-row gap-3">
<div className="w-full">
<p className="text-sm font-bold text-sky-300 mb-2">
Name
<RequiredBadge />
</p>
<input
value={newCollection.name}
onChange={(e) =>
setNewCollection({ ...newCollection, name: e.target.value })
}
type="text"
placeholder="e.g. Example Collection"
className="w-full rounded-md p-3 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
<div className="w-full">
<p className="text-sm font-bold text-sky-300 mb-2">Description</p>
<input
value={newCollection.description}
onChange={(e) =>
setNewCollection({
...newCollection,
description: e.target.value,
})
}
type="text"
placeholder="Collection description"
className="w-full rounded-md p-3 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
</div>
<hr className="border rounded my-2" />
<p className="text-sm font-bold text-sky-300">Members</p>
<div className="relative">
<input
value={memberEmail}
onChange={(e) => {
setMemberEmail(e.target.value);
}}
type="text"
placeholder="Email"
className="w-full rounded-md p-3 pr-12 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<div
onClick={() =>
addMemberToCollection(
session.data?.user.email as string,
memberEmail,
newCollection as unknown as ExtendedCollection,
setMemberState,
"ADD"
)
}
className="absolute flex items-center justify-center right-2 top-2 bottom-2 bg-sky-500 hover:bg-sky-400 duration-100 text-white w-9 rounded-md cursor-pointer"
>
<FontAwesomeIcon icon={faPlus} className="w-4 h-4" />
</div>
</div>
{newCollection.members[0] ? (
<p className="text-center text-gray-500 text-xs sm:text-sm">
(All Members have <b>Read</b> access to this collection.)
</p>
) : null}
<div className="h-36 overflow-auto flex flex-col gap-3 rounded-md shadow-inner">
{newCollection.members.map((e, i) => {
return (
<div
key={i}
className="relative border p-2 rounded-md border-sky-100 flex flex-col sm:flex-row sm:items-center gap-2 justify-between"
>
<FontAwesomeIcon
icon={faClose}
className="absolute right-2 top-2 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer"
title="Remove Member"
onClick={() => {
const updatedMembers = newCollection.members.filter(
(member) => {
return member.email !== e.email;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<div className="flex items-center gap-2">
<ImageWithFallback
key={i}
// @ts-ignore
src={`/api/avatar/${e.id}`}
className="h-10 w-10 shadow rounded-full border-[3px] border-sky-100"
>
<div className="text-white bg-sky-500 h-10 w-10 shadow rounded-full border-[3px] border-sky-100 flex items-center justify-center">
<FontAwesomeIcon icon={faUser} className="w-5 h-5" />
</div>
</ImageWithFallback>
<div>
<p className="text-sm font-bold text-sky-500">{e.name}</p>
<p className="text-sky-900">{e.email}</p>
</div>
</div>
<div className="flex sm:block items-center gap-5">
<div>
<p className="font-bold text-sm text-gray-500">Permissions</p>
<p className="text-xs text-gray-400 mb-2">
(Click to toggle.)
</p>
</div>
<div>
<label className="cursor-pointer mr-1">
<input
type="checkbox"
id="canCreate"
className="peer sr-only"
checked={e.canCreate}
onChange={() => {
const updatedMembers = newCollection.members.map(
(member) => {
if (member.email === e.email) {
return { ...member, canCreate: !e.canCreate };
}
return member;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">
Create
</span>
</label>
<label className="cursor-pointer mr-1">
<input
type="checkbox"
id="canUpdate"
className="peer sr-only"
checked={e.canUpdate}
onChange={() => {
const updatedMembers = newCollection.members.map(
(member) => {
if (member.email === e.email) {
return { ...member, canUpdate: !e.canUpdate };
}
return member;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">
Update
</span>
</label>
<label className="cursor-pointer mr-1">
<input
type="checkbox"
id="canDelete"
className="peer sr-only"
checked={e.canDelete}
onChange={() => {
const updatedMembers = newCollection.members.map(
(member) => {
if (member.email === e.email) {
return { ...member, canDelete: !e.canDelete };
}
return member;
}
);
setNewCollection({
...newCollection,
members: updatedMembers,
});
}}
/>
<span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">
Delete
</span>
</label>
</div>
</div>
</div>
);
})}
</div>
<div
className="mx-auto mt-2 bg-sky-500 text-white flex items-center gap-2 py-2 px-5 rounded-md select-none font-bold cursor-pointer duration-100 hover:bg-sky-400"
onClick={submit}
>
<FontAwesomeIcon icon={faPlus} className="h-5" />
Add Collection
</div>
</div>
);
}

View File

@ -4,10 +4,13 @@
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. // You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { NewCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import { existsSync, mkdirSync } from "fs"; import { existsSync, mkdirSync } from "fs";
export default async function (collection: NewCollection, userId: number) { export default async function (
collection: CollectionIncludingMembers,
userId: number
) {
if (!collection || collection.name.trim() === "") if (!collection || collection.name.trim() === "")
return { return {
response: "Please enter a valid collection.", response: "Please enter a valid collection.",
@ -43,7 +46,7 @@ export default async function (collection: NewCollection, userId: number) {
description: collection.description, description: collection.description,
members: { members: {
create: collection.members.map((e) => ({ create: collection.members.map((e) => ({
user: { connect: { email: e.email } }, user: { connect: { email: e.user.email } },
canCreate: e.canCreate, canCreate: e.canCreate,
canUpdate: e.canUpdate, canUpdate: e.canUpdate,
canDelete: e.canDelete, canDelete: e.canDelete,

View File

@ -4,11 +4,14 @@
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. // You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { ExtendedCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
export default async function (collection: ExtendedCollection, userId: number) { export default async function (
if (!collection) collection: CollectionIncludingMembers,
userId: number
) {
if (!collection.id)
return { response: "Please choose a valid collection.", status: 401 }; return { response: "Please choose a valid collection.", status: 401 };
const collectionIsAccessible = await getPermission(userId, collection.id); const collectionIsAccessible = await getPermission(userId, collection.id);

View File

@ -1,15 +1,15 @@
import { ExtendedCollection, NewCollection } from "@/types/global"; import { CollectionIncludingMembers, Member } from "@/types/global";
import getPublicUserDataByEmail from "./getPublicUserDataByEmail"; import getPublicUserDataByEmail from "./getPublicUserDataByEmail";
const addMemberToCollection = async ( const addMemberToCollection = async (
ownerEmail: string, ownerEmail: string,
memberEmail: string, memberEmail: string,
collection: ExtendedCollection, collection: CollectionIncludingMembers,
setMemberState: Function, setMember: (newMember: Member) => null | undefined
collectionMethod: "ADD" | "UPDATE"
) => { ) => {
const checkIfMemberAlreadyExists = collection.members.find((e: any) => { console.log(collection.members);
const email = collectionMethod === "ADD" ? e.email : e.user.email; const checkIfMemberAlreadyExists = collection.members.find((e) => {
const email = e.user.email;
return email === memberEmail; return email === memberEmail;
}); });
@ -24,18 +24,10 @@ const addMemberToCollection = async (
// Lookup, get data/err, list ... // Lookup, get data/err, list ...
const user = await getPublicUserDataByEmail(memberEmail.trim()); const user = await getPublicUserDataByEmail(memberEmail.trim());
console.log(collection);
if (user.email) { if (user.email) {
const newMember = setMember({
collectionMethod === "ADD"
? {
id: user.id,
name: user.name,
email: user.email,
canCreate: false,
canUpdate: false,
canDelete: false,
}
: {
collectionId: collection.id, collectionId: collection.id,
userId: user.id, userId: user.id,
canCreate: false, canCreate: false,
@ -45,9 +37,7 @@ const addMemberToCollection = async (
name: user.name, name: user.name,
email: user.email, email: user.email,
}, },
}; });
setMemberState(newMember);
} }
} }
}; };

View File

@ -11,7 +11,7 @@ import EditCollection from "@/components/Modal/EditCollection";
import DeleteCollection from "@/components/Modal/DeleteCollection"; import DeleteCollection from "@/components/Modal/DeleteCollection";
import useCollectionStore from "@/store/collections"; import useCollectionStore from "@/store/collections";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import { ExtendedCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import { import {
faAdd, faAdd,
faEllipsis, faEllipsis,
@ -46,7 +46,7 @@ export default function () {
const [sortBy, setSortBy] = useState("Name (A-Z)"); const [sortBy, setSortBy] = useState("Name (A-Z)");
const [activeCollection, setActiveCollection] = const [activeCollection, setActiveCollection] =
useState<ExtendedCollection>(); useState<CollectionIncludingMembers>();
const [sortedLinks, setSortedLinks] = useState(links); const [sortedLinks, setSortedLinks] = useState(links);
@ -128,7 +128,9 @@ export default function () {
Team Team
</div> </div>
{activeCollection?.members {activeCollection?.members
.sort((a, b) => a.userId - b.userId) .sort(
(a, b) => (a.user.id as number) - (b.user.id as number)
)
.map((e, i) => { .map((e, i) => {
return ( return (
<ImageWithFallback <ImageWithFallback
@ -284,7 +286,7 @@ export default function () {
<Modal toggleModal={toggleEditCollectionModal}> <Modal toggleModal={toggleEditCollectionModal}>
<EditCollection <EditCollection
toggleCollectionModal={toggleEditCollectionModal} toggleCollectionModal={toggleEditCollectionModal}
collection={activeCollection} activeCollection={activeCollection}
/> />
</Modal> </Modal>
) : null} ) : null}

View File

@ -4,15 +4,17 @@
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. // You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { create } from "zustand"; import { create } from "zustand";
import { ExtendedCollection, NewCollection } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import useTagStore from "./tags"; import useTagStore from "./tags";
import useLinkStore from "./links"; import useLinkStore from "./links";
type CollectionStore = { type CollectionStore = {
collections: ExtendedCollection[]; collections: CollectionIncludingMembers[];
setCollections: () => void; setCollections: () => void;
addCollection: (body: NewCollection) => Promise<boolean>; addCollection: (body: CollectionIncludingMembers) => Promise<boolean>;
updateCollection: (collection: ExtendedCollection) => Promise<boolean>; updateCollection: (
collection: CollectionIncludingMembers
) => Promise<boolean>;
removeCollection: (collectionId: number) => Promise<boolean>; removeCollection: (collectionId: number) => Promise<boolean>;
}; };

View File

@ -4,7 +4,9 @@
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. // You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import { Collection, Link, Tag, User } from "@prisma/client"; import { Collection, Link, Tag, User } from "@prisma/client";
import { SetStateAction } from "react";
type OptionalExcluding<T, TRequired extends keyof T> = Partial<T> &
Pick<T, TRequired>;
export interface ExtendedLink extends Link { export interface ExtendedLink extends Link {
tags: Tag[]; tags: Tag[];
@ -34,18 +36,20 @@ export interface NewCollection {
}[]; }[];
} }
export interface ExtendedCollection extends Collection { export interface Member {
members: { collectionId?: number;
collectionId: number; userId?: number;
userId: number;
canCreate: boolean; canCreate: boolean;
canUpdate: boolean; canUpdate: boolean;
canDelete: boolean; canDelete: boolean;
user: { user: OptionalExcluding<User, "email" | "name">;
name: string; }
email: string;
}; export interface CollectionIncludingMembers
}[]; extends Omit<Collection, "id" | "createdAt"> {
id?: number;
createdAt?: Date;
members: Member[];
} }
export type SearchSettings = { export type SearchSettings = {