⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
Finished bulk delete links
Isaac Wiseea31eb47aed7
diff --git a/components/LinkViews/Layouts/CardView.tsx b/components/LinkViews/Layouts/CardView.tsxindex 3e341cc0..cb8c5af0 100644--- a/components/LinkViews/Layouts/CardView.tsx+++ b/components/LinkViews/Layouts/CardView.tsx@@ -3,8 +3,10 @@ import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";export default function CardView({links,+ showCheckbox = true,}: {links: LinkIncludingShortenedCollectionAndTags[];+ showCheckbox?: boolean;}) {return (<div className="grid min-[1900px]:grid-cols-4 xl:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">@@ -15,6 +17,7 @@ export default function CardView({link={e}count={i}flipDropdown={i === links.length - 1}+ showCheckbox={showCheckbox}/>);})}diff --git a/components/LinkViews/Layouts/ListView.tsx b/components/LinkViews/Layouts/ListView.tsxindex 18392842..aa42780a 100644--- a/components/LinkViews/Layouts/ListView.tsx+++ b/components/LinkViews/Layouts/ListView.tsx@@ -3,8 +3,10 @@ import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";export default function ListView({links,+ showCheckbox = true}: {links: LinkIncludingShortenedCollectionAndTags[];+ showCheckbox?: boolean;}) {return (<div className="flex flex-col">@@ -14,6 +16,7 @@ export default function ListView({key={i}link={e}count={i}+ showCheckbox={showCheckbox}flipDropdown={i === links.length - 1}/>);diff --git a/components/LinkViews/LinkCard.tsx b/components/LinkViews/LinkCard.tsxindex d6d52ee8..8e7f9321 100644--- a/components/LinkViews/LinkCard.tsx+++ b/components/LinkViews/LinkCard.tsx@@ -16,6 +16,7 @@ import Link from "next/link";import LinkIcon from "./LinkComponents/LinkIcon";import useOnScreen from "@/hooks/useOnScreen";import { generateLinkHref } from "@/lib/client/generateLinkHref";+import useAccountStore from "@/store/account";type Props = {link: LinkIncludingShortenedCollectionAndTags;@@ -28,7 +29,7 @@ type Props = {export default function LinkCard({link,flipDropdown,- showCheckbox,+ showCheckbox = true,}: Props) {const { collections } = useCollectionStore();diff --git a/components/LinkViews/LinkList.tsx b/components/LinkViews/LinkList.tsxindex 27e1859e..e5c07b22 100644--- a/components/LinkViews/LinkList.tsx+++ b/components/LinkViews/LinkList.tsx@@ -25,7 +25,7 @@ type Props = {export default function LinkCardCompact({link,flipDropdown,- showCheckbox,+ showCheckbox = true,}: Props) {const { collections } = useCollectionStore();const { links, setSelectedLinks, selectedLinks } = useLinkStore();diff --git a/components/ModalContent/BulkDeleteLinksModal.tsx b/components/ModalContent/BulkDeleteLinksModal.tsxnew file mode 100644index 00000000..69ba026d--- /dev/null+++ b/components/ModalContent/BulkDeleteLinksModal.tsx@@ -0,0 +1,65 @@+import React from "react";+import useLinkStore from "@/store/links";+import toast from "react-hot-toast";+import Modal from "../Modal";++type Props = {+ onClose: Function;+};++export default function BulkDeleteLinksModal({ onClose }: Props) {+ const { selectedLinks, setSelectedLinks, deleteLinksById } = useLinkStore();++ const deleteLink = async () => {+ const load = toast.loading(`Deleting ${selectedLinks.length} Link${selectedLinks.length > 1 ? "s" : ""}...`);++ const response = await deleteLinksById(selectedLinks);++ toast.dismiss(load);++ response.ok && toast.success(`Deleted ${selectedLinks.length} Link${selectedLinks.length > 1 ? "s" : ""}!`);++ setSelectedLinks([]);+ onClose();+ };++ return (+ <Modal toggleModal={onClose}>+ <p className="text-xl font-thin text-red-500">Delete {selectedLinks.length}</p>++ <div className="divider mb-3 mt-1"></div>++ <div className="flex flex-col gap-3">+ {selectedLinks.length > 1 ? (+ <p>+ Are you sure you want to delete {selectedLinks.length} links?+ </p>+ ) : (+ <p>+ Are you sure you want to delete this link?+ </p>+ )}++ <div role="alert" className="alert alert-warning">+ <i className="bi-exclamation-triangle text-xl" />+ <span>+ <b>Warning:</b> This action is irreversible!+ </span>+ </div>++ <p>+ Hold the <kbd className="kbd kbd-sm">Shift</kbd> key while clicking+ 'Delete' to bypass this confirmation in the future.+ </p>++ <button+ className={`ml-auto btn w-fit text-white flex items-center gap-2 duration-100 bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer`}+ onClick={deleteLink}+ >+ <i className="bi-trash text-xl" />+ Delete+ </button>+ </div>+ </Modal>+ );+}diff --git a/components/ModalContent/DeleteLinkModal.tsx b/components/ModalContent/DeleteLinkModal.tsxindex a2b123ca..1a3a4764 100644--- a/components/ModalContent/DeleteLinkModal.tsx+++ b/components/ModalContent/DeleteLinkModal.tsx@@ -15,7 +15,6 @@ export default function DeleteLinkModal({ onClose, activeLink }: Props) {useState<LinkIncludingShortenedCollectionAndTags>(activeLink);const { removeLink } = useLinkStore();- const [submitLoader, setSubmitLoader] = useState(false);const router = useRouter();diff --git a/components/ModalContent/NewLinkModal.tsx b/components/ModalContent/NewLinkModal.tsxindex 20bcef25..3fde2147 100644--- a/components/ModalContent/NewLinkModal.tsx+++ b/components/ModalContent/NewLinkModal.tsx@@ -20,6 +20,7 @@ export default function NewLinkModal({ onClose }: Props) {const { data } = useSession();const initial = {+ id: 0,name: "",url: "",description: "",@@ -196,9 +197,8 @@ export default function NewLinkModal({ onClose }: Props) {{optionsExpanded ? "Hide" : "More"} Options</p><i- className={`${- optionsExpanded ? "bi-chevron-up" : "bi-chevron-down"- }`}+ className={`${optionsExpanded ? "bi-chevron-up" : "bi-chevron-down"+ }`}></i></div>diff --git a/lib/api/controllers/links/bulk/deleteLinksById.ts b/lib/api/controllers/links/bulk/deleteLinksById.tsnew file mode 100644index 00000000..0bc93b07--- /dev/null+++ b/lib/api/controllers/links/bulk/deleteLinksById.ts@@ -0,0 +1,48 @@+import { prisma } from "@/lib/api/db";+import { UsersAndCollections } from "@prisma/client";+import getPermission from "@/lib/api/getPermission";+import removeFile from "@/lib/api/storage/removeFile";++export default async function deleteLinksById(userId: number, linkIds: number[]) {+ console.log("linkIds: ", linkIds);+ if (!linkIds || linkIds.length === 0) {+ return { response: "Please choose valid links.", status: 401 };+ }++ const deletedLinks = [];++ for (const linkId of linkIds) {+ const collectionIsAccessible = await getPermission({+ userId,+ linkId,+ });++ const memberHasAccess = collectionIsAccessible?.members.some(+ (e: UsersAndCollections) => e.userId === userId && e.canDelete+ );++ if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess)) {+ return { response: "Collection is not accessible.", status: 401 };+ }++ const deletedLink = await prisma.link.delete({+ where: {+ id: linkId,+ },+ });++ removeFile({+ filePath: `archives/${collectionIsAccessible?.id}/${linkId}.pdf`,+ });+ removeFile({+ filePath: `archives/${collectionIsAccessible?.id}/${linkId}.png`,+ });+ removeFile({+ filePath: `archives/${collectionIsAccessible?.id}/${linkId}_readability.json`,+ });++ deletedLinks.push(deletedLink);+ }++ return { response: deletedLinks, status: 200 };+}\ No newline at end of filediff --git a/lib/api/controllers/links/linkId/deleteLinkById.ts b/lib/api/controllers/links/linkId/deleteLinkById.tsindex 90adba40..db68ee7d 100644--- a/lib/api/controllers/links/linkId/deleteLinkById.ts+++ b/lib/api/controllers/links/linkId/deleteLinkById.ts@@ -1,5 +1,5 @@import { prisma } from "@/lib/api/db";-import { Collection, Link, UsersAndCollections } from "@prisma/client";+import { Link, UsersAndCollections } from "@prisma/client";import getPermission from "@/lib/api/getPermission";import removeFile from "@/lib/api/storage/removeFile";diff --git a/pages/api/v1/links/bulk/index.ts b/pages/api/v1/links/bulk/index.tsnew file mode 100644index 00000000..8a5583be--- /dev/null+++ b/pages/api/v1/links/bulk/index.ts@@ -0,0 +1,15 @@+import type { NextApiRequest, NextApiResponse } from "next";+import verifyUser from "@/lib/api/verifyUser";+import deleteLinksById from "@/lib/api/controllers/links/bulk/deleteLinksById";++export default async function links(req: NextApiRequest, res: NextApiResponse) {+ const user = await verifyUser({ req, res });+ if (!user) return;++ if (req.method === "DELETE") {+ const deleted = await deleteLinksById(user.id, req.body.linkIds);+ return res.status(deleted.status).json({+ response: deleted.response,+ });+ }+}diff --git a/pages/collections/[id].tsx b/pages/collections/[id].tsxindex ef84a392..c3b29643 100644--- a/pages/collections/[id].tsx+++ b/pages/collections/[id].tsx@@ -25,13 +25,15 @@ import CardView from "@/components/LinkViews/Layouts/CardView";import ListView from "@/components/LinkViews/Layouts/ListView";import { dropdownTriggerer } from "@/lib/client/utils";import NewCollectionModal from "@/components/ModalContent/NewCollectionModal";+import BulkDeleteLinksModal from "@/components/ModalContent/BulkDeleteLinksModal";+import toast from "react-hot-toast";export default function Index() {const { settings } = useLocalSettingsStore();const router = useRouter();- const { links, selectedLinks, setSelectedLinks } = useLinkStore();+ const { links, selectedLinks, setSelectedLinks, deleteLinksById } = useLinkStore();const { collections } = useCollectionStore();const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);@@ -90,6 +92,7 @@ export default function Index() {const [editCollectionSharingModal, setEditCollectionSharingModal] =useState(false);const [deleteCollectionModal, setDeleteCollectionModal] = useState(false);+ const [bulkDeleteLinksModal, setBulkDeleteLinksModal] = useState(false);const [viewMode, setViewMode] = useState<string>(localStorage.getItem("viewMode") || ViewMode.Card@@ -112,6 +115,16 @@ export default function Index() {}};+ const bulkDeleteLinks = async () => {+ const load = toast.loading(`Deleting ${selectedLinks.length} Link${selectedLinks.length > 1 ? "s" : ""}...`);++ const response = await deleteLinksById(selectedLinks);++ toast.dismiss(load);++ response.ok && toast.success(`Deleted ${selectedLinks.length} Link${selectedLinks.length > 1 ? "s" : ""}!`);+ };+return (<MainLayout><div@@ -295,7 +308,7 @@ export default function Index() {type="checkbox"className="checkbox checkbox-primary"onChange={() => handleSelectAll()}- checked={selectedLinks.length === links.length}+ checked={selectedLinks.length === links.length && links.length > 0}/>{selectedLinks.length > 0 && (<span>@@ -308,7 +321,10 @@ export default function Index() {<button className="btn btn-sm btn-accent dark:border-violet-400 text-white w-fit ml-auto">Edit Links</button>- <button className="btn btn-sm bg-red-400 border-red-400 hover:border-red-500 hover:bg-red-500 text-white w-fit ml-auto">+ <button onClick={(e) => {+ (document?.activeElement as HTMLElement)?.blur();+ e.shiftKey ? bulkDeleteLinks() : setBulkDeleteLinksModal(true);+ }} className="btn btn-sm bg-red-400 border-red-400 hover:border-red-500 hover:bg-red-500 text-white w-fit ml-auto">Delete</button></div>@@ -325,34 +341,37 @@ export default function Index() {<NoLinksFound />)}</div>- {activeCollection ? (+ {activeCollection && (<>- {editCollectionModal ? (+ {editCollectionModal && (<EditCollectionModalonClose={() => setEditCollectionModal(false)}activeCollection={activeCollection}/>- ) : undefined}- {editCollectionSharingModal ? (+ )}+ {editCollectionSharingModal && (<EditCollectionSharingModalonClose={() => setEditCollectionSharingModal(false)}activeCollection={activeCollection}/>- ) : undefined}- {newCollectionModal ? (+ )}+ {newCollectionModal && (<NewCollectionModalonClose={() => setNewCollectionModal(false)}parent={activeCollection}/>- ) : undefined}- {deleteCollectionModal ? (+ )}+ {deleteCollectionModal && (<DeleteCollectionModalonClose={() => setDeleteCollectionModal(false)}activeCollection={activeCollection}/>- ) : undefined}+ )}+ {bulkDeleteLinksModal && (+ <BulkDeleteLinksModal onClose={() => setBulkDeleteLinksModal(false)} />+ )}</>- ) : undefined}+ )}</MainLayout>);}diff --git a/store/links.ts b/store/links.tsindex aa55b595..2393c194 100644--- a/store/links.ts+++ b/store/links.ts@@ -24,6 +24,7 @@ type LinkStore = {link: LinkIncludingShortenedCollectionAndTags) => Promise<ResponseObject>;removeLink: (linkId: number) => Promise<ResponseObject>;+ deleteLinksById: (linkIds: number[]) => Promise<ResponseObject>;resetLinks: () => void;};@@ -146,6 +147,27 @@ const useLinkStore = create<LinkStore>()((set) => ({return { ok: response.ok, data: data.response };},+ deleteLinksById: async (linkIds: number[]) => {+ const response = await fetch("/api/v1/links/bulk", {+ body: JSON.stringify({ linkIds }),+ headers: {+ "Content-Type": "application/json",+ },+ method: "DELETE",+ });++ const data = await response.json();++ if (response.ok) {+ set((state) => ({+ links: state.links.filter((e) => !linkIds.includes(e.id)),+ }));+ useTagStore.getState().setTags();+ useCollectionStore.getState().setCollections();+ }++ return { ok: response.ok, data: data.response };+ },resetLinks: () => set({ links: [] }),}));