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.

Added stats section, turned Globe into server component, removed coordinates endpoint

Steven Tey676c7d4450e2
diff --git a/app/dub.sh/page.tsx b/app/dub.sh/page.tsx
index 911d77a983..91e323455b 100644
--- a/app/dub.sh/page.tsx
+++ b/app/dub.sh/page.tsx
@@ -1,7 +1,8 @@
import Background from "@/components/shared/background";
import Demo from "#/ui/home/demo";
-import Features from "#/ui/home/features";
import Globe from "#/ui/home/globe";
+import Stats from "#/ui/home/stats";
+import Features from "#/ui/home/features";
import Hero from "#/ui/home/hero";
import Logos from "#/ui/home/logos";
import Pricing from "#/ui/home/pricing";
@@ -15,7 +16,10 @@ export default function Home() {
<Hero />
<Demo />
<Logos />
+ {/* @ts-expect-error Async Server Component */}
<Globe />
+ {/* @ts-expect-error Async Server Component */}
+ <Stats />
<Features />
{/* @ts-expect-error Async Server Component */}
<Testimonials />
diff --git a/components/shared/counting-numbers.tsx b/app/ui/counting-numbers.tsx
similarity index 100%
rename from components/shared/counting-numbers.tsx
rename to app/ui/counting-numbers.tsx
diff --git a/app/ui/home/features.tsx b/app/ui/home/features.tsx
index 398314cfd4..96c0bbbf8a 100644
--- a/app/ui/home/features.tsx
+++ b/app/ui/home/features.tsx
@@ -115,7 +115,7 @@ export default function Features() {
// preload videos
<link key={key} rel="preload" as="video" href={demo} />
))}
- <MaxWidthWrapper className="py-10">
+ <MaxWidthWrapper className="pb-10 pt-24">
<div className="mx-auto max-w-md text-center sm:max-w-xl">
<h2 className="font-display text-4xl font-extrabold leading-tight text-black sm:text-5xl sm:leading-tight">
<span className="bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent">
diff --git a/app/ui/home/globe-client.tsx b/app/ui/home/globe-client.tsx
new file mode 100644
index 0000000000..288cac81e6
--- /dev/null
+++ b/app/ui/home/globe-client.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useRef, useState } from "react";
+import createGlobe from "cobe";
+import { AnimatePresence, motion } from "framer-motion";
+import { useSpring } from "react-spring";
+import { Drag, X } from "@/components/shared/icons";
+import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
+
+interface MarkerProps {
+ location: [number, number];
+ size: number;
+}
+
+export default function GlobeClient({ markers }: { markers: MarkerProps[] }) {
+ const divRef = useRef<any>();
+ const entry = useIntersectionObserver(divRef, {});
+ const isVisible = !!entry?.isIntersecting;
+ const [showGlobe, setShowGlobe] = useState(false);
+
+ useEffect(() => {
+ if (isVisible) {
+ setShowGlobe(true);
+ } else {
+ setShowGlobe(false);
+ }
+ }, [isVisible]);
+
+ const [webglSupported, setWebglSupported] = useState(true);
+
+ useEffect(() => {
+ try {
+ const canvas = window.document.createElement("canvas");
+ const ctx =
+ canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
+ (ctx as any).getSupportedExtensions();
+ } catch (e) {
+ // WebGL isn't properly supported
+ setWebglSupported(false);
+ console.log("WebGL not supported, hiding globe animation...");
+ return;
+ }
+ }, []);
+
+ return (
+ <div
+ ref={divRef}
+ className={`${
+ webglSupported ? "min-h-[500px] sm:min-h-[1000px]" : "min-h-[50px]"
+ } h-full`}
+ >
+ {webglSupported && showGlobe && (
+ <GlobeAnimation markers={markers || []} />
+ )}
+ </div>
+ );
+}
+
+const GlobeAnimation = ({ markers }: { markers: MarkerProps[] }) => {
+ const canvasRef = useRef<any>();
+ const pointerInteracting = useRef<number | null>(null);
+ const pointerInteractionMovement = useRef(0);
+
+ const [{ r }, api] = useSpring(() => ({
+ r: 0,
+ config: {
+ mass: 1,
+ tension: 280,
+ friction: 60,
+ precision: 0.001,
+ },
+ }));
+
+ useEffect(() => {
+ let phi = -0.5;
+ let width = 0;
+ const onResize = () =>
+ canvasRef.current && (width = canvasRef.current.offsetWidth);
+ window.addEventListener("resize", onResize);
+ onResize();
+ const globe = createGlobe(canvasRef.current, {
+ devicePixelRatio: 1,
+ width,
+ height: width,
+ phi,
+ theta: 0.15,
+ dark: 0,
+ diffuse: 1.2,
+ scale: 1,
+ mapSamples: 20000,
+ mapBrightness: 4,
+ baseColor: [1, 1, 1],
+ markerColor: [249 / 255, 115 / 255, 22 / 255],
+ offset: [0, 0],
+ glowColor: [0.8, 0.8, 0.8],
+ markers: markers || [],
+ onRender: (state) => {
+ // Called on every animation frame.
+ // `state` will be an empty object, return updated params.
+ phi += 0.002;
+ state.phi = phi + r.get();
+ state.width = width;
+ state.height = width;
+ },
+ });
+ setTimeout(() => (canvasRef.current.style.opacity = "1"));
+ return () => globe.destroy();
+ }, [markers]);
+
+ const [showModal, setShowModal] = useState(true);
+
+ return (
+ <div className="relative flex items-center">
+ <AnimatePresence>
+ {showModal && (
+ <motion.div
+ key="globe-modal"
+ initial={{ scale: 0 }}
+ animate={{ scale: 1 }}
+ exit={{ scale: 0 }}
+ className="group absolute left-0 right-0 z-10 mx-auto max-w-sm rounded-md border border-gray-200 bg-white bg-opacity-90 px-5 py-4 shadow-md backdrop-blur-md sm:py-7"
+ >
+ <button
+ className="group visible absolute right-0 top-0 float-right m-3 rounded-full p-1 transition-all duration-75 hover:bg-gray-100 focus:outline-none active:scale-75 group-hover:visible sm:invisible"
+ autoFocus={false}
+ onClick={() => setShowModal(false)}
+ >
+ <span className="sr-only">Spin Globe</span>
+ <X className="h-4 w-4" />
+ </button>
+ <Drag className="mx-auto mb-2 h-12 w-12 text-gray-700 sm:mb-4" />
+ <p className="text-center text-sm text-gray-700 sm:text-base">
+ This map shows the locations of the last 50 clicks on{" "}
+ <a
+ className="font-semibold text-blue-800"
+ href="https://dub.sh/github"
+ target="_blank"
+ rel="noreferrer"
+ >
+ dub.sh/github
+ </a>
+ .
+ </p>
+ <Link
+ 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 stats
+ </Link>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ <div
+ style={{
+ width: "100%",
+ maxWidth: 1000,
+ aspectRatio: "1",
+ margin: "auto",
+ position: "relative",
+ }}
+ >
+ <canvas
+ ref={canvasRef}
+ onPointerDown={(e) => {
+ pointerInteracting.current =
+ e.clientX - pointerInteractionMovement.current;
+ canvasRef.current.style.cursor = "grabbing";
+ }}
+ onPointerUp={() => {
+ pointerInteracting.current = null;
+ canvasRef.current.style.cursor = "grab";
+ }}
+ onPointerOut={() => {
+ pointerInteracting.current = null;
+ canvasRef.current.style.cursor = "grab";
+ }}
+ onMouseMove={(e) => {
+ if (pointerInteracting.current !== null) {
+ const delta = e.clientX - pointerInteracting.current;
+ pointerInteractionMovement.current = delta;
+ api.start({
+ r: delta / 200,
+ });
+ }
+ }}
+ onTouchMove={(e) => {
+ if (pointerInteracting.current !== null && e.touches[0]) {
+ const delta = e.touches[0].clientX - pointerInteracting.current;
+ pointerInteractionMovement.current = delta;
+ api.start({
+ r: delta / 100,
+ });
+ }
+ }}
+ style={{
+ width: "100%",
+ height: "100%",
+ contain: "layout paint size",
+ opacity: 0,
+ transition: "opacity 1s ease",
+ }}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/app/ui/home/globe.tsx b/app/ui/home/globe.tsx
index ec55aeaac0..5311c6cf4a 100644
--- a/app/ui/home/globe.tsx
+++ b/app/ui/home/globe.tsx
@@ -1,214 +1,26 @@
-"use client";
-
-import Link from "next/link";
-import { useEffect, useRef, useState } from "react";
-import createGlobe from "cobe";
-import { AnimatePresence, motion } from "framer-motion";
-import { useSpring } from "react-spring";
-import useSWR from "swr";
-import { Drag, X } from "@/components/shared/icons";
-import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
-import { fetcher } from "@/lib/utils";
-
-interface MarkerProps {
- location: [number, number];
- size: number;
-}
-
-export default function Globe() {
- const divRef = useRef<any>();
- const entry = useIntersectionObserver(divRef, {});
- const isVisible = !!entry?.isIntersecting;
- const [showGlobe, setShowGlobe] = useState(false);
-
- useEffect(() => {
- if (isVisible) {
- setShowGlobe(true);
- } else {
- setShowGlobe(false);
- }
- }, [isVisible]);
-
- const [webglSupported, setWebglSupported] = useState(true);
-
- const { data: markers } = useSWR<MarkerProps[]>(
- `/api/edge/coordinates`,
- fetcher,
- );
-
- useEffect(() => {
- try {
- const canvas = window.document.createElement("canvas");
- const ctx =
- canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
- (ctx as any).getSupportedExtensions();
- } catch (e) {
- // WebGL isn't properly supported
- setWebglSupported(false);
- console.log("WebGL not supported, hiding globe animation...");
- return;
- }
- }, []);
-
- return (
- <div
- ref={divRef}
- className={`${
- webglSupported ? "min-h-[500px] sm:min-h-[1000px]" : "min-h-[50px]"
- } h-full`}
- >
- {webglSupported && showGlobe && (
- <GlobeAnimation markers={markers || []} />
- )}
- </div>
- );
-}
-
-const GlobeAnimation = ({ markers }: { markers: MarkerProps[] }) => {
- const canvasRef = useRef<any>();
- const pointerInteracting = useRef<number | null>(null);
- const pointerInteractionMovement = useRef(0);
-
- const [{ r }, api] = useSpring(() => ({
- r: 0,
- config: {
- mass: 1,
- tension: 280,
- friction: 60,
- precision: 0.001,
- },
- }));
-
- useEffect(() => {
- let phi = -0.5;
- let width = 0;
- const onResize = () =>
- canvasRef.current && (width = canvasRef.current.offsetWidth);
- window.addEventListener("resize", onResize);
- onResize();
- const globe = createGlobe(canvasRef.current, {
- devicePixelRatio: 1,
- width,
- height: width,
- phi,
- theta: 0.15,
- dark: 0,
- diffuse: 1.2,
- scale: 1,
- mapSamples: 20000,
- mapBrightness: 4,
- baseColor: [1, 1, 1],
- markerColor: [249 / 255, 115 / 255, 22 / 255],
- offset: [0, 0],
- glowColor: [0.8, 0.8, 0.8],
- markers: markers || [],
- onRender: (state) => {
- // Called on every animation frame.
- // `state` will be an empty object, return updated params.
- phi += 0.002;
- state.phi = phi + r.get();
- state.width = width;
- state.height = width;
+import GlobeClient from "./globe-client";
+
+export default async function Globe() {
+ const response = await fetch(
+ `https://api.us-east.tinybird.co/v0/pipes/coordinates.json`,
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
},
- });
- setTimeout(() => (canvasRef.current.style.opacity = "1"));
- return () => globe.destroy();
- }, [markers]);
-
- const [showModal, setShowModal] = useState(true);
-
- return (
- <div className="relative flex items-center">
- <AnimatePresence>
- {showModal && (
- <motion.div
- key="globe-modal"
- initial={{ scale: 0 }}
- animate={{ scale: 1 }}
- exit={{ scale: 0 }}
- className="group absolute left-0 right-0 z-10 mx-auto max-w-sm rounded-md border border-gray-200 bg-white bg-opacity-90 px-5 py-4 shadow-md backdrop-blur-md sm:py-7"
- >
- <button
- className="group visible absolute right-0 top-0 float-right m-3 rounded-full p-1 transition-all duration-75 hover:bg-gray-100 focus:outline-none active:scale-75 group-hover:visible sm:invisible"
- autoFocus={false}
- onClick={() => setShowModal(false)}
- >
- <span className="sr-only">Spin Globe</span>
- <X className="h-4 w-4" />
- </button>
- <Drag className="mx-auto mb-2 h-12 w-12 text-gray-700 sm:mb-4" />
- <p className="text-center text-sm text-gray-700 sm:text-base">
- This map shows the locations of the last 50 clicks on{" "}
- <a
- className="font-semibold text-blue-800"
- href="https://dub.sh/github"
- target="_blank"
- rel="noreferrer"
- >
- dub.sh/github
- </a>
- .
- </p>
- <Link
- 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 stats
- </Link>
- </motion.div>
- )}
- </AnimatePresence>
- <div
- style={{
- width: "100%",
- maxWidth: 1000,
- aspectRatio: "1",
- margin: "auto",
- position: "relative",
- }}
- >
- <canvas
- ref={canvasRef}
- onPointerDown={(e) => {
- pointerInteracting.current =
- e.clientX - pointerInteractionMovement.current;
- canvasRef.current.style.cursor = "grabbing";
- }}
- onPointerUp={() => {
- pointerInteracting.current = null;
- canvasRef.current.style.cursor = "grab";
- }}
- onPointerOut={() => {
- pointerInteracting.current = null;
- canvasRef.current.style.cursor = "grab";
- }}
- onMouseMove={(e) => {
- if (pointerInteracting.current !== null) {
- const delta = e.clientX - pointerInteracting.current;
- pointerInteractionMovement.current = delta;
- api.start({
- r: delta / 200,
- });
- }
- }}
- onTouchMove={(e) => {
- if (pointerInteracting.current !== null && e.touches[0]) {
- const delta = e.touches[0].clientX - pointerInteracting.current;
- pointerInteractionMovement.current = delta;
- api.start({
- r: delta / 100,
- });
- }
- }}
- style={{
- width: "100%",
- height: "100%",
- contain: "layout paint size",
- opacity: 0,
- transition: "opacity 1s ease",
- }}
- />
- </div>
- </div>
- );
-};
+ next: {
+ revalidate: 43200, // every 12 hours
+ },
+ },
+ )
+ .then((res) => res.json())
+ .then((res) => res.data);
+
+ const markers = response.map(({ latitude, longitude }, idx) => {
+ return {
+ location: [latitude, longitude],
+ size: 0.075 - (0.075 / 50) * idx,
+ };
+ });
+
+ return <GlobeClient markers={markers} />;
+}
diff --git a/app/ui/home/oss.tsx b/app/ui/home/oss.tsx
index b828b8977b..f84d18607d 100644
--- a/app/ui/home/oss.tsx
+++ b/app/ui/home/oss.tsx
@@ -1,5 +1,5 @@
import { Github } from "@/components/shared/icons";
-import CountingNumbers from "../../../components/shared/counting-numbers";
+import CountingNumbers from "../counting-numbers";
import MaxWidthWrapper from "../../../components/shared/max-width-wrapper";
import styles from "./features.module.css";
diff --git a/app/ui/home/stats.tsx b/app/ui/home/stats.tsx
new file mode 100644
index 0000000000..2df5e69ec4
--- /dev/null
+++ b/app/ui/home/stats.tsx
@@ -0,0 +1,61 @@
+import { unstable_cache } from "next/cache";
+import prisma from "@/lib/prisma";
+import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
+import { nFormatter } from "@/lib/utils";
+
+export default async function Stats() {
+ const [domains, shortlinks] = await unstable_cache(
+ async () => {
+ return Promise.all([
+ prisma.domain.count({
+ where: {
+ verified: true,
+ },
+ }),
+ prisma.link.count(),
+ ]);
+ },
+ [],
+ {
+ revalidate: 900,
+ },
+ )();
+
+ const clicks = await fetch(
+ `https://api.us-east.tinybird.co/v0/pipes/all_clicks.json`,
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
+ },
+ next: {
+ revalidate: 300,
+ },
+ },
+ )
+ .then((res) => res.json())
+ .then((res) => res.data[0]["count(timestamp)"]);
+
+ return (
+ <div className="border-y border-gray-200 bg-white/10 py-8 shadow-[inset_10px_-50px_94px_0_rgb(199,199,199,0.2)] backdrop-blur">
+ <MaxWidthWrapper className="grid gap-y-4 divide-x divide-gray-200 md:grid-cols-3 md:gap-y-0">
+ {[
+ { name: "Custom Domains", value: domains },
+ { name: "Short Links", value: shortlinks },
+ { name: "Link Redirects", value: clicks },
+ ].map(({ name, value }) => (
+ <div
+ key={name}
+ className="flex flex-col items-center justify-center space-y-2"
+ >
+ <p className="text-4xl font-bold md:text-6xl">
+ {nFormatter(value)}
+ </p>
+ <p className="font-semibold uppercase text-gray-500 md:text-lg">
+ {name}
+ </p>
+ </div>
+ ))}
+ </MaxWidthWrapper>
+ </div>
+ );
+}
diff --git a/pages/api/edge/coordinates.ts b/pages/api/edge/coordinates.ts
deleted file mode 100644
index ddd7e6f14d..0000000000
--- a/pages/api/edge/coordinates.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { NextRequest } from "next/server";
-import { redis } from "@/lib/upstash";
-
-export const config = {
- runtime: "edge",
-};
-
-interface CoordinateProps {
- location: [string, string];
- size: number;
-}
-
-const hasRedisEnv =
- process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN;
-
-export default async function handler(req: NextRequest) {
- if (req.method === "GET") {
- const count = 50;
- let latestCoordinates: CoordinateProps[] = [];
-
- // Check if coordinates are cached in Redis
- const cachedCoordinates =
- hasRedisEnv && (await redis.get<CoordinateProps[]>("coordinates"));
-
- if (cachedCoordinates) {
- latestCoordinates = cachedCoordinates;
-
- // if not cached in Redis, fetch from Tinybird
- } else if (process.env.TINYBIRD_API_KEY) {
- const response = await fetch(
- `https://api.us-east.tinybird.co/v0/pipes/coordinates.json`,
- {
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- },
- },
- )
- .then((res) => res.json())
- .then((res) => res.data);
-
- latestCoordinates = response.map(({ latitude, longitude }, idx) => {
- return {
- location: [latitude, longitude],
- size: 0.075 - (0.075 / count) * idx,
- };
- });
-
- // cache coordinates in Redis for 24 hours
- hasRedisEnv &&
- (await redis.set("coordinates", JSON.stringify(latestCoordinates), {
- ex: 86400,
- }));
- }
-
- return new Response(JSON.stringify(latestCoordinates), {
- status: 200,
- });
- } else {
- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });
- }
-}