remove tag functionality

This commit is contained in:
daniel31x13 2023-11-03 00:09:50 -04:00
parent ae1889e757
commit b5a28f68ad
16 changed files with 123 additions and 448 deletions

View File

@ -6,7 +6,6 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import RequiredBadge from "../../RequiredBadge";
import SubmitButton from "@/components/SubmitButton";
import { HexColorPicker } from "react-colorful";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
@ -61,10 +60,7 @@ export default function CollectionInfo({
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
<div className="flex flex-col sm:flex-row gap-3">
<div className="w-full">
<p className="text-sm text-black dark:text-white mb-2">
Name
<RequiredBadge />
</p>
<p className="text-black dark:text-white mb-2">Name</p>
<div className="flex flex-col gap-3">
<TextInput
value={collection.name}
@ -75,9 +71,7 @@ export default function CollectionInfo({
/>
<div className="color-picker flex justify-between">
<div className="flex flex-col justify-between items-center w-32">
<p className="text-sm w-full text-black dark:text-white mb-2">
Icon Color
</p>
<p className="w-full text-black dark:text-white mb-2">Color</p>
<div style={{ color: collection.color }}>
<FontAwesomeIcon
icon={faFolder}
@ -102,7 +96,7 @@ export default function CollectionInfo({
</div>
<div className="w-full">
<p className="text-sm text-black dark:text-white mb-2">Description</p>
<p className="text-black dark:text-white mb-2">Description</p>
<textarea
className="w-full h-[11.4rem] resize-none border rounded-md duration-100 bg-gray-50 dark:bg-neutral-950 p-2 outline-none border-sky-100 dark:border-neutral-700 focus:border-sky-300 dark:focus:border-sky-600"
placeholder="The purpose of this Collection..."

View File

@ -101,7 +101,7 @@ export default function TeamManagement({
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
{permissions === true && (
<>
<p className="text-sm text-black dark:text-white">Make Public</p>
<p className="text-black dark:text-white">Make Public</p>
<Checkbox
label="Make this a public collection."
@ -119,7 +119,7 @@ export default function TeamManagement({
{collection.isPublic ? (
<div>
<p className="text-sm text-black dark:text-white mb-2">
<p className="text-black dark:text-white mb-2">
Public Link (Click to copy)
</p>
<div
@ -145,9 +145,7 @@ export default function TeamManagement({
{permissions === true && (
<>
<p className="text-sm text-black dark:text-white">
Member Management
</p>
<p className="text-black dark:text-white">Member Management</p>
<div className="flex items-center gap-2">
<TextInput

View File

@ -151,9 +151,7 @@ export default function AddOrEditLink({
{method === "CREATE" ? (
<div className="grid grid-flow-row-dense sm:grid-cols-5 gap-3">
<div className="sm:col-span-3 col-span-5">
<p className="text-sm text-black dark:text-white mb-2">
Address (URL)
</p>
<p className="text-black dark:text-white mb-2">Address (URL)</p>
<TextInput
value={link.url}
onChange={(e) => setLink({ ...link, url: e.target.value })}
@ -161,9 +159,7 @@ export default function AddOrEditLink({
/>
</div>
<div className="sm:col-span-2 col-span-5">
<p className="text-sm text-black dark:text-white mb-2">
Collection
</p>
<p className="text-black dark:text-white mb-2">Collection</p>
{link.collection.name ? (
<CollectionSelection
onChange={setCollection}
@ -193,7 +189,7 @@ export default function AddOrEditLink({
{/* <hr className="mb-3 border border-sky-100 dark:border-neutral-700" /> */}
<div className="grid sm:grid-cols-2 gap-3">
<div className={`${method === "UPDATE" ? "sm:col-span-2" : ""}`}>
<p className="text-sm text-black dark:text-white mb-2">Name</p>
<p className="text-black dark:text-white mb-2">Name</p>
<TextInput
value={link.name}
onChange={(e) => setLink({ ...link, name: e.target.value })}
@ -203,9 +199,7 @@ export default function AddOrEditLink({
{method === "UPDATE" ? (
<div>
<p className="text-sm text-black dark:text-white mb-2">
Collection
</p>
<p className="text-black dark:text-white mb-2">Collection</p>
{link.collection.name ? (
<CollectionSelection
onChange={setCollection}
@ -226,7 +220,7 @@ export default function AddOrEditLink({
) : undefined}
<div>
<p className="text-sm text-black dark:text-white mb-2">Tags</p>
<p className="text-black dark:text-white mb-2">Tags</p>
<TagSelection
onChange={setTags}
defaultValue={link.tags.map((e) => {
@ -236,9 +230,7 @@ export default function AddOrEditLink({
</div>
<div className="sm:col-span-2">
<p className="text-sm text-black dark:text-white mb-2">
Description
</p>
<p className="text-black dark:text-white mb-2">Description</p>
<textarea
value={unescapeString(link.description) as string}
onChange={(e) =>
@ -256,14 +248,14 @@ export default function AddOrEditLink({
</div>
) : undefined}
<div className="flex justify-between items-center mt-2">
<div className="flex justify-between items-stretch mt-2">
<div
onClick={() => setOptionsExpanded(!optionsExpanded)}
className={`${
method === "UPDATE" ? "hidden" : ""
} rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 py-1 px-2 w-fit text-sm`}
} rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 flex items-center px-2 w-fit text-sm`}
>
{optionsExpanded ? "Hide" : "More"} Options
<p>{optionsExpanded ? "Hide" : "More"} Options</p>
</div>
<SubmitButton

View File

@ -1,373 +0,0 @@
import {
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import Image from "next/image";
import ColorThief, { RGBColor } from "colorthief";
import { useEffect, useState } from "react";
import Link from "next/link";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faArrowUpRightFromSquare,
faBoxArchive,
faBuildingColumns,
faCloudArrowDown,
faFolder,
} from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import {
faCalendarDays,
faFileImage,
faFilePdf,
} from "@fortawesome/free-regular-svg-icons";
import isValidUrl from "@/lib/client/isValidUrl";
import { useTheme } from "next-themes";
import unescapeString from "@/lib/client/unescapeString";
import useLinkStore from "@/store/links";
type Props = {
linkId: number;
isOwnerOrMod: boolean;
};
export default function LinkDetails({ linkId, isOwnerOrMod }: Props) {
const { theme } = useTheme();
const { links, getLink } = useLinkStore();
const [link, setLink] = useState<LinkIncludingShortenedCollectionAndTags>(
links.find(
(e) => e.id === linkId
) as LinkIncludingShortenedCollectionAndTags
);
useEffect(() => {
setLink(
links.find(
(e) => e.id === linkId
) as LinkIncludingShortenedCollectionAndTags
);
}, [links]);
useEffect(() => {
let interval: NodeJS.Timer | undefined;
if (link.screenshotPath === "pending" || link.pdfPath === "pending") {
interval = setInterval(() => getLink(link.id as number), 5000);
} else {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [link.screenshotPath, link.pdfPath]);
const [imageError, setImageError] = useState<boolean>(false);
const formattedDate = new Date(link.createdAt as string).toLocaleString(
"en-US",
{
year: "numeric",
month: "short",
day: "numeric",
}
);
const { collections } = useCollectionStore();
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections]);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections]);
const [colorPalette, setColorPalette] = useState<RGBColor[]>();
const colorThief = new ColorThief();
const url = isValidUrl(link.url) ? new URL(link.url) : undefined;
const rgbToHex = (r: number, g: number, b: number): string =>
"#" +
[r, g, b]
.map((x) => {
const hex = x.toString(16);
return hex.length === 1 ? "0" + hex : hex;
})
.join("");
useEffect(() => {
const banner = document.getElementById("link-banner");
const bannerInner = document.getElementById("link-banner-inner");
if (colorPalette && banner && bannerInner) {
if (colorPalette[0] && colorPalette[1]) {
banner.style.background = `linear-gradient(to right, ${rgbToHex(
colorPalette[0][0],
colorPalette[0][1],
colorPalette[0][2]
)}, ${rgbToHex(
colorPalette[1][0],
colorPalette[1][1],
colorPalette[1][2]
)})`;
}
if (colorPalette[2] && colorPalette[3]) {
bannerInner.style.background = `linear-gradient(to right, ${rgbToHex(
colorPalette[2][0],
colorPalette[2][1],
colorPalette[2][2]
)}, ${rgbToHex(
colorPalette[3][0],
colorPalette[3][1],
colorPalette[3][2]
)})`;
}
}
}, [colorPalette, theme]);
const handleDownload = (format: "png" | "pdf") => {
const path = `/api/v1/archives/${link.collection.id}/${link.id}.${format}`;
fetch(path)
.then((response) => {
if (response.ok) {
// Create a temporary link and click it to trigger the download
const link = document.createElement("a");
link.href = path;
link.download = format === "pdf" ? "PDF" : "Screenshot";
link.click();
} else {
console.error("Failed to download file");
}
})
.catch((error) => {
console.error("Error:", error);
});
};
return (
<div
className={`flex flex-col gap-3 sm:w-[35rem] w-80 ${
isOwnerOrMod ? "" : "mt-12"
} ${theme === "dark" ? "banner-dark-mode" : "banner-light-mode"}`}
>
{!imageError && (
<div id="link-banner" className="link-banner h-32 -mx-5 -mt-5 relative">
<div id="link-banner-inner" className="link-banner-inner"></div>
</div>
)}
<div
className={`relative flex gap-5 items-start ${!imageError && "-mt-24"}`}
>
{!imageError && url && (
<Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`}
width={42}
height={42}
alt=""
id={"favicon-" + link.id}
className="select-none mt-2 w-10 rounded-md shadow border-[3px] border-white dark:border-neutral-900 bg-white dark:bg-neutral-900 aspect-square"
draggable="false"
onLoad={(e) => {
try {
const color = colorThief.getPalette(
e.target as HTMLImageElement,
4
);
setColorPalette(color);
} catch (err) {
console.log(err);
}
}}
onError={(e) => {
setImageError(true);
}}
/>
)}
<div className="flex w-full flex-col min-h-[3rem] justify-center drop-shadow">
<p className="text-2xl text-black dark:text-white capitalize break-words hyphens-auto">
{unescapeString(link.name)}
</p>
<Link
href={link.url}
target="_blank"
className={`${
link.name ? "text-sm" : "text-xl"
} text-gray-500 dark:text-gray-300 break-all hover:underline cursor-pointer w-fit`}
>
{url ? url.host : link.url}
</Link>
</div>
</div>
<div className="flex gap-1 items-center flex-wrap">
<Link
href={`/collections/${link.collection.id}`}
className="flex items-center gap-1 cursor-pointer hover:opacity-60 duration-100 mr-2 z-10"
>
<FontAwesomeIcon
icon={faFolder}
className="w-5 h-5 drop-shadow"
style={{ color: collection?.color }}
/>
<p
title={collection?.name}
className="text-black dark:text-white text-lg truncate max-w-[12rem]"
>
{collection?.name}
</p>
</Link>
{link.tags.map((e, i) => (
<Link key={i} href={`/tags/${e.id}`} className="z-10">
<p
title={e.name}
className="px-2 py-1 bg-sky-200 text-black dark:text-white dark:bg-sky-900 text-xs rounded-3xl cursor-pointer hover:opacity-60 duration-100 truncate max-w-[19rem]"
>
{e.name}
</p>
</Link>
))}
</div>
{link.description && (
<>
<div className="text-black dark:text-white max-h-[20rem] my-3 rounded-md overflow-y-auto hyphens-auto">
{unescapeString(link.description)}
</div>
</>
)}
<div className="flex justify-between items-center">
<div className="flex items-center gap-1 text-gray-500 dark:text-gray-300">
<FontAwesomeIcon icon={faBoxArchive} className="w-4 h-4" />
<p>Archived Formats:</p>
</div>
<div
className="flex items-center gap-1 text-gray-500 dark:text-gray-300"
title={"Created at: " + formattedDate}
>
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p>{formattedDate}</p>
</div>
</div>
<div className="flex flex-col gap-2">
{link.screenshotPath && link.screenshotPath !== "pending" ? (
<div className="flex justify-between items-center pr-1 border border-sky-100 dark:border-neutral-700 rounded-md">
<div className="flex gap-2 items-center">
<div className="text-white bg-sky-300 dark:bg-sky-600 p-2 rounded-l-md">
<FontAwesomeIcon icon={faFileImage} className="w-6 h-6" />
</div>
<p className="text-black dark:text-white">Screenshot</p>
</div>
<div className="flex text-black dark:text-white gap-1">
<div
onClick={() => handleDownload("png")}
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faCloudArrowDown}
className="w-5 h-5 cursor-pointer text-sky-500 dark:text-sky-500"
/>
</div>
<Link
href={`/api/v1/archives/${link.collectionId}/${link.id}.png`}
target="_blank"
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
className="w-5 h-5 text-sky-500 dark:text-sky-500"
/>
</Link>
</div>
</div>
) : undefined}
{link.pdfPath && link.pdfPath !== "pending" ? (
<div className="flex justify-between items-center pr-1 border border-sky-100 dark:border-neutral-700 rounded-md">
<div className="flex gap-2 items-center">
<div className="text-white bg-sky-300 dark:bg-sky-600 p-2 rounded-l-md">
<FontAwesomeIcon icon={faFilePdf} className="w-6 h-6" />
</div>
<p className="text-black dark:text-white">PDF</p>
</div>
<div className="flex text-black dark:text-white gap-1">
<div
onClick={() => handleDownload("pdf")}
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faCloudArrowDown}
className="w-5 h-5 cursor-pointer text-sky-500 dark:text-sky-500"
/>
</div>
<Link
href={`/api/v1/archives/${link.collectionId}/${link.id}.pdf`}
target="_blank"
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
className="w-5 h-5 text-sky-500 dark:text-sky-500"
/>
</Link>
</div>
</div>
) : undefined}
<div className="flex justify-between items-center pr-1 border border-sky-100 dark:border-neutral-700 rounded-md">
<div className="flex gap-2 items-center">
<div className="text-white bg-sky-300 dark:bg-sky-600 p-2 rounded-l-md">
<FontAwesomeIcon icon={faBuildingColumns} className="w-6 h-6" />
</div>
<p className="text-black dark:text-white">
Latest archive.org Snapshot
</p>
</div>
<Link
href={`https://web.archive.org/web/${link.url.replace(
/(^\w+:|^)\/\//,
""
)}`}
target="_blank"
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
className="w-5 h-5 text-sky-500 dark:text-sky-500"
/>
</Link>
</div>
</div>
</div>
);
}

View File

@ -18,7 +18,7 @@ export default async function authenticateUser({
if (!userId) {
res.status(401).json({ message: "You must be logged in." });
return null;
} else if (token.isSubscriber === false) {
} else if (process.env.STRIPE_SECRET_KEY && token.isSubscriber === false) {
res.status(401).json({
message:
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app if you think this is an issue.",

View File

@ -0,0 +1,26 @@
import { prisma } from "@/lib/api/db";
export default async function deleteTagById(userId: number, tagId: number) {
if (!tagId)
return { response: "Please choose a valid name for the tag.", status: 401 };
const targetTag = await prisma.tag.findUnique({
where: {
id: tagId,
},
});
if (targetTag?.ownerId !== userId)
return {
response: "Permission denied.",
status: 401,
};
const updatedTag = await prisma.tag.delete({
where: {
id: tagId,
},
});
return { response: updatedTag, status: 200 };
}

View File

@ -1,7 +1,7 @@
import { prisma } from "@/lib/api/db";
import { Tag } from "@prisma/client";
export default async function updateTag(
export default async function updeteTagById(
userId: number,
tagId: number,
data: Tag

View File

@ -17,9 +17,9 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
let PRICE_ID = MONTHLY_PRICE_ID;
if ((Number(req.query.plan) as unknown as Plan) === Plan.monthly)
if ((Number(req.query.plan) as Plan) === Plan.monthly)
PRICE_ID = MONTHLY_PRICE_ID;
else if ((Number(req.query.plan) as unknown as Plan) === Plan.yearly)
else if ((Number(req.query.plan) as Plan) === Plan.yearly)
PRICE_ID = YEARLY_PRICE_ID;
if (req.method === "GET") {

View File

@ -1,6 +1,7 @@
import type { NextApiRequest, NextApiResponse } from "next";
import updateTag from "@/lib/api/controllers/tags/tagId/updeteTagById";
import updeteTagById from "@/lib/api/controllers/tags/tagId/updeteTagById";
import authenticateUser from "@/lib/api/authenticateUser";
import deleteTagById from "@/lib/api/controllers/tags/tagId/deleteTagById";
export default async function tags(req: NextApiRequest, res: NextApiResponse) {
const user = await authenticateUser({ req, res });
@ -9,7 +10,10 @@ export default async function tags(req: NextApiRequest, res: NextApiResponse) {
const tagId = Number(req.query.id);
if (req.method === "PUT") {
const tags = await updateTag(user.id, tagId, req.body);
const tags = await updeteTagById(user.id, tagId, req.body);
return res.status(tags.status).json({ response: tags.response });
} else if (req.method === "DELETE") {
const tags = await deleteTagById(user.id, tagId);
return res.status(tags.status).json({ response: tags.response });
}
}

View File

@ -32,7 +32,7 @@ export default function Links() {
</p>
<p className="capitalize text-black dark:text-white">
All Links from every Collections
Links from every Collections
</p>
</div>
</div>

View File

@ -87,19 +87,19 @@ export default function Account() {
if (response.ok) {
toast.success("Settings Applied!");
if (user.email !== account.email) {
update({
id: data?.user.id,
});
// if (user.email !== account.email) {
// update({
// id: data?.user.id,
// });
signOut();
} else if (
user.username !== account.username ||
user.name !== account.name
)
update({
id: data?.user.id,
});
// signOut();
// } else if (
// user.username !== account.username ||
// user.name !== account.name
// )
// update({
// id: data?.user.id,
// });
} else toast.error(response.data as string);
setSubmitLoader(false);
};
@ -172,18 +172,14 @@ export default function Account() {
<div className="grid sm:grid-cols-2 gap-3 auto-rows-auto">
<div className="flex flex-col gap-3">
<div>
<p className="text-sm text-black dark:text-white mb-2">
Display Name
</p>
<p className="text-black dark:text-white mb-2">Display Name</p>
<TextInput
value={user.name || ""}
onChange={(e) => setUser({ ...user, name: e.target.value })}
/>
</div>
<div>
<p className="text-sm text-black dark:text-white mb-2">
Username
</p>
<p className="text-black dark:text-white mb-2">Username</p>
<TextInput
value={user.username || ""}
onChange={(e) => setUser({ ...user, username: e.target.value })}
@ -192,23 +188,23 @@ export default function Account() {
{emailEnabled ? (
<div>
<p className="text-sm text-black dark:text-white mb-2">Email</p>
<p className="text-black dark:text-white mb-2">Email</p>
{user.email !== account.email &&
process.env.NEXT_PUBLIC_STRIPE_IS_ACTIVE === "true" ? (
<p className="text-gray-500 dark:text-gray-400 mb-2 text-sm">
Updating this field will change your billing email as well
</p>
) : undefined}
<TextInput
value={user.email || ""}
onChange={(e) => setUser({ ...user, email: e.target.value })}
/>
</div>
) : undefined}
{user.email !== account.email ? (
<p className="text-gray-500 dark:text-gray-400">
You will need to log back in after you apply this Email.
</p>
) : undefined}
</div>
<div className="sm:row-span-2 sm:justify-self-center mx-auto my-3">
<p className="text-sm text-black dark:text-white mb-2 text-center">
<p className="text-black dark:text-white mb-2 text-center">
Profile Photo
</p>
<div className="w-28 h-28 flex items-center justify-center rounded-full relative">
@ -258,7 +254,7 @@ export default function Account() {
<div className="flex gap-3 flex-col">
<div>
<p className="text-sm text-black dark:text-white mb-2">
<p className="text-black dark:text-white mb-2">
Import your data from other platforms.
</p>
<div
@ -323,7 +319,7 @@ export default function Account() {
</div>
<div>
<p className="text-sm text-black dark:text-white mb-2">
<p className="text-black dark:text-white mb-2">
Download your data instantly.
</p>
<Link className="w-fit" href="/api/v1/migration">
@ -347,7 +343,6 @@ export default function Account() {
<Checkbox
label="Make profile private"
state={user.isPrivate}
className="text-sm sm:text-base"
onClick={() => setUser({ ...user, isPrivate: !user.isPrivate })}
/>
@ -357,7 +352,7 @@ export default function Account() {
{user.isPrivate && (
<div>
<p className="text-sm text-black dark:text-white mt-2">
<p className="text-black dark:text-white mt-2">
Whitelisted Users
</p>
<p className="text-gray-500 dark:text-gray-300 text-sm mb-3">

View File

@ -8,7 +8,7 @@ export default function Appearance() {
return (
<SettingsLayout>
<p className="mb-3 text-sm">Select Theme</p>
<p className="mb-3">Select Theme</p>
<div className="flex gap-3 w-full">
<div
className={`w-full text-center outline-solid outline-sky-100 outline dark:outline-neutral-700 h-40 duration-100 rounded-md flex items-center justify-center cursor-pointer select-none bg-black ${

View File

@ -79,7 +79,7 @@ export default function Password() {
</p>
<div>
<p className="text-sm mb-2 text-black dark:text-white">
<p className="mb-2 text-black dark:text-white">
Confirm Your Password
</p>

View File

@ -51,7 +51,7 @@ export default function Password() {
should be at least 8 characters.
</p>
<div className="w-full flex flex-col gap-2 justify-between">
<p className="text-sm text-black dark:text-white">New Password</p>
<p className="text-black dark:text-white">New Password</p>
<TextInput
value={newPassword}
@ -60,9 +60,7 @@ export default function Password() {
type="password"
/>
<p className="text-sm text-black dark:text-white">
Confirm New Password
</p>
<p className="text-black dark:text-white">Confirm New Password</p>
<TextInput
value={newPassword2}

View File

@ -23,7 +23,7 @@ export default function Index() {
const router = useRouter();
const { links } = useLinkStore();
const { tags, updateTag } = useTagStore();
const { tags, updateTag, removeTag } = useTagStore();
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
@ -81,6 +81,25 @@ export default function Index() {
setRenameTag(false);
};
const remove = async () => {
setSubmitLoader(true);
const load = toast.loading("Applying...");
let response;
if (activeTag?.id) response = await removeTag(activeTag?.id);
toast.dismiss(load);
if (response?.ok) {
toast.success("Tag Removed.");
router.push("/links");
} else toast.error(response?.data as string);
setSubmitLoader(false);
setRenameTag(false);
};
return (
<MainLayout>
<div className="p-5 flex flex-col gap-5 w-full">
@ -153,6 +172,13 @@ export default function Index() {
setExpandDropdown(false);
},
},
{
name: "Remove Tag",
onClick: () => {
remove();
setExpandDropdown(false);
},
},
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;

View File

@ -10,6 +10,7 @@ type TagStore = {
tags: Tag[];
setTags: () => void;
updateTag: (tag: Tag) => Promise<ResponseObject>;
removeTag: (tagId: number) => Promise<ResponseObject>;
};
const useTagStore = create<TagStore>()((set) => ({
@ -42,6 +43,20 @@ const useTagStore = create<TagStore>()((set) => ({
return { ok: response.ok, data: data.response };
},
removeTag: async (tagId) => {
const response = await fetch(`/api/v1/tags/${tagId}`, {
method: "DELETE",
});
if (response.ok) {
set((state) => ({
tags: state.tags.filter((e) => e.id !== tagId),
}));
}
const data = await response.json();
return { ok: response.ok, data: data.response };
},
}));
export default useTagStore;