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.

fixed some typos

Steven Tey83c9543a30f7
diff --git a/components/app/add-link-modal.tsx b/components/app/add-link-modal.tsx
index cf75cfdd6f..6b1d56467c 100644
--- a/components/app/add-link-modal.tsx
+++ b/components/app/add-link-modal.tsx
@@ -34,7 +34,6 @@ function AddLinkModalHelper({
const [keyExistsError, setKeyExistsError] = useState(false);
const [generatingSlug, setGeneratingSlug] = useState(false);
const [generatingTitle, setGeneratingTitle] = useState(false);
- const [buttonText, setButtonText] = useState("Add link");
const [saving, setSaving] = useState(false);
const [data, setData] = useState<LinkProps>({
@@ -128,17 +127,12 @@ function AddLinkModalHelper({
.then((res) => {
setSaving(false);
if (res.status === 200) {
- setButtonText("Saved!");
mutate(domain ? `/api/projects/${slug}` : `/api/links`);
- setTimeout(() => {
- setButtonText("Add link");
- });
setShowAddLinkModal(false);
}
})
.catch(() => {
setSaving(false);
- setButtonText("Add link");
setKeyExistsError(true);
});
}}
@@ -164,7 +158,7 @@ function AddLinkModalHelper({
</div>
<div className="relative flex mt-1 rounded-md shadow-sm">
<span className="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-5 text-gray-500 sm:text-sm">
- {domain || "dub.sh"}/
+ {domain || "dub.sh"}
</span>
<input
type="text"
@@ -273,7 +267,7 @@ function AddLinkModalHelper({
: "bg-black hover:bg-white hover:text-black border-black text-white"
} flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}
>
- {saving ? <LoadingDots color="#808080" /> : <p>{buttonText}</p>}
+ {saving ? <LoadingDots color="#808080" /> : <p>Add link</p>}
</button>
</form>
</div>
diff --git a/components/app/add-project-modal.tsx b/components/app/add-project-modal.tsx
new file mode 100644
index 0000000000..674facf9c5
--- /dev/null
+++ b/components/app/add-project-modal.tsx
@@ -0,0 +1,238 @@
+import Modal from "@/components/shared/modal";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ Dispatch,
+ SetStateAction,
+} from "react";
+import { useRouter } from "next/router";
+import BlurImage from "@/components/shared/blur-image";
+import {
+ LoadingDots,
+ LoadingCircle,
+ AlertCircleFill,
+} from "@/components/shared/icons";
+import { useDebounce } from "use-debounce";
+import { mutate } from "swr";
+
+function AddProjectModalHelper({
+ showAddProjectModal,
+ setShowAddProjectModal,
+}: {
+ showAddProjectModal: boolean;
+ setShowAddProjectModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const router = useRouter();
+
+ const [slugExistsError, setSlugExistsError] = useState(false);
+ const [generatingSlug, setGeneratingSlug] = useState(false);
+ const [generatingTitle, setGeneratingTitle] = useState(false);
+ const [buttonText, setButtonText] = useState("Add project");
+ const [saving, setSaving] = useState(false);
+
+ const [data, setData] = useState<{
+ name: string;
+ slug: string;
+ domain: string;
+ }>({
+ name: "",
+ slug: "",
+ domain: "",
+ });
+ const { name, slug, domain } = data;
+
+ const [debouncedSlug] = useDebounce(slug, 500);
+ useEffect(() => {
+ if (debouncedSlug.length > 0) {
+ fetch(`/api/projects/${slug}/exists`).then(async (res) => {
+ if (res.status === 200) {
+ const exists = await res.json();
+ setSlugExistsError(exists === 1);
+ }
+ });
+ }
+ }, [debouncedSlug]);
+
+ const generateRandomSlug = useCallback(async () => {
+ setGeneratingSlug(true);
+ const res = await fetch(
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links/random`
+ : `/api/edge/links/random`
+ );
+ const key = await res.json();
+ setData((prev) => ({ ...prev, key }));
+ setGeneratingSlug(false);
+ }, []);
+
+ return (
+ <Modal
+ showModal={showAddProjectModal}
+ setShowModal={setShowAddProjectModal}
+ >
+ <div className="inline-block w-full max-w-md overflow-hidden align-middle transition-all transform bg-white shadow-xl rounded-2xl">
+ <div className="flex flex-col justify-center items-center space-y-3 sm:px-16 px-4 pt-8 py-4 border-b border-gray-200">
+ <BlurImage
+ src={`/static/logo.png`}
+ alt={"dub.sh"}
+ className="w-10 h-10 rounded-full border border-gray-200 dark:border-gray-600"
+ width={20}
+ height={20}
+ />
+ <h3 className="font-medium text-lg">Add a new project</h3>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(`/api/projects`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ })
+ .then((res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ setButtonText("Saved!");
+ mutate(`/api/projects`);
+ setShowAddProjectModal(false);
+ router.push(`/${slug}`);
+ }
+ })
+ .catch(() => {
+ setSaving(false);
+ setButtonText("Add project");
+ setSlugExistsError(true);
+ });
+ }}
+ className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8"
+ >
+ <div>
+ <label
+ htmlFor="key"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Project Name
+ </label>
+ <div className="flex mt-1 rounded-md shadow-sm">
+ <input
+ name="name"
+ id="name"
+ type="text"
+ required
+ className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 block w-full rounded-md focus:outline-none sm:text-sm"
+ placeholder="Dub"
+ value={name}
+ onChange={(e) => {
+ setData({ ...data, name: e.target.value });
+ }}
+ aria-invalid="true"
+ />
+ </div>
+ </div>
+
+ <div>
+ <label
+ htmlFor="slug"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Project Slug
+ </label>
+ <div className="relative flex mt-1 rounded-md shadow-sm">
+ <input
+ name="slug"
+ id="slug"
+ type="text"
+ required
+ className={`${
+ slugExistsError
+ ? "border-red-300 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
+ : "border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500"
+ } pr-10 block w-full rounded-md focus:outline-none sm:text-sm`}
+ placeholder="dub"
+ value={slug}
+ onChange={(e) => {
+ setSlugExistsError(false);
+ setData({ ...data, slug: e.target.value });
+ }}
+ aria-invalid="true"
+ />
+ {slugExistsError && (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ <AlertCircleFill
+ className="h-5 w-5 text-red-500"
+ aria-hidden="true"
+ />
+ </div>
+ )}
+ </div>
+ {slugExistsError && (
+ <p className="mt-2 text-sm text-red-600" id="slug-error">
+ Slug is already in use.
+ </p>
+ )}
+ </div>
+
+ <div>
+ <label
+ htmlFor="domain"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Domain
+ </label>
+ <div className="flex mt-1 rounded-md shadow-sm">
+ <input
+ name="domain"
+ id="domain"
+ type="url"
+ required
+ className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 block w-full rounded-md focus:outline-none sm:text-sm"
+ placeholder="dub.sh"
+ pattern="(https?://)?.+"
+ value={domain}
+ onChange={(e) => {
+ setData({ ...data, domain: e.target.value });
+ }}
+ aria-invalid="true"
+ />
+ </div>
+ </div>
+
+ <button
+ disabled={saving || slugExistsError}
+ className={`${
+ saving || slugExistsError
+ ? "cursor-not-allowed bg-gray-100 border-gray-200 text-gray-400"
+ : "bg-black hover:bg-white hover:text-black border-black text-white"
+ } flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}
+ >
+ {saving ? <LoadingDots color="#808080" /> : <p>{buttonText}</p>}
+ </button>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useAddProjectModal({ domain }: { domain?: string }) {
+ const [showAddProjectModal, setShowAddProjectModal] = useState(false);
+
+ const AddProjectModal = useCallback(() => {
+ return (
+ <AddProjectModalHelper
+ showAddProjectModal={showAddProjectModal}
+ setShowAddProjectModal={setShowAddProjectModal}
+ />
+ );
+ }, [showAddProjectModal, setShowAddProjectModal, domain]);
+
+ return useMemo(
+ () => ({ setShowAddProjectModal, AddProjectModal }),
+ [setShowAddProjectModal, AddProjectModal]
+ );
+}
diff --git a/components/app/edit-link-modal.tsx b/components/app/edit-link-modal.tsx
index b31f883d3a..d0802bbe56 100644
--- a/components/app/edit-link-modal.tsx
+++ b/components/app/edit-link-modal.tsx
@@ -32,7 +32,6 @@ function EditLinkModalHelper({
const { slug } = router.query as { slug: string };
const [saving, setSaving] = useState(false);
- const [buttonText, setButtonText] = useState("Save changes");
const [keyExistsError, setKeyExistsError] = useState(false);
const urlHostname = props.url ? new URL(props.url).hostname : "";
@@ -44,7 +43,7 @@ function EditLinkModalHelper({
if (debouncedKey.length > 0 && debouncedKey !== props.key) {
fetch(
domain
- ? `/api/projects/${domain}/domain/${domain}/links/${debouncedKey}/exists`
+ ? `/api/projects/${slug}/domains/${domain}/links/${debouncedKey}/exists`
: `/api/edge/links/${debouncedKey}/exists`
).then(async (res) => {
if (res.status === 200) {
@@ -87,16 +86,18 @@ function EditLinkModalHelper({
},
body: JSON.stringify(data),
}
- ).then((res) => {
- setSaving(false);
- if (res.status === 200) {
- setButtonText("Saved!");
- mutate(domain ? `/api/projects/${slug}` : `/api/links`);
- setTimeout(() => {
- setButtonText("Save changes");
- });
- }
- });
+ )
+ .then((res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ mutate(domain ? `/api/projects/${slug}` : `/api/links`);
+ setShowEditLinkModal(false);
+ }
+ })
+ .catch(() => {
+ setSaving(false);
+ setKeyExistsError(true);
+ });
}}
className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8"
>
@@ -203,7 +204,7 @@ function EditLinkModalHelper({
: "bg-black hover:bg-white hover:text-black border-black text-white"
} flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}
>
- {saving ? <LoadingDots color="#808080" /> : <p>{buttonText}</p>}
+ {saving ? <LoadingDots color="#808080" /> : <p>Save changes</p>}
</button>
</form>
</div>
diff --git a/lib/upstash.ts b/lib/upstash.ts
index f195351484..d61533225a 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -170,6 +170,10 @@ export async function editLink(
});
} else {
// if key is different
+ const keyExists = await checkIfKeyExists(hostname, newKey);
+ if (keyExists === 1) {
+ return null; // key already exists
+ }
// get number of clicks for key (we'll add it to newKey)
const numClicks = await redis.zcard(`${hostname}:clicks:${key}`);
const pipeline = redis.pipeline();
diff --git a/pages/api/links/[key].ts b/pages/api/links/[key].ts
index 79d569f766..9436198909 100644
--- a/pages/api/links/[key].ts
+++ b/pages/api/links/[key].ts
@@ -34,6 +34,9 @@ export default async function handler(
timestamp,
session.user.id
);
+ if (response === null) {
+ return res.status(400).json({ error: "Key already exists" });
+ }
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET", "POST"]);
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
index 7a217c092e..3a11f1370b 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
@@ -21,6 +21,9 @@ export default withProjectAuth(
title,
timestamp
);
+ if (response === null) {
+ return res.status(400).json({ error: "Key already exists" });
+ }
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["PUT"]);
diff --git a/pages/api/projects/[slug]/exists.ts b/pages/api/projects/[slug]/exists.ts
new file mode 100644
index 0000000000..74e1d6ab4d
--- /dev/null
+++ b/pages/api/projects/[slug]/exists.ts
@@ -0,0 +1,30 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getSession } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ const session = await getSession(req, res);
+ if (!session?.user.id) return res.status(401).end("Unauthorized");
+
+ const { slug } = req.query as { slug: string };
+
+ // GET /api/projects/[slug]/exists – check if a project exists
+ if (req.method === "GET") {
+ const project = await prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ });
+ if (project) {
+ return res.status(200).json(1);
+ } else {
+ return res.status(200).json(0);
+ }
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+}
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index 21bdd7090d..b01d621dd1 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -4,12 +4,28 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { ProjectProps } from "@/lib/types";
import ProjectCard from "@/components/app/project-card";
+import { useAddProjectModal } from "@/components/app/add-project-modal";
export default function App() {
const { data } = useSWR<ProjectProps[]>(`/api/projects`, fetcher);
+ const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal({});
return (
<AppLayout>
+ {data && <AddProjectModal />}
+ <div className="h-36 flex items-center bg-white border-b border-gray-200">
+ <MaxWidthWrapper>
+ <div className="flex justify-between items-center">
+ <h1 className="text-2xl text-gray-600">My Projects</h1>
+ <button
+ onClick={() => setShowAddProjectModal(true)}
+ className="text-gray-500 hover:border-black dark:hover:border-white active:scale-95 font-medium text-sm px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 transition-all duration-75"
+ >
+ Add
+ </button>
+ </div>
+ </MaxWidthWrapper>
+ </div>
<MaxWidthWrapper>
<div className="my-10 grid grid-cols-1 sm:grid-cols-3 gap-5">
{data ? data.map((d) => <ProjectCard key={d.slug} {...d} />) : null}
diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsx
index f861992f12..d333f1b917 100644
--- a/pages/app/links/index.tsx
+++ b/pages/app/links/index.tsx
@@ -21,7 +21,7 @@ export default function Links() {
<div className="h-36 flex items-center bg-white border-b border-gray-200">
<MaxWidthWrapper>
<div className="flex justify-between items-center">
- <h1 className="text-2xl text-gray-600">Dub.sh Links</h1>
+ <h1 className="text-2xl text-gray-600">My Dub.sh Links</h1>
<button
onClick={() => setShowAddLinkModal(true)}
className="font-medium text-sm text-gray-500 px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 hover:border-black dark:hover:border-white active:scale-95 transition-all duration-75"