added cursor based pagination for links

This commit is contained in:
Daniel 2023-06-15 02:04:54 +03:30
parent 6323badbaf
commit 1b6d902c75
29 changed files with 507 additions and 182 deletions

View File

@ -1,4 +1,4 @@
AES_SECRET=very_sensitive_secret1
NEXTAUTH_SECRET=very_sensitive_secret2 NEXTAUTH_SECRET=very_sensitive_secret2
DATABASE_URL=postgresql://user:password@localhost:5432/linkwarden DATABASE_URL=postgresql://user:password@localhost:5432/linkwarden
NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_URL=http://localhost:3000
PAGINATION_TAKE_COUNT=20

View File

@ -1,6 +1,6 @@
import { import {
CollectionIncludingMembers, CollectionIncludingMembers,
LinkIncludingCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import { import {
faFolder, faFolder,
@ -20,7 +20,7 @@ import useAccountStore from "@/store/account";
import useModalStore from "@/store/modals"; import useModalStore from "@/store/modals";
type Props = { type Props = {
link: LinkIncludingCollectionAndTags; link: LinkIncludingShortenedCollectionAndTags;
count: number; count: number;
className?: string; className?: string;
}; };
@ -146,7 +146,7 @@ export default function LinkCard({ link, count, className }: Props) {
className="group/url" className="group/url"
> >
<div className="text-sky-400 font-bold flex items-center gap-1"> <div className="text-sky-400 font-bold flex items-center gap-1">
<p className="truncate max-w-[10rem]">{url.host}</p> <p className="truncate max-w-[12rem]">{url.host}</p>
<FontAwesomeIcon <FontAwesomeIcon
icon={faArrowUpRightFromSquare} icon={faArrowUpRightFromSquare}
className="w-3 opacity-0 group-hover/url:opacity-100 duration-75" className="w-3 opacity-0 group-hover/url:opacity-100 duration-75"

View File

@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import CollectionSelection from "@/components/InputSelect/CollectionSelection"; import CollectionSelection from "@/components/InputSelect/CollectionSelection";
import TagSelection from "@/components/InputSelect/TagSelection"; import TagSelection from "@/components/InputSelect/TagSelection";
import { LinkIncludingCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { faPenToSquare } from "@fortawesome/free-regular-svg-icons"; import { faPenToSquare } from "@fortawesome/free-regular-svg-icons";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import { faPlus } from "@fortawesome/free-solid-svg-icons"; import { faPlus } from "@fortawesome/free-solid-svg-icons";
@ -15,12 +15,12 @@ type Props =
| { | {
toggleLinkModal: Function; toggleLinkModal: Function;
method: "CREATE"; method: "CREATE";
activeLink?: LinkIncludingCollectionAndTags; activeLink?: LinkIncludingShortenedCollectionAndTags;
} }
| { | {
toggleLinkModal: Function; toggleLinkModal: Function;
method: "UPDATE"; method: "UPDATE";
activeLink: LinkIncludingCollectionAndTags; activeLink: LinkIncludingShortenedCollectionAndTags;
}; };
export default function EditLink({ export default function EditLink({
@ -30,7 +30,7 @@ export default function EditLink({
}: Props) { }: Props) {
const { data } = useSession(); const { data } = useSession();
const [link, setLink] = useState<LinkIncludingCollectionAndTags>( const [link, setLink] = useState<LinkIncludingShortenedCollectionAndTags>(
method === "UPDATE" method === "UPDATE"
? activeLink ? activeLink
: { : {

View File

@ -4,7 +4,7 @@ import LinkModal from "./Modal/LinkModal";
import { import {
AccountSettings, AccountSettings,
CollectionIncludingMembers, CollectionIncludingMembers,
LinkIncludingCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import CollectionModal from "./Modal/Collection"; import CollectionModal from "./Modal/Collection";
import UserModal from "./Modal/User"; import UserModal from "./Modal/User";
@ -22,7 +22,7 @@ export default function ModalManagement() {
<LinkModal <LinkModal
toggleLinkModal={toggleModal} toggleLinkModal={toggleModal}
method={modal.method} method={modal.method}
activeLink={modal.active as LinkIncludingCollectionAndTags} activeLink={modal.active as LinkIncludingShortenedCollectionAndTags}
/> />
</Modal> </Modal>
); );

View File

@ -4,10 +4,14 @@ import {
} from "@fortawesome/free-solid-svg-icons"; } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Image from "next/image"; import Image from "next/image";
import { Link as LinkType } from "@prisma/client"; import { Link as LinkType, Tag } from "@prisma/client";
interface LinksIncludingTags extends LinkType {
tags: Tag[];
}
type Props = { type Props = {
link: LinkType; link: LinksIncludingTags;
count: number; count: number;
}; };
@ -58,7 +62,18 @@ export default function LinkCard({ link, count }: Props) {
<p className="text-gray-500 text-sm font-medium"> <p className="text-gray-500 text-sm font-medium">
{link.description} {link.description}
</p> </p>
<div className="flex gap-3 items-center flex-wrap my-3">
<div className="flex gap-1 items-center flex-wrap mt-1">
{link.tags.map((e, i) => (
<p
key={i}
className="px-2 py-1 bg-sky-200 text-sky-700 text-xs rounded-3xl cursor-pointer truncate max-w-[10rem]"
>
{e.name}
</p>
))}
</div>
</div>
<div className="flex gap-2 items-center flex-wrap mt-2"> <div className="flex gap-2 items-center flex-wrap mt-2">
<p className="text-gray-500">{formattedDate}</p> <p className="text-gray-500">{formattedDate}</p>
<div className="text-sky-400 font-bold flex items-center gap-1"> <div className="text-sky-400 font-bold flex items-center gap-1">

View File

@ -25,6 +25,18 @@ export default function SortDropdown({
> >
<p className="mb-2 text-sky-900 text-center font-semibold">Sort by</p> <p className="mb-2 text-sky-900 text-center font-semibold">Sort by</p>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<RadioButton
label="Date (Newest First)"
state={sortBy === Sort.DateNewestFirst}
onClick={() => setSort(Sort.DateNewestFirst)}
/>
<RadioButton
label="Date (Oldest First)"
state={sortBy === Sort.DateOldestFirst}
onClick={() => setSort(Sort.DateOldestFirst)}
/>
<RadioButton <RadioButton
label="Name (A-Z)" label="Name (A-Z)"
state={sortBy === Sort.NameAZ} state={sortBy === Sort.NameAZ}
@ -48,18 +60,6 @@ export default function SortDropdown({
state={sortBy === Sort.DescriptionZA} state={sortBy === Sort.DescriptionZA}
onClick={() => setSort(Sort.DescriptionZA)} onClick={() => setSort(Sort.DescriptionZA)}
/> />
<RadioButton
label="Date (Newest First)"
state={sortBy === Sort.DateNewestFirst}
onClick={() => setSort(Sort.DateNewestFirst)}
/>
<RadioButton
label="Date (Oldest First)"
state={sortBy === Sort.DateOldestFirst}
onClick={() => setSort(Sort.DateOldestFirst)}
/>
</div> </div>
</ClickAwayHandler> </ClickAwayHandler>
); );

View File

@ -0,0 +1,25 @@
import { useState, useEffect } from "react";
const useDetectPageBottom = () => {
const [reachedBottom, setReachedBottom] = useState<boolean>(false);
useEffect(() => {
const handleScroll = () => {
const offsetHeight = document.documentElement.offsetHeight;
const innerHeight = window.innerHeight;
const scrollTop = document.documentElement.scrollTop;
const hasReachedBottom = offsetHeight - (innerHeight + scrollTop) <= 100;
setReachedBottom(hasReachedBottom);
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return reachedBottom;
};
export default useDetectPageBottom;

View File

@ -9,14 +9,14 @@ export default function useInitialData() {
const { status, data } = useSession(); const { status, data } = useSession();
const { setCollections } = useCollectionStore(); const { setCollections } = useCollectionStore();
const { setTags } = useTagStore(); const { setTags } = useTagStore();
const { setLinks } = useLinkStore(); // const { setLinks } = useLinkStore();
const { setAccount } = useAccountStore(); const { setAccount } = useAccountStore();
useEffect(() => { useEffect(() => {
if (status === "authenticated") { if (status === "authenticated") {
setCollections(); setCollections();
setTags(); setTags();
setLinks(); // setLinks();
setAccount(data.user.email as string); setAccount(data.user.email as string);
} }
}, [status]); }, [status]);

58
hooks/useLinks.tsx Normal file
View File

@ -0,0 +1,58 @@
import { LinkRequestQuery } from "@/types/global";
import { useEffect } from "react";
import useDetectPageBottom from "./useDetectPageBottom";
import { useRouter } from "next/router";
import useLinkStore from "@/store/links";
export default function useLinks({
sort,
searchFilter,
searchQuery,
pinnedOnly,
collectionId,
tagId,
}: Omit<LinkRequestQuery, "cursor"> = {}) {
const { links, setLinks, resetLinks } = useLinkStore();
const router = useRouter();
const hasReachedBottom = useDetectPageBottom();
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
const response = await fetch(
`/api/routes/links?cursor=${cursor}${
(sort ? "&sort=" + sort : "") +
(searchQuery && searchFilter
? "&searchQuery=" +
searchQuery +
"&searchFilter=" +
searchFilter.name +
"-" +
searchFilter.url +
"-" +
searchFilter.description +
"-" +
searchFilter.collection +
"-" +
searchFilter.tags
: "") +
(collectionId ? "&collectionId=" + collectionId : "") +
(tagId ? "&tagId=" + tagId : "") +
(pinnedOnly ? "&pinnedOnly=" + pinnedOnly : "")
}`
);
const data = await response.json();
if (response.ok) setLinks(data.response, isInitialCall);
};
useEffect(() => {
resetLinks();
getLinks(true);
}, [router, sort, searchFilter]);
useEffect(() => {
if (hasReachedBottom) getLinks(false, links?.at(-1)?.id);
}, [hasReachedBottom]);
}

View File

@ -1,12 +1,12 @@
import { import {
CollectionIncludingMembers, CollectionIncludingMembers,
LinkIncludingCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
Sort, Sort,
} from "@/types/global"; } from "@/types/global";
import { SetStateAction, useEffect } from "react"; import { SetStateAction, useEffect } from "react";
type Props< type Props<
T extends CollectionIncludingMembers | LinkIncludingCollectionAndTags T extends CollectionIncludingMembers | LinkIncludingShortenedCollectionAndTags
> = { > = {
sortBy: Sort; sortBy: Sort;
@ -15,7 +15,7 @@ type Props<
}; };
export default function useSort< export default function useSort<
T extends CollectionIncludingMembers | LinkIncludingCollectionAndTags T extends CollectionIncludingMembers | LinkIncludingShortenedCollectionAndTags
>({ sortBy, data, setData }: Props<T>) { >({ sortBy, data, setData }: Props<T>) {
useEffect(() => { useEffect(() => {
const dataArray = [...data]; const dataArray = [...data];

View File

@ -1,11 +1,11 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkIncludingCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import fs from "fs"; import fs from "fs";
import { Link, UsersAndCollections } from "@prisma/client"; import { Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
export default async function deleteLink( export default async function deleteLink(
link: LinkIncludingCollectionAndTags, link: LinkIncludingShortenedCollectionAndTags,
userId: number userId: number
) { ) {
if (!link || !link.collectionId) if (!link || !link.collectionId)

View File

@ -1,8 +1,99 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
export default async function getLink(userId: number) { import { LinkRequestQuery, LinkSearchFilter, Sort } from "@/types/global";
const links = await prisma.link.findMany({
export default async function getLink(userId: number, query: LinkRequestQuery) {
query.sort = Number(query.sort) || 0;
query.pinnedOnly = query.pinnedOnly
? JSON.parse(query.pinnedOnly as unknown as string)
: undefined;
if (query.searchFilter) {
const filterParams = (query.searchFilter as unknown as string).split("-");
query.searchFilter = {} as LinkSearchFilter;
query.searchFilter.name = JSON.parse(filterParams[0]);
query.searchFilter.url = JSON.parse(filterParams[1]);
query.searchFilter.description = JSON.parse(filterParams[2]);
query.searchFilter.collection = JSON.parse(filterParams[3]);
query.searchFilter.tags = JSON.parse(filterParams[4]);
}
console.log(query.searchFilter);
// Sorting logic
let order: any;
if (query.sort === Sort.DateNewestFirst)
order = {
createdAt: "desc",
};
else if (query.sort === Sort.DateOldestFirst)
order = {
createdAt: "asc",
};
else if (query.sort === Sort.NameAZ)
order = {
name: "asc",
};
else if (query.sort === Sort.NameZA)
order = {
name: "desc",
};
else if (query.sort === Sort.DescriptionAZ)
order = {
name: "asc",
};
else if (query.sort === Sort.DescriptionZA)
order = {
name: "desc",
};
const links =
// Searching logic
query.searchFilter && query.searchQuery
? await prisma.link.findMany({
take: Number(process.env.PAGINATION_TAKE_COUNT),
skip: query.cursor !== "undefined" ? 1 : undefined,
cursor:
query.cursor !== "undefined"
? {
id: Number(query.cursor),
}
: undefined,
where: { where: {
OR: [
{
name: {
contains: query.searchFilter?.name
? query.searchQuery
: undefined,
mode: "insensitive",
},
},
{
url: {
contains: query.searchFilter?.url
? query.searchQuery
: undefined,
mode: "insensitive",
},
},
{
description: {
contains: query.searchFilter?.description
? query.searchQuery
: undefined,
mode: "insensitive",
},
},
{
collection: { collection: {
name: {
contains: query.searchFilter?.collection
? query.searchQuery
: undefined,
mode: "insensitive",
},
OR: [ OR: [
{ {
ownerId: userId, ownerId: userId,
@ -17,6 +108,43 @@ export default async function getLink(userId: number) {
], ],
}, },
}, },
{
tags: {
// If tagId was defined, search by tag
some: {
name: {
contains: query.searchFilter?.tags
? query.searchQuery
: undefined,
mode: "insensitive",
},
OR: [
{ ownerId: userId }, // Tags owned by the user
{
links: {
some: {
name: {
contains: query.searchFilter?.tags
? query.searchQuery
: undefined,
mode: "insensitive",
},
collection: {
members: {
some: {
userId, // Tags from collections where the user is a member
},
},
},
},
},
},
],
},
},
},
],
},
include: { include: {
tags: true, tags: true,
collection: true, collection: true,
@ -25,6 +153,76 @@ export default async function getLink(userId: number) {
select: { id: true }, select: { id: true },
}, },
}, },
orderBy: order || undefined,
})
: // If not searching
await prisma.link.findMany({
take: Number(process.env.PAGINATION_TAKE_COUNT),
skip: query.cursor !== "undefined" ? 1 : undefined,
cursor:
query.cursor !== "undefined"
? {
id: Number(query.cursor),
}
: undefined,
where: {
pinnedBy: query.pinnedOnly ? { some: { id: userId } } : undefined,
collection: {
id: query.collectionId && Number(query.collectionId), // If collectionId was defined, search by collection
OR: [
{
ownerId: userId,
},
{
members: {
some: {
userId,
},
},
},
],
},
tags: {
some: query.tagId // If tagId was defined, search by tag
? {
id: Number(query.tagId),
OR: [
{ ownerId: userId }, // Tags owned by the user
{
links: {
some: {
collection: {
members: {
some: {
userId, // Tags from collections where the user is a member
},
},
},
},
},
},
],
}
: undefined,
},
},
include: {
tags: true,
collection: {
select: {
id: true,
ownerId: true,
name: true,
color: true,
},
},
pinnedBy: {
where: { id: userId },
select: { id: true },
},
},
orderBy: order || undefined,
}); });
return { response: links, status: 200 }; return { response: links, status: 200 };

View File

@ -1,5 +1,5 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkIncludingCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import getTitle from "../../getTitle"; import getTitle from "../../getTitle";
import archive from "../../archive"; import archive from "../../archive";
import { Link, UsersAndCollections } from "@prisma/client"; import { Link, UsersAndCollections } from "@prisma/client";
@ -7,7 +7,7 @@ import getPermission from "@/lib/api/getPermission";
import { existsSync, mkdirSync } from "fs"; import { existsSync, mkdirSync } from "fs";
export default async function postLink( export default async function postLink(
link: LinkIncludingCollectionAndTags, link: LinkIncludingShortenedCollectionAndTags,
userId: number userId: number
) { ) {
link.collection.name = link.collection.name.trim(); link.collection.name = link.collection.name.trim();

View File

@ -1,10 +1,10 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkIncludingCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { UsersAndCollections } from "@prisma/client"; import { UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
export default async function updateLink( export default async function updateLink(
link: LinkIncludingCollectionAndTags, link: LinkIncludingShortenedCollectionAndTags,
userId: number userId: number
) { ) {
if (!link) return { response: "Please choose a valid link.", status: 401 }; if (!link) return { response: "Please choose a valid link.", status: 401 };

View File

@ -1,35 +1,40 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { PublicLinkRequestQuery } from "@/types/global";
export default async function getCollection(collectionId: number) { export default async function getCollection(query: PublicLinkRequestQuery) {
let data; let data;
const collection = await prisma.collection.findFirst({ const collection = await prisma.collection.findFirst({
where: { where: {
id: collectionId, id: Number(query.collectionId),
isPublic: true, isPublic: true,
}, },
include: {
links: {
select: {
id: true,
name: true,
url: true,
description: true,
collectionId: true,
createdAt: true,
},
},
},
}); });
if (collection) { if (collection) {
const user = await prisma.user.findUnique({ const links = await prisma.link.findMany({
take: Number(process.env.PAGINATION_TAKE_COUNT),
skip: query.cursor !== "undefined" ? 1 : undefined,
cursor:
query.cursor !== "undefined"
? {
id: Number(query.cursor),
}
: undefined,
where: { where: {
id: collection.ownerId, collection: {
id: Number(query.collectionId),
},
},
include: {
tags: true,
},
orderBy: {
createdAt: "desc",
}, },
}); });
data = { ownerName: user?.name, ...collection }; data = { ...collection, links: [...links] };
return { response: data, status: 200 }; return { response: data, status: 200 };
} else { } else {

View File

@ -1,14 +1,26 @@
import { PublicCollectionIncludingLinks } from "@/types/global";
import { Dispatch, SetStateAction } from "react";
const getPublicCollectionData = async ( const getPublicCollectionData = async (
collectionId: string, collectionId: string,
setData?: Function prevData: PublicCollectionIncludingLinks,
setData: Dispatch<SetStateAction<PublicCollectionIncludingLinks | undefined>>
) => { ) => {
const res = await fetch( const res = await fetch(
"/api/public/routes/collections/?collectionId=" + collectionId "/api/public/routes/collections?collectionId=" +
collectionId +
"&cursor=" +
prevData?.links?.at(-1)?.id
); );
const data = await res.json(); const data = await res.json();
if (setData) setData(data.response); prevData
? setData({
...data.response,
links: [...prevData.links, ...data.response.links],
})
: setData(data.response);
return data; return data;
}; };

View File

@ -1,20 +1,21 @@
import getCollection from "@/lib/api/controllers/public/getCollection"; import getCollection from "@/lib/api/controllers/public/getCollection";
import { PublicLinkRequestQuery } from "@/types/global";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
export default async function collections( export default async function collections(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ) {
const collectionId = Number(req.query.collectionId); const query: PublicLinkRequestQuery = req.query;
if (!collectionId) { if (!query) {
return res return res
.status(401) .status(401)
.json({ response: "Please choose a valid collection." }); .json({ response: "Please choose a valid collection." });
} }
if (req.method === "GET") { if (req.method === "GET") {
const collection = await getCollection(collectionId); const collection = await getCollection(query);
return res return res
.status(collection.status) .status(collection.status)
.json({ response: collection.response }); .json({ response: collection.response });

View File

@ -14,7 +14,7 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
} }
if (req.method === "GET") { if (req.method === "GET") {
const links = await getLinks(session.user.id); const links = await getLinks(session.user.id, req.query);
return res.status(links.status).json({ response: links.response }); return res.status(links.status).json({ response: links.response });
} else if (req.method === "POST") { } else if (req.method === "POST") {
const newlink = await postLink(req.body, session.user.id); const newlink = await postLink(req.body, session.user.id);

View File

@ -16,7 +16,7 @@ import { useSession } from "next-auth/react";
import ProfilePhoto from "@/components/ProfilePhoto"; import ProfilePhoto from "@/components/ProfilePhoto";
import SortDropdown from "@/components/SortDropdown"; import SortDropdown from "@/components/SortDropdown";
import useModalStore from "@/store/modals"; import useModalStore from "@/store/modals";
import useSort from "@/hooks/useSort"; import useLinks from "@/hooks/useLinks";
export default function Index() { export default function Index() {
const { setModal } = useModalStore(); const { setModal } = useModalStore();
@ -30,14 +30,12 @@ export default function Index() {
const [expandDropdown, setExpandDropdown] = useState(false); const [expandDropdown, setExpandDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false); const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ); const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [activeCollection, setActiveCollection] = const [activeCollection, setActiveCollection] =
useState<CollectionIncludingMembers>(); useState<CollectionIncludingMembers>();
const [sortedLinks, setSortedLinks] = useState(links); useLinks({ collectionId: Number(router.query.id), sort: sortBy });
useSort({ sortBy, setData: setSortedLinks, data: links });
useEffect(() => { useEffect(() => {
setActiveCollection( setActiveCollection(
@ -223,7 +221,7 @@ export default function Index() {
</div> </div>
</div> </div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5"> <div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
{sortedLinks.map((e, i) => { {links.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />; return <LinkCard key={i} link={e} count={i} />;
})} })}
</div> </div>

View File

@ -20,7 +20,7 @@ export default function Collections() {
const { collections } = useCollectionStore(); const { collections } = useCollectionStore();
const [expandDropdown, setExpandDropdown] = useState(false); const [expandDropdown, setExpandDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false); const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ); const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [sortedCollections, setSortedCollections] = useState(collections); const [sortedCollections, setSortedCollections] = useState(collections);
const session = useSession(); const session = useSession();

View File

@ -12,6 +12,7 @@ import Link from "next/link";
import CollectionCard from "@/components/CollectionCard"; import CollectionCard from "@/components/CollectionCard";
import { Disclosure, Transition } from "@headlessui/react"; import { Disclosure, Transition } from "@headlessui/react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import useLinks from "@/hooks/useLinks";
export default function Dashboard() { export default function Dashboard() {
const { collections } = useCollectionStore(); const { collections } = useCollectionStore();
@ -34,6 +35,8 @@ export default function Dashboard() {
return storedValue ? storedValue === "true" : true; return storedValue ? storedValue === "true" : true;
}); });
useLinks({ pinnedOnly: true });
useEffect(() => { useEffect(() => {
localStorage.setItem( localStorage.setItem(
"tagPinDisclosure", "tagPinDisclosure",
@ -131,9 +134,7 @@ export default function Dashboard() {
leaveTo="transform opacity-0 -translate-y-3" leaveTo="transform opacity-0 -translate-y-3"
> >
<Disclosure.Panel className="flex flex-col gap-5 w-full"> <Disclosure.Panel className="flex flex-col gap-5 w-full">
{links {links.map((e, i) => (
.filter((e) => e.pinnedBy && e.pinnedBy[0])
.map((e, i) => (
<LinkCard key={i} link={e} count={i} /> <LinkCard key={i} link={e} count={i} />
))} ))}
</Disclosure.Panel> </Disclosure.Panel>

View File

@ -1,6 +1,6 @@
import LinkCard from "@/components/LinkCard"; import LinkCard from "@/components/LinkCard";
import SortDropdown from "@/components/SortDropdown"; import SortDropdown from "@/components/SortDropdown";
import useSort from "@/hooks/useSort"; import useLinks from "@/hooks/useLinks";
import MainLayout from "@/layouts/MainLayout"; import MainLayout from "@/layouts/MainLayout";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import { Sort } from "@/types/global"; import { Sort } from "@/types/global";
@ -12,10 +12,9 @@ export default function Links() {
const { links } = useLinkStore(); const { links } = useLinkStore();
const [sortDropdown, setSortDropdown] = useState(false); const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ); const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [sortedLinks, setSortedLinks] = useState(links);
useSort({ sortBy, setData: setSortedLinks, data: links }); useLinks({ sort: sortBy });
return ( return (
<MainLayout> <MainLayout>
@ -54,7 +53,7 @@ export default function Links() {
</div> </div>
</div> </div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5"> <div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
{sortedLinks.map((e, i) => { {links.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />; return <LinkCard key={i} link={e} count={i} />;
})} })}
</div> </div>

View File

@ -1,4 +1,5 @@
import LinkCard from "@/components/PublicPage/LinkCard"; import LinkCard from "@/components/PublicPage/LinkCard";
import useDetectPageBottom from "@/hooks/useDetectPageBottom";
import getPublicCollectionData from "@/lib/client/getPublicCollectionData"; import getPublicCollectionData from "@/lib/client/getPublicCollectionData";
import { PublicCollectionIncludingLinks } from "@/types/global"; import { PublicCollectionIncludingLinks } from "@/types/global";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
@ -6,6 +7,7 @@ import React, { useEffect, useState } from "react";
export default function PublicCollections() { export default function PublicCollections() {
const router = useRouter(); const router = useRouter();
const hasReachedBottom = useDetectPageBottom();
const [data, setData] = useState<PublicCollectionIncludingLinks>(); const [data, setData] = useState<PublicCollectionIncludingLinks>();
@ -13,7 +15,8 @@ export default function PublicCollections() {
if (router.query.id) { if (router.query.id) {
getPublicCollectionData( getPublicCollectionData(
router.query.id as string, router.query.id as string,
(e: PublicCollectionIncludingLinks) => setData(e) data as PublicCollectionIncludingLinks,
setData
); );
} }
@ -27,6 +30,16 @@ export default function PublicCollections() {
// ); // );
}, []); }, []);
useEffect(() => {
if (hasReachedBottom && router.query.id) {
getPublicCollectionData(
router.query.id as string,
data as PublicCollectionIncludingLinks,
setData
);
}
}, [hasReachedBottom]);
return data ? ( return data ? (
<div className="max-w-4xl mx-auto p-5 bg"> <div className="max-w-4xl mx-auto p-5 bg">
<div <div
@ -36,10 +49,6 @@ export default function PublicCollections() {
{data.name} {data.name}
</p> </p>
{data.ownerName && (
<p className="text-sky-500">{"By " + data.ownerName}</p>
)}
<hr className="mt-5 max-w-[30rem] mx-auto border-1 border-slate-400" /> <hr className="mt-5 max-w-[30rem] mx-auto border-1 border-slate-400" />
<p className="mt-2 text-gray-500">{data.description}</p> <p className="mt-2 text-gray-500">{data.description}</p>

View File

@ -1,33 +1,21 @@
import FilterSearchDropdown from "@/components/FilterSearchDropdown"; import FilterSearchDropdown from "@/components/FilterSearchDropdown";
import LinkCard from "@/components/LinkCard"; import LinkCard from "@/components/LinkCard";
import SortDropdown from "@/components/SortDropdown"; import SortDropdown from "@/components/SortDropdown";
import useSort from "@/hooks/useSort"; import useLinks from "@/hooks/useLinks";
import MainLayout from "@/layouts/MainLayout"; import MainLayout from "@/layouts/MainLayout";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import { Sort } from "@/types/global"; import { LinkSearchFilter, Sort } from "@/types/global";
import { faFilter, faSearch, faSort } from "@fortawesome/free-solid-svg-icons"; import { faFilter, faSearch, faSort } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useEffect, useState } from "react"; import { useState } from "react";
type SearchFilter = {
name: boolean;
url: boolean;
description: boolean;
collection: boolean;
tags: boolean;
};
export default function Links() { export default function Links() {
const { links } = useLinkStore(); const { links } = useLinkStore();
const router = useRouter(); const router = useRouter();
const routeQuery = decodeURIComponent( const [searchFilter, setSearchFilter] = useState<LinkSearchFilter>({
router.query.query as string
).toLowerCase();
const [searchFilter, setSearchFilter] = useState<SearchFilter>({
name: true, name: true,
url: true, url: true,
description: true, description: true,
@ -37,32 +25,13 @@ export default function Links() {
const [filterDropdown, setFilterDropdown] = useState(false); const [filterDropdown, setFilterDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false); const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ); const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [filteredLinks, setFilteredLinks] = useState(links); useLinks({
const [sortedLinks, setSortedLinks] = useState(filteredLinks); searchFilter: searchFilter,
searchQuery: router.query.query as string,
useSort({ sortBy, setData: setSortedLinks, data: links }); sort: sortBy,
});
useEffect(() => {
setFilteredLinks([
...sortedLinks.filter((link) => {
if (
(searchFilter.name && link.name.toLowerCase().includes(routeQuery)) ||
(searchFilter.url && link.url.toLowerCase().includes(routeQuery)) ||
(searchFilter.description &&
link.description.toLowerCase().includes(routeQuery)) ||
(searchFilter.collection &&
link.collection.name.toLowerCase().includes(routeQuery)) ||
(searchFilter.tags &&
link.tags.some((tag) =>
tag.name.toLowerCase().includes(routeQuery)
))
)
return true;
}),
]);
}, [searchFilter, sortedLinks, router]);
return ( return (
<MainLayout> <MainLayout>
@ -126,8 +95,8 @@ export default function Links() {
</div> </div>
</div> </div>
</div> </div>
{filteredLinks[0] ? ( {links[0] ? (
filteredLinks.map((e, i) => { links.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />; return <LinkCard key={i} link={e} count={i} />;
}) })
) : ( ) : (

View File

@ -9,7 +9,7 @@ import { Tag } from "@prisma/client";
import useTagStore from "@/store/tags"; import useTagStore from "@/store/tags";
import SortDropdown from "@/components/SortDropdown"; import SortDropdown from "@/components/SortDropdown";
import { Sort } from "@/types/global"; import { Sort } from "@/types/global";
import useSort from "@/hooks/useSort"; import useLinks from "@/hooks/useLinks";
export default function Index() { export default function Index() {
const router = useRouter(); const router = useRouter();
@ -18,13 +18,11 @@ export default function Index() {
const { tags } = useTagStore(); const { tags } = useTagStore();
const [sortDropdown, setSortDropdown] = useState(false); const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ); const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [activeTag, setActiveTag] = useState<Tag>(); const [activeTag, setActiveTag] = useState<Tag>();
const [sortedLinks, setSortedLinks] = useState(links); useLinks({ tagId: Number(router.query.id), sort: sortBy });
useSort({ sortBy, setData: setSortedLinks, data: links });
useEffect(() => { useEffect(() => {
setActiveTag(tags.find((e) => e.id === Number(router.query.id))); setActiveTag(tags.find((e) => e.id === Number(router.query.id)));
@ -69,7 +67,7 @@ export default function Index() {
</div> </div>
</div> </div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5"> <div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
{sortedLinks.map((e, i) => { {links.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />; return <LinkCard key={i} link={e} count={i} />;
})} })}
</div> </div>

View File

@ -1,7 +1,6 @@
import { create } from "zustand"; import { create } from "zustand";
import { CollectionIncludingMembers } from "@/types/global"; import { CollectionIncludingMembers } from "@/types/global";
import useTagStore from "./tags"; import useTagStore from "./tags";
import useLinkStore from "./links";
type CollectionStore = { type CollectionStore = {
collections: CollectionIncludingMembers[]; collections: CollectionIncludingMembers[];
@ -80,7 +79,6 @@ const useCollectionStore = create<CollectionStore>()((set) => ({
collections: state.collections.filter((e) => e.id !== id), collections: state.collections.filter((e) => e.id !== id),
})); }));
useTagStore.getState().setTags(); useTagStore.getState().setTags();
useLinkStore.getState().setLinks();
} }
return response.ok; return response.ok;

View File

@ -1,24 +1,34 @@
import { create } from "zustand"; import { create } from "zustand";
import { LinkIncludingCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import useTagStore from "./tags"; import useTagStore from "./tags";
import useCollectionStore from "./collections"; import useCollectionStore from "./collections";
type LinkStore = { type LinkStore = {
links: LinkIncludingCollectionAndTags[]; links: LinkIncludingShortenedCollectionAndTags[];
setLinks: () => void; setLinks: (
addLink: (body: LinkIncludingCollectionAndTags) => Promise<boolean>; data: LinkIncludingShortenedCollectionAndTags[],
updateLink: (link: LinkIncludingCollectionAndTags) => Promise<boolean>; isInitialCall: boolean
removeLink: (link: LinkIncludingCollectionAndTags) => Promise<boolean>; ) => void;
addLink: (body: LinkIncludingShortenedCollectionAndTags) => Promise<boolean>;
updateLink: (
link: LinkIncludingShortenedCollectionAndTags
) => Promise<boolean>;
removeLink: (
link: LinkIncludingShortenedCollectionAndTags
) => Promise<boolean>;
resetLinks: () => void;
}; };
const useLinkStore = create<LinkStore>()((set) => ({ const useLinkStore = create<LinkStore>()((set) => ({
links: [], links: [],
setLinks: async () => { setLinks: async (data, isInitialCall) => {
const response = await fetch("/api/routes/links"); isInitialCall &&
set(() => ({
const data = await response.json(); links: [],
}));
if (response.ok) set({ links: data.response }); set((state) => ({
links: [...state.links, ...data],
}));
}, },
addLink: async (body) => { addLink: async (body) => {
const response = await fetch("/api/routes/links", { const response = await fetch("/api/routes/links", {
@ -35,7 +45,7 @@ const useLinkStore = create<LinkStore>()((set) => ({
if (response.ok) { if (response.ok) {
set((state) => ({ set((state) => ({
links: [...state.links, data.response], links: [data.response, ...state.links],
})); }));
useTagStore.getState().setTags(); useTagStore.getState().setTags();
useCollectionStore.getState().setCollections(); useCollectionStore.getState().setCollections();
@ -90,6 +100,7 @@ const useLinkStore = create<LinkStore>()((set) => ({
return response.ok; return response.ok;
}, },
resetLinks: () => set({ links: [] }),
})); }));
export default useLinkStore; export default useLinkStore;

View File

@ -1,7 +1,7 @@
import { import {
AccountSettings, AccountSettings,
CollectionIncludingMembers, CollectionIncludingMembers,
LinkIncludingCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import { create } from "zustand"; import { create } from "zustand";
@ -16,13 +16,13 @@ type Modal =
modal: "LINK"; modal: "LINK";
state: boolean; state: boolean;
method: "CREATE"; method: "CREATE";
active?: LinkIncludingCollectionAndTags; active?: LinkIncludingShortenedCollectionAndTags;
} }
| { | {
modal: "LINK"; modal: "LINK";
state: boolean; state: boolean;
method: "UPDATE"; method: "UPDATE";
active: LinkIncludingCollectionAndTags; active: LinkIncludingShortenedCollectionAndTags;
} }
| { | {
modal: "COLLECTION"; modal: "COLLECTION";

View File

@ -3,7 +3,7 @@ import { Collection, Link, Tag, User } from "@prisma/client";
type OptionalExcluding<T, TRequired extends keyof T> = Partial<T> & type OptionalExcluding<T, TRequired extends keyof T> = Partial<T> &
Pick<T, TRequired>; Pick<T, TRequired>;
export interface LinkIncludingCollectionAndTags export interface LinkIncludingShortenedCollectionAndTags
extends Omit<Link, "id" | "createdAt" | "collectionId"> { extends Omit<Link, "id" | "createdAt" | "collectionId"> {
id?: number; id?: number;
createdAt?: string; createdAt?: string;
@ -12,7 +12,10 @@ export interface LinkIncludingCollectionAndTags
pinnedBy?: { pinnedBy?: {
id: number; id: number;
}[]; }[];
collection: OptionalExcluding<Collection, "name" | "ownerId">; collection: OptionalExcluding<
Pick<Collection, "id" | "ownerId" | "name" | "color">,
"name" | "ownerId"
>;
} }
export interface Member { export interface Member {
@ -37,17 +40,42 @@ export interface AccountSettings extends User {
newPassword?: string; newPassword?: string;
} }
export interface PublicCollectionIncludingLinks interface LinksIncludingTags extends Link {
extends Omit<Collection, "ownerId"> { tags: Tag[];
ownerName?: string; }
links: Link[];
export interface PublicCollectionIncludingLinks extends Collection {
links: LinksIncludingTags[];
} }
export enum Sort { export enum Sort {
DateNewestFirst,
DateOldestFirst,
NameAZ, NameAZ,
NameZA, NameZA,
DescriptionAZ, DescriptionAZ,
DescriptionZA, DescriptionZA,
DateNewestFirst,
DateOldestFirst,
} }
export type LinkSearchFilter = {
name: boolean;
url: boolean;
description: boolean;
collection: boolean;
tags: boolean;
};
export type LinkRequestQuery = {
cursor?: string;
collectionId?: number;
tagId?: number;
sort?: Sort;
searchFilter?: LinkSearchFilter;
searchQuery?: string;
pinnedOnly?: boolean;
};
export type PublicLinkRequestQuery = {
cursor?: string;
collectionId?: number;
};