The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add pagination
Steven Tey09f79674389c
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsxindex d1c788b664..a4caa371de 100644--- a/components/app/links/link-card.tsx+++ b/components/app/links/link-card.tsx@@ -248,7 +248,11 @@ export default function LinkCard({ props }: { props: LinkProps }) {<buttononClick={(e) => {e.stopPropagation();- setQueryString(router, "tagId", tag.id);+ setQueryString({+ router,+ param: "tagId",+ value: tag.id,+ });}}className="transition-all duration-75 hover:scale-105 active:scale-100">diff --git a/components/app/links/link-filters.tsx b/components/app/links/link-filters.tsxindex 7ef41a1767..091cb21ade 100644--- a/components/app/links/link-filters.tsx+++ b/components/app/links/link-filters.tsx@@ -37,7 +37,7 @@ export default function LinkFilters() {const { data: tagsCount } = useLinksCount({ groupBy: "tagId" });const router = useRouter();- const { slug, sort, search, domain, userId, tagId, showArchived } =+ const { slug, sort, search, domain, userId, tagId, showArchived, page } =router.query as {slug: string;sort?: string;@@ -46,12 +46,17 @@ export default function LinkFilters() {userId?: string;tagId?: string;showArchived?: string;+ page?: string;};const searchInputRef = useRef(); // this is a hack to clear the search input when the clear button is clickeduseEffect(() => {if (search) {- setQueryString(router, "showArchived", "true");+ setQueryString({+ router,+ param: "showArchived",+ value: "true",+ });}}, [search]);@@ -60,9 +65,13 @@ export default function LinkFilters() {<div className="grid gap-3 py-6"><div className="flex items-center justify-between"><h3 className="ml-1 mt-2 font-semibold">Filter Links</h3>- {(sort || search || domain || userId || tagId || showArchived) && (- <ClearButton searchInputRef={searchInputRef} />- )}+ {(sort ||+ search ||+ domain ||+ userId ||+ tagId ||+ showArchived ||+ page) && <ClearButton searchInputRef={searchInputRef} />}</div><SearchBox searchInputRef={searchInputRef} /></div>@@ -105,7 +114,11 @@ const ClearButton = ({ searchInputRef }) => {const SearchBox = ({ searchInputRef }) => {const router = useRouter();const debounced = useDebouncedCallback((value) => {- setQueryString(router, "search", value);+ setQueryString({+ router,+ param: "search",+ value,+ });}, 500);const { isValidating } = useLinks();@@ -222,7 +235,11 @@ const DomainsFilter = ({ domains, primaryDomain }) => {name={value}checked={router.query.domain === value || domains.length <= 1}onChange={() => {- setQueryString(router, "domain", value);+ setQueryString({+ router,+ param: "domain",+ value,+ });}}type="radio"className="ml-3 h-4 w-4 cursor-pointer rounded-full border-gray-300 text-black focus:outline-none focus:ring-0"@@ -326,7 +343,11 @@ const TagsFilter = ({name={id}checked={router.query.tagId === id}onChange={() => {- setQueryString(router, "tagId", id);+ setQueryString({+ router,+ param: "tagId",+ value: id,+ });}}type="radio"className="ml-3 h-4 w-4 cursor-pointer rounded-full border-gray-300 text-black focus:outline-none focus:ring-0"@@ -510,8 +531,12 @@ const MyLinksFilter = () => {</label><Switchfn={() =>- // @ts-ignore- setQueryString(router, "userId", userId ? "" : session?.user.id)+ setQueryString({+ router,+ param: "userId",+ // @ts-ignore+ value: userId ? "" : session?.user?.id,+ })}checked={userId ? true : false}/>@@ -530,8 +555,11 @@ const ArchiveFilter = () => {</label><Switchfn={() =>- // @ts-ignore- setQueryString(router, "showArchived", showArchived ? "" : "true")+ setQueryString({+ router,+ param: "showArchived",+ value: showArchived ? "" : "true",+ })}checked={showArchived ? true : false}/>diff --git a/components/app/links/link-pagination.tsx b/components/app/links/link-pagination.tsxnew file mode 100644index 0000000000..b2b9ae01fa--- /dev/null+++ b/components/app/links/link-pagination.tsx@@ -0,0 +1,130 @@+import { PAGINATION_LIMIT } from "#/lib/constants";+import useLinksCount from "#/lib/swr/use-links-count";+import { cn, nFormatter, setQueryString } from "#/lib/utils";+import { ChevronLeft, ChevronRight } from "lucide-react";+import { useRouter } from "next/router";+import { useMemo } from "react";++export default function LinkPagination() {+ const router = useRouter();+ const currentPage: number =+ router.query.page && typeof router.query.page === "string"+ ? parseInt(router.query.page)+ : 1;++ const { data: count } = useLinksCount();++ const paginatedCount = Math.ceil(count / PAGINATION_LIMIT);+ const paginationArray = !isNaN(paginatedCount)+ ? Array.from(Array(paginatedCount).keys())+ : [];++ const queryWithoutSlug = useMemo(() => {+ const { slug, ...rest } = router.query;+ return rest;+ }, [router.query]);++ return (+ <div className="sticky bottom-0 z-10 mt-4 flex h-20 scale-[1.02] flex-col items-center justify-center space-y-2 rounded-t-md border border-gray-200 bg-white shadow-lg">+ <div className="flex items-center space-x-2">+ {currentPage > 1 && paginatedCount > 5 && (+ <button+ onClick={() => {+ setQueryString({+ router,+ param: "page",+ value: (currentPage - 1).toString(),+ });+ }}+ className="flex min-w-[1.5rem] items-center justify-center rounded-md bg-white p-1 transition-all hover:bg-gray-100"+ >+ <ChevronLeft className="h-4 w-4" />+ </button>+ )}+ {paginationArray.length > 6 ? (+ currentPage > 3 && currentPage < paginationArray.length - 2 ? (+ <>+ <AnchorLink value={1} />+ <Divider />+ <AnchorLink value={currentPage - 1} />+ <AnchorLink value={currentPage} />+ <AnchorLink value={currentPage + 1} />+ <Divider />+ <AnchorLink value={paginationArray.length} />+ </>+ ) : currentPage <= 3 ? (+ <>+ <AnchorLink value={1} />+ <AnchorLink value={2} />+ <AnchorLink value={3} />+ <Divider />+ <AnchorLink value={paginationArray.length} />+ </>+ ) : (+ <>+ <AnchorLink value={1} />+ <Divider />+ <AnchorLink value={paginationArray.length - 2} />+ <AnchorLink value={paginationArray.length - 1} />+ <AnchorLink value={paginationArray.length} />+ </>+ )+ ) : (+ paginationArray.map((i) => <AnchorLink key={i + 1} value={i + 1} />)+ )}+ {currentPage < paginatedCount && paginatedCount > 5 && (+ <button+ onClick={() => {+ setQueryString({+ router,+ param: "page",+ value: (currentPage + 1).toString(),+ });+ }}+ className="flex min-w-[1.5rem] items-center justify-center rounded-md bg-white p-1 transition-all hover:bg-gray-100"+ >+ <ChevronRight className="h-4 w-4" />+ </button>+ )}+ </div>+ <p className="text-sm text-gray-500">+ Showing {(currentPage - 1) * PAGINATION_LIMIT + 1} -{" "}+ {currentPage * PAGINATION_LIMIT} of {nFormatter(count)} links+ </p>+ </div>+ );+}++const Divider = () => {+ return <div className="w-6 rounded-lg border border-gray-400" />;+};++const AnchorLink = ({ value }: { value: number }) => {+ const router = useRouter();+ const currentPage: number =+ router.query.page && typeof router.query.page === "string"+ ? parseInt(router.query.page)+ : 1;++ const queryWithoutSlug = useMemo(() => {+ const { slug, ...rest } = router.query;+ return rest;+ }, [router.query]);++ return (+ <button+ className={`${+ value === currentPage ? "text-black" : "text-gray-400"+ } flex min-w-[1.5rem] items-center justify-center rounded-md bg-white p-1 font-semibold transition-all hover:bg-gray-100`}+ onClick={() => {+ setQueryString({+ router,+ param: "page",+ value: value.toString(),+ });+ }}+ >+ {value}+ </button>+ );+};diff --git a/components/app/links/links-container.tsx b/components/app/links/links-container.tsxindex 5362516f05..0008f1613b 100644--- a/components/app/links/links-container.tsx+++ b/components/app/links/links-container.tsx@@ -6,6 +6,8 @@ import NoLinksPlaceholder from "./no-links-placeholder";import LinkSort from "./link-sort";import useLinks from "#/lib/swr/use-links";import { useLinkFiltersModal } from "../modals/link-filters-modal";+import LinkPagination from "./link-pagination";+import { useEffect, useRef } from "react";export default function LinksContainer({AddEditLinkButton,@@ -18,7 +20,7 @@ export default function LinksContainer({return (<><LinkFiltersModal />- <MaxWidthWrapper className="pb-10">+ <MaxWidthWrapper><div className="my-5 flex h-10 w-full justify-center lg:justify-end"><LinkFiltersButton /><LinkSort />@@ -27,19 +29,24 @@ export default function LinksContainer({<div className="sticky top-32 col-span-2 hidden max-h-[calc(100vh-150px)] self-start overflow-auto rounded-lg border border-gray-100 bg-white shadow scrollbar-hide lg:block"><LinkFilters /></div>- <ul className="col-span-1 grid auto-rows-min grid-cols-1 gap-3 lg:col-span-5">- {links ? (- links.length > 0 ? (- links.map((props) => <LinkCard key={props.id} props={props} />)+ <div className="col-span-1 auto-rows-min grid-cols-1 lg:col-span-5">+ <ul className="grid min-h-[66.5vh] auto-rows-min gap-3">+ {links ? (+ links.length > 0 ? (+ links.map((props) => (+ <LinkCard key={props.id} props={props} />+ ))+ ) : (+ <NoLinksPlaceholder AddEditLinkButton={AddEditLinkButton} />+ )) : (- <NoLinksPlaceholder AddEditLinkButton={AddEditLinkButton} />- )- ) : (- Array.from({ length: 5 }).map((_, i) => (- <LinkCardPlaceholder key={i} />- ))- )}- </ul>+ Array.from({ length: 5 }).map((_, i) => (+ <LinkCardPlaceholder key={i} />+ ))+ )}+ </ul>+ {links && links.length > 0 && <LinkPagination />}+ </div></div></MaxWidthWrapper></>diff --git a/components/app/links/no-links-placeholder.tsx b/components/app/links/no-links-placeholder.tsxindex 4b8c3ee1c6..b5828f921a 100644--- a/components/app/links/no-links-placeholder.tsx+++ b/components/app/links/no-links-placeholder.tsx@@ -6,7 +6,7 @@ export default function NoLinksPlaceholder({AddEditLinkButton: () => JSX.Element;}) {return (- <div className="flex flex-col items-center justify-center rounded-md border border-gray-200 bg-white py-12">+ <div className="mb-12 flex flex-col items-center justify-center rounded-md border border-gray-200 bg-white py-12"><h2 className="z-10 text-xl font-semibold text-gray-700">No links found.</h2>diff --git a/lib/api/links.ts b/lib/api/links.tsindex 771a32df19..9f72cf9ec8 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -5,7 +5,7 @@ import { LinkProps } from "#/lib/types";import { redis } from "#/lib/upstash";import { getParamsFromURL, nanoid, truncate, validKeyRegex } from "#/lib/utils";import { isReservedKey } from "#/lib/edge-config";-import { NextApiRequest, NextApiResponse } from "next";+import { NextApiRequest } from "next";export async function getLinksForProject({projectId,@@ -13,6 +13,7 @@ export async function getLinksForProject({tagId,search,sort = "createdAt",+ page,userId,showArchived,}: {@@ -21,6 +22,7 @@ export async function getLinksForProject({tagId?: string;search?: string;sort?: "createdAt" | "clicks"; // always descending for both+ page?: string;userId?: string | null;showArchived?: boolean;}): Promise<LinkProps[]> {@@ -52,6 +54,9 @@ export async function getLinksForProject({[sort]: "desc",},take: 100,+ ...(page && {+ skip: (parseInt(page) - 1) * 100,+ }),});}@@ -120,11 +125,14 @@ export async function getLinksCount({return await prisma.link.count({where: {projectId,+ archived: showArchived ? undefined : false,...(userId && { userId }),...(search && {key: { search },url: { search },}),+ ...(domain && { domain }),+ ...(tagId && { tagId }),},});}diff --git a/lib/constants/index.ts b/lib/constants/index.tsindex 856d0c1aa6..5c5c3850bd 100644--- a/lib/constants/index.ts+++ b/lib/constants/index.ts@@ -31,6 +31,8 @@ export const FADE_IN_ANIMATION_SETTINGS = {transition: { duration: 0.2 },};+export const PAGINATION_LIMIT = 100;+/*NOTE: We're using home.localhost:8888 for HOME_DOMAIN and localhost:8888 for APP_DOMAINin local development because Google OAuth doesn't allow subdomain localhost (e.g. app.localhost:8888)diff --git a/lib/utils.ts b/lib/utils.tsindex f83398e963..be0fad1840 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -315,11 +315,15 @@ export const getQueryString = (return `${queryString ? "?" : ""}${queryString}`;};-export const setQueryString = (- router: NextRouter,- param: string,- value: string,-) => {+export const setQueryString = ({+ router,+ param,+ value,+}: {+ router: NextRouter;+ param: string;+ value: string;+}) => {if (param !== "page") delete router.query.page;let newQuery;if (value.length > 0) {diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 59324c69fa..60489cbebf 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -17,12 +17,13 @@ export default withLinksAuth(// GET /api/links – get all links for a project// if no project, get all dub.sh links for userif (req.method === "GET") {- const { domain, tagId, search, sort, userId, showArchived } =+ const { domain, tagId, search, sort, page, userId, showArchived } =req.query as {domain?: string;tagId?: string;search?: string;sort?: "createdAt" | "clicks";+ page?: string;userId?: string;showArchived?: string;};@@ -32,6 +33,7 @@ export default withLinksAuth(tagId,search,sort,+ page,userId: project?.id ? userId : session.user.id,showArchived: showArchived === "true" ? true : false,});diff --git a/yarn.lock b/yarn.lockindex 4c9bb8ba8c..a81e2ca960 100644--- a/yarn.lock+++ b/yarn.lock@@ -176,13 +176,20 @@resolved "https://registry.npmjs.org/@babel/parser/-/parser-7.22.5.tgz"integrity sha512-DFZMC9LJUG9PLOclRC32G63UXwzqS2koQC8dkx+PLdmt1xSePYpbT/NbsrJy8Q/muXz7o/h/d4A7Fuyixm559Q==-"@babel/runtime@^7.10.2", "@babel/runtime@^7.13.10", "@babel/runtime@^7.16.3", "@babel/runtime@^7.20.13", "@babel/runtime@^7.21.0":+"@babel/runtime@^7.10.2", "@babel/runtime@^7.13.10", "@babel/runtime@^7.16.3", "@babel/runtime@^7.20.13":version "7.22.3"resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.3.tgz"integrity sha512-XsDuspWKLUsxwCp6r7EhsExHtYfbe5oAGQ19kqngTdCPUoPQzOPdUbD/pB9PJiwb2ptYKQDjSJT3R6dC+EPqfQ==dependencies:regenerator-runtime "^0.13.11"+"@babel/runtime@^7.21.0":+ version "7.22.10"+ resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.22.10.tgz#ae3e9631fd947cb7e3610d3e9d8fef5f76696682"+ integrity sha512-21t/fkKLMZI4pqP2wlmsQAWnYW1PDyKyyUV4vCi+B25ydmdaYTKXPwCj0BzSUnZf4seIiYvSA3jcZ3gdsMFkLQ==+ dependencies:+ regenerator-runtime "^0.14.0"+"@babel/template@^7.16.7", "@babel/template@^7.22.5":version "7.22.5"resolved "https://registry.npmjs.org/@babel/template/-/template-7.22.5.tgz"@@ -3398,7 +3405,7 @@ cli-table3@^0.6.3:optionalDependencies:"@colors/colors" "1.5.0"[email protected], client-only@^0.0.1:version "0.0.1"resolved "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz"integrity sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==@@ -7388,9 +7395,9 @@ react-textarea-autosize@^8.4.0:use-latest "^1.2.1"react-tweet@^3.0.0:- version "3.0.0"- resolved "https://registry.npmjs.org/react-tweet/-/react-tweet-3.0.0.tgz"- integrity sha512-oLtr5AsBmoYFlZeSm1zWFn1P1oS4Vja/wGAcw1BEtCSJAENcsLlUNnsJdExZ8QTuxv2w3ETjvNeHTv68+xhciA==+ version "3.1.0"+ resolved "https://registry.yarnpkg.com/react-tweet/-/react-tweet-3.1.0.tgz#1fe1d89bebbdf17b1863f532170c0463b87eff65"+ integrity sha512-TZrCzqJIM3mUPZZQgChenrPxEEnswbPkyqMjXgLy3fJSOgcSEaslQqWMeNdcuCjSgLkYfITRBFjX4jQ1EGBPAw==dependencies:"@swc/helpers" "^0.5.1"clsx "^1.2.1"@@ -7555,9 +7562,14 @@ reduce-function-call@^1.0.1:regenerator-runtime@^0.13.11:version "0.13.11"- resolved "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz"+ resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9"integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==+regenerator-runtime@^0.14.0:+ version "0.14.0"+ resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.14.0.tgz#5e19d68eb12d486f797e15a3c6a918f7cec5eb45"+ integrity sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==+rehype-autolink-headings@^6.1.1:version "6.1.1"resolved "https://registry.npmjs.org/rehype-autolink-headings/-/rehype-autolink-headings-6.1.1.tgz"@@ -8136,13 +8148,21 @@ supports-preserve-symlinks-flag@^1.0.0:resolved "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz"integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==-swr@^2.1.5, swr@^2.2.0:+swr@^2.1.5:version "2.2.0"resolved "https://registry.npmjs.org/swr/-/swr-2.2.0.tgz"integrity sha512-AjqHOv2lAhkuUdIiBu9xbuettzAzWXmCEcLONNKJRba87WAefz8Ca9d6ds/SzrPc235n1IxWYdhJ2zF3MNUaoQ==dependencies:use-sync-external-store "^1.2.0"+swr@^2.2.0:+ version "2.2.1"+ resolved "https://registry.yarnpkg.com/swr/-/swr-2.2.1.tgz#19b89a9034a62a73c30dbf06857a0a31981cd60a"+ integrity sha512-KJVA7dGtOBeZ+2sycEuzUfVIP5lZ/cd0xjevv85n2YG0x1uHJQicjAtahVZL6xG3+TjqhbBqimwYzVo3saeVXQ==+ dependencies:+ client-only "^0.0.1"+ use-sync-external-store "^1.2.0"+tabbable@^6.0.1:version "6.0.1"resolved "https://registry.npmjs.org/tabbable/-/tabbable-6.0.1.tgz"@@ -8330,11 +8350,16 @@ ts-pattern@^4.3.0:resolved "https://registry.npmjs.org/ts-pattern/-/ts-pattern-4.3.0.tgz"integrity sha512-pefrkcd4lmIVR0LA49Imjf9DYLK8vtWhqBPA3Ya1ir8xCW0O2yjL9dsCVvI7pCodLC5q7smNpEtDR2yVulQxOg==-tslib@^2.0.0, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.4.0, tslib@^2.4.1:+tslib@^2.0.0, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.4.1:version "2.4.1"resolved "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz"integrity sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==+tslib@^2.4.0:+ version "2.6.1"+ resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.6.1.tgz#fd8c9a0ff42590b25703c0acb3de3d3f4ede0410"+ integrity sha512-t0hLfiEKfMUoqhG+U1oid7Pva4bbDPHYfJNiB7BiIjRkj1pyC++4N3huJfqY6aRH6VTB0rvtzQwjM4K6qpfOig==+version "0.0.11"resolved "https://registry.yarnpkg.com/tw-to-css/-/tw-to-css-0.0.11.tgz#5e7c5e461f946be2cd7994c884b5e3ae798bc5be"@@ -8551,7 +8576,7 @@ use-sidecar@^1.1.2:use-sync-external-store@^1.2.0:version "1.2.0"- resolved "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz"+ resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz#7dbefd6ef3fe4e767a0cf5d7287aacfb5846928a"integrity sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1: