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.

small optimizations & tweaks

Steven Tey5ab1e98379bf
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index bebca70d14..baef75adbf 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -1,6 +1,6 @@
import Link from "next/link";
import { useRouter } from "next/router";
-import { useState } from "react";
+import { 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";
@@ -14,6 +14,7 @@ import {
Chart,
Delete,
Edit,
+ Eye,
LoadingDots,
QR,
ThreeDots,
@@ -30,6 +31,7 @@ import {
nFormatter,
timeAgo,
} from "@/lib/utils";
+import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
export default function LinkCard({ props }: { props: LinkProps }) {
const {
@@ -53,13 +55,19 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const { isOwner } = useProject();
const { exceededUsage } = useUsage();
+ const linkRef = useRef<any>();
+ const entry = useIntersectionObserver(linkRef, {});
+ const isVisible = !!entry?.isIntersecting;
+
const { data: clicks, isValidating } = useSWR<number>(
- domain
- ? `/api/projects/${slug}/domains/${domain}/links/${key}/clicks`
- : `/api/links/${key}/clicks`,
+ isVisible &&
+ (domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${key}/clicks`
+ : `/api/links/${key}/clicks`),
fetcher,
{
fallbackData: props.clicks,
+ dedupingInterval: 15000, // fetch at most once every 15 seconds
},
);
@@ -77,12 +85,14 @@ export default function LinkCard({ props }: { props: LinkProps }) {
props,
});
const [openPopover, setOpenPopover] = useState(false);
- const [unarchiving, setUnarchiving] = useState(false);
const expired = expiresAt && new Date() > new Date(expiresAt);
return (
- <div className="relative rounded-lg border border-gray-100 bg-white p-3 pr-1 shadow transition-all hover:shadow-md sm:p-4">
+ <div
+ ref={linkRef}
+ className="relative rounded-lg border border-gray-100 bg-white p-3 pr-1 shadow transition-all hover:shadow-md sm:p-4"
+ >
<LinkQRModal />
<AddEditLinkModal />
<ArchiveLinkModal />
@@ -146,6 +156,18 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<span className="ml-1 hidden sm:inline-block">clicks</span>
</p>
</Link>
+ {title && description && image && (
+ <a
+ href={`https://${domain || "dub.sh"}/_proxy/${
+ domain || "dub.sh"
+ }/${encodeURI(key)}`}
+ target="_blank"
+ rel="noreferrer"
+ className="group rounded-full bg-gray-100 p-1.5 transition-all duration-75 hover:scale-105 hover:bg-blue-100 active:scale-95"
+ >
+ <Eye className="text-gray-700 transition-all group-hover:text-blue-800" />
+ </a>
+ )}
</div>
<h3 className="max-w-[200px] truncate text-sm font-medium text-gray-700 md:max-w-md lg:max-w-2xl xl:max-w-3xl">
{url}
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 7123086a60..01dca999a8 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -2,9 +2,11 @@ import { useRouter } from "next/router";
import {
Dispatch,
SetStateAction,
+ UIEvent,
useCallback,
useEffect,
useMemo,
+ useRef,
useState,
} from "react";
import { mutate } from "swr";
@@ -67,7 +69,7 @@ function AddEditLinkModal({
createdAt: new Date(),
},
);
- const { key, url, expiresAt } = data;
+ const { key, url, password, expiresAt } = data;
const [debouncedKey] = useDebounce(key, 500);
useEffect(() => {
@@ -97,26 +99,59 @@ function AddEditLinkModal({
setGeneratingSlug(false);
}, []);
- const [generatingMetatags, setGeneratingMetatags] = useState(false);
+ // const onPaste = useCallback(
+ // (e: React.ClipboardEvent<HTMLInputElement>) => {
+ // if (props) return;
+ // const url = e.clipboardData.getData("text");
+ // setShowAddEditLinkModal(true);
+ // try {
+ // new URL(url);
+ // console.log(url);
+ // setData((prev) => ({ ...prev, url }));
+ // } catch (e) {
+ // console.log("not a valid url");
+ // }
+ // },
+ // [props, showAddEditLinkModal, setData],
+ // );
+
+ // useEffect(() => {
+ // window.addEventListener("paste", onPaste as any);
+ // return () => window.removeEventListener("paste", onPaste as any);
+ // }, [onPaste]);
- const [debouncedUrl] = useDebounce(url, 500);
+ const [generatingMetatags, setGeneratingMetatags] = useState(false);
+ const [debouncedUrl] = useDebounce(url.split("?")[0], 500);
useEffect(() => {
- try {
- new URL(debouncedUrl);
- if (
- (!props?.image || debouncedUrl !== props?.url) &&
- showAddEditLinkModal
- ) {
+ // if there's a password, no need to generate metatags
+ if (password) {
+ setData((prev) => ({
+ ...prev,
+ title: "Password Required",
+ description:
+ "This link is password protected. Please enter the password to view it.",
+ image: "/_static/password-protected.png",
+ }));
+ return;
+ }
+ if (
+ // only generate metatags if:
+ showAddEditLinkModal && // modal is open
+ (!props?.image || debouncedUrl !== props?.url.split("?")[0]) // there's no image or the url has changed
+ ) {
+ // using a setTimeout to delay until the loading screen fades in (0.2 delay in framer motion as well)
+ setTimeout(() => {
+ setData((prev) => ({
+ ...prev,
+ title: null,
+ description: null,
+ image: null,
+ }));
+ }, 200);
+ try {
+ // if url is valid, continue to generate metatags, else return null
+ new URL(debouncedUrl);
setGeneratingMetatags(true);
- // using a setTimeout to delay until the loading screen fades in (0.2 delay in framer motion as well)
- setTimeout(() => {
- setData((prev) => ({
- ...prev,
- title: null,
- description: null,
- image: null,
- }));
- }, 200);
fetch(`/api/edge/metatags?url=${debouncedUrl}`).then(async (res) => {
if (res.status === 200) {
const results = await res.json();
@@ -124,11 +159,21 @@ function AddEditLinkModal({
}
setGeneratingMetatags(false);
});
+ } catch (e) {
+ console.log("not a valid url");
}
- } catch (e) {
- console.log("not a valid url");
}
- }, [debouncedUrl]);
+ }, [props, debouncedUrl, password]);
+
+ const logo = useMemo(() => {
+ if (password || (!debouncedUrl && !props)) {
+ return "/_static/logo.png";
+ } else {
+ return `https://www.google.com/s2/favicons?sz=64&domain_url=${getApexDomain(
+ debouncedUrl || props.url,
+ )}`;
+ }
+ }, [password, debouncedUrl, props]);
const endpoint = useMemo(() => {
if (props?.key) {
@@ -150,6 +195,15 @@ function AddEditLinkModal({
const expired = expiresAt && new Date() > new Date(expiresAt);
+ const [scrolled, setScrolled] = useState(false);
+ const handleScroll = (event: UIEvent<HTMLElement>) => {
+ if (event.currentTarget.scrollTop > 144) {
+ setScrolled(true);
+ } else {
+ setScrolled(false);
+ }
+ };
+
return (
<Modal
showModal={showAddEditLinkModal}
@@ -166,52 +220,33 @@ function AddEditLinkModal({
</button>
)}
- <div className="max-h-[80vh] overflow-scroll rounded-l-2xl">
- {/* <div className="flex items-center justify-center space-x-3 border-b border-gray-200 py-5 px-4 sm:px-16">
- <div className="relative flex w-full items-center">
- <BlurImage
- src={heroProps.avatar}
- alt={heroProps.alt}
- className="absolute inset-y-0 left-0 my-2.5 ml-3 h-5 w-5 rounded-full"
- width={20}
- height={20}
- />
- <input
- type="url"
- placeholder="Shorten your link"
- value={url}
- onChange={(e) => {
- setKeyExistsError(false);
- setData({ ...data, url: e.target.value });
- }}
- required
- className="peer block w-full rounded-md border border-gray-100 bg-gray-50 p-2 pl-10 text-sm placeholder:text-gray-400 focus:border-black focus:bg-white focus:outline-none focus:ring-0"
- />
- </div>
- </div> */}
- <div className="sticky top-0 z-10 flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 pt-10 pb-8 sm:px-16">
+ <div
+ className="max-h-[80vh] overflow-scroll rounded-l-2xl"
+ onScroll={handleScroll}
+ >
+ <div
+ className={`${
+ scrolled ? "py-5" : "pt-10 pb-8"
+ } sticky top-0 z-10 flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 transition-all sm:px-16`}
+ >
<BlurImage
- src={
- data.url || props
- ? `https://www.google.com/s2/favicons?sz=64&domain_url=${getApexDomain(
- data.url || props.url,
- )}`
- : "/_static/logo.png"
- }
+ src={logo}
alt="Logo"
className="h-10 w-10 rounded-full"
width={20}
height={20}
/>
- <h3 className="text-lg font-medium">
- {props
- ? `Edit ${linkConstructor({
- key: props.key,
- domain,
- pretty: true,
- })}`
- : "Add a new link"}
- </h3>
+ {!scrolled && (
+ <h3 className="text-lg font-medium">
+ {props
+ ? `Edit ${linkConstructor({
+ key: props.key,
+ domain,
+ pretty: true,
+ })}`
+ : "Add a new link"}
+ </h3>
+ )}
</div>
{/* {id && (
diff --git a/components/app/modals/add-edit-link-modal/preview.tsx b/components/app/modals/add-edit-link-modal/preview.tsx
index 631ceedb0d..d36f404785 100644
--- a/components/app/modals/add-edit-link-modal/preview.tsx
+++ b/components/app/modals/add-edit-link-modal/preview.tsx
@@ -1,7 +1,16 @@
import BlurImage from "@/components/shared/blur-image";
-import { Facebook, LinkedIn, Photo, Twitter } from "@/components/shared/icons";
+import {
+ ExternalLink,
+ Facebook,
+ LinkedIn,
+ LoadingCircle,
+ Photo,
+ Twitter,
+} from "@/components/shared/icons";
import { LinkProps } from "@/lib/types";
+import { getDomainWithoutWWW } from "@/lib/utils";
import { useMemo } from "react";
+import { useDebounce } from "use-debounce";
export default function Preview({
data,
@@ -11,40 +20,18 @@ export default function Preview({
generatingMetatags: boolean;
}) {
const { title, description, image, url, password } = data;
- let hostname;
- try {
- hostname = new URL(url).hostname.replace(/^www\./, "");
- } catch (e) {
- hostname = url;
- }
-
- const { previewTitle, previewDescription, previewHostname } = useMemo(() => {
- if (password) {
- return {
- previewTitle: "Password Required",
- previewDescription:
- "This link is password protected. Please enter the password to view it.",
- previewHostname: "dub.sh",
- };
- } else {
- return {
- previewTitle: title,
- previewDescription: description,
- previewHostname: hostname,
- };
- }
- }, [password, title, description, hostname]);
+ const [debouncedUrl] = useDebounce(url, 500);
+ const hostname = useMemo(() => {
+ if (password) return "dub.sh";
+ return getDomainWithoutWWW(debouncedUrl);
+ }, [password, debouncedUrl]);
const previewImage = useMemo(() => {
- if (password) {
+ if (generatingMetatags) {
return (
- <BlurImage
- src="/_static/password-protected.png"
- alt="Preview"
- width={1200}
- height={627}
- className="h-[250px] w-full border-b border-gray-300 object-cover"
- />
+ <div className="flex h-[250px] w-full flex-col items-center justify-center space-y-4 border-b border-gray-300 bg-gray-100">
+ <LoadingCircle />
+ </div>
);
}
if (image) {
@@ -77,7 +64,7 @@ export default function Preview({
</div>
);
}
- }, [image, password]);
+ }, [image]);
return (
<div className="h-[1200px]">
@@ -99,27 +86,26 @@ export default function Preview({
<div className="flex items-center space-x-2 bg-white px-3">
<Twitter className="h-4 w-4 text-[#1DA1F2]" />
<p className="text-sm text-gray-400">Twitter</p>
+ <ExternalLink className="h-4 w-4 text-gray-400" />
</div>
</div>
</div>
<div className="overflow-hidden rounded-md border border-gray-300">
{previewImage}
<div className="grid gap-1 p-3">
- {previewHostname ? (
- <p className="text-sm text-[#536471]">{previewHostname}</p>
+ {hostname ? (
+ <p className="text-sm text-[#536471]">{hostname}</p>
) : (
<div className="mb-1 h-4 w-24 rounded-md bg-gray-100" />
)}
- {previewTitle ? (
- <h3 className="truncate text-sm text-[#0f1419]">
- {previewTitle}
- </h3>
+ {title ? (
+ <h3 className="truncate text-sm text-[#0f1419]">{title}</h3>
) : (
<div className="mb-1 h-4 w-full rounded-md bg-gray-100" />
)}
- {previewDescription ? (
+ {description ? (
<p className="text-sm text-[#536471] line-clamp-2">
- {previewDescription}
+ {description}
</p>
) : (
<div className="grid gap-2">
@@ -150,23 +136,23 @@ export default function Preview({
<div className="border border-gray-300">
{previewImage}
<div className="grid gap-1 bg-[#f2f3f5] p-3">
- {previewHostname ? (
+ {hostname ? (
<p className="text-[0.8rem] uppercase text-[#606770]">
- {previewHostname}
+ {hostname}
</p>
) : (
<div className="mb-1 h-4 w-24 rounded-md bg-gray-200" />
)}
- {previewTitle ? (
+ {title ? (
<h3 className="truncate font-semibold text-[#1d2129]">
- {previewTitle}
+ {title}
</h3>
) : (
<div className="mb-1 h-5 w-full rounded-md bg-gray-200" />
)}
- {previewDescription ? (
+ {description ? (
<p className="text-sm text-[#606770] line-clamp-2">
- {previewDescription}
+ {description}
</p>
) : (
<div className="grid gap-2">
@@ -197,15 +183,15 @@ export default function Preview({
<div className="overflow-hidden rounded-[2px] shadow-[0_0_0_1px_rgba(0,0,0,0.15),0_2px_3px_rgba(0,0,0,0.2)]">
{previewImage}
<div className="grid gap-1 bg-white p-3">
- {previewTitle ? (
+ {title ? (
<h3 className="truncate font-semibold text-[#000000E6]">
- {previewTitle}
+ {title}
</h3>
) : (
<div className="mb-1 h-5 w-full rounded-md bg-gray-200" />
)}
- {previewHostname ? (
- <p className="text-xs text-[#00000099]">{previewHostname}</p>
+ {hostname ? (
+ <p className="text-xs text-[#00000099]">{hostname}</p>
) : (
<div className="mb-1 h-4 w-24 rounded-md bg-gray-200" />
)}
diff --git a/components/app/modals/complete-setup-modal.tsx b/components/app/modals/complete-setup-modal.tsx
index 2d279e6635..9e02006565 100644
--- a/components/app/modals/complete-setup-modal.tsx
+++ b/components/app/modals/complete-setup-modal.tsx
@@ -63,13 +63,16 @@ function CompleteSetupModal({
);
if (cta === "closeModal") {
return (
- <button onClick={() => setShowCompleteSetupModal(false)}>
+ <button
+ key={display}
+ onClick={() => setShowCompleteSetupModal(false)}
+ >
{contents}
</button>
);
}
return (
- <a target="_blank" rel="noreferrer" href={cta}>
+ <a key={display} target="_blank" rel="noreferrer" href={cta}>
{contents}
</a>
);
diff --git a/components/home/link-card.tsx b/components/home/link-card.tsx
index 310ad181ef..dc89e7924c 100644
--- a/components/home/link-card.tsx
+++ b/components/home/link-card.tsx
@@ -3,7 +3,6 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { motion, useAnimation, useMotionValue } from "framer-motion";
import toast from "react-hot-toast";
import useSWR from "swr";
-import { useDebouncedCallback } from "use-debounce";
import { useLinkQRModal } from "@/components/app/modals/link-qr-modal";
import BlurImage from "@/components/shared/blur-image";
import CopyButton from "@/components/shared/copy-button";
diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.ts
index b6eb6a2d75..7611aa8885 100644
--- a/pages/api/edge/metatags.ts
+++ b/pages/api/edge/metatags.ts
@@ -35,6 +35,7 @@ const getMetadataFromUrl = async (url: string) => {
})
.then((body: string) => {
const obj = {};
+ // get all meta tags
body.replace(
/<meta\s+(?:name|property|itemprop|http-equiv)="([^"]+)"\s+content="([^"]+)"/g,
// @ts-ignore
@@ -42,6 +43,30 @@ const getMetadataFromUrl = async (url: string) => {
obj[key] = unescape(value);
},
);
+ // get all meta tags (reversed order for content & name/property)
+ body.replace(
+ /<meta\s+content="([^"]+)"\s+(?:name|property|itemprop|http-equiv)="([^"]+)"/g,
+ // @ts-ignore
+ (_, value, key) => {
+ obj[key] = unescape(value);
+ },
+ );
+ // get all title tags
+ body.replace(
+ /<title>([^<]+)<\/title>/g,
+ // @ts-ignore
+ (_, value) => {
+ obj["title"] = unescape(value);
+ },
+ );
+ // get all link tags
+ body.replace(
+ /<link\s+(?:rel|itemprop)="([^"]+)"\s+href="([^"]+)"/g,
+ // @ts-ignore
+ (_, key, value) => {
+ obj[key] = unescape(value);
+ },
+ );
console.log(obj);
return {
hostname: new URL(url).hostname,
@@ -50,7 +75,11 @@ const getMetadataFromUrl = async (url: string) => {
obj["description"] ||
obj["og:description"] ||
obj["twitter:description"],
- image: obj["og:image"] || obj["twitter:image"],
+ image:
+ obj["og:image"] ||
+ obj["twitter:image"] ||
+ obj["icon"] ||
+ obj["image_src"],
};
})
.catch((err) => {