added new api route + fixed dropdown

This commit is contained in:
daniel31x13 2023-10-29 00:57:24 -04:00
parent 2856e23a4a
commit 16024f40be
12 changed files with 348 additions and 203 deletions

View File

@ -96,7 +96,6 @@ Here are the other ways to support/cheer this project:
- Starring this repository. - Starring this repository.
- Joining us on [Discord](https://discord.com/invite/CtuYV47nuJ). - Joining us on [Discord](https://discord.com/invite/CtuYV47nuJ).
- Following @daniel31x13 on [Mastodon](https://mastodon.social/@daniel31x13), [Twitter](https://twitter.com/daniel31x13) and [GitHub](https://github.com/daniel31x13).
- Referring Linkwarden to a friend. - Referring Linkwarden to a friend.
If you did any of the above, Thanksss! Otherwise thanks. If you did any of the above, Thanksss! Otherwise thanks.

View File

@ -15,6 +15,13 @@ type Props = {
className?: string; className?: string;
}; };
type DropdownTrigger =
| {
x: number;
y: number;
}
| false;
export default function CollectionCard({ collection, className }: Props) { export default function CollectionCard({ collection, className }: Props) {
const { setModal } = useModalStore(); const { setModal } = useModalStore();
@ -29,11 +36,12 @@ export default function CollectionCard({ collection, className }: Props) {
} }
); );
const [expandDropdown, setExpandDropdown] = useState(false); const [expandDropdown, setExpandDropdown] = useState<DropdownTrigger>(false);
const permissions = usePermissions(collection.id as number); const permissions = usePermissions(collection.id as number);
return ( return (
<>
<div <div
style={{ style={{
backgroundImage: `linear-gradient(45deg, ${collection.color}30 10%, ${ backgroundImage: `linear-gradient(45deg, ${collection.color}30 10%, ${
@ -45,7 +53,7 @@ export default function CollectionCard({ collection, className }: Props) {
}`} }`}
> >
<div <div
onClick={() => setExpandDropdown(!expandDropdown)} onClick={(e) => setExpandDropdown({ x: e.clientX, y: e.clientY })}
id={"expand-dropdown" + collection.id} id={"expand-dropdown" + collection.id}
className="inline-flex absolute top-5 right-5 rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1" className="inline-flex absolute top-5 right-5 rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1"
> >
@ -104,8 +112,10 @@ export default function CollectionCard({ collection, className }: Props) {
</div> </div>
</div> </div>
</Link> </Link>
</div>
{expandDropdown ? ( {expandDropdown ? (
<Dropdown <Dropdown
points={{ x: expandDropdown.x, y: expandDropdown.y }}
items={[ items={[
permissions === true permissions === true
? { ? {
@ -161,9 +171,9 @@ export default function CollectionCard({ collection, className }: Props) {
if (target.id !== "expand-dropdown" + collection.id) if (target.id !== "expand-dropdown" + collection.id)
setExpandDropdown(false); setExpandDropdown(false);
}} }}
className="absolute top-[3.2rem] right-5 z-10 w-fit" className="w-fit"
/> />
) : null} ) : null}
</div> </>
); );
} }

View File

@ -19,9 +19,9 @@ type Props = {
onClickOutside: Function; onClickOutside: Function;
className?: string; className?: string;
items: MenuItem[]; items: MenuItem[];
points: { x: number; y: number }; points?: { x: number; y: number };
style?: React.CSSProperties; style?: React.CSSProperties;
width: number; // in rem width?: number; // in rem
}; };
export default function Dropdown({ export default function Dropdown({
@ -33,6 +33,7 @@ export default function Dropdown({
}: Props) { }: Props) {
const [pos, setPos] = useState<{ x: number; y: number }>(); const [pos, setPos] = useState<{ x: number; y: number }>();
const [dropdownHeight, setDropdownHeight] = useState<number>(); const [dropdownHeight, setDropdownHeight] = useState<number>();
const [dropdownWidth, setDropdownWidth] = useState<number>();
function convertRemToPixels(rem: number) { function convertRemToPixels(rem: number) {
return ( return (
@ -41,48 +42,46 @@ export default function Dropdown({
} }
useEffect(() => { useEffect(() => {
const dropdownWidth = convertRemToPixels(width); if (points) {
let finalX = points.x; let finalX = points.x;
let finalY = points.y; let finalY = points.y;
// Check for x-axis overflow (left side) // Check for x-axis overflow (left side)
if (points.x + dropdownWidth > window.innerWidth) { if (dropdownWidth && points.x + dropdownWidth > window.innerWidth) {
finalX = points.x - dropdownWidth; finalX = points.x - dropdownWidth;
} }
// Check for y-axis overflow (bottom side) // Check for y-axis overflow (bottom side)
if (dropdownHeight && points.y + dropdownHeight > window.innerHeight) { if (dropdownHeight && points.y + dropdownHeight > window.innerHeight) {
finalY = finalY =
window.innerHeight - (dropdownHeight + (window.innerHeight - points.y)); window.innerHeight -
(dropdownHeight + (window.innerHeight - points.y));
} }
setPos({ x: finalX, y: finalY }); setPos({ x: finalX, y: finalY });
}
}, [points, width, dropdownHeight]); }, [points, width, dropdownHeight]);
useEffect(() => {
const dropdownWidth = convertRemToPixels(width);
if (points.x + dropdownWidth > window.innerWidth) {
setPos({ x: points.x - dropdownWidth, y: points.y });
} else setPos(points);
}, [points, width]);
return ( return (
pos && ( (!points || pos) && (
<ClickAwayHandler <ClickAwayHandler
onMount={(e) => { onMount={(e) => {
setDropdownHeight(e.height); setDropdownHeight(e.height);
setDropdownWidth(e.width);
}} }}
style={{ style={
points
? {
position: "fixed", position: "fixed",
top: `${pos?.y}px`, top: `${pos?.y}px`,
left: `${pos?.x}px`, left: `${pos?.x}px`,
}} }
: undefined
}
onClickOutside={onClickOutside} onClickOutside={onClickOutside}
className={`${ className={`${
className || "" className || ""
} py-1 shadow-md border border-sky-100 dark:border-neutral-700 bg-gray-50 dark:bg-neutral-800 rounded-md flex flex-col z-20 w-[${width}rem]`} } py-1 shadow-md border border-sky-100 dark:border-neutral-700 bg-gray-50 dark:bg-neutral-800 rounded-md flex flex-col z-20`}
> >
{items.map((e, i) => { {items.map((e, i) => {
const inner = e && ( const inner = e && (

View File

@ -71,7 +71,7 @@ export default function LinkCard({ link, count, className }: Props) {
); );
}, [collections, links]); }, [collections, links]);
const { removeLink, updateLink } = useLinkStore(); const { removeLink, updateLink, getLink } = useLinkStore();
const pinLink = async () => { const pinLink = async () => {
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0]; const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0];
@ -92,7 +92,7 @@ export default function LinkCard({ link, count, className }: Props) {
}; };
const updateArchive = async () => { const updateArchive = async () => {
const load = toast.loading("Applying..."); const load = toast.loading("Sending request...");
setExpandDropdown(false); setExpandDropdown(false);
@ -104,8 +104,10 @@ export default function LinkCard({ link, count, className }: Props) {
toast.dismiss(load); toast.dismiss(load);
if (response.ok) toast.success(`Link is being archived.`); if (response.ok) {
else toast.error(data); toast.success(`Link is being archived...`);
getLink(link.id as number);
} else toast.error(data);
}; };
const deleteLink = async () => { const deleteLink = async () => {
@ -131,6 +133,7 @@ export default function LinkCard({ link, count, className }: Props) {
); );
return ( return (
<>
<div <div
className={`h-fit border border-solid border-sky-100 dark:border-neutral-700 bg-gradient-to-tr from-slate-200 dark:from-neutral-800 from-10% to-gray-50 dark:to-[#303030] via-20% shadow hover:shadow-none duration-100 rounded-2xl relative group ${ className={`h-fit border border-solid border-sky-100 dark:border-neutral-700 bg-gradient-to-tr from-slate-200 dark:from-neutral-800 from-10% to-gray-50 dark:to-[#303030] via-20% shadow hover:shadow-none duration-100 rounded-2xl relative group ${
className || "" className || ""
@ -227,6 +230,7 @@ export default function LinkCard({ link, count, className }: Props) {
</div> </div>
</div> </div>
</div> </div>
</div>
{expandDropdown ? ( {expandDropdown ? (
<Dropdown <Dropdown
points={{ x: expandDropdown.x, y: expandDropdown.y }} points={{ x: expandDropdown.x, y: expandDropdown.y }}
@ -275,9 +279,9 @@ export default function LinkCard({ link, count, className }: Props) {
if (target.id !== "expand-dropdown" + link.id) if (target.id !== "expand-dropdown" + link.id)
setExpandDropdown(false); setExpandDropdown(false);
}} }}
width={10} className="w-40"
/> />
) : null} ) : null}
</div> </>
); );
} }

View File

@ -23,15 +23,49 @@ import {
import isValidUrl from "@/lib/client/isValidUrl"; import isValidUrl from "@/lib/client/isValidUrl";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import unescapeString from "@/lib/client/unescapeString"; import unescapeString from "@/lib/client/unescapeString";
import useLinkStore from "@/store/links";
type Props = { type Props = {
link: LinkIncludingShortenedCollectionAndTags; linkId: number;
isOwnerOrMod: boolean; isOwnerOrMod: boolean;
}; };
export default function LinkDetails({ link, isOwnerOrMod }: Props) { export default function LinkDetails({ linkId, isOwnerOrMod }: Props) {
const { theme } = useTheme(); 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 [imageError, setImageError] = useState<boolean>(false);
const formattedDate = new Date(link.createdAt as string).toLocaleString( const formattedDate = new Date(link.createdAt as string).toLocaleString(
"en-US", "en-US",
@ -59,6 +93,14 @@ export default function LinkDetails({ link, isOwnerOrMod }: Props) {
); );
}, [collections]); }, [collections]);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections]);
const [colorPalette, setColorPalette] = useState<RGBColor[]>(); const [colorPalette, setColorPalette] = useState<RGBColor[]>();
const colorThief = new ColorThief(); const colorThief = new ColorThief();

View File

@ -64,7 +64,10 @@ export default function LinkModal({
<Tab.Panels> <Tab.Panels>
{activeLink && method === "UPDATE" && ( {activeLink && method === "UPDATE" && (
<Tab.Panel> <Tab.Panel>
<LinkDetails link={activeLink} isOwnerOrMod={isOwnerOrMod} /> <LinkDetails
linkId={activeLink.id as number}
isOwnerOrMod={isOwnerOrMod}
/>
</Tab.Panel> </Tab.Panel>
)} )}
@ -73,7 +76,9 @@ export default function LinkModal({
<AddOrEditLink <AddOrEditLink
toggleLinkModal={toggleLinkModal} toggleLinkModal={toggleLinkModal}
method="UPDATE" method="UPDATE"
activeLink={activeLink} activeLink={
activeLink as LinkIncludingShortenedCollectionAndTags
}
/> />
) : ( ) : (
<AddOrEditLink <AddOrEditLink

View File

@ -21,7 +21,7 @@ export default function SortDropdown({
const target = e.target as HTMLInputElement; const target = e.target as HTMLInputElement;
if (target.id !== "sort-dropdown") toggleSortDropdown(); if (target.id !== "sort-dropdown") toggleSortDropdown();
}} }}
className="absolute top-8 right-0 border border-sky-100 dark:border-neutral-700 shadow-md bg-gray-50 dark:bg-neutral-800 rounded-md p-2 z-20 w-48" className="absolute top-8 right-0 border border-sky-100 dark:border-neutral-700 shadow-md bg-gray-50 dark:bg-neutral-800 rounded-md p-2 z-20 w-52"
> >
<p className="mb-2 text-black dark:text-white text-center font-semibold"> <p className="mb-2 text-black dark:text-white text-center font-semibold">
Sort by Sort by

View File

@ -14,13 +14,29 @@ export default async function archive(
}, },
}); });
// const checkExistingLink = await prisma.link.findFirst({
// where: {
// id: linkId,
// OR: [
// {
// screenshotPath: "pending",
// },
// {
// pdfPath: "pending",
// },
// ],
// },
// });
// if (checkExistingLink) return "A request has already been made.";
const link = await prisma.link.update({ const link = await prisma.link.update({
where: { where: {
id: linkId, id: linkId,
}, },
data: { data: {
screenshotPath: "pending", screenshotPath: user?.archiveAsScreenshot ? "pending" : null,
pdfPath: "pending", pdfPath: user?.archiveAsPDF ? "pending" : null,
}, },
}); });
@ -88,8 +104,8 @@ export default async function archive(
await browser.close(); await browser.close();
} catch (err) { } catch (err) {
console.log(err);
await browser.close(); await browser.close();
return err;
} }
} }
} }

View File

@ -0,0 +1,48 @@
import { prisma } from "@/lib/api/db";
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
export default async function getLinkById(userId: number, linkId: number) {
if (!linkId)
return {
response: "Please choose a valid link.",
status: 401,
};
const collectionIsAccessible = (await getPermission({ userId, linkId })) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canUpdate
);
const isCollectionOwner = collectionIsAccessible?.ownerId === userId;
if (collectionIsAccessible?.ownerId !== userId && !memberHasAccess)
return {
response: "Collection is not accessible.",
status: 401,
};
else {
const updatedLink = await prisma.link.findUnique({
where: {
id: linkId,
},
include: {
tags: true,
collection: true,
pinnedBy: isCollectionOwner
? {
where: { id: userId },
select: { id: true },
}
: undefined,
},
});
return { response: updatedLink, status: 200 };
}
}

View File

@ -4,7 +4,7 @@ import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
import moveFile from "@/lib/api/storage/moveFile"; import moveFile from "@/lib/api/storage/moveFile";
export default async function updateLink( export default async function updateLinkById(
userId: number, userId: number,
linkId: number, linkId: number,
data: LinkIncludingShortenedCollectionAndTags data: LinkIncludingShortenedCollectionAndTags

View File

@ -3,6 +3,7 @@ import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/v1/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import deleteLinkById from "@/lib/api/controllers/links/linkId/deleteLinkById"; import deleteLinkById from "@/lib/api/controllers/links/linkId/deleteLinkById";
import updateLinkById from "@/lib/api/controllers/links/linkId/updateLinkById"; import updateLinkById from "@/lib/api/controllers/links/linkId/updateLinkById";
import getLinkById from "@/lib/api/controllers/links/linkId/getLinkById";
export default async function links(req: NextApiRequest, res: NextApiResponse) { export default async function links(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions); const session = await getServerSession(req, res, authOptions);
@ -15,7 +16,12 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.", "You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
}); });
if (req.method === "PUT") { if (req.method === "GET") {
const updated = await getLinkById(session.user.id, Number(req.query.id));
return res.status(updated.status).json({
response: updated.response,
});
} else if (req.method === "PUT") {
const updated = await updateLinkById( const updated = await updateLinkById(
session.user.id, session.user.id,
Number(req.query.id), Number(req.query.id),

View File

@ -17,6 +17,7 @@ type LinkStore = {
addLink: ( addLink: (
body: LinkIncludingShortenedCollectionAndTags body: LinkIncludingShortenedCollectionAndTags
) => Promise<ResponseObject>; ) => Promise<ResponseObject>;
getLink: (linkId: number) => Promise<ResponseObject>;
updateLink: ( updateLink: (
link: LinkIncludingShortenedCollectionAndTags link: LinkIncludingShortenedCollectionAndTags
) => Promise<ResponseObject>; ) => Promise<ResponseObject>;
@ -65,6 +66,21 @@ const useLinkStore = create<LinkStore>()((set) => ({
return { ok: response.ok, data: data.response }; return { ok: response.ok, data: data.response };
}, },
getLink: async (linkId) => {
const response = await fetch(`/api/v1/links/${linkId}`);
const data = await response.json();
if (response.ok) {
set((state) => ({
links: state.links.map((e) =>
e.id === data.response.id ? data.response : e
),
}));
}
return { ok: response.ok, data: data.response };
},
updateLink: async (link) => { updateLink: async (link) => {
const response = await fetch(`/api/v1/links/${link.id}`, { const response = await fetch(`/api/v1/links/${link.id}`, {
body: JSON.stringify(link), body: JSON.stringify(link),