Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

moved add-project-modal to modal provider, replaced use-endpoint with statscontext

Steven Tey4ffc5e54850f
diff --git a/app/ui/modal-provider.tsx b/app/ui/modal-provider.tsx
new file mode 100644
index 0000000000..cd5fb10ba6
--- /dev/null
+++ b/app/ui/modal-provider.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { Dispatch, ReactNode, SetStateAction, createContext } from "react";
+import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
+
+export const ModalContext = createContext<{
+ setShowAddProjectModal: Dispatch<SetStateAction<boolean>>;
+}>({
+ setShowAddProjectModal: () => {},
+});
+
+export default function ModalProvider({ children }: { children: ReactNode }) {
+ const { AddProjectModal, setShowAddProjectModal } = useAddProjectModal();
+
+ return (
+ <ModalContext.Provider value={{ setShowAddProjectModal }}>
+ <AddProjectModal />
+ {children}
+ </ModalContext.Provider>
+ );
+}
diff --git a/app/ui/stats/index.tsx b/app/ui/stats/index.tsx
index 9f7c9e03f6..3125be1982 100644
--- a/app/ui/stats/index.tsx
+++ b/app/ui/stats/index.tsx
@@ -8,7 +8,7 @@
We use the `useEndpoint()` hook to get the correct layout
*/
-import { createContext, useCallback, useMemo, useRef, useState } from "react";
+import { createContext, useMemo } from "react";
import {
useParams,
usePathname,
@@ -21,7 +21,6 @@ import Feedback from "./feedback";
import Locations from "./locations";
import Referer from "./referer";
import Toggle from "./toggle";
-import useScroll from "#/lib/hooks/use-scroll";
import { X } from "lucide-react";
export const StatsContext = createContext<{
diff --git a/app/ui/stats/toggle.tsx b/app/ui/stats/toggle.tsx
index 1a9c1c1e70..a43d0ef5d0 100644
--- a/app/ui/stats/toggle.tsx
+++ b/app/ui/stats/toggle.tsx
@@ -98,10 +98,10 @@ export default function Toggle() {
const SharePopover = () => {
const [openSharePopover, setopenSharePopoverPopover] = useState(false);
- const { endpoint, domain, key } = useContext(StatsContext);
+ const { endpoint, domain, key, queryString } = useContext(StatsContext);
const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(
- `${endpoint}?domain=${domain}`,
+ `${endpoint}${queryString}`,
fetcher,
);
@@ -111,7 +111,7 @@ const SharePopover = () => {
toast.promise(
new Promise<void>(async (resolve) => {
setUpdating(true);
- const res = await fetch(`${endpoint}?domain=${domain}`, {
+ const res = await fetch(`${endpoint}${queryString}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
@@ -121,7 +121,7 @@ const SharePopover = () => {
}),
});
if (res.status === 200) {
- mutate(`${endpoint}?domain=${domain}`);
+ mutate(`${endpoint}${queryString}`);
// artificial delay to sync toast with the switch change
await new Promise((r) => setTimeout(r, 200));
}
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 5e8f2b736c..c2408c0116 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -3,19 +3,13 @@ import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import useSWR from "swr";
import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal";
-import { useArchiveLinkModal } from "@/components/app/modals/archive-link-modal";
+import { useTagLinkModal } from "@/components/app/modals/tag-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";
import BlurImage from "#/ui/blur-image";
import CopyButton from "@/components/shared/copy-button";
-import {
- Archive,
- Chart,
- Delete,
- QR,
- ThreeDots,
-} from "@/components/shared/icons";
+import { Chart, Delete, QR, ThreeDots } from "@/components/shared/icons";
import Popover from "@/components/shared/popover";
import Tooltip, { TooltipContent } from "#/ui/tooltip";
import useProject from "@/lib/swr/use-project";
@@ -29,7 +23,7 @@ import {
} from "@/lib/utils";
import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
import useDomains from "@/lib/swr/use-domains";
-import { CopyPlus, Edit3 } from "lucide-react";
+import { CopyPlus, Edit3, Tag } from "lucide-react";
import punycode from "punycode/";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
@@ -85,9 +79,8 @@ export default function LinkCard({ props }: { props: LinkProps }) {
},
});
- const { setShowArchiveLinkModal, ArchiveLinkModal } = useArchiveLinkModal({
+ const { setShowTagLinkModal, TagLinkModal } = useTagLinkModal({
props,
- archived: !archived,
});
const { setShowDeleteLinkModal, DeleteLinkModal } = useDeleteLinkModal({
props,
@@ -109,7 +102,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
}
};
- const shortcuts = ["e", "d", "a", "x"];
+ const shortcuts = ["e", "d", "t", "x"];
const onKeyDown = (e: any) => {
// only run shortcut logic if:
// - usage is not exceeded
@@ -128,8 +121,8 @@ export default function LinkCard({ props }: { props: LinkProps }) {
case "d":
setShowDuplicateLinkModal(true);
break;
- case "a":
- setShowArchiveLinkModal(true);
+ case "t":
+ setShowTagLinkModal(true);
break;
case "x":
setShowDeleteLinkModal(true);
@@ -157,7 +150,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<LinkQRModal />
<AddEditLinkModal />
<DuplicateLinkModal />
- <ArchiveLinkModal />
+ <TagLinkModal />
<DeleteLinkModal />
<li className="relative flex items-center justify-between">
<div className="relative flex shrink items-center space-x-2 sm:space-x-4">
@@ -327,16 +320,13 @@ export default function LinkCard({ props }: { props: LinkProps }) {
onClick={(e) => {
e.preventDefault();
setOpenPopover(false);
- setShowArchiveLinkModal(true);
+ 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={archived ? "Unarchive" : "Archive"}
- icon={<Archive className="h-4 w-4" />}
- />
+ <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">
- A
+ T
</kbd>
</button>
<button
diff --git a/components/app/links/link-filters.tsx b/components/app/links/link-filters.tsx
index 11a623992f..b973efcb07 100644
--- a/components/app/links/link-filters.tsx
+++ b/components/app/links/link-filters.tsx
@@ -1,5 +1,13 @@
import { useRouter } from "next/router";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { nFormatter, setQueryString } from "@/lib/utils";
import { ChevronRight, XCircle, Search } from "lucide-react";
import useDomains from "@/lib/swr/use-domains";
@@ -13,6 +21,8 @@ import useLinksCount from "@/lib/swr/use-links-count";
import punycode from "punycode/";
import Switch from "#/ui/switch";
import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+import { ModalContext } from "#/ui/modal-provider";
export default function LinkFilters() {
const { primaryDomain } = useDomains();
@@ -26,6 +36,8 @@ export default function LinkFilters() {
};
const searchInputRef = useRef(); // this is a hack to clear the search input when the clear button is clicked
+ const { setShowAddProjectModal } = useContext(ModalContext);
+
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">
@@ -48,11 +60,28 @@ export default function LinkFilters() {
count: _count,
}))
}
- cta={{
- type: "link",
- text: "Add a domain",
- href: `/${slug}/domains`,
- }}
+ cta={
+ slug ? (
+ <Link
+ href={`/${slug}/domains`}
+ className="rounded-md border border-gray-300 p-1 text-center text-sm"
+ >
+ Add a domain
+ </Link>
+ ) : (
+ <button
+ 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.",
+ );
+ }}
+ className="rounded-md border border-gray-300 p-1 text-center text-sm"
+ >
+ Add a domain
+ </button>
+ )
+ }
/>
</div>
) : (
@@ -61,6 +90,7 @@ export default function LinkFilters() {
</div>
);
}
+
const SearchBox = ({ searchInputRef }: { searchInputRef }) => {
const router = useRouter();
const debounced = useDebouncedCallback((value) => {
@@ -139,12 +169,7 @@ const FilterGroup = ({
}: {
param: string;
options: { value: string; count: number }[];
- cta: {
- type: "link" | "button";
- text: string;
- href?: string;
- action?: () => void;
- };
+ cta: ReactNode;
}) => {
const router = useRouter();
const [collapsed, setCollapsed] = useState(false);
@@ -196,14 +221,7 @@ const FilterGroup = ({
</label>
</div>
))}
- {router.query.slug && cta.href && (
- <Link
- href={cta.href}
- className="rounded-md border border-gray-300 p-1 text-center text-sm"
- >
- {cta.text}
- </Link>
- )}
+ {cta}
</motion.div>
)}
</AnimatePresence>
diff --git a/components/app/modals/add-project-modal.tsx b/components/app/modals/add-project-modal.tsx
index 3ea1cc3660..43ac1e8372 100644
--- a/components/app/modals/add-project-modal.tsx
+++ b/components/app/modals/add-project-modal.tsx
@@ -121,6 +121,7 @@ function AddProjectModalHelper({
slugError: slugErrorResponse,
domainError: domainErrorResponse,
} = await res.json();
+
if (slugErrorResponse) {
setSlugError(slugErrorResponse);
toast.error(slugErrorResponse);
diff --git a/components/app/modals/stats-modal.tsx b/components/app/modals/stats-modal.tsx
deleted file mode 100644
index f2007d7c89..0000000000
--- a/components/app/modals/stats-modal.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { useRouter } from "next/router";
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useMemo,
- useState,
-} from "react";
-import { UIEvent } from "react";
-import { X } from "@/components/shared/icons";
-import Modal from "@/components/shared/modal";
-import Stats from "@/components/stats";
-
-function StatsModalHelper({
- showStatsModal,
- setShowStatsModal,
-}: {
- showStatsModal: boolean;
- setShowStatsModal: Dispatch<SetStateAction<boolean>>;
-}) {
- const router = useRouter();
- const [atModalTop, setAtModalTop] = useState(false);
-
- const handleScroll = (event: UIEvent<HTMLElement>) => {
- if (event.currentTarget.scrollTop > 144) {
- setAtModalTop(true);
- } else {
- setAtModalTop(false);
- }
- };
-
- return (
- <Modal
- showModal={showStatsModal}
- setShowModal={setShowStatsModal}
- bgColor="bg-gray-50"
- >
- <div
- onScroll={handleScroll}
- className="inline-block max-h-[calc(100vh-150px)] w-full max-w-screen-xl transform overflow-scroll bg-gray-50
- align-middle shadow-xl scrollbar-hide sm:rounded-2xl sm:border sm:border-gray-200"
- >
- <button
- className="group sticky top-4 right-4 z-30 float-right hidden rounded-full p-3 transition-all duration-75 hover:bg-gray-100 focus:outline-none active:scale-75 sm:block"
- autoFocus={false}
- onClick={() => {
- router.push("/", undefined, { scroll: false });
- }}
- >
- <X className="h-6 w-6" />
- </button>
- <Stats atModalTop={atModalTop} staticDomain="dub.sh" />
- </div>
- </Modal>
- );
-}
-
-export function useStatsModal() {
- const [showStatsModal, setShowStatsModal] = useState(false);
-
- const StatsModal = useCallback(() => {
- return (
- <StatsModalHelper
- showStatsModal={showStatsModal}
- setShowStatsModal={setShowStatsModal}
- />
- );
- }, [showStatsModal, setShowStatsModal]);
-
- return useMemo(
- () => ({ setShowStatsModal, StatsModal }),
- [setShowStatsModal, StatsModal],
- );
-}
diff --git a/components/app/modals/archive-link-modal.tsx b/components/app/modals/tag-link-modal.tsx
similarity index 62%
rename from components/app/modals/archive-link-modal.tsx
rename to components/app/modals/tag-link-modal.tsx
index 6576b479f8..1bb2e11282 100644
--- a/components/app/modals/archive-link-modal.tsx
+++ b/components/app/modals/tag-link-modal.tsx
@@ -15,20 +15,18 @@ import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
import { toast } from "sonner";
-function ArchiveLinkModal({
- showArchiveLinkModal,
- setShowArchiveLinkModal,
+function TagLinkModal({
+ showTagLinkModal,
+ setShowTagLinkModal,
props,
- archived,
}: {
- showArchiveLinkModal: boolean;
- setShowArchiveLinkModal: Dispatch<SetStateAction<boolean>>;
+ showTagLinkModal: boolean;
+ setShowTagLinkModal: Dispatch<SetStateAction<boolean>>;
props: LinkProps;
- archived: boolean;
}) {
const router = useRouter();
const { slug } = router.query;
- const [archiving, setArchiving] = useState(false);
+ const [tagging, setTagging] = useState(false);
const apexDomain = getApexDomain(props.url);
const { key, domain } = props;
@@ -42,10 +40,7 @@ function ArchiveLinkModal({
}, [key, domain]);
return (
- <Modal
- showModal={showArchiveLinkModal}
- setShowModal={setShowArchiveLinkModal}
- >
+ <Modal showModal={showTagLinkModal} setShowModal={setShowTagLinkModal}>
<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
@@ -55,13 +50,12 @@ function ArchiveLinkModal({
width={20}
height={20}
/>
- <h3 className="text-lg font-medium">
- {archived ? "Archive" : "Unarchive"} {shortlink}
- </h3>
+ <h3 className="text-lg font-medium">Tag {shortlink}</h3>
<p className="text-sm text-gray-500">
- {archived
+ {/* {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."}
+ : "By untagging this link, it will show up on your main dashboard again."} */}
+ Assign a tag to your short link
</p>
</div>
@@ -69,39 +63,35 @@ function ArchiveLinkModal({
<button
onClick={async (e) => {
e.preventDefault();
- setArchiving(true);
+ setTagging(true);
fetch(
- `/api/links/${props.key}/archive${
+ `/api/links/${props.key}/tag${
slug ? `?slug=${slug}&domain=${domain}` : ""
}}`,
{
- method: archived ? "POST" : "DELETE",
+ method: "POST",
headers: {
"Content-Type": "application/json",
},
},
).then(async (res) => {
- setArchiving(false);
+ setTagging(false);
if (res.status === 200) {
mutate(`/api/links${getQueryString(router)}`);
- setShowArchiveLinkModal(false);
+ setShowTagLinkModal(false);
} else {
toast.error(res.statusText);
}
});
}}
- disabled={archiving}
+ disabled={tagging}
className={`${
- archiving
+ 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`}
>
- {archiving ? (
- <LoadingDots color="#808080" />
- ) : (
- <p>Confirm {archived ? "archive" : "unarchive"}</p>
- )}
+ {tagging ? <LoadingDots color="#808080" /> : <p>Confirm tag</p>}
</button>
</div>
</div>
@@ -109,31 +99,24 @@ function ArchiveLinkModal({
);
}
-export function useArchiveLinkModal({
- props,
- archived = true,
-}: {
- props: LinkProps;
- archived: boolean;
-}) {
- const [showArchiveLinkModal, setShowArchiveLinkModal] = useState(false);
+export function useTagLinkModal({ props }: { props: LinkProps }) {
+ const [showTagLinkModal, setShowTagLinkModal] = useState(false);
- const ArchiveLinkModalCallback = useCallback(() => {
+ const TagLinkModalCallback = useCallback(() => {
return props ? (
- <ArchiveLinkModal
- showArchiveLinkModal={showArchiveLinkModal}
- setShowArchiveLinkModal={setShowArchiveLinkModal}
+ <TagLinkModal
+ showTagLinkModal={showTagLinkModal}
+ setShowTagLinkModal={setShowTagLinkModal}
props={props}
- archived={archived}
/>
) : null;
- }, [showArchiveLinkModal, setShowArchiveLinkModal]);
+ }, [showTagLinkModal, setShowTagLinkModal]);
return useMemo(
() => ({
- setShowArchiveLinkModal,
- ArchiveLinkModal: ArchiveLinkModalCallback,
+ setShowTagLinkModal,
+ TagLinkModal: TagLinkModalCallback,
}),
- [setShowArchiveLinkModal, ArchiveLinkModalCallback],
+ [setShowTagLinkModal, TagLinkModalCallback],
);
}
diff --git a/components/app/projects/no-projects-placeholder.tsx b/components/app/projects/no-projects-placeholder.tsx
index cf538d8d3a..cc97f01690 100644
--- a/components/app/projects/no-projects-placeholder.tsx
+++ b/components/app/projects/no-projects-placeholder.tsx
@@ -1,11 +1,11 @@
import Link from "next/link";
import BlurImage from "#/ui/blur-image";
+import { useContext } from "react";
+import { ModalContext } from "#/ui/modal-provider";
+
+export default function NoProjectsPlaceholder() {
+ const { setShowAddProjectModal } = useContext(ModalContext);
-export default function NoProjectsPlaceholder({
- setShowAddProjectModal,
-}: {
- setShowAddProjectModal: (show: boolean) => void;
-}) {
return (
<div className="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">
diff --git a/components/layout/app/index.tsx b/components/layout/app/index.tsx
index c9f2b7585e..c0b95f3573 100644
--- a/components/layout/app/index.tsx
+++ b/components/layout/app/index.tsx
@@ -71,7 +71,7 @@ export default function AppLayout({
<div
className={`min-h-screen w-full ${bgWhite ? "bg-white" : "bg-gray-50"}`}
>
- <div className="sticky left-0 right-0 top-0 z-30 border-b border-gray-200 bg-white">
+ <div className="sticky left-0 right-0 top-0 z-20 border-b border-gray-200 bg-white">
<div className="mx-auto max-w-screen-xl px-2.5 md:px-20">
<div className="flex h-16 items-center justify-between">
<div className="flex items-center">
diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsx
index c35f22c7b4..1a0220eda3 100644
--- a/components/layout/app/project-select.tsx
+++ b/components/layout/app/project-select.tsx
@@ -1,5 +1,5 @@
import { useRouter } from "next/router";
-import { useMemo, useState } from "react";
+import { useContext, useMemo, useState } from "react";
import { useSession } from "next-auth/react";
import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
import BlurImage from "#/ui/blur-image";
@@ -9,10 +9,10 @@ import { PlanProps, ProjectWithDomainProps } from "@/lib/types";
import useProjects from "@/lib/swr/use-projects";
import PlanBadge from "@/components/app/settings/plan-badge";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
+import { ModalContext } from "#/ui/modal-provider";
export default function ProjectSelect() {
const { projects } = useProjects();
- const { AddProjectModal, setShowAddProjectModal } = useAddProjectModal();
const router = useRouter();
const { slug } = router.query as {
@@ -60,15 +60,8 @@ export default function ProjectSelect() {
return (
<div>
- <AddProjectModal />
<Popover
- content={
- <ProjectList
- selected={selected}
- projects={projects}
- setShowAddProjectModal={setShowAddProjectModal}
- />
- }
+ content={<ProjectList selected={selected} projects={projects} />}
openPopover={openPopover}
setOpenPopover={setOpenPopover}
>
@@ -99,7 +92,6 @@ export default function ProjectSelect() {
function ProjectList({
selected,
projects,
- setShowAddProjectModal,
}: {
selected: {
name: string;
@@ -108,16 +100,51 @@ function ProjectList({
plan: PlanProps;
};
projects: ProjectWithDomainProps[];
- setShowAddProjectModal: (show: boolean) => void;
}) {
const router = useRouter();
+ const { data: session } = useSession();
+ const { setShowAddProjectModal } = useContext(ModalContext);
return (
- <div className="relative mt-1 max-h-60 w-full overflow-auto rounded-md bg-white p-2 text-base sm:w-60 sm:text-sm sm:shadow-lg">
+ <div className="relative mt-1 max-h-72 w-full space-y-0.5 overflow-auto rounded-md bg-white p-2 text-base sm:w-60 sm:text-sm sm:shadow-lg">
+ <div className="p-2 text-xs text-gray-500">Personal Account</div>
+ <button
+ key="personal"
+ 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("/")}
+ >
+ <BlurImage
+ src={
+ session?.user?.image ||
+ `https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`
+ }
+ alt={
+ session?.user?.name || session?.user?.email || "Personal Account"
+ }
+ className="h-7 w-7 overflow-hidden rounded-full"
+ width={48}
+ height={48}
+ />
+ <span
+ className={`block truncate text-sm ${
+ selected.slug === "/" ? "font-medium" : "font-normal"
+ }`}
+ >
+ {session?.user?.name || session?.user?.email}
+ </span>
+ {selected.slug === "/" ? (
+ <span className="absolute inset-y-0 right-0 flex items-center pr-3 text-black">
+ <Tick className="h-5 w-5" aria-hidden="true" />
+ </span>
+ ) : null}
+ </button>
+ <div className="p-2 text-xs text-gray-500">Custom Projects</div>
{projects.map(({ name, slug, logo, primaryDomain }) => (
<button
key={slug}
- className={`relative flex w-full items-center space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200 ${
+ 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 === slug ? "font-medium" : ""
} transition-all duration-75`}
onClick={() => router.push(`/${slug}`)}
diff --git a/components/stats/bar-chart.tsx b/components/stats/bar-chart.tsx
index b2c6ff8fe6..0c760ec141 100644
--- a/components/stats/bar-chart.tsx
+++ b/components/stats/bar-chart.tsx
@@ -1,5 +1,5 @@
import { useRouter } from "next/router";
-import { useMemo } from "react";
+import { useContext, useMemo } from "react";
import { AxisBottom, AxisLeft } from "@visx/axis";
import { localPoint } from "@visx/event";
import { GridRows } from "@visx/grid";
@@ -13,7 +13,7 @@ import styles from "./bar-chart.module.css";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { LoadingCircle } from "#/ui/icons";
-import useEndpoint from "@/lib/hooks/use-endpoint";
+import { StatsContext } from ".";
const LEFT_AXIS_WIDTH = 30;
const CHART_MAX_HEIGHT = 400;
@@ -41,7 +41,7 @@ const BarChart = ({ screenWidth }: { screenWidth?: number }) => {
interval?: string;
};
- const { endpoint, queryString } = useEndpoint();
+ const { endpoint, queryString } = useContext(StatsContext);
const { data } = useSWR<{ start: Date; clicks: number }[]>(
router.isReady && `${endpoint}/timeseries${queryString}`,
diff --git a/components/stats/clicks.tsx b/components/stats/clicks.tsx
index db49bf9030..490b5a0596 100644
--- a/components/stats/clicks.tsx
+++ b/components/stats/clicks.tsx
@@ -4,11 +4,12 @@ import { nFormatter } from "@/lib/utils";
import { useRouter } from "next/router";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import useEndpoint from "@/lib/hooks/use-endpoint";
+import { useContext } from "react";
+import { StatsContext } from ".";
export default function Clicks() {
const router = useRouter();
- const { endpoint, queryString } = useEndpoint();
+ const { endpoint, queryString } = useContext(StatsContext);
const { data: totalClicks } = useSWR<number>(
router.isReady && `${endpoint}/clicks${queryString}`,
diff --git a/components/stats/devices.tsx b/components/stats/devices.tsx
index c9490e2840..c9ed08f4b6 100644
--- a/components/stats/devices.tsx
+++ b/components/stats/devices.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useContext, useMemo, useState } from "react";
import { useRouter } from "next/router";
import { motion } from "framer-motion";
import BadgeSelect from "@/components/shared/badge-select";
@@ -8,13 +8,13 @@ import { nFormatter } from "@/lib/utils";
import DeviceIcon from "./device-icon";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import useEndpoint from "@/lib/hooks/use-endpoint";
+import { StatsContext } from ".";
export default function Devices() {
const [tab, setTab] = useState<DeviceTabs>("device");
const router = useRouter();
- const { endpoint, queryString } = useEndpoint();
+ const { endpoint, queryString } = useContext(StatsContext);
const { data } = useSWR<
({
diff --git a/components/stats/index.tsx b/components/stats/index.tsx
index ca10852818..0deeac5276 100644
--- a/components/stats/index.tsx
+++ b/components/stats/index.tsx
@@ -1,9 +1,29 @@
-import Clicks from "@/components/stats/clicks";
-import Devices from "@/components/stats/devices";
-import Feedback from "@/components/stats/feedback";
-import Locations from "@/components/stats/locations";
-import Referer from "@/components/stats/referer";
-import Toggle from "@/components/stats/toggle";
+import { useRouter } from "next/router";
+import { createContext, useMemo } from "react";
+import Clicks from "./clicks";
+import Devices from "./devices";
+import Feedback from "./feedback";
+import Locations from "./locations";
+import Referer from "./referer";
+import Toggle from "./toggle";
+
+export const StatsContext = createContext<{
+ basePath: string;
+ endpoint: string;
+ queryString: string;
+ interval: string;
+ domain: string;
+ key: string;
+ modal?: boolean;
+}>({
+ basePath: "",
+ endpoint: "",
+ queryString: "",
+ interval: "",
+ domain: "",
+ key: "",
+ modal: false,
+});
export default function Stats({
atModalTop,
@@ -12,18 +32,77 @@ export default function Stats({
atModalTop?: boolean;
staticDomain?: string;
}) {
+ const router = useRouter();
+ const {
+ slug,
+ domain: domainSlug,
+ key,
+ interval = "24h",
+ } = router.query as {
+ slug?: string;
+ domain?: string;
+ key: string;
+ interval?: string;
+ };
+
+ const queryString =
+ interval || domainSlug
+ ? `?${new URLSearchParams({
+ ...(slug && { slug }),
+ ...(interval && { interval }),
+ ...(domainSlug && { domain: domainSlug }),
+ }).toString()}`
+ : "";
+
+ const { basePath, domain, endpoint } = useMemo(() => {
+ // Project link page, e.g. app.dub.sh/dub/dub.sh/github
+ if (slug && domainSlug && key) {
+ return {
+ basePath: `/${slug}/${domainSlug}/${encodeURIComponent(key)}`,
+ domain: domainSlug,
+ endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
+ };
+
+ // Generic Dub.sh link page, e.g. app.dub.sh/links/steven
+ } else if (key && router.asPath.startsWith("/links")) {
+ return {
+ basePath: `/links/${encodeURIComponent(key)}`,
+ domain: "dub.sh",
+ endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
+ };
+ }
+
+ // Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergpt
+ return {
+ basePath: `/stats/${encodeURIComponent(key)}`,
+ domain: staticDomain,
+ endpoint: `/api/edge/links/${encodeURIComponent(key)}/stats`,
+ };
+ }, [slug, key, router.asPath]);
+
return (
- <div className="bg-gray-50 py-10">
- <Toggle atModalTop={atModalTop} staticDomain={staticDomain} />
- <div className="mx-auto grid max-w-4xl gap-5">
- <Clicks />
- <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
- <Locations />
- <Devices />
- <Referer />
- <Feedback />
+ <StatsContext.Provider
+ value={{
+ basePath, // basePath for the page (e.g. /stats/[key], /links/[key], /[slug]/[domain]/[key])
+ domain: domain!, // domain for the link (e.g. dub.sh, stey.me, etc.)
+ endpoint, // endpoint for the API (e.g. /api/edge/links/[key]/stats)
+ queryString, // query string for the API (e.g. ?interval=24h&domain=dub.sh, ?interval=24h, etc.)
+ interval, // time interval (e.g. 24h, 7d, 30d, etc.)
+ key, // link key (e.g. github, weathergpt, etc.)
+ }}
+ >
+ <div className="bg-gray-50 py-10">
+ <Toggle atModalTop={atModalTop} />
+ <div className="mx-auto grid max-w-4xl gap-5">
+ <Clicks />
+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
+ <Locations />
+ <Devices />
+ <Referer />
+ <Feedback />
+ </div>
</div>
</div>
- </div>
+ </StatsContext.Provider>
);
}
diff --git a/components/stats/locations.tsx b/components/stats/locations.tsx
index ae498890bc..7e1783352d 100644
--- a/components/stats/locations.tsx
+++ b/components/stats/locations.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useContext, useState } from "react";
import { motion } from "framer-motion";
import BadgeSelect from "@/components/shared/badge-select";
import { COUNTRIES } from "@/lib/constants";
@@ -8,13 +8,13 @@ import { LoadingCircle } from "#/ui/icons";
import { useRouter } from "next/router";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import useEndpoint from "@/lib/hooks/use-endpoint";
+import { StatsContext } from ".";
export default function Locations() {
const [tab, setTab] = useState<LocationTabs>("country");
const router = useRouter();
- const { endpoint, queryString } = useEndpoint();
+ const { endpoint, queryString } = useContext(StatsContext);
const { data } = useSWR<{ country: string; city: string; clicks: number }[]>(
router.isReady && `${endpoint}/${tab}${queryString}`,
diff --git a/components/stats/referer.tsx b/components/stats/referer.tsx
index 594a36f655..7f49638417 100644
--- a/components/stats/referer.tsx
+++ b/components/stats/referer.tsx
@@ -6,13 +6,14 @@ import { LoadingCircle } from "#/ui/icons";
import { nFormatter } from "@/lib/utils";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import useEndpoint from "@/lib/hooks/use-endpoint";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
+import { useContext } from "react";
+import { StatsContext } from ".";
export default function Referer() {
const router = useRouter();
- const { endpoint, queryString } = useEndpoint();
+ const { endpoint, queryString } = useContext(StatsContext);
const { data } = useSWR<{ referer: string; clicks: number }[]>(
router.isReady && `${endpoint}/referer${queryString}`,
diff --git a/components/stats/toggle.tsx b/components/stats/toggle.tsx
index 89f430d772..96f6aac74a 100644
--- a/components/stats/toggle.tsx
+++ b/components/stats/toggle.tsx
@@ -1,5 +1,5 @@
import { useRouter } from "next/router";
-import { useMemo, useState } from "react";
+import { useContext, useMemo, useState } from "react";
import {
Calendar,
ChevronDown,
@@ -17,22 +17,12 @@ import useSWR, { mutate } from "swr";
import { fetcher } from "@/lib/utils";
import { toast } from "sonner";
import Switch from "#/ui/switch";
-import useEndpoint from "@/lib/hooks/use-endpoint";
+import { StatsContext } from ".";
-export default function Toggle({
- atModalTop,
- staticDomain,
-}: {
- atModalTop?: boolean;
- staticDomain?: string;
-}) {
+export default function Toggle({ atModalTop }: { atModalTop?: boolean }) {
const router = useRouter();
- const { key, interval = "24h" } = router.query as {
- key: string;
- interval?: string;
- };
- const { basePath, domain } = useEndpoint(staticDomain);
+ const { basePath, domain, interval, key } = useContext(StatsContext);
const atTop = useScroll(80) || atModalTop;
const [openDatePopover, setOpenDatePopover] = useState(false);
@@ -121,10 +111,10 @@ const SharePopover = () => {
const [openSharePopover, setopenSharePopoverPopover] = useState(false);
- const { endpoint, domain } = useEndpoint();
+ const { endpoint, domain, queryString } = useContext(StatsContext);
const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(
- `${endpoint}?domain=${domain}`,
+ `${endpoint}${queryString}`,
fetcher,
);
@@ -134,7 +124,7 @@ const SharePopover = () => {
toast.promise(
new Promise<void>(async (resolve) => {
setUpdating(true);
- const res = await fetch(`${endpoint}?domain=${domain}`, {
+ const res = await fetch(`${endpoint}${queryString}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
@@ -144,7 +134,7 @@ const SharePopover = () => {
}),
});
if (res.status === 200) {
- mutate(`${endpoint}?domain=${domain}`);
+ mutate(`${endpoint}${queryString}`);
// artificial delay to sync toast with the switch change
await new Promise((r) => setTimeout(r, 200));
}
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 5d345786a1..ff870b39c9 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -99,10 +99,11 @@ export async function getLinksCount({
projectId: string;
userId?: string | null;
}) {
- const { groupBy, search, domain } = req.query as {
- groupBy?: "domain";
+ const { groupBy, search, domain, tagId } = req.query as {
+ groupBy?: "domain" | "tagId";
search?: string;
domain?: string;
+ tagId?: string;
};
if (groupBy) {
@@ -119,6 +120,10 @@ export async function getLinksCount({
groupBy !== "domain" && {
domain,
}),
+ ...(tagId &&
+ groupBy !== "tagId" && {
+ tagId,
+ }),
},
_count: true,
orderBy: {
diff --git a/lib/auth.ts b/lib/auth.ts
index b4704405e0..7c374d2260 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -183,13 +183,13 @@ interface WithLinksAuthNextApiHandler {
1. Check if user is logged in, if not, return 401 right away.
2. Check if there's a `slug` in the query params:
a. If there is no slug, it means that it's the generic dub.sh links
- i. Make sure the domain is `dub.sh` (prevent SQL injection)
+ i. Make sure the domain is `dub.sh` (prevent query injection)
ii. If link `key` is provided, make sure user is the owner of the link
b. If there is a slug, it means that it's a custom project
i. Make sure the project exists
ii. Make sure the user is part of the project
iii. Make sure the project is within its usage limits
- iv. Make sure the domain is part of the project (prevent SQL injection)
+ iv. Make sure the domain is part of the project (prevent query injection)
*/
const withLinksAuth =
@@ -204,6 +204,8 @@ const withLinksAuth =
} = {},
) =>
async (req: NextApiRequest, res: NextApiResponse) => {
+ console.log("Running withLinksAuth helper for endpoint: ", req.url);
+
const session = await getSession(req, res);
if (!session?.user.id) {
return res.status(401).end("Unauthorized: Login required.");
@@ -221,7 +223,7 @@ const withLinksAuth =
// if there is no slug, it's the default dub.sh link
if (!slug) {
- // prevent domain from being SQL injected by
+ // prevent domain from being query injected by
// making sure that all instances of `domain` are `dub.sh`
if (
(domain && domain !== "dub.sh") ||
@@ -298,7 +300,7 @@ const withLinksAuth =
// if domain is defined
if (domain) {
- // prevent domain from being SQL injected by
+ // prevent domain from being query injected by
// comparing the domain in the query params to the domain in the body
if (req.body.domain && req.body.domain !== domain) {
return res.status(403).end("Unauthorized: Invalid domain.");
diff --git a/lib/hooks/use-endpoint.ts b/lib/hooks/use-endpoint.ts
deleted file mode 100644
index f79bdc302f..0000000000
--- a/lib/hooks/use-endpoint.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { useRouter } from "next/router";
-import { useMemo } from "react";
-
-export default function useEndpoint(staticDomain?: string) {
- const router = useRouter();
- const {
- slug,
- domain: domainSlug,
- key,
- interval = "24h",
- } = router.query as {
- slug?: string;
- domain?: string;
- key: string;
- interval?: string;
- };
-
- const queryString =
- interval || domainSlug
- ? `?${new URLSearchParams({
- ...(slug && { slug }),
- ...(interval && { interval }),
- ...(domainSlug && { domain: domainSlug }),
- }).toString()}`
- : "";
-
- const { basePath, domain, endpoint } = useMemo(() => {
- // Project link page, e.g. app.dub.sh/dub/dub.sh/github
- if (slug && domainSlug && key) {
- return {
- basePath: `/${slug}/${domainSlug}/${encodeURIComponent(key)}`,
- domain: domainSlug,
- endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
- };
-
- // Generic Dub.sh link page, e.g. app.dub.sh/links/steven
- } else if (key && router.asPath.startsWith("/links")) {
- return {
- basePath: `/links/${encodeURIComponent(key)}`,
- domain: "dub.sh",
- endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
- };
- }
-
- // Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergpt
- return {
- basePath: `/stats/${encodeURIComponent(key)}`,
- domain: staticDomain,
- endpoint: `/api/edge/links/${encodeURIComponent(key)}/stats`,
- };
- }, [slug, key, router.asPath]);
-
- return {
- basePath,
- domain,
- endpoint,
- queryString,
- };
-}
diff --git a/pages/_app.tsx b/pages/_app.tsx
index af68d826c9..4c1b25891a 100644
--- a/pages/_app.tsx
+++ b/pages/_app.tsx
@@ -6,6 +6,7 @@ import { Toaster } from "sonner";
import "@/styles/globals.css";
import clsx from "clsx";
import { satoshi, inter } from "@/styles/fonts";
+import ModalProvider from "#/ui/modal-provider";
function MyApp({
Component,
@@ -14,9 +15,11 @@ function MyApp({
return (
<SessionProvider session={session}>
<Toaster />
- <main className={clsx(satoshi.variable, inter.variable)}>
- <Component {...pageProps} />
- </main>
+ <ModalProvider>
+ <main className={clsx(satoshi.variable, inter.variable)}>
+ <Component {...pageProps} />
+ </main>
+ </ModalProvider>
<Analytics />
</SessionProvider>
);
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index 76850bd91a..8a13b957be 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -45,7 +45,7 @@ export default withUserAuth(
if (slugError || validDomain !== true) {
return res.status(422).json({
slugError,
- domainError: validDomain || "Invalid domain",
+ domainError: validDomain ? null : "Invalid domain",
});
}
const [slugExist, domainExist] = await Promise.all([
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index 3588a3a568..facf37319d 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -1,18 +1,18 @@
-import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
import NoProjectsPlaceholder from "@/components/app/projects/no-projects-placeholder";
import ProjectCard from "@/components/app/projects/project-card";
import ProjectCardPlaceholder from "@/components/app/projects/project-card-placeholder";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import AppLayout from "components/layout/app";
import useProjects from "@/lib/swr/use-projects";
+import { useContext } from "react";
+import { ModalContext } from "#/ui/modal-provider";
export default function App() {
const { projects } = useProjects();
- const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal();
+ const { setShowAddProjectModal } = useContext(ModalContext);
return (
<AppLayout>
- <AddProjectModal />
<div className="flex h-36 items-center border-b border-gray-200 bg-white">
<MaxWidthWrapper>
<div className="flex items-center justify-between">
@@ -36,9 +36,7 @@ export default function App() {
projects.length > 0 ? (
projects.map((d) => <ProjectCard key={d.slug} {...d} />)
) : (
- <NoProjectsPlaceholder
- setShowAddProjectModal={setShowAddProjectModal}
- />
+ <NoProjectsPlaceholder />
)
) : (
Array.from({ length: 6 }).map((_, i) => (
diff --git a/posts/changelog/keyboard-shortcuts.mdx b/posts/changelog/keyboard-shortcuts.mdx
index cc19a9334f..75f0f09dee 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 |
-| `a` | Archive the selected short link | Yes |
+| `t` | Tag 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).