Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add default domain
Marc Seitzafe8abb215c4
diff --git a/components/domains/domain-card.tsx b/components/domains/domain-card.tsxindex 95d459d3..8359752a 100644--- a/components/domains/domain-card.tsx+++ b/components/domains/domain-card.tsx@@ -1,31 +1,67 @@-import { useState } from "react";+import Link from "next/link";++import { useRef, useState } from "react";import { useTeam } from "@/context/team-context";+import { motion } from "framer-motion";+import {+ ChevronDownIcon,+ CircleCheckIcon,+ FlagIcon,+ GlobeIcon,+ MoreVertical,+ RefreshCwIcon,+ SettingsIcon,+ TrashIcon,+} from "lucide-react";import { mutate } from "swr";import { useAnalytics } from "@/lib/analytics";+import { cn } from "@/lib/utils";-import AlertCircle from "../shared/icons/alert-circle";-import CheckCircle2 from "../shared/icons/check-cirlce-2";-import ExternalLink from "../shared/icons/external-link";-import XCircle from "../shared/icons/x-circle";import { Button } from "../ui/button";-import LoadingSpinner from "../ui/loading-spinner";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "../ui/dropdown-menu";+import { StatusBadge } from "../ui/status-badge";import DomainConfiguration from "./domain-configuration";import { useDomainStatus } from "./use-domain-status";export default function DomainCard({domain,+ isDefault,onDelete,}: {domain: string;+ isDefault: boolean;onDelete: (deletedDomain: string) => void;}) {- const { status, loading } = useDomainStatus({ domain });const [deleting, setDeleting] = useState<boolean>(false);+ const [showDetails, setShowDetails] = useState(false);+ const [groupHover, setGroupHover] = useState(false);+ const [menuOpen, setMenuOpen] = useState(false);++ const domainRef = useRef<HTMLDivElement>(null);++ const {+ status,+ loading,+ domainJson,+ configJson,+ mutate: mutateDomain,+ } = useDomainStatus({+ domain,+ });const teamInfo = useTeam();const analytics = useAnalytics();+ const isInvalid =+ status && !["Valid Configuration", "Pending Verification"].includes(status);+const handleDelete = async () => {setDeleting(true);const response = await fetch(@@ -49,66 +85,181 @@ export default function DomainCard({setDeleting(false);};+ const handleMakeDefault = async () => {+ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}`,+ { method: "PATCH" },+ );++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ // Update domains by refetching+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/domains`);+ };+return (<>- <div className="flex flex-col space-y-3 rounded-lg bg-white px-5 py-8 ring-1 ring-gray-200 hover:ring-gray-400 dark:bg-secondary dark:ring-gray-700 hover:dark:ring-gray-500 sm:px-10">- <div className="flex flex-col justify-between space-y-4 sm:flex-row sm:space-x-4">- <div className="flex items-center space-x-2">- <a- href={`http://${domain}`}- target="_blank"- rel="noreferrer"- className="flex items-center space-x-2"- >- <p className="flex items-center text-xl font-semibold">- {domain}- </p>- <ExternalLink className="h-5 w-5" />- </a>+ <div+ ref={domainRef}+ className="hover:drop-shadow-card-hover group rounded-xl border border-gray-200 bg-white p-4 transition-[filter] sm:p-5"+ onPointerEnter={() => setGroupHover(true)}+ onPointerLeave={() => setGroupHover(false)}+ >+ <div className="flex items-center justify-between gap-3 sm:gap-4">+ <div className="flex min-w-0 items-center gap-4">+ <div className="hidden rounded-full border border-gray-200 sm:block">+ <div+ className={cn(+ "rounded-full",+ "border border-white bg-gradient-to-t from-gray-100 p-1 md:p-3",+ )}+ >+ <GlobeIcon className="size-5" />+ </div>+ </div>+ <div className="overflow-hidden">+ <div className="flex items-center gap-1.5 sm:gap-2.5">+ <a+ href={`http://${domain}`}+ target="_blank"+ rel="noreferrer"+ className="truncate text-sm font-medium"+ title={domain}+ >+ {domain}+ </a>++ {isDefault ? (+ <span className="xs:px-3 xs:py-1 flex items-center gap-1 rounded-full bg-sky-400/[.15] px-1.5 py-0.5 text-xs font-medium text-sky-600">+ <FlagIcon className="hidden h-3 w-3 sm:block" />+ Default+ </span>+ ) : null}+ </div>+ </div></div>- <div className="flex space-x-3">++ <div className="flex items-center justify-end gap-2 sm:gap-3">+ {/* Status */}+ <div className="hidden sm:block">+ {status && !loading ? (+ <StatusBadge+ variant={+ status === "Valid Configuration"+ ? "success"+ : status === "Pending Verification"+ ? "pending"+ : "error"+ }+ >+ {status === "Valid Configuration"+ ? "Active"+ : status === "Pending Verification"+ ? "Pending"+ : "Invalid"}+ </StatusBadge>+ ) : (+ <div className="h-6 w-16 animate-pulse rounded-md bg-gray-200" />+ )}+ </div><Buttonvariant="secondary"- className="bg-gray-300 hover:bg-gray-300/80 dark:bg-gray-700 hover:dark:bg-gray-700/80"- loading={loading}- onClick={() => {- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`,- );- }}+ className={cn(+ "h-8 w-auto px-2 opacity-100 transition-opacity lg:h-9",+ !showDetails &&+ !isInvalid &&+ "sm:opacity-0 sm:group-hover:opacity-100",+ )}+ onClick={() => setShowDetails((s) => !s)}+ data-state={showDetails ? "open" : "closed"}>- Refresh- </Button>- <Button- variant="destructive"- onClick={handleDelete}- loading={deleting}- >- Delete+ <div className="flex items-center gap-1">+ <div className="relative">+ <SettingsIcon+ className={cn(+ "h-4 w-4",+ showDetails ? "text-gray-800" : "text-gray-600",+ )}+ />+ {/* Error indicator */}+ {status && isInvalid && (+ <div className="absolute -right-px -top-px h-[5px] w-[5px] rounded-full bg-red-500">+ <div className="h-full w-full animate-pulse rounded-full ring-2 ring-red-500/30" />+ </div>+ )}+ </div>+ <ChevronDownIcon+ className={cn(+ "hidden h-4 w-4 text-gray-400 transition-transform sm:block",+ showDetails && "rotate-180",+ )}+ />+ </div></Button>+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger asChild>+ <Button+ // size="icon"+ variant="outline"+ className="z-20 h-8 w-8 border-gray-200 bg-transparent p-0 hover:bg-gray-200 dark:border-gray-700 hover:dark:bg-gray-700 lg:h-9 lg:w-9"+ >+ <span className="sr-only">Open menu</span>+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Actions</DropdownMenuLabel>+ <DropdownMenuItem+ disabled={isDefault}+ onClick={handleMakeDefault}+ >+ <FlagIcon className="mr-2 h-4 w-4" />+ Make default+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => mutateDomain()}+ disabled={loading}+ >+ <RefreshCwIcon className="mr-2 h-4 w-4" />+ Refresh+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-destructive transition-colors duration-200 focus:bg-destructive focus:text-destructive-foreground"+ onClick={handleDelete}+ >+ <TrashIcon className="mr-2 h-4 w-4" />+ Delete domain+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></div></div>- <div className="flex h-10 flex-col space-y-2 sm:flex-row sm:items-center sm:space-x-5 sm:space-y-0">- <div className="flex items-center space-x-2">- {status ? (- status === "Valid Configuration" ? (- <CheckCircle2 className="h-6 w-6 text-emerald-500" />- ) : status === "Pending Verification" ? (- <AlertCircle className="h-6 w-6 text-yellow-500" />- ) : (- <XCircle className="h-6 w-6 text-red-500" />- )+ <motion.div+ initial={false}+ animate={{ height: showDetails ? "auto" : 0 }}+ className="overflow-hidden"+ >+ {status ? (+ status === "Valid Configuration" ? (+ <div className="mt-6 flex items-center gap-2 text-pretty rounded-lg bg-green-100/80 p-3 text-sm text-green-600">+ <CircleCheckIcon className="h-5 w-5 shrink-0" />+ <div>+ Good news! Your DNS records are set up correctly, but it can+ take some time for them to propagate globally.+ </div>+ </div>) : (- <LoadingSpinner className="mr-1 h-5 w-5" />- )}- <p className="text-sm text-muted-foreground">- {status ? status : "Checking Domain Status"}- </p>- </div>- </div>- {status && status !== "Valid Configuration" && (- <DomainConfiguration domain={domain} />- )}+ <DomainConfiguration+ status={status}+ response={{ domainJson, configJson }}+ />+ )+ ) : (+ <div className="mt-6 h-6 w-32 animate-pulse rounded-md bg-gray-200" />+ )}+ </motion.div></div></>);diff --git a/components/domains/domain-configuration.tsx b/components/domains/domain-configuration.tsxindex 835afd8e..02cb981f 100644--- a/components/domains/domain-configuration.tsx+++ b/components/domains/domain-configuration.tsx@@ -1,155 +1,216 @@-"use client";+import { Fragment, useState } from "react";-import { useState } from "react";+import { InfoIcon } from "lucide-react";import { getSubdomain } from "@/lib/domains";+import { DomainVerificationStatusProps } from "@/lib/types";import { cn } from "@/lib/utils";-import { useDomainStatus } from "./use-domain-status";+import { TabSelect } from "../ui/tab-select";-export const InlineSnippet = ({- className,- children,+export default function DomainConfiguration({+ status,+ response,}: {- className?: string;- children: string;-}) => {+ status: DomainVerificationStatusProps;+ response: { domainJson: any; configJson: any };+}) {+ const { domainJson, configJson } = response;+ const subdomain = getSubdomain(domainJson.name, domainJson.apexName);+ const [recordType, setRecordType] = useState(!!subdomain ? "CNAME" : "A");++ if (status === "Pending Verification") {+ const txtVerification = domainJson.verification.find(+ (x: any) => x.type === "TXT",+ );+ return (+ <div>+ <DnsRecord+ instructions={`Please set the following TXT record on <code>${domainJson.apexName}</code> to prove ownership of <code>${domainJson.name}</code>:`}+ records={[+ {+ type: txtVerification.type,+ name: txtVerification.domain.slice(+ 0,+ txtVerification.domain.length - domainJson.apexName.length - 1,+ ),+ value: txtVerification.value,+ },+ ]}+ warning="Warning: if you are using this domain for another site, setting this TXT record will transfer domain ownership away from that site and break it. Please exercise caution when setting this record; make sure that the domain that is shown in the TXT verification value is actually the <b><i>domain you want to use on Papermark.io</i></b> – <b><i>not your production site</i></b>."+ />+ </div>+ );+ }++ if (status === "Conflicting DNS Records") {+ return (+ <div className="pt-5">+ <div className="flex justify-start space-x-4">+ <div className="ease border-b-2 border-black pb-1 text-sm text-black transition-all duration-150">+ {configJson?.conflicts.some((x: any) => x.type === "A")+ ? "A Record (recommended)"+ : "CNAME Record (recommended)"}+ </div>+ </div>+ <DnsRecord+ instructions="Please remove the following conflicting DNS records from your DNS provider:"+ records={configJson?.conflicts.map(+ ({+ name,+ type,+ value,+ }: {+ name: string;+ type: string;+ value: string;+ }) => ({+ name,+ type,+ value,+ }),+ )}+ />+ <DnsRecord+ instructions="Afterwards, set the following record on your DNS provider:"+ records={[+ {+ type: recordType,+ name: recordType === "A" ? "@" : (subdomain ?? "www"),+ value:+ recordType === "A" ? `76.76.21.21` : `cname.vercel-dns.com`,+ ttl: "86400",+ },+ ]}+ />+ </div>+ );+ }++ if (status === "Unknown Error") {+ return (+ <div className="pt-5">+ <p className="mb-5 text-sm">{response.domainJson.error.message}</p>+ </div>+ );+ }+return (- <span- className={cn(- "inline-block rounded-md bg-blue-100 px-1 py-0.5 font-mono text-blue-900 dark:bg-blue-900 dark:text-blue-100",- className,- )}- >- {children}- </span>- );-};-export default function DomainConfiguration({ domain }: { domain: string }) {- const { status, domainJson } = useDomainStatus({ domain });+ <div className="pt-2">+ <div className="-ml-1.5 border-b border-gray-200">+ <TabSelect+ options={[+ { id: "A", label: `A Record${!subdomain ? " (recommended)" : ""}` },+ {+ id: "CNAME",+ label: `CNAME Record${subdomain ? " (recommended)" : ""}`,+ },+ ]}+ selected={recordType}+ onSelect={setRecordType}+ />+ </div>- const subdomain = domainJson- ? getSubdomain(domainJson.name, domainJson.apexName)- : null;- const [recordType, setRecordType] = useState<"CNAME" | "A">(- !!subdomain ? "CNAME" : "A",+ <DnsRecord+ instructions={`To configure your ${+ recordType === "A" ? "apex domain" : "subdomain"+ } <code>${+ recordType === "A" ? domainJson.apexName : domainJson.name+ }</code>, set the following ${recordType} record on your DNS provider:`}+ records={[+ {+ type: recordType,+ name: recordType === "A" ? "@" : (subdomain ?? "www"),+ value: recordType === "A" ? `76.76.21.21` : `cname.vercel-dns.com`,+ ttl: "86400",+ },+ ]}+ />+ </div>);+}- if (!status || status === "Valid Configuration" || !domainJson) return null;+const MarkdownText = ({ text }: { text: string }) => {+ return (+ <p+ className="prose-sm max-w-none prose-code:rounded-md prose-code:bg-gray-100 prose-code:p-1 prose-code:font-mono prose-code:text-[.8125rem] prose-code:font-medium prose-code:text-gray-900"+ dangerouslySetInnerHTML={{ __html: text }}+ />+ );+};- const txtVerification =- (status === "Pending Verification" &&- domainJson.verification.find((x: any) => x.type === "TXT")) ||- null;+const DnsRecord = ({+ instructions,+ records,+ warning,+}: {+ instructions: string;+ records: { type: string; name: string; value: string; ttl?: string }[];+ warning?: string;+}) => {+ const hasTtl = records.some((x) => x.ttl);return (- <div className="border-t border-gray-200 pb-5 pt-7 dark:border-gray-700">- {txtVerification ? (- <>- <p className="text-sm dark:text-white">- Please set the following TXT record on{" "}- <InlineSnippet>{domainJson.apexName}</InlineSnippet> to prove- ownership of <InlineSnippet>{domainJson.name}</InlineSnippet>:+ <div className="mt-3 text-left text-gray-600">+ <div className="my-5">+ <MarkdownText text={instructions} />+ </div>+ <div+ className={cn(+ "scrollbar-hide grid items-end gap-x-10 gap-y-1 overflow-x-auto rounded-lg bg-gray-100/80 p-4 text-sm",+ hasTtl+ ? "grid-cols-[repeat(4,min-content)]"+ : "grid-cols-[repeat(3,min-content)]",+ )}+ >+ {["Type", "Name", "Value"].concat(hasTtl ? "TTL" : []).map((s) => (+ <p key={s} className="font-medium text-gray-950">+ {s}</p>- <div className="my-5 flex items-start justify-start space-x-10 rounded-md bg-gray-50 p-2 dark:bg-gray-800 dark:text-white">- <div>- <p className="text-sm font-bold">Type</p>- <p className="mt-2 font-mono text-sm">{txtVerification.type}</p>- </div>- <div>- <p className="text-sm font-bold">Name</p>- <p className="mt-2 font-mono text-sm">- {txtVerification.domain.slice(- 0,- txtVerification.domain.length -- domainJson.apexName.length -- 1,- )}- </p>- </div>- <div>- <p className="text-sm font-bold">Value</p>- <p className="mt-2 font-mono text-sm">- <span className="text-ellipsis">{txtVerification.value}</span>- </p>- </div>- </div>- <p className="text-sm dark:text-muted-foreground">- Warning: if you are using this domain for another site, setting this- TXT record will transfer domain ownership away from that site and- break it. Please exercise caution when setting this record.- </p>- </>- ) : status === "Unknown Error" ? (- <p className="mb-5 text-sm dark:text-white">- {domainJson.error.message}- </p>- ) : (- <>- <div className="flex justify-start space-x-4">- <button- type="button"- onClick={() => setRecordType("A")}- className={`${- recordType == "A"- ? "border-black text-black dark:border-white dark:text-white"- : " text-stone-400 dark:text-stone-600"- } ease border-b-2 pb-1 text-sm transition-all duration-150`}- >- A Record{!subdomain && " (recommended)"}- </button>- <button- type="button"- onClick={() => setRecordType("CNAME")}- className={`${- recordType == "CNAME"- ? "border-black text-black dark:border-white dark:text-white"- : " text-stone-400 dark:text-stone-600"- } ease border-b-2 pb-1 text-sm transition-all duration-150`}- >- CNAME Record{subdomain && " (recommended)"}- </button>- </div>- <div className="my-3 text-left">- <p className="my-5 text-sm dark:text-white">- To configure your{" "}- {recordType === "A" ? "apex domain" : "subdomain"} (- <InlineSnippet>- {recordType === "A" ? domainJson.apexName : domainJson.name}- </InlineSnippet>- ), set the following {recordType} record on your DNS provider to- continue:+ ))}++ {records.map((record, idx) => (+ <Fragment key={idx}>+ <p key={record.type} className="font-mono">+ {record.type}</p>- <div className="flex items-center justify-start space-x-10 rounded-md bg-gray-50 p-2 dark:bg-gray-800 dark:text-white">- <div>- <p className="text-sm font-bold">Type</p>- <p className="mt-2 font-mono text-sm">{recordType}</p>- </div>- <div>- <p className="text-sm font-bold">Name</p>- <p className="mt-2 font-mono text-sm">- {recordType === "A" ? "@" : subdomain ?? "www"}- </p>- </div>- <div>- <p className="text-sm font-bold">Value</p>- <p className="mt-2 font-mono text-sm">- {recordType === "A" ? `76.76.21.21` : `cname.vercel-dns.com`}- </p>- </div>- <div>- <p className="text-sm font-bold">TTL</p>- <p className="mt-2 font-mono text-sm">86400</p>- </div>- </div>- <p className="mt-5 text-sm dark:text-white">- Note: for TTL, if <InlineSnippet>86400</InlineSnippet> is not- available, set the highest value possible. Also, domain- propagation can take up to an hour.+ <p key={record.name} className="font-mono">+ {record.name}</p>- </div>- </>+ <p key={record.value} className="flex items-end gap-1 font-mono">+ {record.value}{" "}+ {/* <CopyButton+ variant="neutral"+ className="-mb-0.5"+ value={record.value}+ /> */}+ </p>+ {hasTtl && (+ <p key={record.ttl} className="font-mono">+ {record.ttl}+ </p>+ )}+ </Fragment>+ ))}+ </div>+ {(warning || hasTtl) && (+ <div+ className={cn(+ "mt-4 flex items-center gap-2 rounded-lg p-3",+ warning+ ? "bg-orange-50 text-orange-600"+ : "bg-indigo-50 text-indigo-600",+ )}+ >+ <InfoIcon className="h-5 w-5 shrink-0" />+ <MarkdownText+ text={+ warning ||+ "If a TTL value of 86400 is not available, choose the highest available value. Domain propagation may take up to 12 hours."+ }+ />+ </div>)}</div>);-}+};diff --git a/components/domains/use-domain-status.ts b/components/domains/use-domain-status.tsindex e4805893..6c0d34af 100644--- a/components/domains/use-domain-status.ts+++ b/components/domains/use-domain-status.ts@@ -1,28 +1,32 @@import { useTeam } from "@/context/team-context";-import useSWR from "swr";+import useSWRImmutable from "swr/immutable";-import { DomainResponse, DomainVerificationStatusProps } from "@/lib/types";+import {+ DomainConfigResponse,+ DomainResponse,+ DomainVerificationStatusProps,+} from "@/lib/types";import { fetcher } from "@/lib/utils";export function useDomainStatus({ domain }: { domain: string }) {const teamInfo = useTeam();- const { data, isValidating } = useSWR<{+ const { data, isValidating, mutate } = useSWRImmutable<{status: DomainVerificationStatusProps;- domainJson: DomainResponse & { error: { code: string; message: string } };+ response: {+ domainJson: DomainResponse & { error: { code: string; message: string } };+ configJson: DomainConfigResponse;+ };}>(`/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`,- (input, init) => fetcher(input, { ...init, cache: "no-store" }),- {- revalidateOnMount: true,- refreshInterval: 5000,- keepPreviousData: true,- },+ fetcher,);return {status: data?.status,- domainJson: data?.domainJson,+ domainJson: data?.response.domainJson,+ configJson: data?.response.configJson,loading: isValidating,+ mutate,};}diff --git a/components/links/link-sheet/domain-section.tsx b/components/links/link-sheet/domain-section.tsxindex 9c23ef32..c218f4aa 100644--- a/components/links/link-sheet/domain-section.tsx+++ b/components/links/link-sheet/domain-section.tsx@@ -1,6 +1,6 @@import Link from "next/link";-import { Dispatch, SetStateAction, useState } from "react";+import { Dispatch, SetStateAction, useEffect, useState } from "react";import { useTeam } from "@/context/team-context";import { Domain } from "@prisma/client";@@ -30,12 +30,14 @@ export default function DomainSection({domains,plan,linkType,+ editLink,}: {data: DEFAULT_LINK_TYPE;setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;domains?: Domain[];plan?: BasePlan | null;linkType: "DOCUMENT_LINK" | "DATAROOM_LINK";+ editLink?: boolean;}) {const [isModalOpen, setModalOpen] = useState(false);const teamInfo = useTeam();@@ -59,6 +61,22 @@ export default function DomainSection({mutate(`/api/teams/${teamInfo?.currentTeam?.id}/domains`);};+ useEffect(() => {+ console.log("data.domain", data.domain);+ if (domains && !editLink) {+ console.log("data.domain", data.domain);+ const defaultDomain = domains.find((domain) => domain.isDefault);+ setData({+ ...data,+ domain: defaultDomain?.slug ?? "papermark.io",+ });+ }+ }, [domains, editLink]);++ const defaultDomain = editLink+ ? (data.domain ?? "papermark.io")+ : (domains?.find((domain) => domain.isDefault)?.slug ?? "papermark.io");+const currentDomain = domains?.find((domain) => domain.slug === data.domain);const isDomainVerified = currentDomain?.verified;@@ -67,7 +85,7 @@ export default function DomainSection({<Label htmlFor="link-domain">Domain</Label><div className="flex"><Select- defaultValue={data.domain || "papermark.io"}+ defaultValue={defaultDomain}onValueChange={handleDomainChange}onOpenChange={handleSelectFocus}>diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex 8ffaa2e1..8475a68b 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -243,6 +243,7 @@ export default function LinkSheet({{...{ data, setData, domains }}plan={plan}linkType={linkType}+ editLink={!!currentLink}/></div>diff --git a/components/shared/icons/index.tsx b/components/shared/icons/index.tsxnew file mode 100644index 00000000..fc90fb53--- /dev/null+++ b/components/shared/icons/index.tsx@@ -0,0 +1,7 @@+"use client";++import { ComponentType, SVGProps } from "react";++import { LucideIcon } from "lucide-react";++export type Icon = LucideIcon | ComponentType<SVGProps<SVGSVGElement>>;diff --git a/components/ui/status-badge.tsx b/components/ui/status-badge.tsxnew file mode 100644index 00000000..f3f7952a--- /dev/null+++ b/components/ui/status-badge.tsx@@ -0,0 +1,63 @@+import { type VariantProps, cva } from "class-variance-authority";+import {+ CircleCheckIcon as CircleCheck,+ CircleDashedIcon as CircleHalfDottedClock,+ InfoIcon as CircleInfo,+ CircleAlertIcon as CircleWarning,+} from "lucide-react";++import { cn } from "@/lib/utils";++import { Icon } from "../shared/icons";++const statusBadgeVariants = cva(+ "flex gap-1.5 items-center max-w-fit rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap",+ {+ variants: {+ variant: {+ neutral: "bg-gray-500/[.15] text-gray-600",+ success: "bg-green-500/[.15] text-green-600",+ pending: "bg-orange-500/[.15] text-orange-600",+ error: "bg-red-500/[.15] text-red-600",+ },+ },+ defaultVariants: {+ variant: "neutral",+ },+ },+);++const defaultIcons = {+ neutral: CircleInfo,+ success: CircleCheck,+ pending: CircleHalfDottedClock,+ error: CircleWarning,+};++interface BadgeProps+ extends React.HTMLAttributes<HTMLSpanElement>,+ VariantProps<typeof statusBadgeVariants> {+ icon?: Icon;+}++function StatusBadge({+ className,+ variant,+ icon,+ children,+ ...props+}: BadgeProps) {+ const Icon =+ icon !== null ? (icon ?? defaultIcons[variant ?? "neutral"]) : null;+ return (+ <span+ className={cn(statusBadgeVariants({ variant }), className)}+ {...props}+ >+ {Icon && <Icon className="h-3 w-3 shrink-0" />}+ {children}+ </span>+ );+}++export { StatusBadge, statusBadgeVariants };diff --git a/components/ui/tab-select.tsx b/components/ui/tab-select.tsxnew file mode 100644index 00000000..bf8fff50--- /dev/null+++ b/components/ui/tab-select.tsx@@ -0,0 +1,54 @@+import { Dispatch, SetStateAction, useId } from "react";++import { LayoutGroup, motion } from "framer-motion";++import { cn } from "@/lib/utils";++export function TabSelect<T extends string>({+ options,+ selected,+ onSelect,+ className,+}: {+ options: { id: T; label: string }[];+ selected: string | null;+ onSelect?: Dispatch<SetStateAction<T>> | ((id: T) => void);+ className?: string;+}) {+ const layoutGroupId = useId();++ return (+ <div className={cn("flex text-sm", className)}>+ <LayoutGroup id={layoutGroupId}>+ {options.map(({ id, label }) => (+ <div key={id} className="relative">+ <button+ type="button"+ onClick={() => onSelect?.(id)}+ className={cn(+ "p-4 transition-colors duration-75",+ id === selected+ ? "text-black"+ : "text-gray-400 hover:text-gray-500",+ )}+ aria-selected={id === selected}+ >+ {label}+ </button>+ {id === selected && (+ <motion.div+ layoutId="indicator"+ transition={{+ duration: 0.1,+ }}+ className="absolute bottom-0 w-full px-1.5"+ >+ <div className="h-0.5 bg-black" />+ </motion.div>+ )}+ </div>+ ))}+ </LayoutGroup>+ </div>+ );+}diff --git a/lib/domains.ts b/lib/domains.tsindex a52ef778..2e908c5f 100644--- a/lib/domains.ts+++ b/lib/domains.ts@@ -62,7 +62,7 @@ export const getDomainResponse = async (domain: string,): Promise<DomainResponse & { error: { code: string; message: string } }> => {return await fetch(- `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}?teamId=${process.env.TEAM_ID_VERCEL}`,+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,{method: "GET",headers: {@@ -79,7 +79,7 @@ export const getConfigResponse = async (domain: string,): Promise<DomainConfigResponse> => {return await fetch(- `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.TEAM_ID_VERCEL}`,+ `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${process.env.TEAM_ID_VERCEL}`,{method: "GET",headers: {@@ -94,7 +94,7 @@ export const verifyDomain = async (domain: string,): Promise<DomainVerificationResponse> => {return await fetch(- `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}/verify?teamId=${process.env.TEAM_ID_VERCEL}`,+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}/verify?teamId=${process.env.TEAM_ID_VERCEL}`,{method: "POST",headers: {@@ -119,10 +119,10 @@ export const getApexDomain = (url: string) => {}const parts = domain.split(".");if (parts.length > 2) {- // if it's a subdomain (e.g. dub.vercel.app), return the last 2 parts+ // if it's a subdomain (e.g. papermark.vercel.app), return the last 2 partsreturn parts.slice(-2).join(".");}- // if it's a normal domain (e.g. dub.sh), we return the domain+ // if it's a normal domain (e.g. papermark.io), we return the domainreturn domain;};diff --git a/lib/types.ts b/lib/types.tsindex c75779c6..11b48a6c 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -110,7 +110,8 @@ export type DomainVerificationStatusProps =| "Invalid Configuration"| "Pending Verification"| "Domain Not Found"- | "Unknown Error";+ | "Unknown Error"+ | "Conflicting DNS Records";// From https://vercel.com/docs/rest-api/endpoints#get-a-project-domainexport interface DomainResponse {@@ -141,6 +142,12 @@ export interface DomainConfigResponse {acceptedChallenges?: ("dns-01" | "http-01")[];/** Whether or not the domain is configured AND we can automatically generate a TLS certificate. */misconfigured: boolean;+ /** conflicts */+ conflicts: {+ name: string;+ type: string;+ value: string;+ }[];}// From https://vercel.com/docs/rest-api/endpoints#verify-project-domaindiff --git a/pages/api/teams/[teamId]/domains/[domain]/index.ts b/pages/api/teams/[teamId]/domains/[domain]/index.tsindex b959ce44..e58114b1 100644--- a/pages/api/teams/[teamId]/domains/[domain]/index.ts+++ b/pages/api/teams/[teamId]/domains/[domain]/index.ts@@ -72,9 +72,74 @@ export default async function handle(});errorhandler(error, res);}+ } else if (req.method === "PATCH") {+ // PATCH /api/teams/:teamId/domains/:domain+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ // Assuming the domain slug is sent in the request body.+ const { teamId, domain } = req.query as { teamId: string; domain: string };++ const userId = (session.user as CustomUser).id;++ if (!domain) {+ return res.status(400).json("Domain is required for deletion");+ }++ try {+ const { domain: domainToBeUpdated } = await getTeamWithDomain({+ teamId,+ userId,+ domain,+ });++ if (!domainToBeUpdated) {+ return res.status(404).json("Domain not found");+ }++ const updateDefaultPromise = prisma.domain.update({+ where: {+ id: domainToBeUpdated.id,+ teamId: teamId,+ },+ data: {+ isDefault: true,+ },+ });++ const updateNonDefaultPromise = prisma.domain.updateMany({+ where: {+ teamId,+ slug: {+ not: domain,+ },+ },+ data: {+ isDefault: false,+ },+ });++ const response = await Promise.all([+ updateDefaultPromise,+ updateNonDefaultPromise,+ ]);++ console.log("promise response", response);++ return res.status(200).json({ message: "Domain set to default" }); // 204 No Content response for successful deletes+ } catch (error) {+ log({+ message: `Failed to set domain: _${domain}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ mention: true,+ });+ errorhandler(error, res);+ }} else {// We only allow POST requests- res.setHeader("Allow", ["DELETE"]);+ res.setHeader("Allow", ["DELETE", "PATCH"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}}diff --git a/pages/api/teams/[teamId]/domains/[domain]/verify.ts b/pages/api/teams/[teamId]/domains/[domain]/verify.tsindex 8f8b0010..66b776c9 100644--- a/pages/api/teams/[teamId]/domains/[domain]/verify.ts+++ b/pages/api/teams/[teamId]/domains/[domain]/verify.ts@@ -1,6 +1,8 @@import { NextApiRequest, NextApiResponse } from "next";-import { identifyUser, trackAnalytics } from "@/lib/analytics";+import { waitUntil } from "@vercel/functions";++import { trackAnalytics } from "@/lib/analytics";import {getConfigResponse,getDomainResponse,@@ -26,13 +28,34 @@ export default async function handle(if (domainJson?.error?.code === "not_found") {// domain not found on Vercel projectstatus = "Domain Not Found";-+ return res.status(200).json({+ status,+ response: { domainJson, configJson },+ });// unknown error} else if (domainJson.error) {status = "Unknown Error";+ return res.status(200).json({+ status,+ response: { domainJson, configJson },+ });+ }++ /**+ * Domain has DNS conflicts+ */+ if (configJson?.conflicts.length > 0) {+ status = "Conflicting DNS Records";+ return res.status(200).json({+ status,+ response: { domainJson, configJson },+ });+ }- // if domain is not verified, we try to verify now- } else if (!domainJson.verified) {+ /**+ * If domain is not verified, we try to verify now+ */+ if (!domainJson.verified) {status = "Pending Verification";const verificationJson = await verifyDomain(domain);@@ -40,18 +63,14 @@ export default async function handle(if (verificationJson && verificationJson.verified) {status = "Valid Configuration";}- } else if (configJson.misconfigured) {- status = "Invalid Configuration";- await prisma.domain.update({- where: {- slug: domain,- },- data: {- verified: false,- lastChecked: new Date(),- },++ return res.status(200).json({+ status,+ response: { domainJson, configJson },});- } else {+ }++ if (!configJson.misconfigured) {status = "Valid Configuration";const currentDomain = await prisma.domain.findUnique({where: {@@ -77,14 +96,24 @@ export default async function handle(});if (!currentDomain!.verified && updatedDomain.verified) {- // await identifyUser(updatedDomain.userId);- await trackAnalytics({ event: "Domain Verified", slug: domain });+ waitUntil(trackAnalytics({ event: "Domain Verified", slug: domain }));}+ } else {+ status = "Invalid Configuration";+ await prisma.domain.update({+ where: {+ slug: domain,+ },+ data: {+ verified: false,+ lastChecked: new Date(),+ },+ });}return res.status(200).json({status,- domainJson,+ response: { domainJson, configJson },});} else {res.setHeader("Allow", ["GET"]);diff --git a/pages/api/teams/[teamId]/domains/index.ts b/pages/api/teams/[teamId]/domains/index.tsindex aad4f01f..6d799a24 100644--- a/pages/api/teams/[teamId]/domains/index.ts+++ b/pages/api/teams/[teamId]/domains/index.ts@@ -34,6 +34,7 @@ export default async function handle(select: {slug: true,verified: true,+ isDefault: true,},orderBy: {createdAt: "asc",diff --git a/pages/settings/domains.tsx b/pages/settings/domains.tsxindex 7b9c2e04..893b1853 100644--- a/pages/settings/domains.tsx+++ b/pages/settings/domains.tsx@@ -64,6 +64,7 @@ export default function Domains() {<li key={index} className="mt-4"><DomainCarddomain={domain.slug}+ isDefault={domain.isDefault}onDelete={handleDomainDeletion}/></li>diff --git a/prisma/migrations/20240901000000_add_domain_default/migration.sql b/prisma/migrations/20240901000000_add_domain_default/migration.sqlnew file mode 100644index 00000000..a3276e89--- /dev/null+++ b/prisma/migrations/20240901000000_add_domain_default/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "Domain" ADD COLUMN "isDefault" BOOLEAN NOT NULL DEFAULT false;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex e125b1bc..2a2ad913 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -252,6 +252,7 @@ model Domain {teamId StringTeam Team @relation(fields: [teamId], references: [id], onDelete: Cascade)verified Boolean @default(false) // Whether the domain has been verified+ isDefault Boolean @default(false) // Whether the domain is the primary domainlastChecked DateTime @default(now())createdAt DateTime @default(now())updatedAt DateTime @updatedAt