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
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 {
CollectionIncludingMembers,
LinkIncludingCollectionAndTags,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import {
faFolder,
@ -20,7 +20,7 @@ import useAccountStore from "@/store/account";
import useModalStore from "@/store/modals";
type Props = {
link: LinkIncludingCollectionAndTags;
link: LinkIncludingShortenedCollectionAndTags;
count: number;
className?: string;
};
@ -146,7 +146,7 @@ export default function LinkCard({ link, count, className }: Props) {
className="group/url"
>
<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
icon={faArrowUpRightFromSquare}
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 CollectionSelection from "@/components/InputSelect/CollectionSelection";
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 useLinkStore from "@/store/links";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
@ -15,12 +15,12 @@ type Props =
| {
toggleLinkModal: Function;
method: "CREATE";
activeLink?: LinkIncludingCollectionAndTags;
activeLink?: LinkIncludingShortenedCollectionAndTags;
}
| {
toggleLinkModal: Function;
method: "UPDATE";
activeLink: LinkIncludingCollectionAndTags;
activeLink: LinkIncludingShortenedCollectionAndTags;
};
export default function EditLink({
@ -30,7 +30,7 @@ export default function EditLink({
}: Props) {
const { data } = useSession();
const [link, setLink] = useState<LinkIncludingCollectionAndTags>(
const [link, setLink] = useState<LinkIncludingShortenedCollectionAndTags>(
method === "UPDATE"
? activeLink
: {

View File

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

View File

@ -4,10 +4,14 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
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 = {
link: LinkType;
link: LinksIncludingTags;
count: number;
};
@ -58,7 +62,18 @@ export default function LinkCard({ link, count }: Props) {
<p className="text-gray-500 text-sm font-medium">
{link.description}
</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">
<p className="text-gray-500">{formattedDate}</p>
<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>
<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
label="Name (A-Z)"
state={sortBy === Sort.NameAZ}
@ -48,18 +60,6 @@ export default function SortDropdown({
state={sortBy === 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>
</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 { setCollections } = useCollectionStore();
const { setTags } = useTagStore();
const { setLinks } = useLinkStore();
// const { setLinks } = useLinkStore();
const { setAccount } = useAccountStore();
useEffect(() => {
if (status === "authenticated") {
setCollections();
setTags();
setLinks();
// setLinks();
setAccount(data.user.email as string);
}
}, [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 {
CollectionIncludingMembers,
LinkIncludingCollectionAndTags,
LinkIncludingShortenedCollectionAndTags,
Sort,
} from "@/types/global";
import { SetStateAction, useEffect } from "react";
type Props<
T extends CollectionIncludingMembers | LinkIncludingCollectionAndTags
T extends CollectionIncludingMembers | LinkIncludingShortenedCollectionAndTags
> = {
sortBy: Sort;
@ -15,7 +15,7 @@ type Props<
};
export default function useSort<
T extends CollectionIncludingMembers | LinkIncludingCollectionAndTags
T extends CollectionIncludingMembers | LinkIncludingShortenedCollectionAndTags
>({ sortBy, data, setData }: Props<T>) {
useEffect(() => {
const dataArray = [...data];

View File

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

View File

@ -1,31 +1,229 @@
import { prisma } from "@/lib/api/db";
export default async function getLink(userId: number) {
const links = await prisma.link.findMany({
where: {
collection: {
OR: [
{
ownerId: userId,
},
{
members: {
some: {
userId,
import { LinkRequestQuery, LinkSearchFilter, Sort } from "@/types/global";
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: {
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: {
name: {
contains: query.searchFilter?.collection
? query.searchQuery
: undefined,
mode: "insensitive",
},
OR: [
{
ownerId: userId,
},
{
members: {
some: {
userId,
},
},
},
],
},
},
{
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: {
tags: true,
collection: true,
pinnedBy: {
where: { id: userId },
select: { id: true },
},
},
],
},
},
include: {
tags: true,
collection: true,
pinnedBy: {
where: { id: userId },
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 };
}

View File

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

View File

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

View File

@ -1,35 +1,40 @@
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;
const collection = await prisma.collection.findFirst({
where: {
id: collectionId,
id: Number(query.collectionId),
isPublic: true,
},
include: {
links: {
select: {
id: true,
name: true,
url: true,
description: true,
collectionId: true,
createdAt: true,
},
},
},
});
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: {
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 };
} else {

View File

@ -1,14 +1,26 @@
import { PublicCollectionIncludingLinks } from "@/types/global";
import { Dispatch, SetStateAction } from "react";
const getPublicCollectionData = async (
collectionId: string,
setData?: Function
prevData: PublicCollectionIncludingLinks,
setData: Dispatch<SetStateAction<PublicCollectionIncludingLinks | undefined>>
) => {
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();
if (setData) setData(data.response);
prevData
? setData({
...data.response,
links: [...prevData.links, ...data.response.links],
})
: setData(data.response);
return data;
};

View File

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

View File

@ -14,7 +14,7 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
}
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 });
} else if (req.method === "POST") {
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 SortDropdown from "@/components/SortDropdown";
import useModalStore from "@/store/modals";
import useSort from "@/hooks/useSort";
import useLinks from "@/hooks/useLinks";
export default function Index() {
const { setModal } = useModalStore();
@ -30,14 +30,12 @@ export default function Index() {
const [expandDropdown, setExpandDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [activeCollection, setActiveCollection] =
useState<CollectionIncludingMembers>();
const [sortedLinks, setSortedLinks] = useState(links);
useSort({ sortBy, setData: setSortedLinks, data: links });
useLinks({ collectionId: Number(router.query.id), sort: sortBy });
useEffect(() => {
setActiveCollection(
@ -223,7 +221,7 @@ export default function Index() {
</div>
</div>
<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} />;
})}
</div>

View File

@ -20,7 +20,7 @@ export default function Collections() {
const { collections } = useCollectionStore();
const [expandDropdown, setExpandDropdown] = 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 session = useSession();

View File

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

View File

@ -1,6 +1,6 @@
import LinkCard from "@/components/LinkCard";
import SortDropdown from "@/components/SortDropdown";
import useSort from "@/hooks/useSort";
import useLinks from "@/hooks/useLinks";
import MainLayout from "@/layouts/MainLayout";
import useLinkStore from "@/store/links";
import { Sort } from "@/types/global";
@ -12,10 +12,9 @@ export default function Links() {
const { links } = useLinkStore();
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.NameAZ);
const [sortedLinks, setSortedLinks] = useState(links);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
useSort({ sortBy, setData: setSortedLinks, data: links });
useLinks({ sort: sortBy });
return (
<MainLayout>
@ -54,7 +53,7 @@ export default function Links() {
</div>
</div>
<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} />;
})}
</div>

View File

@ -1,4 +1,5 @@
import LinkCard from "@/components/PublicPage/LinkCard";
import useDetectPageBottom from "@/hooks/useDetectPageBottom";
import getPublicCollectionData from "@/lib/client/getPublicCollectionData";
import { PublicCollectionIncludingLinks } from "@/types/global";
import { useRouter } from "next/router";
@ -6,6 +7,7 @@ import React, { useEffect, useState } from "react";
export default function PublicCollections() {
const router = useRouter();
const hasReachedBottom = useDetectPageBottom();
const [data, setData] = useState<PublicCollectionIncludingLinks>();
@ -13,7 +15,8 @@ export default function PublicCollections() {
if (router.query.id) {
getPublicCollectionData(
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 ? (
<div className="max-w-4xl mx-auto p-5 bg">
<div
@ -36,10 +49,6 @@ export default function PublicCollections() {
{data.name}
</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" />
<p className="mt-2 text-gray-500">{data.description}</p>

View File

@ -1,33 +1,21 @@
import FilterSearchDropdown from "@/components/FilterSearchDropdown";
import LinkCard from "@/components/LinkCard";
import SortDropdown from "@/components/SortDropdown";
import useSort from "@/hooks/useSort";
import useLinks from "@/hooks/useLinks";
import MainLayout from "@/layouts/MainLayout";
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 { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
type SearchFilter = {
name: boolean;
url: boolean;
description: boolean;
collection: boolean;
tags: boolean;
};
import { useState } from "react";
export default function Links() {
const { links } = useLinkStore();
const router = useRouter();
const routeQuery = decodeURIComponent(
router.query.query as string
).toLowerCase();
const [searchFilter, setSearchFilter] = useState<SearchFilter>({
const [searchFilter, setSearchFilter] = useState<LinkSearchFilter>({
name: true,
url: true,
description: true,
@ -37,32 +25,13 @@ export default function Links() {
const [filterDropdown, setFilterDropdown] = 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);
const [sortedLinks, setSortedLinks] = useState(filteredLinks);
useSort({ sortBy, setData: setSortedLinks, data: links });
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]);
useLinks({
searchFilter: searchFilter,
searchQuery: router.query.query as string,
sort: sortBy,
});
return (
<MainLayout>
@ -126,8 +95,8 @@ export default function Links() {
</div>
</div>
</div>
{filteredLinks[0] ? (
filteredLinks.map((e, i) => {
{links[0] ? (
links.map((e, 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 SortDropdown from "@/components/SortDropdown";
import { Sort } from "@/types/global";
import useSort from "@/hooks/useSort";
import useLinks from "@/hooks/useLinks";
export default function Index() {
const router = useRouter();
@ -18,13 +18,11 @@ export default function Index() {
const { tags } = useTagStore();
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 [sortedLinks, setSortedLinks] = useState(links);
useSort({ sortBy, setData: setSortedLinks, data: links });
useLinks({ tagId: Number(router.query.id), sort: sortBy });
useEffect(() => {
setActiveTag(tags.find((e) => e.id === Number(router.query.id)));
@ -69,7 +67,7 @@ export default function Index() {
</div>
</div>
<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} />;
})}
</div>

View File

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

View File

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

View File

@ -1,7 +1,7 @@
import {
AccountSettings,
CollectionIncludingMembers,
LinkIncludingCollectionAndTags,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import { create } from "zustand";
@ -16,13 +16,13 @@ type Modal =
modal: "LINK";
state: boolean;
method: "CREATE";
active?: LinkIncludingCollectionAndTags;
active?: LinkIncludingShortenedCollectionAndTags;
}
| {
modal: "LINK";
state: boolean;
method: "UPDATE";
active: LinkIncludingCollectionAndTags;
active: LinkIncludingShortenedCollectionAndTags;
}
| {
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> &
Pick<T, TRequired>;
export interface LinkIncludingCollectionAndTags
export interface LinkIncludingShortenedCollectionAndTags
extends Omit<Link, "id" | "createdAt" | "collectionId"> {
id?: number;
createdAt?: string;
@ -12,7 +12,10 @@ export interface LinkIncludingCollectionAndTags
pinnedBy?: {
id: number;
}[];
collection: OptionalExcluding<Collection, "name" | "ownerId">;
collection: OptionalExcluding<
Pick<Collection, "id" | "ownerId" | "name" | "color">,
"name" | "ownerId"
>;
}
export interface Member {
@ -37,17 +40,42 @@ export interface AccountSettings extends User {
newPassword?: string;
}
export interface PublicCollectionIncludingLinks
extends Omit<Collection, "ownerId"> {
ownerName?: string;
links: Link[];
interface LinksIncludingTags extends Link {
tags: Tag[];
}
export interface PublicCollectionIncludingLinks extends Collection {
links: LinksIncludingTags[];
}
export enum Sort {
DateNewestFirst,
DateOldestFirst,
NameAZ,
NameZA,
DescriptionAZ,
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;
};