The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Replaced useEndpoint with StatsContext, migrated some more stuff over to App Router
Steven Teyaff8aa084af1
diff --git a/app/(marketing)/@modal/(...)stats/[key]/modal.tsx b/app/(marketing)/@modal/(...)stats/[key]/modal.tsxnew file mode 100644index 0000000000..2b428435c5--- /dev/null+++ b/app/(marketing)/@modal/(...)stats/[key]/modal.tsx@@ -0,0 +1,48 @@+"use client";++import { useCallback, useRef, useEffect } from "react";+import { useRouter } from "next/navigation";+import { AnimatePresence, motion } from "framer-motion";++export default function Modal({ children }) {+ const backdrop = useRef<HTMLDivElement | null>(null);+ const wrapper = useRef<HTMLDivElement | null>(null);+ const router = useRouter();++ const onKeyDown = useCallback((e: KeyboardEvent) => {+ if (e.key === "Escape") {+ router.back();+ }+ }, []);++ useEffect(() => {+ document.addEventListener("keydown", onKeyDown);+ return () => document.removeEventListener("keydown", onKeyDown);+ }, [onKeyDown]);++ return (+ <AnimatePresence>+ <div className="absolute">+ <motion.div+ ref={wrapper}+ key="desktop-modal"+ initial={{ scale: 0.95 }}+ animate={{ scale: 1 }}+ exit={{ scale: 0.95 }}+ className="fixed inset-0 z-40 hidden min-h-screen items-center justify-center sm:flex"+ >+ {children}+ </motion.div>+ <motion.div+ ref={backdrop}+ key="modal-backdrop"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ className="fixed inset-0 z-30 bg-gray-100 bg-opacity-10 backdrop-blur"+ onClick={() => router.back()}+ />+ </div>+ </AnimatePresence>+ );+}diff --git a/app/(marketing)/@modal/(...)stats/[key]/page.tsx b/app/(marketing)/@modal/(...)stats/[key]/page.tsxnew file mode 100644index 0000000000..13d41d2faa--- /dev/null+++ b/app/(marketing)/@modal/(...)stats/[key]/page.tsx@@ -0,0 +1,15 @@+import Stats from "#/ui/stats";+import Modal from "./modal";++export default function StatsModal({ params }: { params: { key: string } }) {+ return (+ <Modal>+ <div+ 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"+ >+ <Stats staticDomain="dub.sh" staticKey={params.key} />+ </div>+ </Modal>+ );+}diff --git a/app/(marketing)/@modal/default.tsx b/app/(marketing)/@modal/default.tsxnew file mode 100644index 0000000000..6ddf1b76fa--- /dev/null+++ b/app/(marketing)/@modal/default.tsx@@ -0,0 +1,3 @@+export default function Default() {+ return null;+}diff --git a/app/(marketing)/layout.tsx b/app/(marketing)/layout.tsxindex e717bd23e2..b188b476bd 100644--- a/app/(marketing)/layout.tsx+++ b/app/(marketing)/layout.tsx@@ -1,65 +1,13 @@-import Image from "next/image";import Link from "next/link";import { Github, Logo, Twitter } from "@/components/shared/icons";-import NavigationMenu from "./navigation-menu";+import Nav from "#/ui/home/nav";-const title = "Dub - Link Management for Modern Marketing Teams";-const description =- "Dub is an open-source link management tool for modern marketing teams to create, share, and track short links.";--export const metadata = {- title,- description,- twitter: {- card: "summary_large_image",- title,- description,- creator: "@dubdotsh",- },- metadataBase: new URL("https://dub.sh"),- themeColor: "#FFF",-};--export default function MarketingLayout({- children,-}: {- children: React.ReactNode;-}) {+export default function MarketingLayout(props) {return (<div className="flex min-h-screen flex-col justify-between">- <div className="z-20">- <div className="mx-auto max-w-screen-xl px-5 md:px-20">- <div className="flex h-16 items-center justify-between">- <div className="flex items-center">- <Link href="/">- <Image- src="/_static/logotype.svg"- alt="Dub.sh logo"- width={834}- height={236}- className="w-24"- />- </Link>- </div>-- <NavigationMenu />-- <div className="w-24">- <Link- href={- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "https://app.dub.sh/login"- : "http://app.localhost:3000/login"- }- className="rounded-full border border-black bg-black py-1.5 px-5 text-sm text-white transition-all hover:bg-white hover:text-black"- >- Sign in- </Link>- </div>- </div>- </div>- </div>- {children}+ <Nav />+ {props.children}+ {props.modal}<div className="z-10 flex h-20 items-center justify-center space-x-12 border-t border-gray-200"><a href="https://twitter.com/dubdotsh" target="_blank" rel="noreferrer"><span className="sr-only">Twitter</span>diff --git a/public/_static/background.png b/app/(marketing)/stats/[key]/background.pngsimilarity index 100%rename from public/_static/background.pngrename to app/(marketing)/stats/[key]/background.pngdiff --git a/app/(marketing)/stats/[key]/logo.png b/app/(marketing)/stats/[key]/logo.pngnew file mode 100644index 0000000000..1653c4e3cdBinary files /dev/null and b/app/(marketing)/stats/[key]/logo.png differdiff --git a/pages/api/og/stats.tsx b/app/(marketing)/stats/[key]/opengraph-image.tsxsimilarity index 79%rename from pages/api/og/stats.tsxrename to app/(marketing)/stats/[key]/opengraph-image.tsxindex c90c481806..78a9433d84 100644--- a/pages/api/og/stats.tsx+++ b/app/(marketing)/stats/[key]/opengraph-image.tsx@@ -1,32 +1,31 @@+import { ImageResponse } from "next/server";+import { headers } from "next/headers";import { getLinkViaEdge } from "@/lib/planetscale";import { getStats } from "@/lib/stats";-import { nFormatter, truncate } from "@/lib/utils";-import { ImageResponse } from "@vercel/og";-import { NextRequest } from "next/server";+import { isHomeHostname, nFormatter, truncate } from "@/lib/utils";-export const config = {- runtime: "edge",-};+export const runtime = "edge";+export const contentType = "image/png";const satoshiBLack = fetch(- new URL("../../../styles/Satoshi-Black.ttf", import.meta.url),+ new URL("@/styles/Satoshi-Black.ttf", import.meta.url),).then((res) => res.arrayBuffer());const satoshiBold = fetch(- new URL("../../../styles/Satoshi-Bold.ttf", import.meta.url),+ new URL("@/styles/Satoshi-Bold.ttf", import.meta.url),).then((res) => res.arrayBuffer());-export default async function handler(req: NextRequest) {+export default async function StatsOG({ params }: { params: { key: string } }) {const [satoshiBlackData, satoshiBoldData] = await Promise.all([satoshiBLack,satoshiBold,]);- const { searchParams } = req.nextUrl;- const domain = searchParams.get("domain") || "dub.sh";- const key = searchParams.get("key") || "github";+ const headersList = headers();+ let domain = headersList.get("host") as string;+ if (isHomeHostname(domain)) domain = "dub.sh";- const data = await getLinkViaEdge(domain, key);+ const data = await getLinkViaEdge(domain, params.key);if (!data?.publicStats) {return new Response(`Stats for this link are not public`, {status: 403,@@ -35,7 +34,7 @@ export default async function handler(req: NextRequest) {const timeseries = await getStats({domain,- key,+ key: params.key,endpoint: "timeseries",interval: "30d",});@@ -54,16 +53,13 @@ export default async function handler(req: NextRequest) {alignItems: "center",backgroundColor: "white",backgroundImage: `url(${new URL(- "../../../public/_static/background.png",+ "./background.png",import.meta.url,).toString()})`,}}><img- src={new URL(- "../../../public/_static/logo.png",- import.meta.url,- ).toString()}+ src={new URL("./logo.png", import.meta.url).toString()}style={{width: "80px",height: "80px",@@ -84,7 +80,7 @@ export default async function handler(req: NextRequest) {lineHeight: "7rem",}}>- {domain}/{truncate(key, 12)}+ {domain}/{truncate(params.key, 12)}</h1><pstyle={{diff --git a/app/(marketing)/stats/[key]/page.tsx b/app/(marketing)/stats/[key]/page.tsxnew file mode 100644index 0000000000..6ff66a3e93--- /dev/null+++ b/app/(marketing)/stats/[key]/page.tsx@@ -0,0 +1,58 @@+import { headers } from "next/headers";+import { notFound } from "next/navigation";+import { isHomeHostname } from "@/lib/utils";+import { getLinkViaEdge } from "@/lib/planetscale";+import Stats from "#/ui/stats";++export const runtime = "edge";++export async function generateMetadata({+ params,+}: {+ params: { key: string };+}) {+ const headersList = headers();+ let domain = headersList.get("host") as string;+ if (isHomeHostname(domain)) domain = "dub.sh";++ const data = await getLinkViaEdge(domain, params.key);++ if (!data || !data.publicStats) {+ return;+ }++ const title = `Stats for ${domain}/${params.key} - Dub`;+ const description = `Stats page for ${domain}/${params.key}, which redirects to ${data.url}.`;++ return {+ title,+ description,+ twitter: {+ card: "summary_large_image",+ title,+ description,+ creator: "@dubdotsh",+ },+ };+}++export default async function StatsPage({+ params,+}: {+ params: { key: string };+}) {+ const headersList = headers();+ let domain = headersList.get("host") as string;+ if (isHomeHostname(domain)) domain = "dub.sh";+ const data = await getLinkViaEdge(domain, params.key);++ if (!data || !data.publicStats) {+ notFound();+ }++ return (+ <div className="bg-gray-50">+ <Stats staticDomain={domain} />+ </div>+ );+}diff --git a/app/(marketing)/atom/route.ts b/app/atom/route.tssimilarity index 100%rename from app/(marketing)/atom/route.tsrename to app/atom/route.tsdiff --git a/app/default.tsx b/app/default.tsxnew file mode 100644index 0000000000..6ddf1b76fa--- /dev/null+++ b/app/default.tsx@@ -0,0 +1,3 @@+export default function Default() {+ return null;+}diff --git a/app/layout.tsx b/app/layout.tsxindex af0fcc5eb2..b521e1a130 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -2,8 +2,26 @@ import "@/styles/globals.css";import { satoshi, inter } from "@/styles/fonts";import { Analytics } from "@vercel/analytics/react";import clsx from "clsx";+import { Providers } from "./providers";-export default async function RootLayout({+const title = "Dub - Link Management for Modern Marketing Teams";+const description =+ "Dub is an open-source link management tool for modern marketing teams to create, share, and track short links.";++export const metadata = {+ title,+ description,+ twitter: {+ card: "summary_large_image",+ title,+ description,+ creator: "@dubdotsh",+ },+ metadataBase: new URL("https://dub.sh"),+ themeColor: "#FFF",+};++export default function RootLayout({children,}: {children: React.ReactNode;@@ -11,8 +29,10 @@ export default async function RootLayout({return (<html lang="en"><body className={clsx(satoshi.variable, inter.variable)}>- {children}- <Analytics />+ <Providers>+ {children}+ <Analytics />+ </Providers></body></html>);diff --git a/app/lib/hooks/use-scroll.ts b/app/lib/hooks/use-scroll.tsnew file mode 100644index 0000000000..6be621b58a--- /dev/null+++ b/app/lib/hooks/use-scroll.ts@@ -0,0 +1,28 @@+import { useCallback, useEffect, useState, RefObject } from "react";++export default function useScroll(+ threshold: number,+ ref?: RefObject<HTMLDivElement>,+) {+ const [scrolled, setScrolled] = useState(false);++ const onScroll = useCallback(() => {+ if (ref && ref.current) {+ setScrolled(ref.current.scrollTop > threshold);+ } else {+ setScrolled(window.pageYOffset > threshold);+ }+ }, [threshold, ref]);++ useEffect(() => {+ if (ref && ref.current) {+ ref.current.addEventListener("scroll", onScroll);+ return () => ref.current?.removeEventListener("scroll", onScroll);+ } else {+ window.addEventListener("scroll", onScroll);+ return () => window.removeEventListener("scroll", onScroll);+ }+ }, [onScroll, ref]);++ return scrolled;+}diff --git a/app/lib/hooks/use-window-size.ts b/app/lib/hooks/use-window-size.tsnew file mode 100644index 0000000000..a285b7838f--- /dev/null+++ b/app/lib/hooks/use-window-size.ts@@ -0,0 +1,32 @@+import { useState, useEffect } from "react";+// Define general type for useWindowSize hook, which includes width and height+interface Size {+ width: number | undefined;+ height: number | undefined;+}+// Hook+export default function useWindowSize(): Size {+ // Initialize state with undefined width/height so server and client renders match+ // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/+ const [windowSize, setWindowSize] = useState<Size>({+ width: undefined,+ height: undefined,+ });+ useEffect(() => {+ // Handler to call on window resize+ function handleResize() {+ // Set window width/height to state+ setWindowSize({+ width: window.innerWidth,+ height: window.innerHeight,+ });+ }+ // Add event listener+ window.addEventListener("resize", handleResize);+ // Call handler right away so state gets updated with initial window size+ handleResize();+ // Remove event listener on cleanup+ return () => window.removeEventListener("resize", handleResize);+ }, []); // Empty array ensures that effect is only run on mount+ return windowSize;+}diff --git a/app/opengraph-image.png b/app/opengraph-image.pngnew file mode 100644index 0000000000..068f83422eBinary files /dev/null and b/app/opengraph-image.png differdiff --git a/app/providers.tsx b/app/providers.tsxnew file mode 100644index 0000000000..b9e836628a--- /dev/null+++ b/app/providers.tsx@@ -0,0 +1,12 @@+"use client";++import { Toaster } from "sonner";++export function Providers({ children }: { children: React.ReactNode }) {+ return (+ <div>+ <Toaster />+ {children}+ </div>+ );+}diff --git a/app/ui/home/demo.tsx b/app/ui/home/demo.tsxindex fd9ee2cdd4..c6f7bf5805 100644--- a/app/ui/home/demo.tsx+++ b/app/ui/home/demo.tsx@@ -11,6 +11,7 @@ import Tooltip, { TooltipContent } from "#/ui/tooltip";import { FRAMER_MOTION_LIST_ITEM_VARIANTS } from "@/lib/constants";import useLocalStorage from "@/lib/hooks/use-local-storage";import { SimpleLinkProps } from "@/lib/types";+import { toast } from "sonner";const Demo = () => {const [saving, setSaving] = useState(false);@@ -36,6 +37,12 @@ const Demo = () => {const json = await response.json();setHashes([...hashes, json]);setUrl("");+ // auto copy to clipboard+ navigator.clipboard+ .writeText(`https://dub.sh/${json.key}`)+ .then(() => {+ toast.success("Copied shortlink to clipboard!");+ });}});}}diff --git a/app/ui/home/features.tsx b/app/ui/home/features.tsxindex 71863e3fef..398314cfd4 100644--- a/app/ui/home/features.tsx+++ b/app/ui/home/features.tsx@@ -20,10 +20,7 @@ const featureList = ["Dub provides powerful analytics for your links, including geolocation, device, browser, and referrer information.",cta: (<Link- href={{ pathname: "/", query: { key: "github" } }}- as="/stats/github"- shallow- scroll={false}+ href="/stats/github"className="block max-w-fit rounded-full border border-black bg-black px-4 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black">View demodiff --git a/app/ui/home/globe.tsx b/app/ui/home/globe.tsxindex 58d9b9d38f..ec55aeaac0 100644--- a/app/ui/home/globe.tsx+++ b/app/ui/home/globe.tsx@@ -150,10 +150,7 @@ const GlobeAnimation = ({ markers }: { markers: MarkerProps[] }) => {.</p><Link- href={{ pathname: "/", query: { key: "github" } }}- as="/stats/github"- shallow- scroll={false}+ href="/stats/github"className="mx-auto mt-2 block max-w-fit rounded-full border border-black bg-black px-4 py-1.5 text-sm text-white hover:bg-white hover:text-black sm:mt-4">View all statsdiff --git a/app/ui/home/link-card.tsx b/app/ui/home/link-card.tsxindex e81279c846..02ab201042 100644--- a/app/ui/home/link-card.tsx+++ b/app/ui/home/link-card.tsx@@ -1,7 +1,7 @@import Link from "next/link";import { useEffect, useMemo, useRef, useState } from "react";import { motion, useAnimation, useMotionValue } from "framer-motion";-import toast from "react-hot-toast";+import { toast } from "sonner";import useSWR from "swr";import { useAddEditLinkModal } from "#/ui/modals/add-edit-link-modal";import { useLinkQRModal } from "#/ui/modals/link-qr-modal";@@ -170,10 +170,7 @@ export default function LinkCard({<QR className="text-gray-700 transition-all group-hover:text-blue-800" /></button><Link- href={{ pathname: "/", query: { key } }}- as={`/stats/${encodeURI(key)}`}- shallow- scroll={false}+ href={`/stats/${encodeURI(key)}`}className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 text-gray-700 transition-all duration-75 hover:scale-105 active:scale-95"><Chart className="h-4 w-4" />diff --git a/app/ui/home/nav.tsx b/app/ui/home/nav.tsxnew file mode 100644index 0000000000..4c1a9ef20d--- /dev/null+++ b/app/ui/home/nav.tsx@@ -0,0 +1,53 @@+"use client";++import Link from "next/link";+import Image from "next/image";+import { usePathname } from "next/navigation";+import useScroll from "#/lib/hooks/use-scroll";+import clsx from "clsx";++export default function Nav() {+ const pathname = usePathname();+ const scrolled = useScroll(80);+ return (+ <div+ className={clsx(`sticky inset-x-0 top-0 z-20 w-full transition-all`, {+ "border-b border-gray-200 bg-white/75 backdrop-blur-lg": scrolled,+ "border-b border-gray-200": pathname !== "/",+ })}+ >+ <div className="mx-auto w-full max-w-screen-xl px-5 md:px-20">+ <div className="flex h-16 items-center justify-between">+ <Link href="/">+ <Image+ src="/_static/logotype.svg"+ alt="Dub.sh logo"+ width={834}+ height={236}+ className="w-24"+ />+ </Link>++ <div className="flex items-center space-x-6">+ <Link+ href="/changelog"+ className="rounded-md text-sm font-medium text-gray-500 transition-colors ease-out hover:text-black"+ >+ Changelog+ </Link>+ <Link+ href={+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "https://app.dub.sh/login"+ : "http://app.localhost:3000/login"+ }+ className="rounded-full border border-black bg-black px-5 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"+ >+ Sign in+ </Link>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/app/(marketing)/navigation-menu.tsx b/app/ui/home/navigation-menu.tsxsimilarity index 88%rename from app/(marketing)/navigation-menu.tsxrename to app/ui/home/navigation-menu.tsxindex d791392ef7..58fc069b8c 100644--- a/app/(marketing)/navigation-menu.tsx+++ b/app/ui/home/navigation-menu.tsx@@ -26,7 +26,7 @@ const comparisons = [export default function NavigationMenu() {return (- <NavigationMenuPrimitive.Root className="relative hidden md:block">+ <NavigationMenuPrimitive.Root><NavigationMenuPrimitive.List className="flex flex-row space-x-2 p-2">{/* <NavigationMenuPrimitive.Item><NavigationMenuPrimitive.Trigger@@ -111,25 +111,19 @@ export default function NavigationMenu() {</NavigationMenuPrimitive.Content></NavigationMenuPrimitive.Item> */}- <NavigationMenuPrimitive.Item asChild>+ {/* <NavigationMenuPrimitive.Item asChild><Link- href="/#pricing"- className={clsx(- "rounded-md px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-900",- "text-sm font-medium text-gray-700 dark:text-gray-100",- )}+ href="/pricing"+ className="rounded-md px-3 py-2 text-sm font-medium text-gray-500 transition-colors ease-out hover:text-black">Pricing</Link>- </NavigationMenuPrimitive.Item>+ </NavigationMenuPrimitive.Item> */}{/* <NavigationMenuPrimitive.Item asChild><Linkhref="/blog"- className={clsx(- "rounded-md px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-900",- "text-sm font-medium text-gray-700 dark:text-gray-100",- )}+ className="rounded-md px-3 py-2 text-sm font-medium text-gray-500 transition-colors ease-out hover:text-black">Blog</Link>@@ -138,10 +132,7 @@ export default function NavigationMenu() {<NavigationMenuPrimitive.Item asChild><Linkhref="/changelog"- className={clsx(- "rounded-md px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-900",- "text-sm font-medium text-gray-700 dark:text-gray-100",- )}+ className="rounded-md px-3 py-2 text-sm font-medium text-gray-500 transition-colors ease-out hover:text-black">Changelog</Link>diff --git a/app/ui/modal.tsx b/app/ui/modal.tsxindex f5e03f8052..04f353beca 100644--- a/app/ui/modal.tsx+++ b/app/ui/modal.tsx@@ -9,7 +9,7 @@ import {} from "react";import FocusTrap from "focus-trap-react";import { AnimatePresence, motion, useAnimation } from "framer-motion";-import { useParams, useRouter } from "next/navigation";+import { useRouter } from "next/navigation";export default function Modal({children,@@ -27,7 +27,6 @@ export default function Modal({mobileOnly?: boolean;}) {const router = useRouter();- const { key } = useParams() as { key?: string };const mobileModalRef = useRef<HTMLDivElement | null>(null);const desktopModalRef = useRef<HTMLDivElement | null>(null);@@ -35,13 +34,11 @@ export default function Modal({(closeWithX?: boolean) => {if (closeWithX) {return;- } else if (key) {- router.push("/");} else {setShowModal(false);}},- [key, router, setShowModal],+ [router, setShowModal],);const onKeyDown = useCallback((e: KeyboardEvent) => {diff --git a/app/ui/modals/link-qr-modal.tsx b/app/ui/modals/link-qr-modal.tsxindex 2229314edc..f3f798aee8 100644--- a/app/ui/modals/link-qr-modal.tsx+++ b/app/ui/modals/link-qr-modal.tsx@@ -21,7 +21,7 @@ import { getApexDomain, linkConstructor } from "@/lib/utils";import IconMenu from "@/components/shared/icon-menu";import { Download, Photo } from "@/components/shared/icons";import Popover from "#/ui/popover";-import toast from "react-hot-toast";+import { toast } from "sonner";import { GOOGLE_FAVICON_URL } from "@/lib/constants";function LinkQRModalHelper({@@ -154,7 +154,7 @@ function LinkQRModalHelper({<div className="grid grid-cols-2 gap-2 px-4 sm:px-16"><buttononClick={async () => {- toast.promise(copyToClipboard(), {+ toast.promise(copyToClipboard, {loading: "Copying...",success: "Copied!",error: "Failed to copy",diff --git a/app/ui/stats/bar-chart.module.css b/app/ui/stats/bar-chart.module.cssnew file mode 100644index 0000000000..d2bfad0680--- /dev/null+++ b/app/ui/stats/bar-chart.module.css@@ -0,0 +1,26 @@+.bar {+ transform-origin: bottom !important;+ fill: #2563eb;+}++.tooltip {+ z-index: 40;+ width: 200px;+ padding: 1rem !important;+ border-radius: 5px !important;+ box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px !important;+}++.tooltip::after {+ content: "";+ position: absolute;+ width: 0px;+ height: 0px;+ margin: auto;++ border: 7px solid transparent;+ border-top-color: white;++ top: 100%;+ left: 95px;+}diff --git a/app/ui/stats/bar-chart.tsx b/app/ui/stats/bar-chart.tsxnew file mode 100644index 0000000000..577fff6ae5--- /dev/null+++ b/app/ui/stats/bar-chart.tsx@@ -0,0 +1,225 @@+import { useMemo, useContext } from "react";+import { AxisBottom, AxisLeft } from "@visx/axis";+import { localPoint } from "@visx/event";+import { GridRows } from "@visx/grid";+import { scaleBand, scaleLinear } from "@visx/scale";+import { useTooltip, useTooltipInPortal } from "@visx/tooltip";+import { motion } from "framer-motion";+import { intervalData } from "@/lib/stats";+import { nFormatter } from "@/lib/utils";+import styles from "./bar-chart.module.css";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { LoadingCircle } from "#/ui/icons";+import { StatsContext } from ".";+import useWindowSize from "#/lib/hooks/use-window-size";++const LEFT_AXIS_WIDTH = 30;+const CHART_MAX_HEIGHT = 400;+const CHART_MAX_WIDTH = 800;++type TooltipData = {+ start: Date;+ end: Date;+ clicks: number;+ link: string;+};++const rangeFormatter = (maxN: number): number => {+ if (maxN < 5) return 5;+ /**+ * Get the max range for a chart based on the maxN value+ */+ return Math.ceil(maxN / 5) * 5;+};++export default function BarChart() {+ const { endpoint, queryString, interval } = useContext(StatsContext);++ const { data } = useSWR<{ start: Date; clicks: number }[]>(+ `${endpoint}/timeseries${queryString}`,+ fetcher,+ );++ const { width: screenWidth } = useWindowSize();++ const [CHART_WIDTH, CHART_HEIGHT] = useMemo(() => {+ const width = screenWidth+ ? Math.min(screenWidth * 0.8, CHART_MAX_WIDTH)+ : CHART_MAX_WIDTH;+ const height = screenWidth+ ? Math.min(screenWidth * 0.5, CHART_MAX_HEIGHT)+ : CHART_MAX_HEIGHT;+ return [width, height];+ }, [screenWidth]);++ const xScale = useMemo(() => {+ return scaleBand({+ range: [0, CHART_WIDTH],+ domain: data ? data.map((d) => d.start) : [],+ padding: 0.4,+ });+ }, [data, interval]);++ const yScale = useMemo(() => {+ return scaleLinear({+ range: [CHART_HEIGHT, 0],+ domain: [+ 0,+ data ? rangeFormatter(Math.max(...data.map((d) => d.clicks))) : 0,+ ],+ nice: true,+ round: true,+ });+ }, [data, interval]);++ const {+ tooltipOpen,+ tooltipLeft,+ tooltipTop,+ tooltipData,+ hideTooltip,+ showTooltip,+ } = useTooltip<TooltipData>();++ const { containerRef, TooltipInPortal } = useTooltipInPortal({+ // TooltipInPortal is rendered in a separate child of <body /> and positioned+ // with page coordinates which should be updated on scroll. consider using+ // Tooltip or TooltipWithBounds if you don't need to render inside a Portal+ scroll: true,+ debounce: 100, // to avoid a weird tooltip flickering bug+ });++ let tooltipTimeout: number | undefined;+ return (+ <figure+ className={`+ ${+ data && data.length > 0 ? "" : "items-center justify-center"+ } my-10 flex`}+ style={{ width: CHART_WIDTH, height: CHART_HEIGHT }}+ >+ {data && data.length > 0 ? (+ <>+ <svg ref={containerRef} width={LEFT_AXIS_WIDTH}>+ <AxisLeft+ hideAxisLine+ hideTicks+ left={8}+ numTicks={4}+ scale={yScale}+ tickFormat={(d) => nFormatter(d as number)}+ tickLabelProps={() => ({+ fill: "#666666",+ filter: data ? "none" : "blur(8px)",+ fontSize: 14,+ textAnchor: "start",+ transition: "all 0.4s ease-in-out",+ })}+ />+ </svg>+ <svg+ className="overflow-visible"+ height={CHART_HEIGHT}+ width={`calc(100% - ${LEFT_AXIS_WIDTH}px)`}+ >+ <AxisBottom+ hideAxisLine+ hideTicks+ scale={xScale}+ tickFormat={intervalData[interval].format}+ tickLabelProps={() => ({+ fill: "#666666",+ filter: data ? "none" : "blur(8px)",+ fontSize: 12,+ textAnchor: "middle",+ transition: "all 0.4s ease-in-out",+ })}+ numTicks={6}+ top={CHART_HEIGHT - 5}+ />+ <GridRows+ numTicks={5}+ scale={yScale}+ stroke="#E1E1E1"+ width={CHART_WIDTH}+ />+ {data.map(({ start, clicks }) => {+ const barWidth = xScale.bandwidth();+ const barHeight = CHART_HEIGHT - (yScale(clicks) ?? 0);+ const barX = xScale(start) ?? 0;+ const barY = CHART_HEIGHT - barHeight;+ return (+ <motion.rect+ key={`bar-${interval}-${start}`}+ transition={{ ease: "easeOut", duration: 0.3 }}+ className={styles.bar} // to override transformOrigin+ initial={{ transform: "scaleY(0)" }}+ animate={{ transform: "scaleY(1)" }}+ x={barX}+ y={barY}+ width={barWidth}+ height={barHeight}+ onMouseLeave={() => {+ tooltipTimeout = window.setTimeout(() => {+ hideTooltip();+ }, 300);+ }}+ onMouseMove={(event) => {+ if (tooltipTimeout) clearTimeout(tooltipTimeout);+ // TooltipInPortal expects coordinates to be relative to containerRef+ // localPoint returns coordinates relative to the nearest SVG, which+ // is what containerRef is set to in this example.+ const eventSvgCoords = localPoint(event) ?? {+ x: 0,+ y: 0,+ };+ const left = barX + barWidth / 2 - 81;+ showTooltip({+ tooltipData: {+ start,+ end:+ new Date(start).getTime() ++ intervalData[interval].interval,+ clicks,+ link: "https://google.com",+ },+ tooltipTop: eventSvgCoords.y - 150,+ tooltipLeft: left,+ });+ }}+ />+ );+ })}+ </svg>+ {tooltipOpen && tooltipData && (+ <TooltipInPortal+ top={tooltipTop}+ left={tooltipLeft}+ className={styles.tooltip}+ >+ <div className="text-center">+ <h3 className="my-1 text-black">+ <span className="text-2xl font-semibold">+ {nFormatter(tooltipData.clicks)}+ </span>{" "}+ clicks+ </h3>+ <p className="text-xs text-gray-600">+ {intervalData[interval].format(tooltipData.start)} -{" "}+ {interval === "24h"+ ? new Date(tooltipData.end).toLocaleTimeString("en-us", {+ hour: "numeric",+ })+ : intervalData[interval].format(tooltipData.end)}+ </p>+ </div>+ </TooltipInPortal>+ )}+ </>+ ) : (+ <LoadingCircle />+ )}+ </figure>+ );+}diff --git a/app/ui/stats/clicks.tsx b/app/ui/stats/clicks.tsxnew file mode 100644index 0000000000..5dd252d802--- /dev/null+++ b/app/ui/stats/clicks.tsx@@ -0,0 +1,37 @@+import { Chart } from "@/components/shared/icons";+import BarChart from "./bar-chart";+import { nFormatter } from "@/lib/utils";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { StatsContext } from ".";+import { useContext } from "react";++export default function Clicks() {+ const { endpoint, queryString } = useContext(StatsContext);++ const { data: totalClicks } = useSWR<number>(+ `${endpoint}/clicks${queryString}`,+ fetcher,+ );++ return (+ <div className="max-w-4xl border border-gray-200 bg-white p-5 sm:rounded-lg sm:border-gray-100 sm:p-10 sm:pr-20 sm:shadow-lg ">+ <div className="mb-5 text-left">+ <div className="flex items-end space-x-1">+ {totalClicks || totalClicks === 0 ? (+ <h1 className="text-3xl font-bold sm:text-4xl">+ {nFormatter(totalClicks)}+ </h1>+ ) : (+ <div className="h-10 w-12 animate-pulse rounded-md bg-gray-200" />+ )}+ <Chart className="mb-1 h-6 w-6 text-gray-600" />+ </div>+ <p className="text-sm font-medium uppercase text-gray-600">+ Total Clicks+ </p>+ </div>+ <BarChart />+ </div>+ );+}diff --git a/app/ui/stats/device-icon.tsx b/app/ui/stats/device-icon.tsxnew file mode 100644index 0000000000..56ab54e507--- /dev/null+++ b/app/ui/stats/device-icon.tsx@@ -0,0 +1,97 @@+import BlurImage from "#/ui/blur-image";+import { Apple, Chrome, Safari } from "@/components/shared/icons/devices";+import { DeviceTabs } from "@/lib/stats";++export default function DeviceIcon({+ display,+ tab,+ className,+}: {+ display: string;+ tab: DeviceTabs;+ className: string;+}) {+ if (display === "Bot") {+ return (+ <img+ alt={display}+ src={`https://avatars.dicebear.com/api/bottts/dub.svg`}+ className={className}+ />+ );+ }+ if (tab === "device") {+ return (+ <BlurImage+ src={+ display === "Desktop"+ ? `https://faisalman.github.io/ua-parser-js/images/types/default.png`+ : `https://faisalman.github.io/ua-parser-js/images/types/${display.toLowerCase()}.png`+ }+ alt={display}+ width={20}+ height={20}+ sizes="10vw"+ className={className}+ />+ );+ } else if (tab === "browser") {+ if (display === "Chrome") {+ return <Chrome className={className} />;+ } else if (display === "Safari" || display === "Mobile Safari") {+ return <Safari className={className} />;+ } else {+ return (+ <BlurImage+ src={`https://faisalman.github.io/ua-parser-js/images/browsers/${display.toLowerCase()}.png`}+ alt={display}+ width={20}+ height={20}+ className={className}+ />+ );+ }+ } else if (tab === "os") {+ if (display === "Mac OS") {+ return (+ <BlurImage+ src="/_static/icons/macos.png"+ alt={display}+ width={20}+ height={20}+ className="h-4 w-4"+ />+ );+ } else if (display === "iOS") {+ return <Apple className="-ml-1 h-5 w-5" />;+ } else {+ return (+ <BlurImage+ src={`https://faisalman.github.io/ua-parser-js/images/os/${display.toLowerCase()}.png`}+ alt={display}+ width={30}+ height={20}+ className="h-4 w-5"+ />+ );+ }+ } else if (tab === "bot") {+ return (+ <img+ alt={display}+ src={`https://avatars.dicebear.com/api/bottts/${display}.svg`}+ className={className}+ />+ );+ } else {+ return (+ <BlurImage+ src={`https://faisalman.github.io/ua-parser-js/images/companies/default.png`}+ alt={display}+ width={20}+ height={20}+ className={className}+ />+ );+ }+}diff --git a/app/ui/stats/devices.tsx b/app/ui/stats/devices.tsxnew file mode 100644index 0000000000..e76d40f744--- /dev/null+++ b/app/ui/stats/devices.tsx@@ -0,0 +1,94 @@+import { useContext, useState } from "react";+import { motion } from "framer-motion";+import BadgeSelect from "@/components/shared/badge-select";+import { LoadingCircle } from "#/ui/icons";+import { DeviceTabs, uaToBot } from "@/lib/stats";+import { nFormatter } from "@/lib/utils";+import DeviceIcon from "./device-icon";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { StatsContext } from ".";++export default function Devices() {+ const [tab, setTab] = useState<DeviceTabs>("device");++ const { endpoint, queryString } = useContext(StatsContext);++ const { data } = useSWR<+ ({+ [key in DeviceTabs]: string;+ } & { clicks: number })[]+ >(`${endpoint}/${tab}${queryString}`, fetcher);++ const { data: totalClicks } = useSWR<number>(+ `${endpoint}/clicks${queryString}`,+ fetcher,+ );++ return (+ <div className="relative h-[420px] overflow-scroll border border-gray-200 bg-white px-7 py-5 scrollbar-hide sm:rounded-lg sm:border-gray-100 sm:shadow-lg">+ <div className="mb-5 flex justify-between">+ <h1 className="text-xl font-semibold">Devices</h1>+ <BadgeSelect+ options={["device", "browser", "os", "bot"]}+ selected={tab}+ // @ts-ignore+ selectAction={setTab}+ />+ </div>+ <div+ className={+ data && data.length > 0+ ? "grid gap-4"+ : "flex h-[300px] items-center justify-center"+ }+ >+ {data ? (+ data.length > 0 ? (+ data.map((d, idx) => (+ <div key={idx} className="flex items-center justify-between">+ <div className="relative z-10 flex w-full max-w-[calc(100%-3rem)] items-center">+ <span className="z-10 flex items-center space-x-2 px-2">+ <DeviceIcon+ display={tab === "bot" ? uaToBot(d.ua) : d[tab]}+ tab={tab}+ className="h-4 w-4"+ />+ <p className="text-sm text-gray-800">+ {tab === "bot" ? uaToBot(d.ua) : d[tab]}+ </p>+ </span>+ <motion.div+ style={{+ width: `${+ (d.clicks /+ (tab === "bot"+ ? data?.reduce(+ (acc, curr) => acc + curr.clicks,+ 0,+ ) || 0+ : totalClicks || 0)) *+ 100+ }%`,+ }}+ className="absolute h-8 origin-left bg-green-100"+ transition={{ ease: "easeOut", duration: 0.3 }}+ initial={{ transform: "scaleX(0)" }}+ animate={{ transform: "scaleX(1)" }}+ />+ </div>+ <p className="z-10 text-sm text-gray-600">+ {nFormatter(d.clicks)}+ </p>+ </div>+ ))+ ) : (+ <p className="text-sm text-gray-600">No data available</p>+ )+ ) : (+ <LoadingCircle />+ )}+ </div>+ </div>+ );+}diff --git a/app/ui/stats/feedback.tsx b/app/ui/stats/feedback.tsxnew file mode 100644index 0000000000..3cac5f95db--- /dev/null+++ b/app/ui/stats/feedback.tsx@@ -0,0 +1,134 @@+import { useState } from "react";+import { AnimatePresence, motion } from "framer-motion";+import { LoadingDots } from "#/ui/icons";+import { CheckCircle } from "lucide-react";+import { useDebouncedCallback } from "use-debounce";++export default function Feedback() {+ const [data, setData] = useState({+ email: "",+ feedback: "",+ });+ const [state, setState] = useState("idle");++ const handleSubmit = async (e) => {+ e.preventDefault();+ setState("submitting");+ await fetch("/api/site/feedback", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(data),+ })+ .then((res) => res.json())+ .then(() => {+ setState("submitted");+ });+ };++ const handleKeyDown = async (e) => {+ if (e.key === "Enter" && e.metaKey) {+ await handleSubmit(e);+ }+ };++ // Pre-warm the API endpoint to avoid cold start+ // Ideally we'd use an edge function for this but+ // node-mailer is not edge compatible+ const prewarm = useDebouncedCallback(+ () => {+ fetch("/api/site/feedback", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ email: "prewarm",+ feedback: null,+ }),+ });+ },+ 30000,+ { leading: true },+ );++ return (+ <div className="relative h-[420px] overflow-scroll border border-gray-200 bg-white px-7 py-5 scrollbar-hide sm:rounded-lg sm:border-gray-100 sm:shadow-lg">+ <div className="mb-5 flex">+ <h1 className="text-xl font-semibold">Feedback</h1>+ </div>+ <AnimatePresence>+ {state === "submitted" ? (+ <motion.div+ className="flex h-[280px] flex-col items-center justify-center space-y-3"+ initial={{ opacity: 0, y: 10 }}+ animate={{ opacity: 1, y: 0 }}+ >+ <CheckCircle+ fill="currentColor"+ className="h-10 w-10 text-green-500"+ />+ <p className="text-gray-500">Thank you for your feedback!</p>+ </motion.div>+ ) : (+ <motion.form+ className="grid gap-5"+ onSubmit={handleSubmit}+ initial={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -10 }}+ >+ <div>+ <label+ htmlFor="email"+ className="mb-2 block text-xs font-medium text-gray-500"+ >+ </label>+ <input+ name="email"+ type="email"+ placeholder="[email protected]"+ autoComplete="email"+ onFocus={prewarm}+ onChange={(e) => setData({ ...data, email: e.target.value })}+ className="block w-full rounded-md border-gray-300 pr-10 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ />+ </div>+ <div>+ <label+ htmlFor="feedback"+ className="mb-2 block text-xs font-medium text-gray-500"+ >+ FEEDBACK+ </label>+ <textarea+ name="feedback"+ id="feedback"+ required={true}+ rows={6}+ onKeyDown={handleKeyDown}+ className="block w-full rounded-md border-gray-300 pr-10 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ placeholder="What other data would you like to see?"+ value={data.feedback}+ onFocus={prewarm}+ onChange={(e) => setData({ ...data, feedback: e.target.value })}+ aria-invalid="true"+ />+ </div>+ <button+ disabled={state === "submitting"}+ className={`${+ state === "submitting"+ ? "cursor-not-allowed border-gray-200 bg-gray-100"+ : "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`}+ >+ {state === "submitting" ? (+ <LoadingDots color="#808080" />+ ) : (+ <p>Submit feedback</p>+ )}+ </button>+ </motion.form>+ )}+ </AnimatePresence>+ </div>+ );+}diff --git a/app/ui/stats/index.tsx b/app/ui/stats/index.tsxnew file mode 100644index 0000000000..7bfc5ac9c2--- /dev/null+++ b/app/ui/stats/index.tsx@@ -0,0 +1,123 @@+"use client";+/*+ This Stats component lives in 3 different places:+ 1. Project link page, e.g. app.dub.sh/dub/dub.sh/github+ 2. Generic Dub.sh link page, e.g. app.dub.sh/links/steven+ 3. Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergpt++ We use the `useEndpoint()` hook to get the correct layout+*/++import { createContext, useMemo, useRef } from "react";+import { useParams, usePathname, useSearchParams } from "next/navigation";+import Clicks from "./clicks";+import Devices from "./devices";+import Feedback from "./feedback";+import Locations from "./locations";+import Referer from "./referer";+import Toggle from "./toggle";+import useScroll from "#/lib/hooks/use-scroll";++export const StatsContext = createContext<{+ basePath: string;+ endpoint: string;+ queryString: string;+ interval: string;+ domain: string;+ key: string;+}>({+ basePath: "",+ endpoint: "",+ queryString: "",+ interval: "",+ domain: "",+ key: "",+});++export default function Stats({+ staticDomain,+ staticKey,+}: {+ staticDomain?: string;+ staticKey?: string;+}) {+ const ref = useRef<HTMLDivElement | null>(null);+ const scrolled = useScroll(80, ref);++ const params = useParams();+ const searchParams = useSearchParams() || new URLSearchParams();+ const pathname = usePathname();++ let {+ slug,+ domain: domainSlug,+ key,+ } = params as {+ slug?: string;+ domain?: string;+ key: string;+ };+ if (staticKey) key = staticKey;++ const interval = searchParams.get("interval") || "24h";++ const queryString =+ interval || domainSlug+ ? `?${new URLSearchParams({+ ...(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}/${key}`,+ domain: domainSlug,+ endpoint: `/api/projects/${slug}/links/${key}/stats`,+ };++ // Generic Dub.sh link page, e.g. app.dub.sh/links/steven+ } else if (key && pathname?.startsWith("/links")) {+ return {+ basePath: `/links/${key}`,+ domain: "dub.sh",+ endpoint: `/api/links/${key}/stats`,+ };+ }++ // Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergpt+ return {+ basePath: `/stats/${key}`,+ domain: staticDomain,+ endpoint: `/api/edge/links/${key}/stats`,+ };+ }, [slug, key, pathname]);++ return (+ <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 ref={ref} className="bg-gray-50 py-10">+ <Toggle scrolled={scrolled} />+ <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>+ </StatsContext.Provider>+ );+}diff --git a/app/ui/stats/locations.tsx b/app/ui/stats/locations.tsxnew file mode 100644index 0000000000..3324c1ab20--- /dev/null+++ b/app/ui/stats/locations.tsx@@ -0,0 +1,83 @@+import { useContext, useState } from "react";+import { motion } from "framer-motion";+import BadgeSelect from "@/components/shared/badge-select";+import { COUNTRIES } from "@/lib/constants";+import { LocationTabs } from "@/lib/stats";+import { nFormatter } from "@/lib/utils";+import { LoadingCircle } from "#/ui/icons";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { StatsContext } from ".";++export default function Locations() {+ const [tab, setTab] = useState<LocationTabs>("country");++ const { endpoint, queryString } = useContext(StatsContext);++ const { data } = useSWR<{ country: string; city: string; clicks: number }[]>(+ `${endpoint}/${tab}${queryString}`,+ fetcher,+ );++ const { data: totalClicks } = useSWR<number>(+ `${endpoint}/clicks${queryString}`,+ fetcher,+ );++ return (+ <div className="relative h-[420px] overflow-scroll border border-gray-200 bg-white px-7 py-5 scrollbar-hide sm:rounded-lg sm:border-gray-100 sm:shadow-lg">+ <div className="mb-5 flex justify-between">+ <h1 className="text-xl font-semibold">Locations</h1>+ <BadgeSelect+ options={["country", "city"]}+ selected={tab}+ // @ts-ignore+ selectAction={setTab}+ />+ </div>+ <div+ className={+ data && data.length > 0+ ? "grid gap-4"+ : "flex h-[300px] items-center justify-center"+ }+ >+ {data ? (+ data.length > 0 ? (+ data.map(({ country, city, clicks }, idx) => (+ <div key={idx} className="flex items-center justify-between">+ <div className="relative z-10 flex w-full max-w-[calc(100%-3rem)] items-center">+ <span className="z-10 flex items-center space-x-2 px-2">+ <img+ src={`https://flag.vercel.app/m/${country}.svg`}+ className="h-3 w-5"+ />+ <p className="text-sm text-gray-800">+ {tab === "country" ? COUNTRIES[country] : city}+ </p>+ </span>+ <motion.div+ style={{+ width: `${(clicks / (totalClicks || 0)) * 100}%`,+ }}+ className="absolute h-8 origin-left bg-orange-100"+ transition={{ ease: "easeOut", duration: 0.3 }}+ initial={{ transform: "scaleX(0)" }}+ animate={{ transform: "scaleX(1)" }}+ />+ </div>+ <p className="z-10 text-sm text-gray-600">+ {nFormatter(clicks)}+ </p>+ </div>+ ))+ ) : (+ <p className="text-sm text-gray-600">No data available</p>+ )+ ) : (+ <LoadingCircle />+ )}+ </div>+ </div>+ );+}diff --git a/app/ui/stats/referer.tsx b/app/ui/stats/referer.tsxnew file mode 100644index 0000000000..e0a7f61a79--- /dev/null+++ b/app/ui/stats/referer.tsx@@ -0,0 +1,80 @@+import { motion } from "framer-motion";+import BlurImage from "#/ui/blur-image";+import { Link2 } from "lucide-react";+import { LoadingCircle } from "#/ui/icons";+import { nFormatter } from "@/lib/utils";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { GOOGLE_FAVICON_URL } from "@/lib/constants";+import { StatsContext } from ".";+import { useContext } from "react";++export default function Referer() {+ const { endpoint, queryString } = useContext(StatsContext);++ const { data } = useSWR<{ referer: string; clicks: number }[]>(+ `${endpoint}/referer${queryString}`,+ fetcher,+ );++ const { data: totalClicks } = useSWR<number>(+ `${endpoint}/clicks${queryString}`,+ fetcher,+ );++ return (+ <div className="relative h-[420px] overflow-scroll border border-gray-200 bg-white px-7 py-5 scrollbar-hide sm:rounded-lg sm:border-gray-100 sm:shadow-lg">+ <div className="mb-5 flex">+ <h1 className="text-xl font-semibold">Referrers</h1>+ </div>+ <div+ className={+ data && data.length > 0+ ? "grid gap-4"+ : "flex h-[300px] items-center justify-center"+ }+ >+ {data ? (+ data.length > 0 ? (+ data.map(({ referer, clicks }, idx) => (+ <div key={idx} className="flex items-center justify-between">+ <div className="relative z-10 flex w-full max-w-[calc(100%-3rem)] items-center">+ <span className="z-10 flex items-center space-x-2 px-2">+ {referer === "(direct)" ? (+ <Link2 className="h-4 w-4" />+ ) : (+ <BlurImage+ src={`${GOOGLE_FAVICON_URL}${referer}`}+ alt={referer}+ width={20}+ height={20}+ className="h-4 w-4 rounded-full"+ />+ )}+ <p className="text-sm text-gray-800">{referer}</p>+ </span>+ <motion.div+ style={{+ width: `${(clicks / (totalClicks || 0)) * 100}%`,+ }}+ className="absolute h-8 origin-left rounded bg-red-100"+ transition={{ ease: "easeOut", duration: 0.3 }}+ initial={{ transform: "scaleX(0)" }}+ animate={{ transform: "scaleX(1)" }}+ />+ </div>+ <p className="z-10 text-sm text-gray-600">+ {nFormatter(clicks)}+ </p>+ </div>+ ))+ ) : (+ <p className="text-sm text-gray-600">No data available</p>+ )+ ) : (+ <LoadingCircle />+ )}+ </div>+ </div>+ );+}diff --git a/app/ui/stats/toggle.tsx b/app/ui/stats/toggle.tsxnew file mode 100644index 0000000000..57d07dfc0e--- /dev/null+++ b/app/ui/stats/toggle.tsx@@ -0,0 +1,198 @@+import { useContext, useMemo, useState } from "react";+import {+ Calendar,+ ChevronDown,+ Copy,+ Share,+ Tick,+} from "@/components/shared/icons";+import { ExpandingArrow } from "#/ui/icons";+import { INTERVALS } from "@/lib/constants";+import { linkConstructor } from "@/lib/utils";+import IconMenu from "@/components/shared/icon-menu";+import Popover from "#/ui/popover";+import useSWR, { mutate } from "swr";+import { fetcher } from "@/lib/utils";+import { toast } from "react-hot-toast";+import Switch from "#/ui/switch";+import Link from "next/link";+import { StatsContext } from ".";++export default function Toggle({ scrolled }: { scrolled: boolean }) {+ const { basePath, domain, interval, key } = useContext(StatsContext);++ const [openDatePopover, setOpenDatePopover] = useState(false);++ const selectedInterval = useMemo(() => {+ return INTERVALS.find((s) => s.slug === interval) || INTERVALS[1];+ }, [interval]);++ return (+ <div+ className={`z-20 mb-5 ${+ basePath.startsWith("/stats") ? "top-0" : "top-[6.95rem]"+ } sticky bg-gray-50 py-3 sm:py-5 ${scrolled ? "shadow-md" : ""}`}+ >+ <div className="mx-auto flex max-w-4xl flex-col items-center justify-between space-y-3 px-2.5 sm:flex-row sm:space-y-0 lg:px-0">+ <a+ className="group flex text-lg font-semibold text-gray-800 sm:text-xl"+ href={linkConstructor({ key, domain })}+ target="_blank"+ rel="noreferrer"+ >+ {linkConstructor({ key, domain, pretty: true })}+ <ExpandingArrow className="h-5 w-5" />+ </a>+ <div className="flex items-center">+ {!basePath.startsWith("/stats") && key !== "_root" && (+ <SharePopover />+ )}+ <Popover+ content={+ <div className="w-full p-2 md:w-48">+ {INTERVALS.map(({ display, slug }) => (+ <Link+ key={slug}+ href={`${basePath}?interval=${slug}`}+ className="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"+ >+ <p className="text-sm">{display}</p>+ {selectedInterval.slug === slug && (+ <Tick className="h-4 w-4" aria-hidden="true" />+ )}+ </Link>+ ))}+ </div>+ }+ openPopover={openDatePopover}+ setOpenPopover={setOpenDatePopover}+ >+ <button+ onClick={() => setOpenDatePopover(!openDatePopover)}+ className="flex w-full items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95 sm:w-48"+ >+ <IconMenu+ text={selectedInterval.display}+ icon={<Calendar className="h-4 w-4" />}+ />+ <ChevronDown+ className={`h-5 w-5 text-gray-400 ${+ openDatePopover ? "rotate-180 transform" : ""+ } transition-all duration-75`}+ />+ </button>+ </Popover>+ </div>+ </div>+ </div>+ );+}++const SharePopover = () => {+ const [openSharePopover, setopenSharePopoverPopover] = useState(false);++ const { endpoint, domain, key } = useContext(StatsContext);++ const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(+ `${endpoint}?domain=${domain}`,+ fetcher,+ );++ const [updating, setUpdating] = useState(false);++ const handleChange = async () => {+ toast.promise(+ new Promise<void>(async (resolve) => {+ setUpdating(true);+ const res = await fetch(`${endpoint}?domain=${domain}`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ publicStats: !publicStats,+ }),+ });+ if (res.status === 200) {+ mutate(`${endpoint}?domain=${domain}`);+ // artificial delay to sync toast with the switch change+ await new Promise((r) => setTimeout(r, 200));+ }+ setUpdating(false);+ resolve();+ }),+ {+ loading: "Updating...",+ success: `Stats page is now ${publicStats ? "private" : "public"}`,+ error: "Something went wrong",+ },+ );+ };+ const [copied, setCopied] = useState(false);++ return (+ <Popover+ content={+ <div className="w-full divide-y divide-gray-200 text-sm sm:w-60">+ <div className="p-4">+ <p className="text-gray-500">Share stats for</p>+ <p className="truncate font-semibold text-gray-800">+ {linkConstructor({ key, domain, pretty: true })}+ </p>+ </div>+ <div className="p-4">+ <div className="mb-2 flex items-center justify-between">+ <p className="font-semibold text-gray-800">Public Stats Page</p>+ <Switch+ checked={publicStats}+ fn={handleChange}+ disabled={updating}+ />+ </div>+ <p className="text-gray-500">+ Making stats public will allow anyone with the link to see the+ stats for this short link.+ </p>+ </div>+ <div className="p-4">+ <p className="font-semibold text-gray-800">Share Link</p>+ <div className="divide-x-200 mt-2 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">+ <div className="overflow-scroll pl-2 scrollbar-hide">+ <p className="whitespace-nowrap text-gray-600">+ https://{domain}/stats/{key}+ </p>+ </div>+ <button+ className="h-8 flex-none border-l bg-white px-2 hover:bg-gray-50 active:bg-gray-100"+ onClick={() => {+ navigator.clipboard.writeText(+ `https://${domain}/stats/${key}`,+ );+ setCopied(true);+ toast.success("Copied to clipboard");+ setTimeout(() => setCopied(false), 3000);+ }}+ >+ {copied ? (+ <Tick className="h-4 w-4 text-gray-500" />+ ) : (+ <Copy className="h-4 w-4 text-gray-500" />+ )}+ </button>+ </div>+ </div>+ </div>+ }+ align="end"+ openPopover={openSharePopover}+ setOpenPopover={setopenSharePopoverPopover}+ >+ <button+ onClick={() => setopenSharePopoverPopover(!openSharePopover)}+ className="mr-2 flex w-24 items-center justify-center space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95"+ >+ <IconMenu text="Share" icon={<Share className="h-4 w-4" />} />+ </button>+ </Popover>+ );+};diff --git a/components/app/projects/project-card.tsx b/components/app/projects/project-card.tsxindex 4b500c04db..7163617474 100644--- a/components/app/projects/project-card.tsx+++ b/components/app/projects/project-card.tsx@@ -71,14 +71,14 @@ export default function ProjectCard({<div className="flex items-center space-x-4"><div className="flex items-center space-x-2 text-gray-500"><Globe className="h-4 w-4" />- <h2 className="text-sm">+ <h2 className="whitespace-nowrap text-sm">{nFormatter(domains.length)} domain{domains.length > 1 && "s"}</h2></div><div className="flex items-center space-x-2 text-gray-500"><Link2 className="h-4 w-4" />{count || count === 0 ? (- <h2 className="text-sm">+ <h2 className="whitespace-nowrap text-sm">{nFormatter(count)} link{count != 1 && "s"}</h2>) : (@@ -87,7 +87,7 @@ export default function ProjectCard({</div><div className="flex items-center space-x-2 text-gray-500"><BarChart2 className="h-4 w-4" />- <h2 className="text-sm">+ <h2 className="whitespace-nowrap text-sm">{nFormatter(usage)} click{usage != 1 && "s"}</h2></div>diff --git a/components/layout/home/index.tsx b/components/layout/home/index.tsxdeleted file mode 100644index d09f6ced97..0000000000--- a/components/layout/home/index.tsx+++ /dev/null@@ -1,101 +0,0 @@-import Image from "next/image";-import Link from "next/link";-import { useRouter } from "next/router";-import { ReactNode } from "react";-import { useSession } from "next-auth/react";-import { Github, Logo, Twitter } from "@/components/shared/icons";-import Meta from "../meta";-import { motion, AnimatePresence } from "framer-motion";-import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";-import NavigationMenu from "../../../app/(marketing)/navigation-menu";--export default function HomeLayout({- meta,- children,-}: {- meta?: {- title?: string;- description?: string;- image?: string;- };- children: ReactNode;-}) {- const { data: session, status } = useSession();- const router = useRouter();- const { key } = router.query as { key?: string };- return (- <div className="flex min-h-screen flex-col justify-between">- <Meta {...meta} />- <div className={`${key ? "bg-gray-50" : ""} z-20`}>- <div className="mx-auto max-w-screen-xl px-5 md:px-20">- <div className="flex h-16 items-center justify-between">- <div className="flex items-center">- <Link href="/">- <Image- src="/_static/logotype.svg"- alt="Dub.sh logo"- width={834}- height={236}- className="w-24"- />- </Link>- </div>-- <NavigationMenu />-- <div className="w-24">- {status !== "loading" && (- <AnimatePresence>- {session ? (- <motion.a- {...FADE_IN_ANIMATION_SETTINGS}- href={- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "https://app.dub.sh"- : "http://app.localhost:3000"- }- className="rounded-full border border-black bg-black py-1.5 px-5 text-sm text-white transition-all hover:bg-white hover:text-black"- >- Dashboard- </motion.a>- ) : (- <motion.a- {...FADE_IN_ANIMATION_SETTINGS}- href={- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "https://app.dub.sh/login"- : "http://app.localhost:3000/login"- }- className="rounded-full border border-black bg-black py-1.5 px-5 text-sm text-white transition-all hover:bg-white hover:text-black"- >- Sign in- </motion.a>- )}- </AnimatePresence>- )}- </div>- </div>- </div>- </div>- {children}- <div className="z-10 flex h-20 items-center justify-center space-x-12 border-t border-gray-200">- <a href="https://twitter.com/dubdotsh" target="_blank" rel="noreferrer">- <span className="sr-only">Twitter</span>- <Twitter className="h-6 w-6 text-gray-600" />- </a>- <Link href="/">- <span className="sr-only">Dub.sh Logo</span>- <Logo className="h-7 w-7 text-gray-600" />- </Link>- <a- href="https://github.com/steven-tey/dub"- target="_blank"- rel="noreferrer"- >- <span className="sr-only">Github</span>- <Github className="h-6 w-6 text-gray-600" />- </a>- </div>- </div>- );-}diff --git a/components/shared/copy-button.tsx b/components/shared/copy-button.tsxindex 32ce455257..f7caa06481 100644--- a/components/shared/copy-button.tsx+++ b/components/shared/copy-button.tsx@@ -1,5 +1,6 @@import { useState } from "react";import { Copy, Tick } from "@/components/shared/icons";+import { toast } from "sonner";export default function CopyButton({ url }: { url: string }) {const [copied, setCopied] = useState(false);@@ -8,7 +9,9 @@ export default function CopyButton({ url }: { url: string }) {onClick={(e) => {e.stopPropagation();setCopied(true);- navigator.clipboard.writeText(url);+ navigator.clipboard.writeText(url).then(() => {+ toast.success("Copied shortlink to clipboard");+ });setTimeout(() => setCopied(false), 3000);}}className="group rounded-full bg-gray-100 p-1.5 transition-all duration-75 hover:scale-105 hover:bg-blue-100 active:scale-95"diff --git a/components/stats/index.tsx b/components/stats/index.tsxindex d8d849f397..ca10852818 100644--- a/components/stats/index.tsx+++ b/components/stats/index.tsx@@ -1,5 +1,3 @@-"use client";-import Clicks from "@/components/stats/clicks";import Devices from "@/components/stats/devices";import Feedback from "@/components/stats/feedback";diff --git a/components/stats/toggle.tsx b/components/stats/toggle.tsxindex 35f4c939eb..06344068a2 100644--- a/components/stats/toggle.tsx+++ b/components/stats/toggle.tsx@@ -9,7 +9,7 @@ import {} from "@/components/shared/icons";import { ExpandingArrow } from "#/ui/icons";import { INTERVALS } from "@/lib/constants";-import useScroll from "@/lib/hooks/use-scroll";+import useScroll from "#/lib/hooks/use-scroll";import { linkConstructor } from "@/lib/utils";import IconMenu from "@/components/shared/icon-menu";import Popover from "@/components/shared/popover";diff --git a/lib/hooks/use-scroll.ts b/lib/hooks/use-scroll.tsdeleted file mode 100644index 3c8014e31d..0000000000--- a/lib/hooks/use-scroll.ts+++ /dev/null@@ -1,16 +0,0 @@-import { useCallback, useEffect, useState } from "react";--export default function useScroll(threshold: number) {- const [scrolled, setScrolled] = useState(false);-- const onScroll = useCallback(() => {- setScrolled(window.pageYOffset > threshold);- }, [threshold]);-- useEffect(() => {- window.addEventListener("scroll", onScroll);- return () => window.removeEventListener("scroll", onScroll);- }, [onScroll]);-- return scrolled;-}diff --git a/lib/planetscale.ts b/lib/planetscale.tsindex b69fd633d7..1ccf4d5347 100644--- a/lib/planetscale.ts+++ b/lib/planetscale.ts@@ -6,7 +6,7 @@ export const pscale_config = {export const conn = process.env.DATABASE_URL ? connect(pscale_config) : null;-export async function getLinkViaEdge(domain: string, key: string) {+export const getLinkViaEdge = async (domain: string, key: string) => {if (!conn) return null;const { rows } =@@ -24,4 +24,4 @@ export async function getLinkViaEdge(domain: string, key: string) {publicStats: boolean;}): null;-}+};diff --git a/package.json b/package.jsonindex 1f61428f13..461ac3c112 100644--- a/package.json+++ b/package.json@@ -47,7 +47,7 @@"contentlayer": "^0.3.2","crisp-sdk-web": "^1.0.18","focus-trap-react": "^10.0.1",- "framer-motion": "^10.12.4",+ "framer-motion": "^10.12.8","html-escaper": "^3.0.3","i": "^0.3.7","js-cookie": "^3.0.5",@@ -75,6 +75,7 @@"rehype-slug": "^5.1.0","remark-gfm": "^3.0.1","shiki": "^0.14.1",+ "sonner": "^0.3.5","stripe": "^11.1.0","swr": "^2.1.5","tailwind-scrollbar-hide": "^1.1.7",diff --git a/pages/stats/[key].tsx b/pages/stats/[key].tsxdeleted file mode 100644index 14438be7ae..0000000000--- a/pages/stats/[key].tsx+++ /dev/null@@ -1,56 +0,0 @@-import HomeLayout from "@/components/layout/home";-import Stats from "@/components/stats";-import { isHomeHostname, nFormatter } from "@/lib/utils";-import { GetServerSideProps } from "next";-import { getLinkViaEdge } from "@/lib/planetscale";--export const config = {- runtime: "experimental-edge",-};--export default function StatsPage({- url,- _key,- domain,-}: {- url: string;- _key: string;- domain?: string;-}) {- return (- <HomeLayout- meta={{- title: `Stats for ${domain}/${_key} - Dub`,- description: `Stats page for ${domain}/${_key}, which redirects to ${url}.`,- image: `https://dub.sh/api/og/stats?domain=${domain}&key=${_key}`,- }}- >- <div className="bg-gray-50">- <Stats staticDomain={domain} />- </div>- </HomeLayout>- );-}--export const getServerSideProps: GetServerSideProps = async ({- req,- params,-}) => {- const { key } = params as { key: string };- let domain = req.headers.host as string;- if (isHomeHostname(domain)) domain = "dub.sh";-- const data = await getLinkViaEdge(domain, key);-- if (data && data.publicStats) {- return {- props: {- ...data,- _key: key,- domain,- },- };- } else {- return { notFound: true };- }-};diff --git a/yarn.lock b/yarn.lockindex 555c72f4e5..2d0191b9d5 100644--- a/yarn.lock+++ b/yarn.lock@@ -4205,10 +4205,10 @@ fraction.js@^4.2.0:resolved "https://registry.yarnpkg.com/fraction.js/-/fraction.js-4.2.0.tgz#448e5109a313a3527f5a3ab2119ec4cf0e0e2950"integrity sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==-framer-motion@^10.12.4:- version "10.12.4"- resolved "https://registry.yarnpkg.com/framer-motion/-/framer-motion-10.12.4.tgz#905fdfa5b63dae53a63d2549b29aef6193eb78c7"- integrity sha512-9gLtv8T6dui0tujHROR+VM3kdJyKiFCFiD94IQE+0OuX6LaIyXtdVpviokVdrHSb1giWhmmX4yzoucALMx6mtw==+framer-motion@^10.12.8:+ version "10.12.8"+ resolved "https://registry.yarnpkg.com/framer-motion/-/framer-motion-10.12.8.tgz#2b2c99818d9e8531165d07eef569828a3b135d51"+ integrity sha512-ylobYq3tGFjjAmRdBs5pL/R1+4AmOm69g/JbF5DcNETfRe8L9CjaX4acG83MjYdIsbsTGJmtR5qKx4glNmXO4A==dependencies:tslib "^2.4.0"optionalDependencies:@@ -8278,6 +8278,11 @@ socks@^2.3.3, socks@^2.6.2:ip "^2.0.0"smart-buffer "^4.2.0"+sonner@^0.3.5:+ version "0.3.5"+ resolved "https://registry.yarnpkg.com/sonner/-/sonner-0.3.5.tgz#5ef175732cb7b637c6460620ab01a0fba0e6a36b"+ integrity sha512-yIwaQ4dftMvFApuruto2t7wGyyaPRpj5qYBWYJIz4Z7uGcVn0IfqI/hWN0JyJN4izNbZFuCYZISf3fOGnvSlNQ==+sort-keys@^5.0.0:version "5.0.0"resolved "https://registry.yarnpkg.com/sort-keys/-/sort-keys-5.0.0.tgz#5d775f8ae93ecc29bc7312bbf3acac4e36e3c446"