The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Wrap up final changes for links API consolidation
Steven Tey7282a4f06e6d
diff --git a/app/ui/button.tsx b/app/ui/button.tsxindex 5a66740ee6..7078ee2b16 100644--- a/app/ui/button.tsx+++ b/app/ui/button.tsx@@ -15,7 +15,7 @@ export default function Button({}: {text: string;variant?: "primary" | "secondary" | "danger";- onClick?: () => void;+ onClick?: any;disabled?: boolean;loading?: boolean;disabledTooltip?: string | ReactNode;diff --git a/app/ui/modals/add-edit-link-modal/index.tsx b/app/ui/modals/add-edit-link-modal/index.tsxindex 6ce1968baa..31399ee7a1 100644--- a/app/ui/modals/add-edit-link-modal/index.tsx+++ b/app/ui/modals/add-edit-link-modal/index.tsx@@ -112,7 +112,7 @@ function AddEditLinkModal({const generateRandomKey = useCallback(async () => {setGeneratingKey(true);const res = await fetch(- `/api/links/random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,+ `/api/links/_random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,);const key = await res.json();setData((prev) => ({ ...prev, key }));@@ -316,7 +316,7 @@ function AddEditLinkModal({mutate((key) =>typeof key === "string" &&- key.startsWith(`/api/links/count`),+ key.startsWith(`/api/links/_count`),undefined,{ revalidate: true },);diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsxindex c2408c0116..21126497bf 100644--- a/components/app/links/link-card.tsx+++ b/components/app/links/link-card.tsx@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";import useSWR from "swr";import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal";import { useTagLinkModal } from "@/components/app/modals/tag-link-modal";+import { useArchiveLinkModal } from "@/components/app/modals/archive-link-modal";import { useDeleteLinkModal } from "@/components/app/modals/delete-link-modal";import { useLinkQRModal } from "@/components/app/modals/link-qr-modal";import IconMenu from "@/components/shared/icon-menu";@@ -23,7 +24,7 @@ import {} from "@/lib/utils";import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";import useDomains from "@/lib/swr/use-domains";-import { CopyPlus, Edit3, Tag } from "lucide-react";+import { Archive, CopyPlus, Edit3, Tag } from "lucide-react";import punycode from "punycode/";import { GOOGLE_FAVICON_URL } from "@/lib/constants";@@ -82,6 +83,10 @@ export default function LinkCard({ props }: { props: LinkProps }) {const { setShowTagLinkModal, TagLinkModal } = useTagLinkModal({props,});+ const { setShowArchiveLinkModal, ArchiveLinkModal } = useArchiveLinkModal({+ props,+ archived: !archived,+ });const { setShowDeleteLinkModal, DeleteLinkModal } = useDeleteLinkModal({props,});@@ -102,7 +107,8 @@ export default function LinkCard({ props }: { props: LinkProps }) {}};- const shortcuts = ["e", "d", "t", "x"];+ // const shortcuts = slug ? ["e", "d", "t", "a", "x"] : ["e", "d", "a", "x"];+ const shortcuts = ["e", "d", "a", "x"];const onKeyDown = (e: any) => {// only run shortcut logic if:// - usage is not exceeded@@ -121,8 +127,11 @@ export default function LinkCard({ props }: { props: LinkProps }) {case "d":setShowDuplicateLinkModal(true);break;- case "t":- setShowTagLinkModal(true);+ // case "t":+ // setShowTagLinkModal(true);+ // break;+ case "a":+ setShowArchiveLinkModal(true);break;case "x":setShowDeleteLinkModal(true);@@ -150,19 +159,32 @@ export default function LinkCard({ props }: { props: LinkProps }) {<LinkQRModal /><AddEditLinkModal /><DuplicateLinkModal />- <TagLinkModal />+ {/* {slug && <TagLinkModal />} */}+ <ArchiveLinkModal /><DeleteLinkModal /><li className="relative flex items-center justify-between">- <div className="relative flex shrink items-center space-x-2 sm:space-x-4">- <BlurImage- src={`${GOOGLE_FAVICON_URL}${apexDomain}`}- alt={apexDomain}- className="h-8 w-8 rounded-full sm:h-10 sm:w-10"- unoptimized- width={20}- height={20}- />- <div>+ <div className="relative flex shrink items-center">+ {archived ? (+ <Tooltip content="This link is archived. It will still work, but won't be shown in your dashboard.">+ <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-300 px-0 sm:h-10 sm:w-10">+ <Archive className="h-4 w-4 text-gray-500 sm:h-5 sm:w-5" />+ </div>+ </Tooltip>+ ) : (+ <BlurImage+ src={`${GOOGLE_FAVICON_URL}${apexDomain}`}+ alt={apexDomain}+ className="h-8 w-8 rounded-full sm:h-10 sm:w-10"+ unoptimized+ width={20}+ height={20}+ />+ )}+ {/*+ Here, we're manually setting ml-* values because if we do space-x-* in the parent div,+ it messes up the tooltip positioning.+ */}+ <div className="ml-2 sm:ml-4"><div className="flex max-w-fit items-center space-x-2">{slug && !verified && !loading ? (<Tooltip@@ -187,7 +209,9 @@ export default function LinkCard({ props }: { props: LinkProps }) {onClick={(e) => {e.stopPropagation();}}- className="w-24 truncate text-sm font-semibold text-blue-800 sm:w-full sm:text-base"+ className={`w-24 truncate text-sm font-semibold ${+ archived ? "text-gray-500" : "text-blue-800"+ } sm:w-full sm:text-base`}href={linkConstructor({ key, domain })}target="_blank"rel="noreferrer"@@ -316,17 +340,35 @@ export default function LinkCard({ props }: { props: LinkProps }) {</kbd></button>)}+ {/* {slug && (+ <button+ onClick={(e) => {+ e.preventDefault();+ setOpenPopover(false);+ setShowTagLinkModal(true);+ }}+ className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"+ >+ <IconMenu text="Tag" icon={<Tag className="h-4 w-4" />} />+ <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-500 transition-all duration-75 group-hover:bg-gray-200 sm:inline-block">+ T+ </kbd>+ </button>+ )} */}<buttononClick={(e) => {e.preventDefault();setOpenPopover(false);- setShowTagLinkModal(true);+ setShowArchiveLinkModal(true);}}className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100">- <IconMenu text="Tag" icon={<Tag className="h-4 w-4" />} />+ <IconMenu+ text="Archive"+ icon={<Archive className="h-4 w-4" />}+ /><kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-500 transition-all duration-75 group-hover:bg-gray-200 sm:inline-block">- T+ A</kbd></button><buttondiff --git a/components/app/links/link-filters.tsx b/components/app/links/link-filters.tsxindex b973efcb07..da09413c5b 100644--- a/components/app/links/link-filters.tsx+++ b/components/app/links/link-filters.tsx@@ -4,7 +4,6 @@ import {useCallback,useContext,useEffect,- useMemo,useRef,useState,} from "react";@@ -27,39 +26,50 @@ import { ModalContext } from "#/ui/modal-provider";export default function LinkFilters() {const { primaryDomain } = useDomains();const { data: domains } = useLinksCount({ groupBy: "domain" });+ // const { data: tags } = useLinksCount({ groupBy: "tagId" });const router = useRouter();- const { slug, search, domain, userId } = router.query as {+ const { slug, search, domain, userId, tagId } = router.query as {slug: string;search?: string;domain?: string;userId?: string;+ tagId?: string;};const searchInputRef = useRef(); // this is a hack to clear the search input when the clear button is clickedconst { setShowAddProjectModal } = useContext(ModalContext);+ // return domains && tags ? (return domains ? (<div className="grid w-full rounded-md bg-white px-5 lg:divide-y lg:divide-gray-300"><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>- {(search || domain || userId) && (+ {(search || domain || userId || tagId) && (<ClearButton searchInputRef={searchInputRef} />)}</div><SearchBox searchInputRef={searchInputRef} /></div>- {slug && <MyLinksFilter />}<FilterGroup+ displayName="Domains"param="domain"options={domains.length === 0- ? [{ value: primaryDomain || "", count: 0 }]+ ? [+ {+ name: primaryDomain || "",+ value: primaryDomain || "",+ count: 0,+ },+ ]: domains.map(({ domain, _count }) => ({+ name: domain,value: domain,count: _count,}))}+ checkDefault={domains.length <= 1}cta={slug ? (<Link@@ -73,7 +83,7 @@ export default function LinkFilters() {onClick={() => {setShowAddProjectModal(true);toast.error(- "You can only add a domain to a project. Please create a new project or navigate to an existing one.",+ "You can only add a domain to a custom project. Please create a new project or navigate to an existing one.",);}}className="rounded-md border border-gray-300 p-1 text-center text-sm"@@ -83,10 +93,35 @@ export default function LinkFilters() {)}/>+ {slug && (+ <>+ {/* <FilterGroup+ displayName="Tags"+ param="tagId"+ options={tags.map(({ tag, tagId, _count }) => ({+ name: tag,+ value: tagId,+ count: _count,+ }))}+ cta={+ <button+ onClick={() => {+ toast.success("add a tag to a project");+ }}+ className="rounded-md border border-gray-300 p-1 text-center text-sm"+ >+ Add a tag+ </button>+ }+ /> */}+ <MyLinksFilter />+ </>+ )}+ <ArchiveFilter /></div>) : (<div className="grid h-full gap-6 rounded-md bg-white p-5">- <div className="h-[300px] w-full animate-pulse rounded-md bg-gray-200" />+ <div className="h-[calc(100vh-190px)] w-full animate-pulse rounded-md bg-gray-200" /></div>);}@@ -162,20 +197,44 @@ const MyLinksFilter = () => {);};+const ArchiveFilter = () => {+ const router = useRouter();+ const { showArchived } = router.query as { showArchived?: string };++ return (+ <div className="flex items-center justify-between py-6">+ <label className="text-sm font-medium text-gray-600">+ Include archived links+ </label>+ <Switch+ fn={() =>+ // @ts-ignore+ setQueryString(router, "showArchived", showArchived ? "" : "true")+ }+ checked={showArchived ? true : false}+ />+ </div>+ );+};+const FilterGroup = ({+ displayName,param,options,+ checkDefault = false,cta,}: {+ displayName: string;param: string;- options: { value: string; count: number }[];+ options: { name: string; value: string; count: number }[];+ checkDefault?: boolean;cta: ReactNode;}) => {const router = useRouter();const [collapsed, setCollapsed] = useState(false);return (- <fieldset className="py-6">+ <fieldset className="overflow-hidden py-6"><div className="flex h-8 items-center justify-between"><buttononClick={() => {@@ -186,7 +245,7 @@ const FilterGroup = ({<ChevronRightclassName={`${collapsed ? "" : "rotate-90"} h-5 w-5 transition-all`}/>- <h4 className="font-medium capitalize text-gray-900">{param}</h4>+ <h4 className="font-medium text-gray-900">{displayName}</h4></button></div><AnimatePresence initial={false}>@@ -195,7 +254,7 @@ const FilterGroup = ({className="mt-4 grid gap-2"{...SWIPE_REVEAL_ANIMATION_SETTINGS}>- {options?.map(({ value, count }) => (+ {options?.map(({ name, value, count }) => (<divkey={value}className="relative flex cursor-pointer items-center space-x-3 rounded-md bg-gray-50 transition-all hover:bg-gray-100"@@ -203,9 +262,7 @@ const FilterGroup = ({<inputid={value}name={value}- checked={- router.query[param] === value || options.length === 1- }+ checked={router.query[param] === value || checkDefault}onChange={() => {setQueryString(router, param, value);}}@@ -216,7 +273,7 @@ const FilterGroup = ({htmlFor={value}className="flex w-full cursor-pointer justify-between px-3 py-2 pl-0 text-sm font-medium text-gray-700">- <p>{punycode.toUnicode(value || "")}</p>+ <p>{punycode.toUnicode(name || "")}</p><p className="text-gray-500">{nFormatter(count)}</p></label></div>@@ -248,3 +305,11 @@ const ClearButton = ({ searchInputRef }: { searchInputRef }) => {</button>);};++const FilterGroupPlaceholder = () => {+ return (+ <div className="py-6">+ <div className="h-8 animate-pulse rounded-md bg-gray-100" />+ </div>+ );+};diff --git a/components/app/links/links-container.tsx b/components/app/links/links-container.tsxindex a6043feb43..9f62e6ab51 100644--- a/components/app/links/links-container.tsx+++ b/components/app/links/links-container.tsx@@ -24,7 +24,7 @@ export default function LinksContainer({<LinkSort /></div><div className="grid grid-cols-1 gap-5 lg:grid-cols-7">- <div className="sticky top-32 col-span-2 hidden max-h-[500px] self-start rounded-lg border border-gray-100 bg-white shadow lg:block">+ <div className="sticky top-32 col-span-2 hidden max-h-[calc(100vh-150px)] self-start overflow-scroll rounded-lg border border-gray-100 bg-white shadow lg:block"><LinkFilters /></div><ul className="col-span-1 grid auto-rows-min grid-cols-1 gap-3 lg:col-span-5">diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsxindex c8c3b21eb4..5efdb788b6 100644--- a/components/app/modals/add-edit-link-modal/index.tsx+++ b/components/app/modals/add-edit-link-modal/index.tsx@@ -106,7 +106,7 @@ function AddEditLinkModal({setKeyError(null);setGeneratingKey(true);const res = await fetch(- `/api/links/random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,+ `/api/links/_random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,);const key = await res.json();setData((prev) => ({ ...prev, key }));@@ -306,7 +306,7 @@ function AddEditLinkModal({mutate((key) =>typeof key === "string" &&- key.startsWith(`/api/links/count`),+ key.startsWith(`/api/links/_count`),undefined,{ revalidate: true },);diff --git a/components/app/modals/add-project-modal.tsx b/components/app/modals/add-project-modal.tsxindex 43ac1e8372..8e874ccecd 100644--- a/components/app/modals/add-project-modal.tsx+++ b/components/app/modals/add-project-modal.tsx@@ -96,7 +96,7 @@ function AddProjectModalHelper({width={20}height={20}/>- <h3 className="text-lg font-medium">Add a new project</h3>+ <h3 className="text-lg font-medium">Create a new project</h3></div><formdiff --git a/components/app/modals/archive-link-modal.tsx b/components/app/modals/archive-link-modal.tsxnew file mode 100644index 0000000000..f985e941d0--- /dev/null+++ b/components/app/modals/archive-link-modal.tsx@@ -0,0 +1,142 @@+import { useRouter } from "next/router";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { mutate } from "swr";+import BlurImage from "#/ui/blur-image";+import { LoadingDots } from "#/ui/icons";+import Modal from "@/components/shared/modal";+import { LinkProps } from "@/lib/types";+import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";+import { GOOGLE_FAVICON_URL } from "@/lib/constants";+import { toast } from "sonner";+import Button from "#/ui/button";++function ArchiveLinkModal({+ showArchiveLinkModal,+ setShowArchiveLinkModal,+ props,+ archived,+}: {+ showArchiveLinkModal: boolean;+ setShowArchiveLinkModal: Dispatch<SetStateAction<boolean>>;+ props: LinkProps;+ archived: boolean;+}) {+ const router = useRouter();+ const { slug } = router.query;+ const [archiving, setArchiving] = useState(false);+ const apexDomain = getApexDomain(props.url);++ const { key, domain } = props;++ const shortlink = useMemo(() => {+ return linkConstructor({+ key,+ domain,+ pretty: true,+ });+ }, [key, domain]);++ return (+ <Modal+ showModal={showArchiveLinkModal}+ setShowModal={setShowArchiveLinkModal}+ >+ <div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 text-center sm:px-16">+ <BlurImage+ src={`${GOOGLE_FAVICON_URL}${apexDomain}`}+ alt={apexDomain}+ className="h-10 w-10 rounded-full"+ width={20}+ height={20}+ />+ <h3 className="text-lg font-medium">+ {archived ? "Archive" : "Unarchive"} {shortlink}+ </h3>+ <p className="text-sm text-gray-500">+ {archived+ ? "Archived links will still work - they just won't show up on your main dashboard."+ : "By unarchiving this link, it will show up on your main dashboard again."}+ </p>+ </div>++ <div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16">+ <Button+ onClick={async (e) => {+ e.preventDefault();+ setArchiving(true);+ fetch(+ `/api/links/${props.key}/archive${+ slug ? `?slug=${slug}&domain=${domain}` : ""+ }`,+ {+ method: archived ? "POST" : "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ },+ ).then(async (res) => {+ setArchiving(false);+ if (res.status === 200) {+ mutate(`/api/links${getQueryString(router)}`);+ mutate(+ (key) =>+ typeof key === "string" &&+ key.startsWith(`/api/links/_count`),+ undefined,+ { revalidate: true },+ );+ setShowArchiveLinkModal(false);+ toast.success(+ `Successfully ${+ archived ? "archived" : "unarchived"+ } link!`,+ );+ } else {+ toast.error(res.statusText);+ }+ });+ }}+ loading={archiving}+ text={`Confirm ${archived ? "archive" : "unarchive"}`}+ />+ </div>+ </div>+ </Modal>+ );+}++export function useArchiveLinkModal({+ props,+ archived = true,+}: {+ props: LinkProps;+ archived: boolean;+}) {+ const [showArchiveLinkModal, setShowArchiveLinkModal] = useState(false);++ const ArchiveLinkModalCallback = useCallback(() => {+ return props ? (+ <ArchiveLinkModal+ showArchiveLinkModal={showArchiveLinkModal}+ setShowArchiveLinkModal={setShowArchiveLinkModal}+ props={props}+ archived={archived}+ />+ ) : null;+ }, [showArchiveLinkModal, setShowArchiveLinkModal]);++ return useMemo(+ () => ({+ setShowArchiveLinkModal,+ ArchiveLinkModal: ArchiveLinkModalCallback,+ }),+ [setShowArchiveLinkModal, ArchiveLinkModalCallback],+ );+}diff --git a/components/app/modals/delete-link-modal.tsx b/components/app/modals/delete-link-modal.tsxindex e5581b7370..4994ed3882 100644--- a/components/app/modals/delete-link-modal.tsx+++ b/components/app/modals/delete-link-modal.tsx@@ -14,6 +14,7 @@ import { LinkProps } from "@/lib/types";import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";import { toast } from "sonner";import { GOOGLE_FAVICON_URL } from "@/lib/constants";+import Button from "#/ui/button";function DeleteLinkModal({showDeleteLinkModal,@@ -81,7 +82,7 @@ function DeleteLinkModal({mutate((key) =>typeof key === "string" &&- key.startsWith(`/api/links/count`),+ key.startsWith(`/api/links/_count`),undefined,{ revalidate: true },);@@ -116,16 +117,7 @@ function DeleteLinkModal({</div></div>- <button- disabled={deleting}- className={`${- deleting- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"- : "border-red-600 bg-red-600 text-white hover:bg-white hover:text-red-600"- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}- >- {deleting ? <LoadingDots color="#808080" /> : <p>Confirm delete</p>}- </button>+ <Button variant="danger" text="Confirm delete" loading={deleting} /></form></div></Modal>diff --git a/components/app/modals/tag-link-modal.tsx b/components/app/modals/tag-link-modal.tsxindex 1bb2e11282..5557f67d5b 100644--- a/components/app/modals/tag-link-modal.tsx+++ b/components/app/modals/tag-link-modal.tsx@@ -14,6 +14,7 @@ import { LinkProps } from "@/lib/types";import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";import { GOOGLE_FAVICON_URL } from "@/lib/constants";import { toast } from "sonner";+import Button from "#/ui/button";function TagLinkModal({showTagLinkModal,@@ -29,7 +30,7 @@ function TagLinkModal({const [tagging, setTagging] = useState(false);const apexDomain = getApexDomain(props.url);- const { key, domain } = props;+ const { key, domain, tagId } = props;const shortlink = useMemo(() => {return linkConstructor({@@ -52,48 +53,34 @@ function TagLinkModal({/><h3 className="text-lg font-medium">Tag {shortlink}</h3><p className="text-sm text-gray-500">- {/* {archived- ? "Archived links will still work - they just won't show up on your main dashboard."- : "By untagging this link, it will show up on your main dashboard again."} */}Assign a tag to your short link</p></div>- <div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16">- <button- onClick={async (e) => {- e.preventDefault();- setTagging(true);- fetch(- `/api/links/${props.key}/tag${- slug ? `?slug=${slug}&domain=${domain}` : ""- }}`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- },- ).then(async (res) => {- setTagging(false);- if (res.status === 200) {- mutate(`/api/links${getQueryString(router)}`);- setShowTagLinkModal(false);- } else {- toast.error(res.statusText);- }- });- }}- disabled={tagging}- className={`${- tagging- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"- : "border-black bg-black text-white hover:bg-white hover:text-black"- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}- >- {tagging ? <LoadingDots color="#808080" /> : <p>Confirm tag</p>}- </button>- </div>+ <form+ className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"+ onSubmit={async (e) => {+ e.preventDefault();+ setTagging(true);+ fetch(`/api/links/${props.key}/tag?slug=${slug}&domain=${domain}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ }).then(async (res) => {+ setTagging(false);+ if (res.status === 200) {+ mutate(`/api/links${getQueryString(router)}`);+ setShowTagLinkModal(false);+ } else {+ const error = await res.text();+ toast.error(error);+ }+ });+ }}+ >+ <Button loading={tagging} text="Confirm tag" />+ </form></div></Modal>);diff --git a/components/app/projects/project-card.tsx b/components/app/projects/project-card.tsxindex 84d28c7675..a6a8c9d74c 100644--- a/components/app/projects/project-card.tsx+++ b/components/app/projects/project-card.tsx@@ -19,7 +19,7 @@ export default function ProjectCard({primaryDomain,}: ProjectWithDomainProps) {const { data: count } = useSWR<number>(- `/api/links/count?slug=${slug}`,+ `/api/links/_count?slug=${slug}`,fetcher,);return (diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsxindex 1a0220eda3..a56b87d84d 100644--- a/components/layout/app/project-select.tsx+++ b/components/layout/app/project-select.tsx@@ -113,7 +113,7 @@ function ProjectList({className={`relative flex w-full items-center space-x-2 rounded-md px-2 py-1.5 hover:bg-gray-100 active:bg-gray-200 ${selected.slug === "/" ? "font-medium" : ""} transition-all duration-75`}- onClick={() => router.push("/")}+ onClick={() => router.push("/links")}><BlurImagesrc={diff --git a/lib/api/links.ts b/lib/api/links.tsindex ff870b39c9..ad8443cd9f 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -58,29 +58,33 @@ const getFiltersFromStatus = (status: string) => {export async function getLinksForProject({projectId,domain,- status = "active",- tag,+ tagId,search,sort = "createdAt",userId,+ showArchived,}: {projectId: string;domain?: string;- status?: string;- tag?: string;+ tagId?: string;search?: string;sort?: "createdAt" | "clicks"; // always descending for bothuserId?: string | null;+ showArchived?: boolean;}): Promise<LinkProps[]> {+ /*+ TODO: add pagination+ */return await prisma.link.findMany({where: {projectId,+ archived: showArchived ? undefined : false,...(domain && { domain }),...(search && {key: { search },url: { search },}),- // ...(tag && { tags: { has: tag } }),+ ...(tagId && { tagId }),...(userId && { userId }),},orderBy: {@@ -99,18 +103,20 @@ export async function getLinksCount({projectId: string;userId?: string | null;}) {- const { groupBy, search, domain, tagId } = req.query as {+ let { groupBy, search, domain, tagId, showArchived } = req.query as {groupBy?: "domain" | "tagId";search?: string;domain?: string;tagId?: string;+ showArchived?: boolean;};if (groupBy) {- return await prisma.link.groupBy({+ const inputs = await prisma.link.groupBy({by: [groupBy],where: {projectId,+ archived: showArchived ? undefined : false,...(userId && { userId }),...(search && {key: { search },@@ -120,10 +126,12 @@ export async function getLinksCount({groupBy !== "domain" && {domain,}),- ...(tagId &&- groupBy !== "tagId" && {- tagId,- }),+ ...(groupBy === "tagId" && {+ tagId,+ NOT: {+ tagId: null,+ },+ }),},_count: true,orderBy: {@@ -132,6 +140,27 @@ export async function getLinksCount({},},});+ if (groupBy === "tagId") {+ // for tags, we need to get the tag name+ const tags = await prisma.tag.findMany({+ where: {+ projectId,+ id: {+ // @ts-ignore+ in: inputs.map((input) => input.tagId),+ },+ },+ });+ return inputs.map((input) => {+ const tag = tags.find((tag) => tag.id === input.tagId)!;+ return {+ ...input,+ tag: tag.name,+ };+ });+ } else {+ return inputs;+ }} else {return await prisma.link.count({where: {diff --git a/lib/auth.ts b/lib/auth.tsindex 7c374d2260..12f972dd53 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -189,7 +189,8 @@ interface WithLinksAuthNextApiHandler {i. Make sure the project existsii. Make sure the user is part of the projectiii. Make sure the project is within its usage limits- iv. Make sure the domain is part of the project (prevent query injection)+ iv. Make sure the action is allowed for the project's plan+ v. Make sure the domain is part of the project (prevent query injection)*/const withLinksAuth =@@ -198,9 +199,11 @@ const withLinksAuth ={needNotExceededUsage, // if the action needs the user to not have exceeded their usageexcludeGet, // if the action doesn't need to be gated for GET requests+ requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan}: {needNotExceededUsage?: boolean;excludeGet?: boolean;+ requiredPlan?: Array<PlanProps>;} = {},) =>async (req: NextApiRequest, res: NextApiResponse) => {@@ -298,6 +301,10 @@ const withLinksAuth =return res.status(403).end("Unauthorized: Usage limits exceeded.");}+ if (requiredPlan && !requiredPlan.includes(project.plan)) {+ return res.status(403).end("Unauthorized: Need higher plan.");+ }+// if domain is definedif (domain) {// prevent domain from being query injected bydiff --git a/lib/constants/index.ts b/lib/constants/index.tsindex 52ae349ccc..4b756bdc5f 100644--- a/lib/constants/index.ts+++ b/lib/constants/index.ts@@ -44,7 +44,7 @@ export const SWIPE_REVEAL_ANIMATION_SETTINGS = {initial: { height: 0 },animate: { height: "auto" },exit: { height: 0 },- transition: { duration: 0.2, bounce: 0 },+ transition: { duration: 0.15, ease: "easeOut" },};export const FADE_IN_ANIMATION_SETTINGS = {diff --git a/lib/swr/use-links-count.ts b/lib/swr/use-links-count.tsindex 45e62446df..e92078b28d 100644--- a/lib/swr/use-links-count.ts+++ b/lib/swr/use-links-count.ts@@ -2,17 +2,16 @@ import { useRouter } from "next/router";import useSWR from "swr";import { fetcher, getQueryString } from "@/lib/utils";-export default function useLinksCount({ groupBy }: { groupBy: "domain" }) {+export default function useLinksCount({+ groupBy,+}: {+ groupBy: "domain" | "tagId";+}) {const router = useRouter();- const { data, error } = useSWR<- {- [groupBy]: string;- _count: number;- }[]- >(+ const { data, error } = useSWR<any[]>(router.isReady &&- `/api/links/count${getQueryString(+ `/api/links/_count${getQueryString(router,groupBy ? { groupBy } : undefined,)}`,diff --git a/lib/types.ts b/lib/types.tsindex 1dd290a893..3ad93334aa 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -23,6 +23,7 @@ export interface LinkProps {clicks: number;userId?: string | null;+ tagId?: string | null;createdAt?: Date;updatedAt?: Date;diff --git a/pages/api/links/[key]/archive.ts b/pages/api/links/[key]/archive.tsnew file mode 100644index 0000000000..63de95ef53--- /dev/null+++ b/pages/api/links/[key]/archive.ts@@ -0,0 +1,17 @@+import { archiveLink } from "@/lib/api/links";+import { withLinksAuth } from "@/lib/auth";++export default withLinksAuth(async (req, res, _session, _project, domain) => {+ const { key } = req.query as { key: string };++ if (req.method === "POST") {+ const response = await archiveLink(domain || "dub.sh", key, true);+ return res.status(200).json(response);+ } else if (req.method === "DELETE") {+ const response = await archiveLink(domain || "dub.sh", key, false);+ return res.status(200).json(response);+ } else {+ res.setHeader("Allow", ["POST", "DELETE"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+});diff --git a/pages/api/links/[key]/exists.ts b/pages/api/links/[key]/exists.tsindex 56f29581bc..50a17edf7a 100644--- a/pages/api/links/[key]/exists.ts+++ b/pages/api/links/[key]/exists.ts@@ -9,6 +9,6 @@ export default withLinksAuth(async (req, res, _session, _project, domain) => {return res.status(200).json(response);} else {res.setHeader("Allow", ["GET"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}});diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.tsindex 838fde1ca1..15c12ca35f 100644--- a/pages/api/links/[key]/index.ts+++ b/pages/api/links/[key]/index.ts@@ -50,7 +50,7 @@ export default withLinksAuth(oldKey,),...(!project- ? [fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok)]+ ? [fetch(`${GOOGLE_FAVICON_URL}${url}`).then((res) => !res.ok)]: []),// @ts-ignore]).then((results) => results.map((result) => result.value));@@ -80,9 +80,7 @@ export default withLinksAuth(return res.status(200).json(response);} else {res.setHeader("Allow", ["GET", "PUT", "DELETE"]);- return res- .status(405)- .json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}},{diff --git a/pages/api/links/[key]/stats/[endpoint].ts b/pages/api/links/[key]/stats/[endpoint].tsindex 85d2ab2a99..28612d60c8 100644--- a/pages/api/links/[key]/stats/[endpoint].ts+++ b/pages/api/links/[key]/stats/[endpoint].ts@@ -18,17 +18,13 @@ export default withLinksAuth(});if (!response) {- return res- .status(405)- .json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}return res.status(200).json(response);} else {res.setHeader("Allow", ["GET"]);- return res- .status(405)- .json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}},{diff --git a/pages/api/links/[key]/stats/index.ts b/pages/api/links/[key]/stats/index.tsindex b956b5d28f..abac4833b3 100644--- a/pages/api/links/[key]/stats/index.ts+++ b/pages/api/links/[key]/stats/index.ts@@ -40,6 +40,6 @@ export default withLinksAuth(async (req, res, _session, _project, domain) => {return res.status(200).json(response);} else {res.setHeader("Allow", ["PUT"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}});diff --git a/pages/api/links/[key]/tag.ts b/pages/api/links/[key]/tag.tsnew file mode 100644index 0000000000..119e8429bf--- /dev/null+++ b/pages/api/links/[key]/tag.ts@@ -0,0 +1,18 @@+import { withLinksAuth } from "@/lib/auth";++export default withLinksAuth(+ async (req, res, _session, _project, domain) => {+ const { key, tagId } = req.query as { key: string; tagId: string };++ if (req.method === "POST") {+ const response = key;+ return res.status(200).json(response);+ } else {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+ },+ {+ requiredPlan: ["pro", "enterprise"],+ },+);diff --git a/pages/api/links/count.ts b/pages/api/links/_count.tssimilarity index 88%rename from pages/api/links/count.tsrename to pages/api/links/_count.tsindex e925651f7c..3b2b247ac4 100644--- a/pages/api/links/count.ts+++ b/pages/api/links/_count.ts@@ -14,6 +14,6 @@ export default withLinksAuth(async (req, res, session, project) => {return res.status(200).json(count);} else {res.setHeader("Allow", ["GET"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}});diff --git a/pages/api/links/random.ts b/pages/api/links/_random.tssimilarity index 81%rename from pages/api/links/random.tsrename to pages/api/links/_random.tsindex 9c735bd11f..f61a24f226 100644--- a/pages/api/links/random.ts+++ b/pages/api/links/_random.ts@@ -7,6 +7,6 @@ export default withLinksAuth(async (req, res, _session, _project, domain) => {return res.status(200).json(response);} else {res.setHeader("Allow", ["GET"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}});diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 651597a222..7bb9891883 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -17,22 +17,23 @@ 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, status, tag, search, sort, userId } = req.query as {- domain?: string;- status?: string;- tag?: string;- search?: string;- sort?: "createdAt" | "clicks";- userId?: string;- };+ const { domain, tagId, search, sort, userId, showArchived } =+ req.query as {+ domain?: string;+ tagId?: string;+ search?: string;+ sort?: "createdAt" | "clicks";+ userId?: string;+ showArchived?: boolean;+ };const response = await getLinksForProject({projectId: project?.id || DUB_PROJECT_ID,domain,- status,- tag,+ tagId,search,sort,userId: project?.id ? userId : session.user.id,+ showArchived,});return res.status(200).json(response);@@ -65,7 +66,7 @@ export default withLinksAuth(userId: session.user.id,}),...(!project- ? [fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok)]+ ? [fetch(`${GOOGLE_FAVICON_URL}${url}`).then((res) => !res.ok)]: []),// @ts-ignore]).then((results) => results.map((result) => result.value));@@ -91,9 +92,7 @@ export default withLinksAuth(return res.status(200).json(response);} else {res.setHeader("Allow", ["GET", "POST"]);- return res- .status(405)- .json({ error: `Method ${req.method} Not Allowed` });+ return res.status(405).end(`Method ${req.method} Not Allowed`);}},{diff --git a/posts/changelog/keyboard-shortcuts.mdx b/posts/changelog/keyboard-shortcuts.mdxindex 75f0f09dee..cc19a9334f 100644--- a/posts/changelog/keyboard-shortcuts.mdx+++ b/posts/changelog/keyboard-shortcuts.mdx@@ -16,7 +16,7 @@ Here's a list of all the shortcuts to get you started:| `/` | Focus on the link search input | No || `e` | Edit the selected short link | Yes || `d` | Duplicate the selected short link | Yes |-| `t` | Tag the selected short link | Yes |+| `a` | Archive the selected short link | Yes || `x` | Delete the selected short link | Yes |Have any suggestions for new shortcuts? Let us know by creating a [new issue](https://github.com/steven-tey/dub/issues/new?title=Shortcut%20Request&labels=enhancement).diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex b7e45cf87d..01d45639dc 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -157,7 +157,7 @@ model Link {domain String // domain of the link (e.g. dub.sh) – also stored on Rediskey String // key of the link (e.g. /github) – also stored on Redisurl String @db.LongText // target url (e.g. https://github.com/steven-tey/dub) – also stored on Redis- archived Boolean @default(false) // whether the link is archived or not (TODO: REMOVE AFTER ADDING TAGS)+ archived Boolean @default(false) // whether the link is archived or notexpiresAt DateTime? // when the link expires – stored on Redis via ttlpassword String? // password to access the link – also stored on Redis