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.

updated /domains endpoints

Steven Tey7e1089661bbc
diff --git a/components/app/domains/domain-card.tsx b/components/app/domains/domain-card.tsx
index a11d0832f1..42624fb238 100644
--- a/components/app/domains/domain-card.tsx
+++ b/components/app/domains/domain-card.tsx
@@ -8,36 +8,36 @@ import {
LoadingDots,
XCircleFill,
} from "@/components/shared/icons";
-import useProject from "@/lib/swr/use-project";
-import { DomainVerificationStatusProps } from "@/lib/types";
-import { fetcher } from "@/lib/utils";
-import { useEditDomainModal } from "../modals/edit-domain-modal";
+import { DomainProps, DomainVerificationStatusProps } from "@/lib/types";
+import { capitalize, fetcher, getDomainWithoutWWW } from "@/lib/utils";
+import { useAddEditDomainModal } from "../modals/add-edit-domain-modal";
import DomainConfiguration from "./domain-configuration";
-export default function DomainCard({ domain }: { domain: string }) {
+export default function DomainCard({ props }: { props: DomainProps }) {
const router = useRouter();
const { slug } = router.query as { slug: string };
+ const { slug: domain, primary, target, type } = props || {};
+
const { data, isValidating } = useSWR<{
status: DomainVerificationStatusProps;
response: any;
- }>(
- slug && domain && `/api/projects/${slug}/domains/${domain}/verify`,
- fetcher,
- {
- revalidateOnMount: true,
- refreshInterval: 5000,
- },
- );
+ }>(slug && `/api/projects/${slug}/domains/${domain}/verify`, fetcher, {
+ revalidateOnMount: true,
+ refreshInterval: 5000,
+ });
- const { setShowEditDomainModal, EditDomainModal } = useEditDomainModal();
+ const { setShowAddEditDomainModal, AddEditDomainModal } =
+ useAddEditDomainModal({
+ props,
+ });
return (
- <div className="max-w-full rounded-lg border border-gray-200 bg-white py-5 sm:py-10">
- {domain && <EditDomainModal />}
- <div className="flex flex-col space-y-3 px-5 sm:px-10">
+ <>
+ <AddEditDomainModal />
+ <div className="flex flex-col space-y-3 rounded-lg border border-gray-200 bg-white px-5 py-8 sm:px-10">
<div className="flex flex-col justify-between space-y-4 sm:flex-row sm:space-x-4">
- {domain ? (
+ <div className="flex items-center space-x-2">
<a
href={`http://${domain}`}
target="_blank"
@@ -49,59 +49,78 @@ export default function DomainCard({ domain }: { domain: string }) {
</p>
<ExternalLink className="h-5 w-5" />
</a>
- ) : (
- <div className="h-8 w-32 animate-pulse rounded-md bg-gray-200" />
- )}
- <div className="flex space-x-3">
- {domain ? (
- <button
- onClick={() => {
- mutate(`/api/projects/${slug}/domains/${domain}/verify`);
- }}
- disabled={isValidating}
- className={`${
- isValidating
- ? "cursor-not-allowed bg-gray-100"
- : "bg-white hover:border-black hover:text-black"
- } h-9 w-24 rounded-md border border-solid border-gray-200 text-sm text-gray-500 transition-all duration-150 ease-in-out focus:outline-none`}
- >
- {isValidating ? <LoadingDots /> : "Refresh"}
- </button>
- ) : (
- <div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
+ {primary && (
+ <span className="rounded-full bg-blue-500 px-3 py-0.5 text-xs text-white">
+ Primary Domain
+ </span>
)}
- {domain ? (
- <button
- onClick={() => setShowEditDomainModal(true)}
- className="h-9 w-24 rounded-md border border-solid border-black bg-black text-sm text-white transition-all duration-150 ease-in-out hover:bg-white hover:text-black focus:outline-none"
- >
- Change
- </button>
+ </div>
+ <div className="flex space-x-3">
+ <button
+ onClick={() => {
+ mutate(`/api/projects/${slug}/domains/${slug}/verify`);
+ }}
+ disabled={isValidating}
+ className={`${
+ isValidating
+ ? "cursor-not-allowed bg-gray-100"
+ : "bg-white hover:border-black hover:text-black"
+ } h-9 w-24 rounded-md border border-gray-200 text-sm font-medium text-gray-500 transition-all duration-150 ease-in-out focus:outline-none`}
+ >
+ {isValidating ? <LoadingDots /> : "Refresh"}
+ </button>
+ <button
+ onClick={() => setShowAddEditDomainModal(true)}
+ className="h-9 w-24 rounded-md border border-gray-200 bg-white text-sm font-medium text-gray-500 transition-all duration-150 ease-in-out hover:border-black hover:text-black focus:outline-none"
+ >
+ Edit
+ </button>
+ </div>
+ </div>
+ <div className="flex h-10 items-center space-x-5">
+ <div className="flex items-center space-x-2">
+ {data ? (
+ data.status === "Valid Configuration" ? (
+ <CheckCircleFill className="h-6 w-6 text-blue-500" />
+ ) : data.status === "Pending Verification" ? (
+ <AlertCircleFill className="h-6 w-6 text-yellow-500" />
+ ) : (
+ <XCircleFill className="h-6 w-6 text-red-500" />
+ )
) : (
- <div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
+ <LoadingCircle dimensions="w-5 h-5 mr-1" />
)}
+ <p className="text-sm text-gray-500">
+ {data ? data.status : "Checking Domain Status"}
+ </p>
</div>
- </div>
- <div className="flex h-10 items-center space-x-2">
- {data ? (
- data.status === "Valid Configuration" ? (
+ <div className="flex items-center space-x-2">
+ {target ? (
<CheckCircleFill className="h-6 w-6 text-blue-500" />
- ) : data.status === "Pending Verification" ? (
- <AlertCircleFill className="h-6 w-6 text-yellow-500" />
) : (
- <XCircleFill className="h-6 w-6 text-red-500" />
- )
- ) : (
- <LoadingCircle dimensions="w-5 h-5 mr-1" />
- )}
- <p className="text-sm text-gray-500">
- {data ? data.status : "Checking Domain Status"}
- </p>
+ <XCircleFill className="h-6 w-6 text-gray-400" />
+ )}
+ <div className="flex space-x-1">
+ <p className="text-sm text-gray-500">
+ {target ? `${capitalize(type)}s to` : `No ${type} configured`}
+ </p>
+ {target && (
+ <a
+ href={target}
+ target="_blank"
+ rel="noreferrer"
+ className="text-sm font-medium text-gray-600"
+ >
+ {getDomainWithoutWWW(target)}
+ </a>
+ )}
+ </div>
+ </div>
</div>
{data && data.status !== "Valid Configuration" && (
<DomainConfiguration data={data} />
)}
</div>
- </div>
+ </>
);
}
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index f7e73fade0..3e2196b71e 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -42,7 +42,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const { slug } = router.query as { slug: string };
const { isOwner } = useProject();
- const { verified } = useDomains(domain);
+ const { verified, loading } = useDomains(domain);
const { exceededUsage } = useUsage();
const linkRef = useRef<any>();
@@ -105,7 +105,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
/>
<div>
<div className="flex max-w-fit items-center space-x-2">
- {slug && !verified ? (
+ {slug && !verified && !loading ? (
<Tooltip
content={
<TooltipContent
@@ -116,17 +116,11 @@ export default function LinkCard({ props }: { props: LinkProps }) {
}
>
<div className="w-24 -translate-x-2 cursor-not-allowed truncate text-sm font-semibold text-gray-400 line-through sm:w-full sm:text-base">
- <span className="hidden sm:block">
- {linkConstructor({ key, domain, pretty: true })}
- </span>
- <span className="sm:hidden">
- {linkConstructor({
- key,
- domain,
- pretty: true,
- noDomain: true,
- })}
- </span>
+ {linkConstructor({
+ key,
+ domain,
+ pretty: true,
+ })}
</div>
</Tooltip>
) : (
@@ -136,17 +130,11 @@ export default function LinkCard({ props }: { props: LinkProps }) {
target="_blank"
rel="noreferrer"
>
- <span className="hidden sm:block">
- {linkConstructor({ key, domain, pretty: true })}
- </span>
- <span className="sm:hidden">
- {linkConstructor({
- key,
- domain,
- pretty: true,
- noDomain: true,
- })}
- </span>
+ {linkConstructor({
+ key,
+ domain,
+ pretty: true,
+ })}
</a>
)}
<CopyButton url={linkConstructor({ key, domain })} />
diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsx
new file mode 100644
index 0000000000..8e9e33d151
--- /dev/null
+++ b/components/app/modals/add-edit-domain-modal.tsx
@@ -0,0 +1,354 @@
+import { useRouter } from "next/router";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { mutate } from "swr";
+import { useDebounce } from "use-debounce";
+import BlurImage from "@/components/shared/blur-image";
+import { AlertCircleFill, Lock } from "@/components/shared/icons";
+import LoadingDots from "@/components/shared/icons/loading-dots";
+import Modal from "@/components/shared/modal";
+import { DomainProps } from "@/lib/types";
+import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
+import useProject from "@/lib/swr/use-project";
+import { getPlanFromUsageLimit } from "@/lib/stripe/constants";
+
+function AddEditDomainModal({
+ showAddEditDomainModal,
+ setShowAddEditDomainModal,
+ props,
+}: {
+ showAddEditDomainModal: boolean;
+ setShowAddEditDomainModal: Dispatch<SetStateAction<boolean>>;
+ props?: DomainProps;
+}) {
+ const router = useRouter();
+ const { slug } = router.query;
+ const { project: { logo } = {} } = useProject();
+
+ const [data, setData] = useState<DomainProps>(
+ props || {
+ slug: "",
+ verified: false,
+ primary: false,
+ target: "",
+ type: "redirect",
+ },
+ );
+
+ const { slug: domain, primary, target, type } = data;
+
+ const [debouncedDomain] = useDebounce(domain, 500);
+ useEffect(() => {
+ if (debouncedDomain.length > 0 && debouncedDomain !== domain) {
+ fetch(`/api/projects/${slug}/domains/${debouncedDomain}/exists`).then(
+ async (res) => {
+ if (res.status === 200) {
+ const exists = await res.json();
+ setDomainError(exists === 1 ? "Domain is already in use." : null);
+ }
+ },
+ );
+ }
+ }, [debouncedDomain]);
+
+ const [lockDomain, setLockDomain] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [domainError, setDomainError] = useState(null);
+
+ const saveDisabled = useMemo(() => {
+ /*
+ Disable save if:
+ - modal is not open
+ - saving is in progress
+ - domain is invalid
+ - for an existing domain, there's no changes
+ */
+ if (
+ !showAddEditDomainModal ||
+ saving ||
+ domainError ||
+ (props &&
+ Object.entries(props).every(([key, value]) => data[key] === value))
+ ) {
+ return true;
+ } else {
+ return false;
+ }
+ }, [showAddEditDomainModal, saving, domainError, props, data]);
+
+ const endpoint = useMemo(() => {
+ if (props?.slug) {
+ return {
+ method: "PUT",
+ url: `/api/projects/${slug}/domains/${domain}`,
+ };
+ } else {
+ return {
+ method: "POST",
+ url: `/api/projects/${slug}/domains`,
+ };
+ }
+ }, [props]);
+
+ return (
+ <Modal
+ showModal={showAddEditDomainModal}
+ setShowModal={setShowAddEditDomainModal}
+ >
+ <div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
+ <BlurImage
+ src={logo || `https://avatar.vercel.sh/${slug}`}
+ alt={`Logo for ${slug}`}
+ className="h-10 w-10 rounded-full border border-gray-200"
+ width={20}
+ height={20}
+ />
+ <h3 className="text-lg font-medium">
+ {props ? "Edit" : "Add"} Domain
+ </h3>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(endpoint.url, {
+ method: endpoint.method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ }).then(async (res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ mutate(`/api/projects/${slug}/domains`);
+ setShowAddEditDomainModal(false);
+ } else if (res.status === 422) {
+ const { domainError: domainErrorResponse } = await res.json();
+ if (domainErrorResponse) {
+ setDomainError(domainErrorResponse);
+ }
+ } else {
+ setDomainError("Something went wrong. Please try again.");
+ }
+ });
+ }}
+ className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"
+ >
+ <div>
+ <div className="flex items-center justify-between">
+ <label
+ htmlFor="domain"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Domain
+ </label>
+ {props && lockDomain && (
+ <button
+ className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95"
+ type="button"
+ onClick={() => {
+ window.confirm(
+ "Warning: Changing your project's domain will break all existing short links and reset their analytics. Are you sure you want to continue?",
+ ) && setLockDomain(false);
+ }}
+ >
+ <Lock className="h-3 w-3" />
+ <p>Unlock</p>
+ </button>
+ )}
+ </div>
+ {props && lockDomain ? (
+ <div className="mt-1 cursor-not-allowed rounded-md border border-gray-300 bg-gray-100 px-3 py-2 text-sm text-gray-500 shadow-sm">
+ {domain}
+ </div>
+ ) : (
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="domain"
+ id="domain"
+ required
+ pattern="[a-zA-Z0-9\-.]+"
+ className={`${
+ domainError
+ ? "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"
+ } block w-full rounded-md pr-10 text-sm focus:outline-none`}
+ placeholder="dub.sh"
+ value={domain}
+ onChange={(e) => {
+ setDomainError(null);
+ setData({ ...data, slug: e.target.value });
+ }}
+ aria-invalid="true"
+ aria-describedby="domain-error"
+ />
+ {domainError && (
+ <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>
+ )}
+ {domainError &&
+ (domainError === "Domain is already in use." ? (
+ <p className="mt-2 text-sm text-red-600" id="domain-error">
+ Domain is already in use.{" "}
+ <a
+ className="underline"
+ href="mailto:[email protected]?subject=My Domain Is Already In Use"
+ >
+ Contact us
+ </a>{" "}
+ if you'd like to use this domain for your project.
+ </p>
+ ) : (
+ <p className="mt-2 text-sm text-red-600" id="domain-error">
+ {domainError}
+ </p>
+ ))}
+ </div>
+
+ <div>
+ <label
+ htmlFor="target"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Landing Page
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="url"
+ name="target"
+ id="target"
+ className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ placeholder="https://example.com"
+ value={target}
+ onChange={(e) => setData({ ...data, target: e.target.value })}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label
+ htmlFor="type"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Behavior
+ </label>
+ <select
+ value={type}
+ onChange={(e) =>
+ setData({
+ ...data,
+ type: e.target.value as "redirect" | "rewrite",
+ })
+ }
+ className="mt-1 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-500 shadow-sm focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ >
+ <option value="redirect">Redirect</option>
+ <option value="rewrite">Rewrite</option>
+ </select>
+ </div>
+
+ <button
+ disabled={saveDisabled}
+ className={`${
+ saveDisabled
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
+ >
+ {saving ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>{props ? "Save changes" : "Add domain"}</p>
+ )}
+ </button>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+function AddEditDomainButton({
+ setShowAddEditDomainModal,
+}: {
+ setShowAddEditDomainModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug?: string };
+
+ const { project: { ownerUsageLimit } = {} } = useProject();
+
+ return slug && ownerUsageLimit < 1000000 ? ( // only show exceeded usage tooltip if user is on a project page
+ <Tooltip
+ content={
+ <TooltipContent
+ title={`You can only add 1 custom domain on the ${getPlanFromUsageLimit(
+ ownerUsageLimit,
+ )} plan. Upgrade to add more.`}
+ cta="Upgrade"
+ ctaLink="/settings"
+ />
+ }
+ >
+ <div className="cursor-not-allowed rounded-md border border-gray-200 px-5 py-2 text-sm font-medium text-gray-300 transition-all duration-75">
+ Add
+ </div>
+ </Tooltip>
+ ) : (
+ <button
+ onClick={() => setShowAddEditDomainModal(true)}
+ className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
+ >
+ Add
+ </button>
+ );
+}
+
+export function useAddEditDomainModal({ props }: { props?: DomainProps }) {
+ const [showAddEditDomainModal, setShowAddEditDomainModal] = useState(false);
+
+ const AddEditDomainModalCallback = useCallback(() => {
+ return (
+ <AddEditDomainModal
+ showAddEditDomainModal={showAddEditDomainModal}
+ setShowAddEditDomainModal={setShowAddEditDomainModal}
+ props={props}
+ />
+ );
+ }, [showAddEditDomainModal, setShowAddEditDomainModal]);
+
+ const AddEditDomainButtonCallback = useCallback(() => {
+ return (
+ <AddEditDomainButton
+ setShowAddEditDomainModal={setShowAddEditDomainModal}
+ />
+ );
+ }, [setShowAddEditDomainModal]);
+
+ return useMemo(
+ () => ({
+ setShowAddEditDomainModal,
+ AddEditDomainModal: AddEditDomainModalCallback,
+ AddEditDomainButton: AddEditDomainButtonCallback,
+ }),
+ [
+ setShowAddEditDomainModal,
+ AddEditDomainModalCallback,
+ AddEditDomainButtonCallback,
+ ],
+ );
+}
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 5b09cb03a2..a15b4fc978 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -209,16 +209,11 @@ function AddEditLinkModal({
} else {
return false;
}
- }, [saving, keyExistsError, urlError, props, data, showAddEditLinkModal]);
+ }, [showAddEditLinkModal, saving, keyExistsError, urlError, props, data]);
const randomIdx = Math.floor(Math.random() * 100);
- const [lockKey, setLockKey] = useState(false);
- useEffect(() => {
- if (props?.key) {
- setLockKey(true);
- }
- }, [props?.key]);
+ const [lockKey, setLockKey] = useState(true);
return (
<Modal
@@ -252,7 +247,7 @@ function AddEditLinkModal({
{props
? `Edit ${linkConstructor({
key: props.key,
- domain,
+ domain: props.domain,
pretty: true,
})}`
: "Add a new link"}
@@ -347,7 +342,7 @@ function AddEditLinkModal({
>
Short Link
</label>
- {lockKey ? (
+ {props && lockKey ? (
<button
className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95"
type="button"
@@ -378,26 +373,22 @@ function AddEditLinkModal({
</div>
<div className="relative mt-1 flex rounded-md shadow-sm">
<select
- disabled={lockKey}
- dir="ltr"
+ disabled={props && lockKey}
+ value={domain}
+ onChange={(e) => {
+ setData({ ...data, domain: e.target.value });
+ }}
className={`${
- lockKey ? "cursor-not-allowed" : ""
+ props && lockKey ? "cursor-not-allowed" : ""
} w-40 rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-5 text-sm text-gray-500 focus:border-gray-300 focus:outline-none focus:ring-0`}
>
{domains?.map(({ slug }) => (
- <option
- key={slug}
- value={slug}
- selected={slug === domain}
- onClick={() => {
- setData({ ...data, domain: slug });
- }}
- >
+ <option key={slug} value={slug}>
{slug}
</option>
))}
</select>
- {lockKey ? (
+ {props && lockKey ? (
<div className="block w-full cursor-not-allowed select-none rounded-r-md border border-gray-300 bg-gray-100 px-3 py-2 text-sm text-gray-500">
{props.key}
</div>
diff --git a/components/app/modals/delete-project-modal.tsx b/components/app/modals/delete-project-modal.tsx
index 6db09af76d..eca032b733 100644
--- a/components/app/modals/delete-project-modal.tsx
+++ b/components/app/modals/delete-project-modal.tsx
@@ -22,7 +22,7 @@ function DeleteProjectModal({
}) {
const router = useRouter();
const { slug } = router.query as { slug: string };
- const { project: { domain } = {} } = useProject();
+ const { project: { logo } = {} } = useProject();
const [deleting, setDeleting] = useState(false);
return (
@@ -33,8 +33,8 @@ function DeleteProjectModal({
<div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
<div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
<BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${domain}`}
- alt={domain}
+ src={logo || `https://avatar.vercel.sh/${slug}`}
+ alt={`Logo for ${slug}`}
className="h-10 w-10 rounded-full border border-gray-200"
width={20}
height={20}
@@ -55,7 +55,6 @@ function DeleteProjectModal({
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify(domain),
}).then(async (res) => {
setDeleting(false);
if (res.status === 200) {
diff --git a/components/app/modals/edit-domain-modal.tsx b/components/app/modals/edit-domain-modal.tsx
deleted file mode 100644
index 5b0805cfed..0000000000
--- a/components/app/modals/edit-domain-modal.tsx
+++ /dev/null
@@ -1,236 +0,0 @@
-import { useRouter } from "next/router";
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useEffect,
- useMemo,
- useState,
-} from "react";
-import { mutate } from "swr";
-import { useDebounce } from "use-debounce";
-import BlurImage from "@/components/shared/blur-image";
-import { AlertCircleFill } from "@/components/shared/icons";
-import LoadingDots from "@/components/shared/icons/loading-dots";
-import Modal from "@/components/shared/modal";
-import useProject from "@/lib/swr/use-project";
-
-function EditDomainModal({
- showEditDomainModal,
- setShowEditDomainModal,
-}: {
- showEditDomainModal: boolean;
- setShowEditDomainModal: Dispatch<SetStateAction<boolean>>;
-}) {
- const router = useRouter();
- const { slug } = router.query;
- const [saving, setSaving] = useState(false);
- const [domainError, setDomainError] = useState(null);
- const { project: { domain } = {} } = useProject();
-
- const [newDomain, setNewDomain] = useState("");
-
- const [debouncedDomain] = useDebounce(newDomain, 500);
- useEffect(() => {
- if (debouncedDomain.length > 0 && debouncedDomain !== domain) {
- fetch(`/api/projects/${slug}/domains/${debouncedDomain}/exists`).then(
- async (res) => {
- if (res.status === 200) {
- const exists = await res.json();
- setDomainError(exists === 1 ? "Domain is already in use." : null);
- }
- },
- );
- }
- }, [debouncedDomain]);
-
- return (
- <Modal
- showModal={showEditDomainModal}
- setShowModal={setShowEditDomainModal}
- >
- <div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
- <BlurImage
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${domain}`}
- alt={domain}
- className="h-10 w-10 rounded-full border border-gray-200"
- width={20}
- height={20}
- />
- <h3 className="text-lg font-medium">Change Domain</h3>
- <p className="text-center text-sm text-gray-500">
- Warning: Changing your project's domain will break all existing
- short links and reset their analytics.
- </p>
- </div>
-
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- setSaving(true);
- fetch(`/api/projects/${slug}/domains/${domain}`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(newDomain),
- }).then(async (res) => {
- setSaving(false);
- if (res.status === 200) {
- mutate(`/api/projects/${slug}`);
- setShowEditDomainModal(false);
- } else if (res.status === 422) {
- const { domainError: domainErrorResponse } = await res.json();
- if (domainErrorResponse) {
- setDomainError(domainErrorResponse);
- }
- } else if (res.status === 400) {
- setDomainError("Domain is already in use.");
- }
- });
- }}
- className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"
- >
- <div>
- <label
- htmlFor="old-domain"
- className="block text-sm font-medium text-gray-700"
- >
- Old Domain
- </label>
- <div className="relative mt-1 rounded-md shadow-sm">
- <input
- type="text"
- name="old-domain"
- id="old-domain"
- autoFocus={false}
- readOnly
- className="text-gray-90 pointer-events-none block w-full rounded-md border-gray-300 pr-10 focus:outline-none focus:ring-0 sm:text-sm"
- value={domain}
- />
- </div>
- </div>
-
- <div>
- <label
- htmlFor="new-domain"
- className="block text-sm font-medium text-gray-700"
- >
- New Domain
- </label>
- <div className="relative mt-1 rounded-md shadow-sm">
- <input
- type="text"
- name="new-domain"
- id="new-domain"
- required
- pattern="[a-zA-Z0-9\-.]+"
- autoFocus={false}
- className={`${
- domainError
- ? "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"
- } block w-full rounded-md pr-10 focus:outline-none sm:text-sm`}
- placeholder="newdomain.com"
- value={newDomain}
- onChange={(e) => {
- setDomainError(null);
- setNewDomain(e.target.value);
- }}
- aria-invalid="true"
- aria-describedby="domain-error"
- />
- {domainError && (
- <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>
- {domainError &&
- (domainError === "Domain is already in use." ? (
- <p className="mt-2 text-sm text-red-600" id="domain-error">
- Domain is already in use.{" "}
- <a
- className="underline"
- href="mailto:[email protected]?subject=My Domain Is Already In Use"
- >
- Contact us
- </a>{" "}
- if you'd like to use this domain for your project.
- </p>
- ) : (
- <p className="mt-2 text-sm text-red-600" id="domain-error">
- {domainError}
- </p>
- ))}
- </div>
-
- <div>
- <label
- htmlFor="verification"
- className="block text-sm text-gray-700"
- >
- To verify, type{" "}
- <span className="font-semibold text-red-600">
- yes, change my domain
- </span>{" "}
- below
- </label>
- <div className="relative mt-1 rounded-md shadow-sm">
- <input
- type="text"
- name="verification"
- id="verification"
- pattern="yes, change my domain"
- placeholder="yes, change my domain"
- required
- autoFocus={false}
- 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>
-
- <button
- disabled={saving || domainError}
- className={`${
- saving || domainError
- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
- : "border-red-600 bg-red-600 text-white hover:bg-white hover:text-red-600"
- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
- >
- {saving ? (
- <LoadingDots color="#808080" />
- ) : (
- <p>Confirm domain change</p>
- )}
- </button>
- </form>
- </div>
- </Modal>
- );
-}
-
-export function useEditDomainModal() {
- const [showEditDomainModal, setShowEditDomainModal] = useState(false);
-
- const EditDomainModalCallback = useCallback(() => {
- return (
- <EditDomainModal
- showEditDomainModal={showEditDomainModal}
- setShowEditDomainModal={setShowEditDomainModal}
- />
- );
- }, [showEditDomainModal, setShowEditDomainModal]);
-
- return useMemo(
- () => ({
- setShowEditDomainModal,
- EditDomainModal: EditDomainModalCallback,
- }),
- [setShowEditDomainModal, EditDomainModalCallback],
- );
-}
diff --git a/components/app/modals/link-qr-modal.tsx b/components/app/modals/link-qr-modal.tsx
index d083262743..23eaf3a8f8 100644
--- a/components/app/modals/link-qr-modal.tsx
+++ b/components/app/modals/link-qr-modal.tsx
@@ -15,7 +15,7 @@ import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import { QRCodeSVG, getQRAsCanvas, getQRAsSVGDataUri } from "@/lib/qr";
import useProject from "@/lib/swr/use-project";
import useUsage from "@/lib/swr/use-usage";
-import { LinkProps, SimpleLinkProps } from "@/lib/types";
+import { SimpleLinkProps } from "@/lib/types";
import { getApexDomain, linkConstructor } from "@/lib/utils";
import IconMenu from "@/components/shared/icon-menu";
import { Download, Photo } from "@/components/shared/icons";
@@ -30,7 +30,7 @@ function LinkQRModalHelper({
}: {
showLinkQRModal: boolean;
setShowLinkQRModal: Dispatch<SetStateAction<boolean>>;
- props: LinkProps;
+ props: SimpleLinkProps;
}) {
const anchorRef = useRef<HTMLAnchorElement>();
const { project: { logo } = {} } = useProject();
@@ -344,7 +344,7 @@ function QrDropdown({ download, qrData, showLogo, logo }) {
);
}
-export function useLinkQRModal({ props }: { props: LinkProps }) {
+export function useLinkQRModal({ props }: { props: SimpleLinkProps }) {
const [showLinkQRModal, setShowLinkQRModal] = useState(false);
const LinkQRModal = useCallback(() => {
diff --git a/components/app/settings/delete-project.tsx b/components/app/settings/delete-project.tsx
index 3682aad753..4c7e64714a 100644
--- a/components/app/settings/delete-project.tsx
+++ b/components/app/settings/delete-project.tsx
@@ -4,7 +4,7 @@ export default function DeleteProject() {
const { setShowDeleteProjectModal, DeleteProjectModal } =
useDeleteProjectModal();
return (
- <div className="rounded-lg border border-gray-200 bg-white">
+ <div className="rounded-lg border border-red-600 bg-white">
<DeleteProjectModal />
<div className="flex flex-col space-y-3 p-5 sm:p-10">
<h2 className="text-xl font-medium">Delete Project</h2>
@@ -14,7 +14,7 @@ export default function DeleteProject() {
with caution.
</p>
</div>
- <div className="border-b border-gray-200" />
+ <div className="border-b border-red-600" />
<div className="flex items-center justify-end px-5 py-4 sm:px-10">
<button
diff --git a/components/app/settings/landing-page.tsx b/components/app/settings/landing-page.tsx
deleted file mode 100644
index 6ba5fb3547..0000000000
--- a/components/app/settings/landing-page.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import { useRouter } from "next/router";
-import { useState } from "react";
-import toast from "react-hot-toast";
-import useSWR from "swr";
-import { Chart, LoadingDots } from "@/components/shared/icons";
-import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
-import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
-import { fetcher, nFormatter } from "@/lib/utils";
-import Link from "next/link";
-
-export default function LandingPage() {
- const router = useRouter();
- const { slug } = router.query as { slug: string };
-
- const { project: { domain, domainVerified } = {}, isOwner } = useProject();
-
- const { plan } = useUsage();
-
- const { data: rootDomain } = useSWR<string>(
- slug && domain && `/api/projects/${slug}/domains/${domain}/root`,
- fetcher,
- );
-
- const { data: clicks } = useSWR<string>(
- slug && domain && `/api/projects/${slug}/domains/${domain}/root/clicks`,
- fetcher,
- );
-
- const [saving, setSaving] = useState(false);
-
- return (
- <form
- onSubmit={(e) => {
- e.preventDefault();
- setSaving(true);
- fetch(`/api/projects/${slug}/domains/${domain}/root`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- // @ts-ignore
- rootDomain: e.target.root.value,
- }),
- }).then(async (res) => {
- setSaving(false);
- if (res.status === 200) {
- toast.success("Successfully updated landing page");
- }
- });
- }}
- className="rounded-lg border border-gray-200 bg-white"
- >
- <div className="relative flex flex-col space-y-3 p-5 sm:p-10">
- <h2 className="text-xl font-medium">Landing Page</h2>
- <div className="flex items-center space-x-1">
- <p className="text-sm text-gray-500">
- Configure a page to redirect visitors when they land on{" "}
- <a
- href={`https://${domain}`}
- target="_blank"
- rel="noreferrer"
- className="text-sm font-semibold text-blue-800 transition-all hover:text-black"
- >
- {domain}
- </a>
- </p>
- {domainVerified && (
- <Link
- href={`/${slug}/_root`}
- className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-95"
- >
- <Chart className="h-4 w-4" />
- <p className="text-sm text-gray-500">
- {!clicks ? (
- <LoadingDots color="#71717A" />
- ) : (
- nFormatter(parseInt(clicks))
- )}{" "}
- clicks
- </p>
- </Link>
- )}
- </div>
- <div />
- {plan !== "Free" ? (
- <input
- type="url"
- name="root"
- id="root"
- placeholder="https://yourdomain.com"
- required
- defaultValue={rootDomain}
- className="w-full max-w-md rounded-md border border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
- />
- ) : (
- <Tooltip
- content={
- <TooltipContent
- title={`You can't configure a custom landing page on a free plan. ${
- isOwner
- ? "Upgrade to a Pro plan to proceed."
- : "Ask your project owner to upgrade to a Pro plan."
- }`}
- cta={isOwner && "Upgrade to Pro"}
- ctaLink={isOwner && "/settings"}
- />
- }
- >
- <div className="w-full max-w-md cursor-not-allowed rounded-md border border-gray-300 px-3 py-2 text-left text-sm text-gray-300">
- https://yourdomain.com
- </div>
- </Tooltip>
- )}
- </div>
-
- <div className="border-b border-gray-200" />
-
- <div className="px-5 py-4 sm:flex sm:items-center sm:justify-end sm:px-10">
- {plan !== "Free" ? (
- <button
- disabled={saving}
- className={`${
- saving
- ? "cursor-not-allowed border-gray-200 bg-gray-100"
- : "border-black bg-black hover:bg-white hover:text-black"
- } h-9 w-full rounded-md border text-sm text-white transition-all duration-150 ease-in-out focus:outline-none sm:w-32`}
- >
- {saving ? <LoadingDots /> : "Save Changes"}
- </button>
- ) : (
- <Tooltip
- content={
- <TooltipContent
- title={`You can't configure a custom landing page on a free plan. ${
- isOwner
- ? "Upgrade to a Pro plan to proceed."
- : "Ask your project owner to upgrade to a Pro plan."
- }`}
- cta={isOwner && "Upgrade to Pro"}
- ctaLink={isOwner && "/settings"}
- />
- }
- fullWidth
- >
- <div className="flex h-9 w-full cursor-not-allowed items-center justify-center rounded-md border border-gray-200 bg-gray-100 text-sm text-gray-300 sm:w-32">
- Save Changes
- </div>
- </Tooltip>
- )}
- </div>
- </form>
- );
-}
diff --git a/components/app/settings/project-name.tsx b/components/app/settings/project-name.tsx
new file mode 100644
index 0000000000..8701fe91ee
--- /dev/null
+++ b/components/app/settings/project-name.tsx
@@ -0,0 +1,86 @@
+import { useRouter } from "next/router";
+import { useEffect, useMemo, useState } from "react";
+import toast from "react-hot-toast";
+import { LoadingDots } from "@/components/shared/icons";
+import useProject from "@/lib/swr/use-project";
+import { mutate } from "swr";
+
+export default function ProjectName() {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
+ const { project: { name } = {} } = useProject();
+ const [newName, setNewName] = useState(null);
+ useEffect(() => {
+ setNewName(name);
+ }, [name]);
+ const [saving, setSaving] = useState(false);
+ const saveDisabled = useMemo(() => {
+ return saving || !newName || newName === name;
+ }, [saving, newName, name]);
+
+ return (
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(`/api/projects/${slug}`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: newName,
+ }),
+ }).then(async (res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ mutate(`/api/projects`);
+ mutate(`/api/projects/${slug}`);
+ toast.success("Successfully updated project name");
+ }
+ });
+ }}
+ className="rounded-lg border border-gray-200 bg-white"
+ >
+ <div className="relative flex flex-col space-y-3 p-5 sm:p-10">
+ <h2 className="text-xl font-medium">Project Name</h2>
+ <div className="flex items-center space-x-1">
+ <p className="text-sm text-gray-500">
+ This is the name of your project on Dub.
+ </p>
+ </div>
+ <div />
+ {newName ? (
+ <input
+ type="text"
+ name="project-name"
+ id="project-name"
+ placeholder="Dub"
+ required
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ className="w-full max-w-md rounded-md border border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ />
+ ) : (
+ <div className="h-[2.35rem] w-full max-w-md animate-pulse rounded-md bg-gray-200" />
+ )}
+ </div>
+
+ <div className="border-b border-gray-200" />
+
+ <div className="px-5 py-4 sm:flex sm:items-center sm:justify-end sm:px-10">
+ <button
+ disabled={saveDisabled}
+ className={`${
+ saveDisabled
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } h-9 w-full rounded-md border text-sm transition-all duration-150 ease-in-out focus:outline-none sm:w-32`}
+ >
+ {saving ? <LoadingDots /> : "Save Changes"}
+ </button>
+ </div>
+ </form>
+ );
+}
diff --git a/components/app/settings/project-slug.tsx b/components/app/settings/project-slug.tsx
new file mode 100644
index 0000000000..f68578edd4
--- /dev/null
+++ b/components/app/settings/project-slug.tsx
@@ -0,0 +1,88 @@
+import { useRouter } from "next/router";
+import { useEffect, useMemo, useState } from "react";
+import toast from "react-hot-toast";
+import { LoadingDots } from "@/components/shared/icons";
+import { mutate } from "swr";
+
+export default function ProjectSlug() {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
+ const [newSlug, setNewSlug] = useState(null);
+ useEffect(() => {
+ setNewSlug(slug);
+ }, [slug]);
+ const [saving, setSaving] = useState(false);
+ const saveDisabled = useMemo(() => {
+ return saving || !newSlug || newSlug === slug;
+ }, [saving, newSlug, slug]);
+
+ return (
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(`/api/projects/${slug}`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ newSlug,
+ }),
+ }).then(async (res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ mutate(`/api/projects`);
+ router.push(`/${newSlug}/settings`);
+ toast.success("Successfully updated project slug");
+ } else if (res.status === 422) {
+ toast.error("Project slug already exists");
+ } else {
+ toast.error("Something went wrong");
+ }
+ });
+ }}
+ className="rounded-lg border border-gray-200 bg-white"
+ >
+ <div className="relative flex flex-col space-y-3 p-5 sm:p-10">
+ <h2 className="text-xl font-medium">Project Slug</h2>
+ <div className="flex items-center space-x-1">
+ <p className="text-sm text-gray-500">
+ This is your project's URL slug on Dub.
+ </p>
+ </div>
+ <div />
+ {newSlug ? (
+ <input
+ type="text"
+ name="project-slug"
+ id="project-slug"
+ placeholder="dub"
+ required
+ value={newSlug}
+ onChange={(e) => setNewSlug(e.target.value)}
+ className="w-full max-w-md rounded-md border border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ />
+ ) : (
+ <div className="h-[2.35rem] w-full max-w-md animate-pulse rounded-md bg-gray-200" />
+ )}
+ </div>
+
+ <div className="border-b border-gray-200" />
+
+ <div className="px-5 py-4 sm:flex sm:items-center sm:justify-end sm:px-10">
+ <button
+ disabled={saveDisabled}
+ className={`${
+ saveDisabled
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } h-9 w-full rounded-md border text-sm transition-all duration-150 ease-in-out focus:outline-none sm:w-32`}
+ >
+ {saving ? <LoadingDots /> : "Save Changes"}
+ </button>
+ </div>
+ </form>
+ );
+}
diff --git a/components/layout/app/index.tsx b/components/layout/app/index.tsx
index 740923e146..af1fe64afd 100644
--- a/components/layout/app/index.tsx
+++ b/components/layout/app/index.tsx
@@ -24,8 +24,9 @@ export default function AppLayout({
bgWhite?: boolean;
}) {
const router = useRouter();
- const { slug, key } = router.query as {
+ const { slug, domain, key } = router.query as {
slug?: string;
+ domain?: string;
key?: string;
};
@@ -59,7 +60,7 @@ export default function AppLayout({
href={`/${slug}/links/${key}`}
className="text-sm font-medium"
>
- {key}
+ {domain || "dub.sh"}/{key}
</Link>
</>
)}
diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsx
index 0aed5c573f..fec4d07bb0 100644
--- a/components/layout/app/project-select.tsx
+++ b/components/layout/app/project-select.tsx
@@ -15,9 +15,8 @@ export default function ProjectSelect() {
const { AddProjectModal, setShowAddProjectModal } = useAddProjectModal({});
const router = useRouter();
- const { slug, key } = router.query as {
+ const { slug } = router.query as {
slug?: string;
- key?: string;
};
const { data: session } = useSession();
@@ -25,7 +24,7 @@ export default function ProjectSelect() {
const selected = useMemo(() => {
return (
projects?.find((project) => project.slug === slug) || {
- name: session?.user?.name || session?.user?.email || "User",
+ name: session?.user?.name || session?.user?.email,
slug: "/",
domain: "dub.sh",
logo:
@@ -44,7 +43,7 @@ export default function ProjectSelect() {
);
return (
- <div className={`${key && slug ? "w-32" : "w-48"} sm:w-60`}>
+ <div>
<AddProjectModal />
<Popover
content={
@@ -59,31 +58,24 @@ export default function ProjectSelect() {
>
<button
onClick={() => setOpenPopover(!openPopover)}
- className={`relative ${
- key && slug ? "w-32" : "w-48"
- } cursor-pointer rounded-lg bg-white py-1.5 pl-1 text-left text-sm transition-all duration-75 hover:bg-gray-100 focus:outline-none active:bg-gray-200 sm:w-60 sm:pl-3 sm:pr-10`}
+ className="flex w-60 items-center justify-between rounded-lg bg-white p-1.5 text-left text-sm transition-all duration-75 hover:bg-gray-100 focus:outline-none active:bg-gray-200"
>
- <div className="flex items-center justify-start space-x-3">
+ <div className="flex items-center justify-start space-x-3 pr-2">
<BlurImage
src={
selected.logo ||
`https://www.google.com/s2/favicons?sz=64&domain_url=${selected.domain}`
}
alt={selected.slug}
- className="h-6 w-6 overflow-hidden rounded-full sm:h-8 sm:w-8"
+ className="h-6 w-6 flex-none overflow-hidden rounded-full sm:h-8 sm:w-8"
width={48}
height={48}
/>
- <span className="block truncate text-sm font-medium">
+ <span className="truncate text-sm font-medium">
{selected.name}
</span>
</div>
- <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-1 sm:pr-2">
- <ChevronUpDown
- className="h-4 w-4 text-gray-400"
- aria-hidden="true"
- />
- </span>
+ <ChevronUpDown className="h-4 w-4 text-gray-400" aria-hidden="true" />
</button>
</Popover>
</div>
diff --git a/components/stats/clicks.tsx b/components/stats/clicks.tsx
index 5dce6e7c7b..5d2f9980ad 100644
--- a/components/stats/clicks.tsx
+++ b/components/stats/clicks.tsx
@@ -4,21 +4,16 @@ import { nFormatter } from "@/lib/utils";
import { useRouter } from "next/router";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import useProject from "@/lib/swr/use-project";
export default function Clicks() {
const router = useRouter();
- const {
- slug,
- key,
- interval = "24h",
- } = router.query as {
+ const { slug, domain, key, interval } = router.query as {
slug?: string;
+ domain?: string;
key: string;
interval?: string;
};
- const { project: { domain } = {} } = useProject();
const { data: totalClicks } = useSWR<number>(
router.isReady &&
`${
diff --git a/lib/domains.ts b/lib/api/domains.ts
similarity index 80%
rename from lib/domains.ts
rename to lib/api/domains.ts
index ad4da60294..905b743415 100644
--- a/lib/domains.ts
+++ b/lib/api/domains.ts
@@ -1,3 +1,26 @@
+import prisma from "@/lib/prisma";
+import { validDomainRegex } from "@/lib/utils";
+
+export const validateDomain = async (domain: string) => {
+ const validDomain =
+ validDomainRegex.test(domain) && !domain.endsWith(".dub.sh");
+ if (!validDomain) {
+ return "Invalid domain";
+ }
+ const domainExists = await prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ select: {
+ slug: true,
+ },
+ });
+ if (domainExists) {
+ return "Domain is already in use.";
+ }
+ return true;
+};
+
interface CustomResponse extends Response {
json: () => Promise<any>;
error?: { code: string; projectId: string; message: string };
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 0debd3d182..e52cf0cbc9 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -5,9 +5,59 @@ import { LinkProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { getParamsFromURL, nanoid, truncate } from "@/lib/utils";
+const getFiltersFromStatus = (status: string) => {
+ if (status === "all" || status === "none") {
+ return {
+ archived: undefined,
+ expiresAt: undefined,
+ };
+ }
+ const selectedStatus = status.split(",");
+ const activeSelected = selectedStatus.includes("active");
+ const expiredSelected = selectedStatus.includes("expired");
+ const archivedSelected = selectedStatus.includes("archived");
+ return {
+ AND: [
+ {
+ // archived can be either true or false
+ archived:
+ archivedSelected && selectedStatus.length === 1
+ ? true
+ : !archivedSelected
+ ? false
+ : undefined,
+ },
+ {
+ OR: [
+ {
+ /* expiresAt can be either:
+ - null
+ - a date that's in the past
+ - a date that's in the future
+ */
+ expiresAt:
+ expiredSelected && !activeSelected
+ ? { lt: new Date() }
+ : activeSelected && !expiredSelected
+ ? { gte: new Date() }
+ : undefined,
+ },
+ {
+ expiresAt: activeSelected && !expiredSelected ? null : undefined,
+ },
+ {
+ archived: archivedSelected && !activeSelected ? true : undefined,
+ },
+ ],
+ },
+ ],
+ };
+};
+
export async function getLinksForProject({
projectId,
domain,
+ status = "active",
tag,
search,
sort = "createdAt",
@@ -15,22 +65,25 @@ export async function getLinksForProject({
}: {
projectId: string;
domain?: string;
+ status?: string;
tag?: string;
search?: string;
sort?: "createdAt" | "clicks"; // always descending for both
userId?: string;
}): Promise<LinkProps[]> {
+ const filters = getFiltersFromStatus(status);
return await prisma.link.findMany({
where: {
projectId,
domain,
- ...(tag && { tags: { has: tag } }),
- ...(search && {
- key: { search },
- url: { search },
- title: { search },
- description: { search },
- }),
+ ...filters,
+ // ...(tag && { tags: { has: tag } }),
+ // ...(search && {
+ // key: { search },
+ // url: { search },
+ // title: { search },
+ // description: { search },
+ // }),
...(userId && { userId }),
},
orderBy: {
diff --git a/lib/constants/index.ts b/lib/constants/index.ts
index 6d711effc8..a7f940b027 100644
--- a/lib/constants/index.ts
+++ b/lib/constants/index.ts
@@ -137,3 +137,5 @@ export const DEFAULT_LINK_PROPS = {
proxy: false,
};
+
+export const DUB_PROJECT_ID = "cl7pj5kq4006835rbjlt2ofka";
diff --git a/lib/cron/domains.tsx b/lib/cron/domains.tsx
index 359862a9fb..0b502ef3c7 100644
--- a/lib/cron/domains.tsx
+++ b/lib/cron/domains.tsx
@@ -2,18 +2,16 @@ import sendMail from "emails";
import InvalidDomain from "emails/InvalidDomain";
import ProjectDeleted from "emails/ProjectDeleted";
import { log } from "@/lib/utils";
-import { removeDomain } from "@/lib/domains";
+import { removeDomain } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { deleteProjectLinks } from "@/lib/api/links";
import { getClicksUsage } from "@/lib/tinybird";
export const handleDomainUpdates = async (
- projectSlug: string,
domain: string,
createdAt: Date,
verified: boolean,
changed: boolean,
- sentEmails: string[],
) => {
if (changed) {
await log(`Domain *${domain}* changed status to *${verified}*`, "cron");
diff --git a/lib/types.ts b/lib/types.ts
index 30bed3c7e8..da26706f75 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -1,4 +1,5 @@
export interface SimpleLinkProps {
+ domain?: string;
key: string;
url: string;
}
@@ -75,4 +76,6 @@ export interface DomainProps {
slug: string;
verified: boolean;
primary: boolean;
+ target?: string;
+ type: "redirect" | "rewrite";
}
diff --git a/pages/api/cron/domains.ts b/pages/api/cron/domains.ts
index cb9b4507c2..b6257b0d84 100644
--- a/pages/api/cron/domains.ts
+++ b/pages/api/cron/domains.ts
@@ -5,7 +5,7 @@ import {
getConfigResponse,
getDomainResponse,
verifyDomain,
-} from "@/lib/domains";
+} from "@/lib/api/domains";
import prisma from "@/lib/prisma";
/**
@@ -17,13 +17,12 @@ import prisma from "@/lib/prisma";
async function handler(_req: NextApiRequest, res: NextApiResponse) {
try {
- const projects = await prisma.project.findMany({
+ const domains = await prisma.domain.findMany({
select: {
slug: true,
- domain: true,
domainVerified: true,
createdAt: true,
- sentEmails: true,
+ projectId: true,
},
orderBy: {
domainLastChecked: "asc",
@@ -31,12 +30,12 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
take: 100,
});
- const results = await Promise.all(
- projects.map(async (project) => {
- const { domain, domainVerified, createdAt } = project;
+ const results = await Promise.allSettled(
+ domains.map(async (domain) => {
+ const { slug, domainVerified, createdAt, projectId } = domain;
const [domainJson, configJson] = await Promise.all([
- getDomainResponse(domain),
- getConfigResponse(domain),
+ getDomainResponse(slug),
+ getConfigResponse(slug),
]);
let newDomainVerified;
@@ -44,7 +43,7 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
if (domainJson?.error?.code === "not_found") {
newDomainVerified = false;
} else if (!domainJson.verified) {
- const verificationJson = await verifyDomain(domain);
+ const verificationJson = await verifyDomain(slug);
if (verificationJson && verificationJson.verified) {
newDomainVerified = true;
} else {
@@ -56,9 +55,9 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
newDomainVerified = false;
}
- const prismaResponse = await prisma.project.update({
+ const prismaResponse = await prisma.domain.update({
where: {
- domain,
+ slug,
},
data: {
domainVerified: newDomainVerified,
@@ -69,12 +68,10 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
const changed = newDomainVerified !== domainVerified;
const updates = await handleDomainUpdates(
- project.slug,
- domain,
+ slug,
createdAt,
newDomainVerified,
changed,
- project.sentEmails.map((email) => email.type),
);
return {
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index c16e3fc1a5..8f0a53f2be 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -3,6 +3,7 @@ import { addLink, getLinksForProject } from "@/lib/api/links";
import { Session, withUserAuth } from "@/lib/auth";
import { isBlacklistedDomain } from "@/lib/utils";
import { log } from "@/lib/utils";
+import { DUB_PROJECT_ID } from "@/lib/constants";
export const config = {
api: {
@@ -22,7 +23,7 @@ export default withUserAuth(
sort?: "createdAt" | "clicks";
};
const response = await getLinksForProject({
- domain: "dub.sh",
+ projectId: DUB_PROJECT_ID,
status,
sort,
userId: session.user.id,
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index 2333d88b38..6cf472672e 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { addDomain, removeDomain } from "@/lib/domains";
+import { addDomain, removeDomain } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { validDomainRegex } from "@/lib/utils";
import { changeDomainForImages, changeDomainForLinks } from "@/lib/api/links";
@@ -42,13 +42,12 @@ export default withProjectAuth(
await Promise.allSettled([
removeDomain(domain),
addDomain(newDomain),
- prisma.project.update({
+ prisma.domain.update({
where: {
- slug,
+ slug: domain,
},
data: {
- domain: newDomain,
- domainVerified: false,
+ slug: newDomain,
},
}),
changeDomainForLinks(project.id, domain, newDomain),
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
index e42c39eac4..7ba14fec7e 100644
--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -4,7 +4,7 @@ import {
getConfigResponse,
getDomainResponse,
verifyDomain,
-} from "@/lib/domains";
+} from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { DomainVerificationStatusProps } from "@/lib/types";
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
index 2d147ed97f..471b6e87d9 100644
--- a/pages/api/projects/[slug]/domains/index.ts
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -2,6 +2,8 @@ import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { ProjectProps } from "@/lib/types";
import prisma from "@/lib/prisma";
+import { addDomain } from "@/lib/api/domains";
+import { redis } from "@/lib/upstash";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
@@ -15,11 +17,47 @@ export default withProjectAuth(
slug: true,
verified: true,
primary: true,
+ target: true,
+ type: true,
},
});
return res.status(200).json(domains);
- // PUT /api/projects/[slug]/domains/[domain]/root - change root domain
+ // POST /api/projects/[slug]/domains - add a domain
+ } else if (req.method === "POST") {
+ const { slug: domain, primary, target, type } = req.body;
+ if (!domain || typeof domain !== "string") {
+ return res.status(400).json({ error: "Missing domain" });
+ }
+ const response = await Promise.allSettled([
+ prisma.domain.create({
+ data: {
+ slug: domain,
+ type,
+ projectId: project.id,
+ primary,
+ },
+ }),
+ addDomain(domain),
+ target &&
+ redis.set(`root:${domain}`, {
+ target,
+ rewrite: type === "rewrite",
+ }),
+ primary &&
+ (await prisma.domain.updateMany({
+ where: {
+ projectId: project.id,
+ slug: {
+ not: domain,
+ },
+ },
+ data: {
+ primary: false,
+ },
+ })),
+ ]);
+ return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET", "POST"]);
return res
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index 3ee1ed2327..3068445683 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { removeDomain } from "@/lib/domains";
+import { removeDomain } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { ProjectProps } from "@/lib/types";
import { deleteProjectLinks } from "@/lib/api/links";
@@ -17,39 +17,55 @@ export default withProjectAuth(
// GET /api/projects/[slug] – get a specific project
if (req.method === "GET") {
return res.status(200).json(project);
+
+ // PUT /api/projects/[slug] – edit a specific project
+ } else if (req.method === "PUT") {
+ const { name, newSlug } = req.body;
+ try {
+ const response = await prisma.project.update({
+ where: {
+ slug,
+ },
+ data: {
+ ...(name && { name }),
+ ...(newSlug && { slug: newSlug }),
+ },
+ });
+ return res.status(200).json(response);
+ } catch (error) {
+ if (error.code === "P2002") {
+ return res.status(422).json({ error: "Key already exists" });
+ }
+ }
// DELETE /api/projects/[slug] – delete a project
} else if (req.method === "DELETE") {
- const domain = req.body;
- if (!domain || typeof domain !== "string" || domain !== project.domain) {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured domain" });
- }
+ const domains = (
+ await prisma.domain.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ slug: true,
+ },
+ })
+ ).map((domain) => domain.slug);
- const [
- prismaResponse,
- domainResponse,
- upstashResponse,
- cloudinaryResponse,
- ] = await Promise.all([
+ const response = await Promise.allSettled([
prisma.project.delete({
where: {
slug,
},
}),
- removeDomain(domain),
- deleteProjectLinks(domain),
- cloudinary.v2.api.delete_resources_by_prefix(domain),
+ ...domains.map((domain) => removeDomain(domain)),
+ ...domains.map((domain) => deleteProjectLinks(domain)),
+ ...domains.map((domain) =>
+ cloudinary.v2.api.delete_resources_by_prefix(domain),
+ ),
]);
- return res.status(200).json({
- prismaResponse,
- domainResponse,
- upstashResponse,
- cloudinaryResponse,
- });
+ return res.status(200).json(response);
} else {
- res.setHeader("Allow", ["GET", "DELETE"]);
+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index 5d53ebc3ec..224d513644 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -14,8 +14,9 @@ export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project, session) => {
// GET /api/projects/[slug]/domains/[domain]/links - Get all links for a project
if (req.method === "GET") {
- const { domain, tag, search, sort, userId } = req.query as {
+ const { domain, status, tag, search, sort, userId } = req.query as {
domain?: string;
+ status?: string;
tag?: string;
search?: string;
sort?: "createdAt" | "clicks";
@@ -24,6 +25,7 @@ export default withProjectAuth(
const response = await getLinksForProject({
projectId: project.id,
domain,
+ status,
tag,
search,
sort,
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index ebe8a17e75..763dde969f 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,7 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { Session, withUserAuth } from "@/lib/auth";
import { DEFAULT_REDIRECTS, RESERVED_KEYS } from "@/lib/constants";
-import { addDomain, removeDomain } from "@/lib/domains";
+import { addDomain, removeDomain } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { validDomainRegex } from "@/lib/utils";
@@ -51,12 +51,12 @@ export default withUserAuth(
slug: true,
},
}),
- prisma.project.findUnique({
+ prisma.domain.findUnique({
where: {
- domain,
+ slug: domain,
},
select: {
- domain: true,
+ slug: true,
},
}),
]);
@@ -76,26 +76,32 @@ export default withUserAuth(
},
});
- const [prismaResponse, domainResponse] = await Promise.all([
- prisma.project.create({
- data: {
- name,
- slug,
- domain,
- ownerUsageLimit,
- users: {
- create: {
- userId: session.user.id,
- role: "owner",
- },
+ const project = await prisma.project.create({
+ data: {
+ name,
+ slug,
+ domain,
+ ownerUsageLimit,
+ users: {
+ create: {
+ userId: session.user.id,
+ role: "owner",
},
},
+ },
+ });
+ const response = await Promise.allSettled([
+ prisma.domain.create({
+ data: {
+ slug: domain,
+ projectId: project.id,
+ primary: true,
+ },
}),
addDomain(domain),
]);
- return res
- .status(200)
- .json({ project: prismaResponse, domain: domainResponse });
+
+ return res.status(200).json({ project, ...response });
} else {
res.setHeader("Allow", ["GET", "POST"]);
return res
diff --git a/pages/app/[slug]/[domain]/[key].tsx b/pages/app/[slug]/[domain]/[key].tsx
index 6722f29427..da2c55a827 100644
--- a/pages/app/[slug]/[domain]/[key].tsx
+++ b/pages/app/[slug]/[domain]/[key].tsx
@@ -16,7 +16,6 @@ export default function StatsPage() {
if (error && error.status === 404) {
return <ErrorPage statusCode={404} />;
}
-
return (
<AppLayout>
{exceededUsage && (
@@ -51,7 +50,7 @@ export default function StatsPage() {
</div>
</MaxWidthWrapper>
)}
- {project && !exceededUsage && <Stats domain={project.domain} />}
+ {project && !exceededUsage && <Stats />}
</AppLayout>
);
}
diff --git a/pages/app/[slug]/[domain]/index.tsx b/pages/app/[slug]/[domain]/index.tsx
deleted file mode 100644
index 4e0ddad237..0000000000
--- a/pages/app/[slug]/[domain]/index.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import ErrorPage from "next/error";
-import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import AppLayout from "components/layout/app";
-import useProject from "@/lib/swr/use-project";
-import { useRouter } from "next/router";
-
-export default function ProjectDomains() {
- const router = useRouter();
- const { slug, domain } = router.query as {
- slug: string;
- domain: string;
- };
-
- const { project, error } = useProject();
-
- if (error && error.status === 404) {
- return <ErrorPage statusCode={404} />;
- }
-
- return (
- <AppLayout>
- <div className="flex h-36 items-center border-b border-gray-200 bg-white">
- <MaxWidthWrapper>
- <div className="flex items-center justify-between">
- <h1 className="text-2xl text-gray-600">{domain}</h1>
- </div>
- </MaxWidthWrapper>
- </div>
- </AppLayout>
- );
-}
diff --git a/pages/app/[slug]/domains.tsx b/pages/app/[slug]/domains.tsx
index 8041cab81a..3671bef33b 100644
--- a/pages/app/[slug]/domains.tsx
+++ b/pages/app/[slug]/domains.tsx
@@ -1,6 +1,6 @@
import ErrorPage from "next/error";
import LinksContainer from "@/components/app/links/links-container";
-import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal";
+import { useAddEditDomainModal } from "@/components/app/modals/add-edit-domain-modal";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import AppLayout from "components/layout/app";
import useProject from "@/lib/swr/use-project";
@@ -18,7 +18,7 @@ export default function ProjectDomains() {
const { project, error } = useProject();
- const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal({});
+ const { AddEditDomainModal, AddEditDomainButton } = useAddEditDomainModal({});
if (error && error.status === 404) {
return <ErrorPage statusCode={404} />;
@@ -35,21 +35,21 @@ export default function ProjectDomains() {
return (
<AppLayout>
- {project && <AddEditLinkModal />}
+ {project && <AddEditDomainModal />}
<div className="flex h-36 items-center border-b border-gray-200 bg-white">
<MaxWidthWrapper>
<div className="flex items-center justify-between">
<h1 className="text-2xl text-gray-600">Domains</h1>
- <AddEditLinkButton />
+ <AddEditDomainButton />
</div>
</MaxWidthWrapper>
</div>
{domains && (
<MaxWidthWrapper className="py-10">
<ul className="grid grid-cols-1 gap-3">
- {domains.map(({ slug: domain }) => (
- <li key={domain}>
- <DomainCard domain={domain} />
+ {domains.map((domain) => (
+ <li key={domain.slug}>
+ <DomainCard props={domain} />
</li>
))}
</ul>
diff --git a/pages/app/[slug]/settings/index.tsx b/pages/app/[slug]/settings/index.tsx
index 61e1c56ff4..5228b5f4fa 100644
--- a/pages/app/[slug]/settings/index.tsx
+++ b/pages/app/[slug]/settings/index.tsx
@@ -1,11 +1,13 @@
import DeleteProject from "@/components/app/settings/delete-project";
-import LandingPage from "@/components/app/settings/landing-page";
+import ProjectName from "@/components/app/settings/project-name";
import SettingsLayout from "@/components/app/settings/layout";
+import ProjectSlug from "@/components/app/settings/project-slug";
export default function ProjectSettingsGeneral() {
return (
<SettingsLayout>
- <LandingPage />
+ <ProjectName />
+ <ProjectSlug />
<DeleteProject />
</SettingsLayout>
);
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 513caae3d3..5e1e3ece0c 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -4,11 +4,12 @@
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
+ referentialIntegrity = "prisma"
}
generator client {
provider = "prisma-client-js"
- previewFeatures = ["fullTextSearch", "fullTextIndex"]
+ previewFeatures = ["referentialIntegrity", "fullTextSearch", "fullTextIndex"]
}
model User {