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.

Update domain/link transfer modals & logic (#2995)

Steven Tey8b1089f7bfd4
diff --git a/apps/web/app/(ee)/api/cron/domains/transfer/route.ts b/apps/web/app/(ee)/api/cron/domains/transfer/route.ts
index 196abca6b1..021e0fa92f 100644
--- a/apps/web/app/(ee)/api/cron/domains/transfer/route.ts
+++ b/apps/web/app/(ee)/api/cron/domains/transfer/route.ts
@@ -62,6 +62,15 @@ export async function POST(req: Request) {
},
data: {
projectId: newWorkspaceId,
+ // reset all stats and folder
+ clicks: 0,
+ leads: 0,
+ sales: 0,
+ saleAmount: 0,
+ conversions: 0,
+ lastClicked: null,
+ lastLeadAt: null,
+ lastConversionAt: null,
folderId: null,
},
}),
diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.ts
index 14a6cd201e..a74a8f2504 100644
--- a/apps/web/app/api/domains/[domain]/transfer/route.ts
+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts
@@ -1,4 +1,3 @@
-import { getAnalytics } from "@/lib/analytics/get-analytics";
import { getDomainOrThrow } from "@/lib/api/domains/get-domain-or-throw";
import { transformDomain } from "@/lib/api/domains/transform-domain";
import { DubApiError } from "@/lib/api/errors";
@@ -31,7 +30,7 @@ export const POST = withWorkspace(
if (newWorkspaceId === workspace.id) {
throw new DubApiError({
code: "bad_request",
- message: "Please select another workspace to transfer the domain to.",
+ message: "You cannot transfer a domain to the same workspace.",
});
}
@@ -103,49 +102,17 @@ export const POST = withWorkspace(
});
}
- const { clicks: totalLinkClicks } = await getAnalytics({
- domain,
- event: "clicks",
- groupBy: "count",
- workspaceId: workspace.id,
- interval: "30d",
- });
-
// Update the domain to use the new workspace
- const [domainResponse] = await Promise.all([
- prisma.domain.update({
- where: { slug: domain, projectId: workspace.id },
- data: {
- projectId: newWorkspaceId,
- primary: newWorkspace.domains.length === 0,
- },
- include: {
- registeredDomain: true,
- },
- }),
- prisma.project.update({
- where: { id: workspace.id },
- data: {
- usage: {
- set: Math.max(workspace.usage - totalLinkClicks, 0),
- },
- linksUsage: {
- set: Math.max(workspace.linksUsage - linksCount, 0),
- },
- },
- }),
- prisma.project.update({
- where: { id: newWorkspaceId },
- data: {
- usage: {
- increment: totalLinkClicks,
- },
- linksUsage: {
- increment: linksCount,
- },
- },
- }),
- ]);
+ const domainResponse = await prisma.domain.update({
+ where: { slug: domain, projectId: workspace.id },
+ data: {
+ projectId: newWorkspaceId,
+ primary: newWorkspace.domains.length === 0,
+ },
+ include: {
+ registeredDomain: true,
+ },
+ });
await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/transfer`,
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index 4131479c3f..e9dc5e8649 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -1,4 +1,3 @@
-import { getAnalytics } from "@/lib/analytics/get-analytics";
import { DubApiError } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";
@@ -7,6 +6,7 @@ import { withWorkspace } from "@/lib/auth";
import { verifyFolderAccess } from "@/lib/folder/permissions";
import { recordLink } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
+import { isDubDomain } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -26,6 +26,14 @@ export const POST = withWorkspace(
linkId: params.linkId,
});
+ if (!isDubDomain(link.domain)) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "You can only transfer Dub default domain links to another workspace.",
+ });
+ }
+
if (link.folderId) {
await verifyFolderAccess({
workspace,
@@ -37,6 +45,13 @@ export const POST = withWorkspace(
const { newWorkspaceId } = transferLinkBodySchema.parse(await req.json());
+ if (newWorkspaceId === workspace.id) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "You cannot transfer a link to the same workspace.",
+ });
+ }
+
const newWorkspace = await prisma.project.findUnique({
where: { id: newWorkspaceId },
select: {
@@ -67,24 +82,24 @@ export const POST = withWorkspace(
});
}
- const { clicks: linkClicks } = await getAnalytics({
- event: "clicks",
- groupBy: "count",
- linkId: link.id,
- interval: "30d",
- });
-
const updatedLink = await prisma.link.update({
where: {
id: link.id,
},
data: {
projectId: newWorkspaceId,
- // remove tags when transferring link
+ // reset all stats, tags, and folder when transferring link
+ clicks: 0,
+ leads: 0,
+ sales: 0,
+ saleAmount: 0,
+ conversions: 0,
+ lastClicked: null,
+ lastLeadAt: null,
+ lastConversionAt: null,
tags: {
deleteMany: {},
},
- // remove folder when transferring link
folderId: null,
},
});
@@ -95,21 +110,6 @@ export const POST = withWorkspace(
recordLink(updatedLink),
- // increment new workspace usage
- prisma.project.update({
- where: {
- id: newWorkspaceId,
- },
- data: {
- usage: {
- increment: linkClicks,
- },
- linksUsage: {
- increment: 1,
- },
- },
- }),
-
// Remove the webhooks associated with the link
prisma.linkWebhook.deleteMany({
where: {
diff --git a/apps/web/ui/modals/send-test-webhook-modal.tsx b/apps/web/ui/modals/send-test-webhook-modal.tsx
index 60183ee914..cbc259b715 100644
--- a/apps/web/ui/modals/send-test-webhook-modal.tsx
+++ b/apps/web/ui/modals/send-test-webhook-modal.tsx
@@ -2,13 +2,7 @@ import { sendTestWebhookEvent } from "@/lib/actions/send-test-webhook";
import useWorkspace from "@/lib/swr/use-workspace";
import { WebhookProps, WebhookTrigger } from "@/lib/types";
import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "@/lib/webhook/constants";
-import {
- Button,
- InputSelect,
- InputSelectItemProps,
- Logo,
- Modal,
-} from "@dub/ui";
+import { Button, Combobox, ComboboxOption, Modal } from "@dub/ui";
import { useAction } from "next-safe-action/hooks";
import {
Dispatch,
@@ -29,8 +23,9 @@ function SendTestWebhookModal({
webhook: WebhookProps | undefined;
}) {
const workspace = useWorkspace();
- const [selectedTrigger, setSelectedTrigger] =
- useState<InputSelectItemProps | null>(null);
+ const [selectedTrigger, setSelectedTrigger] = useState<ComboboxOption | null>(
+ null,
+ );
const { execute, isPending } = useAction(sendTestWebhookEvent, {
onSuccess: () => {
@@ -44,8 +39,8 @@ function SendTestWebhookModal({
const triggers = Object.entries(WEBHOOK_TRIGGER_DESCRIPTIONS).map(
([key, value]) => ({
- id: key,
- value: value,
+ value: key,
+ label: value,
}),
);
@@ -54,12 +49,10 @@ function SendTestWebhookModal({
showModal={showSendTestWebhookModal}
setShowModal={setShowSendTestWebhookModal}
>
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-4 pt-8 text-center sm:px-16">
- <Logo />
- <h3 className="text-lg font-medium">Send test webhook event</h3>
- <p className="text-center text-sm text-neutral-500">
- Choose a webhook event to send to your receiver endpoint
- </p>
+ <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">
+ Send test webhook event
+ </h3>
</div>
<form
onSubmit={async (e) => {
@@ -72,23 +65,39 @@ function SendTestWebhookModal({
execute({
workspaceId: workspace.id!,
webhookId: webhook.id,
- trigger: selectedTrigger?.id as WebhookTrigger,
+ trigger: selectedTrigger?.value as WebhookTrigger,
});
}}
>
- <div className="flex flex-col space-y-28 bg-neutral-50 px-4 py-8 text-left sm:space-y-3 sm:rounded-b-2xl sm:px-16">
- <InputSelect
- items={triggers}
- selectedItem={selectedTrigger}
- setSelectedItem={setSelectedTrigger}
- inputAttrs={{
- placeholder: "Select a webhook event",
- }}
+ <div className="bg-neutral-50 p-4 sm:p-6">
+ <p className="text-sm text-neutral-800">
+ Choose a webhook event to send to your receiver endpoint
+ </p>
+
+ <div className="mt-4">
+ <Combobox
+ options={triggers}
+ selected={selectedTrigger}
+ setSelected={setSelectedTrigger}
+ placeholder="Select a webhook event"
+ matchTriggerWidth
+ caret
+ />
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
+ <Button
+ onClick={() => setShowSendTestWebhookModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
/>
<Button
disabled={!selectedTrigger}
text="Send test webhook"
loading={isPending}
+ className="h-8 w-fit px-3"
/>
</div>
</form>
diff --git a/apps/web/ui/modals/transfer-domain-modal.tsx b/apps/web/ui/modals/transfer-domain-modal.tsx
index a31f88a958..12a9be6812 100644
--- a/apps/web/ui/modals/transfer-domain-modal.tsx
+++ b/apps/web/ui/modals/transfer-domain-modal.tsx
@@ -2,14 +2,7 @@ import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
import useWorkspaces from "@/lib/swr/use-workspaces";
import { DomainProps } from "@/lib/types";
-import {
- Button,
- InputSelect,
- InputSelectItemProps,
- LinkLogo,
- Modal,
-} from "@dub/ui";
-import { APP_NAME, OG_AVATAR_URL } from "@dub/utils";
+import { Button, Globe, Modal, useMediaQuery } from "@dub/ui";
import {
Dispatch,
SetStateAction,
@@ -18,27 +11,54 @@ import {
useState,
} from "react";
import { toast } from "sonner";
+import { WorkspaceSelector } from "../workspaces/workspace-selector";
-function TransferDomainModal({
- showTransferDomainModal,
- setShowTransferDomainModal,
- props,
-}: {
+type TransferDomainModalProps = {
showTransferDomainModal: boolean;
setShowTransferDomainModal: Dispatch<SetStateAction<boolean>>;
props: DomainProps;
-}) {
- const { slug: domain } = props;
+ onSuccess?: () => void;
+};
- const currentWorkspace = useWorkspace();
- const { workspaces } = useWorkspaces();
+function TransferDomainModal(props: TransferDomainModalProps) {
+ return (
+ <Modal
+ showModal={props.showTransferDomainModal}
+ setShowModal={props.setShowTransferDomainModal}
+ >
+ <TransferDomainModalInner {...props} />
+ </Modal>
+ );
+}
+
+function TransferDomainModalInner({
+ setShowTransferDomainModal,
+ props,
+ onSuccess,
+}: TransferDomainModalProps) {
+ const { slug: domain } = props;
+ const { id: currentWorkspaceId } = useWorkspace();
const [transferring, setTransferring] = useState(false);
- const [selectedWorkspace, setSelectedWorkspace] =
- useState<InputSelectItemProps | null>(null);
+ const { workspaces } = useWorkspaces();
+ const [selectedWorkspace, setSelectedWorkspace] = useState<string | null>(
+ null,
+ );
+ const [verificationText, setVerificationText] = useState("");
+
+ const { isMobile } = useMediaQuery();
+
+ const transferDomain = async (domain: string, selectedWorkspace: string) => {
+ setTransferring(true);
+ const newWorkspaceId = workspaces?.find(
+ (workspace) => workspace.slug === selectedWorkspace,
+ )?.id;
+ if (!newWorkspaceId) {
+ toast.error("New workspace not found.");
+ return;
+ }
- const transferDomain = async (domain: string, newWorkspaceId: string) => {
return await fetch(
- `/api/domains/${domain}/transfer?workspaceId=${currentWorkspace.id}`,
+ `/api/domains/${domain}/transfer?workspaceId=${currentWorkspaceId}`,
{
method: "POST",
headers: {
@@ -50,69 +70,113 @@ function TransferDomainModal({
if (res.ok) {
mutatePrefix("/api/domains");
setShowTransferDomainModal(false);
- return true;
+ onSuccess?.();
} else {
- setTransferring(false);
const { error } = await res.json();
- throw new Error(error.message);
+ toast.error(error.message || "Failed to transfer domain.");
}
+
+ setTransferring(false);
});
};
return (
- <Modal
- showModal={showTransferDomainModal}
- setShowModal={setShowTransferDomainModal}
- >
+ <>
+ <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">Transfer domain</h3>
+ </div>
+
+ <div className="bg-neutral-50 p-4 sm:p-6">
+ <p className="text-sm text-neutral-800">
+ Are you sure you want to transfer this domain?
+ </p>
+
+ <p className="mt-4 text-sm font-medium text-neutral-800">
+ Transferring a domain will fully reset the stats for all associated
+ links and is irreversible – please proceed with caution.
+ </p>
+
+ <div className="scrollbar-hide mt-4 flex max-h-[190px] flex-col gap-2 overflow-y-auto rounded-2xl border border-neutral-200 p-2">
+ <div className="flex items-center space-x-2 rounded-lg bg-white p-3">
+ <div className="flex h-8 w-8 items-center justify-center rounded-full bg-neutral-100">
+ <Globe className="size-4 rounded-full" />
+ </div>
+ <div className="flex-1">
+ <p className="text-sm font-medium text-neutral-900">{domain}</p>
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-4">
+ <WorkspaceSelector
+ selectedWorkspace={selectedWorkspace || ""}
+ setSelectedWorkspace={setSelectedWorkspace}
+ />
+ </div>
+ </div>
+
<form
onSubmit={async (e) => {
e.preventDefault();
if (selectedWorkspace) {
- setTransferring(true);
- toast.promise(transferDomain(domain, selectedWorkspace.id), {
- loading: `Transferring ${domain}...`,
- success:
- "Domain transfer initiated. We'll send you an email once it's complete.",
- error: (message) => message || "Failed to transfer domain.",
- });
+ await transferDomain(domain, selectedWorkspace);
}
}}
+ className="flex flex-col bg-neutral-50 text-left"
>
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-4 pt-8 text-center sm:px-16">
- <LinkLogo apexDomain={domain} />
- <h3 className="text-lg font-medium">Transfer {domain}</h3>
- <p className="text-sm text-neutral-500">
- Transfer this domain and its links to another {APP_NAME} workspace.
- Link tags will not be transferred.
- </p>
+ <div className="px-4 sm:px-6">
+ <label
+ htmlFor="verification"
+ className="block text-sm text-neutral-700"
+ >
+ To verify, type{" "}
+ <span className="font-semibold">confirm transfer domain</span> below
+ </label>
+ <div className="relative mt-1.5 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="verification"
+ id="verification"
+ pattern="confirm transfer domain"
+ required
+ autoFocus={!isMobile}
+ autoComplete="off"
+ value={verificationText}
+ onChange={(e) => setVerificationText(e.target.value)}
+ className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ />
+ </div>
</div>
- <div className="flex flex-col space-y-28 bg-neutral-50 px-4 py-8 text-left sm:space-y-3 sm:rounded-b-2xl sm:px-16">
- <InputSelect
- items={(workspaces || []).map((workspace) => ({
- id: workspace.id,
- value: workspace.name,
- image: workspace.logo || `${OG_AVATAR_URL}${workspace.name}`,
- disabled: workspace.id === currentWorkspace.id,
- label: workspace.id === currentWorkspace.id ? "Current" : "",
- }))}
- selectedItem={selectedWorkspace}
- setSelectedItem={setSelectedWorkspace}
- inputAttrs={{
- placeholder: "Select a workspace",
- }}
+
+ <div className="mt-8 flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
+ <Button
+ onClick={() => setShowTransferDomainModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
/>
<Button
- disabled={!selectedWorkspace}
+ disabled={
+ !selectedWorkspace ||
+ verificationText !== "confirm transfer domain"
+ }
loading={transferring}
- text="Confirm transfer"
+ text="Transfer domain"
+ className="h-8 w-fit px-3"
/>
</div>
</form>
- </Modal>
+ </>
);
}
-export function useTransferDomainModal({ props }: { props: DomainProps }) {
+export function useTransferDomainModal({
+ props,
+ onSuccess,
+}: {
+ props: DomainProps;
+ onSuccess?: () => void;
+}) {
const [showTransferDomainModal, setShowTransferDomainModal] = useState(false);
const TransferDomainModalCallback = useCallback(() => {
@@ -121,6 +185,7 @@ export function useTransferDomainModal({ props }: { props: DomainProps }) {
showTransferDomainModal={showTransferDomainModal}
setShowTransferDomainModal={setShowTransferDomainModal}
props={props}
+ onSuccess={onSuccess}
/>
) : null;
}, [showTransferDomainModal, setShowTransferDomainModal]);
diff --git a/apps/web/ui/modals/transfer-link-modal.tsx b/apps/web/ui/modals/transfer-link-modal.tsx
index 7f32ab06bb..ea4aa87986 100644
--- a/apps/web/ui/modals/transfer-link-modal.tsx
+++ b/apps/web/ui/modals/transfer-link-modal.tsx
@@ -1,22 +1,8 @@
-import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
import useWorkspaces from "@/lib/swr/use-workspaces";
import { LinkProps } from "@/lib/types";
-import {
- Button,
- InputSelect,
- InputSelectItemProps,
- LinkLogo,
- Modal,
-} from "@dub/ui";
-import {
- APP_NAME,
- OG_AVATAR_URL,
- getApexDomain,
- isDubDomain,
- linkConstructor,
-} from "@dub/utils";
+import { Button, Modal, useMediaQuery } from "@dub/ui";
import {
Dispatch,
SetStateAction,
@@ -25,6 +11,8 @@ import {
useState,
} from "react";
import { toast } from "sonner";
+import { SimpleLinkCard } from "../links/simple-link-card";
+import { WorkspaceSelector } from "../workspaces/workspace-selector";
type TransferLinkModalProps = {
showTransferLinkModal: boolean;
@@ -38,7 +26,6 @@ function TransferLinkModal(props: TransferLinkModalProps) {
<Modal
showModal={props.showTransferLinkModal}
setShowModal={props.setShowTransferLinkModal}
- className="overflow-y-visible"
>
<TransferLinkModalInner {...props} />
</Modal>
@@ -50,96 +37,128 @@ function TransferLinkModalInner({
props,
onSuccess,
}: TransferLinkModalProps) {
- const { id } = useWorkspace();
- const { workspaces } = useWorkspaces();
+ const { id: currentWorkspaceId } = useWorkspace();
const [transferring, setTransferring] = useState(false);
- const [selectedWorkspace, setSelectedWorkspace] =
- useState<InputSelectItemProps | null>(null);
+ const { workspaces } = useWorkspaces();
+ const [selectedWorkspace, setSelectedWorkspace] = useState<string | null>(
+ null,
+ );
+ const [verificationText, setVerificationText] = useState("");
- const apexDomain = getApexDomain(props.url);
- const { key, domain } = props;
+ const { isMobile } = useMediaQuery();
- const shortlink = useMemo(() => {
- return linkConstructor({
- key,
- domain,
- pretty: true,
- });
- }, [key, domain]);
+ const transferLink = async (linkId: string, selectedWorkspace: string) => {
+ setTransferring(true);
+ const newWorkspaceId = workspaces?.find(
+ (workspace) => workspace.slug === selectedWorkspace,
+ )?.id;
+ if (!newWorkspaceId) {
+ toast.error("New workspace not found.");
+ return;
+ }
- const transferLink = async (linkId: string, newWorkspaceId: string) => {
- return await fetch(`/api/links/${linkId}/transfer?workspaceId=${id}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
+ return await fetch(
+ `/api/links/${linkId}/transfer?workspaceId=${currentWorkspaceId}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ newWorkspaceId }),
},
- body: JSON.stringify({ newWorkspaceId }),
- }).then(async (res) => {
+ ).then(async (res) => {
if (res.ok) {
mutatePrefix("/api/links");
setShowTransferLinkModal(false);
onSuccess?.();
- return true;
} else {
- const error = await res.json();
- throw new Error(error.message);
+ const { error } = await res.json();
+ toast.error(error.message || "Failed to transfer link.");
}
+
+ setTransferring(false);
});
};
return (
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- if (selectedWorkspace) {
- setTransferring(true);
- toast.promise(transferLink(props.id, selectedWorkspace.id), {
- loading: "Transferring link...",
- success: "Successfully transferred link.",
- error: "Failed to transfer link.",
- });
- }
- }}
- >
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-4 pt-8 text-center sm:px-16">
- <LinkLogo apexDomain={apexDomain} />
- <h3 className="text-lg font-medium">Transfer {shortlink}</h3>
- <p className="text-sm text-neutral-500">
- Transfer this link and its analytics to another {APP_NAME} workspace.
- Link tags will not be transferred.
+ <>
+ <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">Transfer link</h3>
+ </div>
+
+ <div className="bg-neutral-50 p-4 sm:p-6">
+ <p className="text-sm text-neutral-800">
+ Are you sure you want to transfer this link?
+ </p>
+
+ <p className="mt-4 text-sm font-medium text-neutral-800">
+ Transferring a link will fully reset its stats and is irreversible –
+ please proceed with caution.
</p>
+
+ <div className="scrollbar-hide mt-4 flex max-h-[190px] flex-col gap-2 overflow-y-auto rounded-2xl border border-neutral-200 p-2">
+ <SimpleLinkCard link={props} />
+ </div>
+
+ <div className="mt-4">
+ <WorkspaceSelector
+ selectedWorkspace={selectedWorkspace || ""}
+ setSelectedWorkspace={setSelectedWorkspace}
+ />
+ </div>
</div>
- <div className="flex flex-col space-y-28 bg-neutral-50 px-4 py-8 text-left sm:space-y-3 sm:rounded-b-2xl sm:px-16">
- <InputSelect
- items={
- workspaces
- ? workspaces.map((workspace) => ({
- id: workspace.id,
- value: workspace.name,
- image: workspace.logo || `${OG_AVATAR_URL}${workspace.name}`,
- disabled:
- normalizeWorkspaceId(workspace.id) === props.projectId,
- label:
- normalizeWorkspaceId(workspace.id) === props.projectId
- ? "Current"
- : "",
- }))
- : []
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (selectedWorkspace) {
+ await transferLink(props.id, selectedWorkspace);
}
- selectedItem={selectedWorkspace}
- setSelectedItem={setSelectedWorkspace}
- inputAttrs={{
- placeholder: "Select a workspace",
- }}
- />
- <Button
- disabled={!selectedWorkspace || !isDubDomain(domain)}
- loading={transferring}
- text="Confirm transfer"
- />
- </div>
- </form>
+ }}
+ className="flex flex-col bg-neutral-50 text-left"
+ >
+ <div className="px-4 sm:px-6">
+ <label
+ htmlFor="verification"
+ className="block text-sm text-neutral-700"
+ >
+ To verify, type{" "}
+ <span className="font-semibold">confirm transfer link</span> below
+ </label>
+ <div className="relative mt-1.5 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="verification"
+ id="verification"
+ pattern="confirm transfer link"
+ required
+ autoFocus={!isMobile}
+ autoComplete="off"
+ value={verificationText}
+ onChange={(e) => setVerificationText(e.target.value)}
+ className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ />
+ </div>
+ </div>
+
+ <div className="mt-8 flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
+ <Button
+ onClick={() => setShowTransferLinkModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ />
+ <Button
+ disabled={
+ !selectedWorkspace || verificationText !== "confirm transfer link"
+ }
+ loading={transferring}
+ text="Transfer link"
+ className="h-8 w-fit px-3"
+ />
+ </div>
+ </form>
+ </>
);
}
diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsx
index 089bd801fd..43e26d1743 100644
--- a/packages/ui/src/index.tsx
+++ b/packages/ui/src/index.tsx
@@ -21,7 +21,6 @@ export * from "./filter";
export * from "./form";
export * from "./grid";
export * from "./input";
-export * from "./input-select";
export * from "./label";
export * from "./menu-item";
export * from "./mini-area-chart";
diff --git a/packages/ui/src/input-select.tsx b/packages/ui/src/input-select.tsx
deleted file mode 100644
index 0acb5ee153..0000000000
--- a/packages/ui/src/input-select.tsx
+++ /dev/null
@@ -1,454 +0,0 @@
-import { cn } from "@dub/utils";
-import {
- flip,
- offset,
- size,
- useDismiss,
- useFloating,
- useInteractions,
-} from "@floating-ui/react";
-import { Command, useCommandState } from "cmdk";
-import { Check, ChevronDown, Search, X } from "lucide-react";
-import {
- Dispatch,
- HTMLAttributes,
- InputHTMLAttributes,
- ReactNode,
- SetStateAction,
- createContext,
- forwardRef,
- useContext,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { Drawer } from "vaul";
-import { Badge } from "./badge";
-import { BlurImage } from "./blur-image";
-import { useMediaQuery } from "./hooks";
-import { useScrollProgress } from "./hooks/use-scroll-progress";
-
-const InputSelectContext = createContext<{
- inputAttrs: InputHTMLAttributes<HTMLInputElement>;
- openCommandList: boolean;
- setOpenCommandList: Dispatch<SetStateAction<boolean>>;
- inputValue: string;
- setInputValue: Dispatch<SetStateAction<string>>;
- disabled: boolean;
- selectedItem: InputSelectItemProps | null;
- setSelectedItem: Dispatch<SetStateAction<InputSelectItemProps | null>>;
-}>({
- inputAttrs: {},
- openCommandList: false,
- setOpenCommandList: () => {},
- inputValue: "",
- setInputValue: () => {},
- disabled: false,
- selectedItem: null,
- setSelectedItem: () => {},
-});
-
-export interface InputSelectItemProps {
- id: string;
- value: string;
- color?: string;
- icon?: ReactNode;
- image?: string;
- disabled?: boolean;
- label?: string;
-}
-
-export function InputSelect({
- items,
- selectedItem,
- setSelectedItem,
- className,
- disabled,
- adjustForMobile,
- icon,
- inputAttrs,
- noItemsElement,
-}: {
- items: InputSelectItemProps[] | [];
- selectedItem: InputSelectItemProps | null;
- setSelectedItem: Dispatch<SetStateAction<InputSelectItemProps | null>>;
- className?: string;
- disabled?: boolean;
- adjustForMobile?: boolean;
- icon?: ReactNode;
- inputAttrs?: InputHTMLAttributes<HTMLInputElement>;
- noItemsElement?: ReactNode;
-}) {
- const { isMobile } = useMediaQuery();
-
- const commandRef = useRef<HTMLDivElement | null>(null);
- const [openCommandList, setOpenCommandList] = useState(false);
- const [inputValue, setInputValue] = useState("");
-
- // Whether the input has changed since opening
- const [inputChanged, setInputChanged] = useState(false);
-
- useEffect(() => {
- // Reset inputChanged when the command list is opened
- if (openCommandList) setInputChanged(false);
- }, [openCommandList]);
-
- useEffect(() => setInputChanged(true), [inputValue]);
-
- useEffect(() => {
- if (selectedItem) setInputValue(selectedItem.value);
- }, [selectedItem]);
-
- const filteredItems = useMemo(() => {
- const search = inputValue.toLowerCase();
-
- return inputChanged
- ? // Filter the items
- items.filter((item: InputSelectItemProps) =>
- item.value.toLowerCase().includes(search),
- )
- : inputValue
- ? // Just sort the items instead of filtering
- items.sort(
- (a: InputSelectItemProps, b: InputSelectItemProps) =>
- (b.value.toLowerCase().includes(search) ? 1 : 0) -
- (a.value.toLowerCase().includes(search) ? 1 : 0),
- )
- : items;
- }, [inputChanged, inputValue, items]);
-
- const {
- refs: floatingRefs,
- floatingStyles,
- context,
- } = useFloating({
- open: openCommandList,
- onOpenChange: setOpenCommandList,
- middleware: [
- offset(8),
- size({
- apply({ elements: { floating }, availableHeight }) {
- Object.assign(floating.style, {
- // Minimum height before 'flip' takes over is 112px
- maxHeight: `${Math.max(75, Math.min(availableHeight, 290))}px`,
- });
- },
- padding: 8,
- }),
- flip({
- fallbackStrategy: "initialPlacement",
- padding: 8,
- }),
- ],
- });
-
- const dismiss = useDismiss(context, {
- // useDismiss seems to break the mobile drawer for some reason
- enabled: !isMobile || !adjustForMobile,
- });
-
- const { getReferenceProps, getFloatingProps } = useInteractions([dismiss]);
-
- const scrollRef = useRef<HTMLDivElement>(null);
- const { scrollProgress, updateScrollProgress } = useScrollProgress(scrollRef);
-
- const iconElement = useMemo(() => {
- if (selectedItem && selectedItem.icon) return selectedItem.icon;
- if (selectedItem && selectedItem.image)
- return (
- <BlurImage
- src={selectedItem.image}
- alt={selectedItem.value}
- className="size-4 rounded-full"
- width={16}
- height={16}
- />
- );
- return icon || <Search className="size-4 text-neutral-400" />;
- }, [selectedItem, icon]);
-
- return (
- <InputSelectContext.Provider
- value={{
- inputAttrs: inputAttrs || {},
- openCommandList,
- setOpenCommandList,
- inputValue,
- setInputValue,
- disabled: Boolean(disabled),
- selectedItem,
- setSelectedItem,
- }}
- >
- {isMobile && adjustForMobile ? (
- // when adjustForMobile is true, render the input as a drawer
- <Drawer.Root open={openCommandList} onOpenChange={setOpenCommandList}>
- <Drawer.Trigger className="sm:hidden" asChild>
- <Command
- ref={commandRef}
- className="relative"
- shouldFilter={false}
- loop
- >
- <InputGroup className={className} iconElement={iconElement} />
- </Command>
- </Drawer.Trigger>
- <Drawer.Overlay className="fixed inset-0 z-40 bg-neutral-100 bg-opacity-10 backdrop-blur" />
- <Drawer.Portal>
- <Drawer.Content
- className="fixed bottom-0 left-0 right-0 z-50 mt-24 rounded-t-lg border-t border-neutral-200 bg-white"
- onPointerDownOutside={(e) => {
- // Prevent dismissal when clicking inside a toast
- if (
- e.target instanceof Element &&
- e.target.closest("[data-sonner-toast]")
- ) {
- e.preventDefault();
- }
- }}
- >
- <Command
- ref={commandRef}
- className="relative"
- shouldFilter={false}
- loop
- >
- <div className="p-2">
- <InputGroup className={className} iconElement={iconElement} />
- </div>
- {openCommandList && (
- <Command.List className="dub-scrollbar h-[70vh] overflow-y-auto p-2">
- {items.length === 0 &&
- inputValue === "" &&
- (noItemsElement ? (
- <div>{noItemsElement}</div>
- ) : (
- <p className="px-4 py-2 text-sm text-neutral-600">
- No items found.
- </p>
- ))}
- {inputValue !== "" && (
- <Command.Empty className="px-4 py-2 text-sm text-neutral-600">
- No results found.
- </Command.Empty>
- )}
- <SelectorList items={filteredItems} />
- </Command.List>
- )}
- </Command>
- </Drawer.Content>
- <Drawer.Overlay />
- </Drawer.Portal>
- </Drawer.Root>
- ) : (
- <Command
- ref={commandRef}
- className="relative"
- shouldFilter={false}
- loop
- >
- <InputGroup
- className={className}
- iconElement={iconElement}
- ref={floatingRefs.setReference}
- {...getReferenceProps()}
- />
- {openCommandList && (
- <div
- ref={floatingRefs.setFloating}
- style={floatingStyles}
- {...getFloatingProps()}
- className="z-20 flex w-full min-w-[160px] flex-col overflow-hidden rounded-md border border-neutral-200 bg-white shadow-md"
- >
- <div
- ref={scrollRef}
- onScroll={updateScrollProgress}
- className="grow overflow-y-auto p-2"
- >
- <Command.List>
- {items.length === 0 &&
- inputValue === "" &&
- (noItemsElement ? (
- <div>{noItemsElement}</div>
- ) : (
- <p className="px-4 py-2 text-sm text-neutral-600">
- No items found.
- </p>
- ))}
- {inputValue !== "" && (
- <Command.Empty className="px-4 py-2 text-sm text-neutral-600">
- No results found.
- </Command.Empty>
- )}
- </Command.List>
- <SelectorList items={filteredItems} />
- </div>
-
- {/* Bottom scroll fade */}
- <div
- className="pointer-events-none absolute bottom-0 left-0 hidden h-16 w-full bg-gradient-to-t from-white sm:block"
- style={{ opacity: 1 - Math.pow(scrollProgress, 2) }}
- />
- </div>
- )}
- </Command>
- )}
- </InputSelectContext.Provider>
- );
-}
-
-type InputGroupProps = {
- iconElement: ReactNode;
-} & HTMLAttributes<HTMLLabelElement>;
-
-const InputGroup = forwardRef<HTMLLabelElement, InputGroupProps>(
- ({ iconElement, className, ...rest }: InputGroupProps, ref) => {
- return (
- <label
- ref={ref}
- className={cn(
- "group relative flex cursor-pointer gap-2 rounded-md border border-neutral-200 bg-white px-1 pl-3 transition-all focus-within:border-neutral-500 focus-within:ring-4 focus-within:ring-neutral-200",
- className,
- )}
- {...rest}
- >
- <div className="flex shrink-0 items-center justify-center text-neutral-400">
- {iconElement}
- </div>
- <div className="flex h-10 grow">
- <CommandInput />
- <CloseChevron />
- </div>
- </label>
- );
- },
-);
-
-const CommandInput = forwardRef<HTMLInputElement>((_, ref) => {
- const isEmpty = useCommandState((state: any) => state.filtered.count === 0);
-
- const {
- inputAttrs,
- openCommandList,
- setOpenCommandList,
- inputValue,
- setInputValue,
- disabled,
- } = useContext(InputSelectContext);
-
- return (
- <Command.Input
- ref={ref}
- placeholder={inputAttrs?.placeholder || "Search..."}
- // hacky focus on the input when the dropdown opens
- autoFocus={openCommandList}
- onFocus={() => setOpenCommandList(true)}
- value={inputValue}
- onValueChange={setInputValue}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- e.preventDefault();
- setOpenCommandList(false);
- // listen for cases where empty results and enter is pressed
- } else if (e.key === "Enter" && isEmpty) {
- setOpenCommandList(false);
- // if it's a letter or a number and there's no meta key pressed, openCommandList dropdown
- } else if (e.key.match(/^[a-z0-9]$/i) && !e.metaKey) {
- setOpenCommandList(true);
- }
- }}
- disabled={disabled}
- className="block w-full truncate rounded-md border-none px-0 text-base text-neutral-900 placeholder-neutral-400 outline-none outline-0 transition-all duration-300 focus:ring-0 md:text-sm"
- autoCapitalize="none"
- />
- );
-});
-
-function CloseChevron() {
- const {
- setSelectedItem,
- openCommandList,
- setOpenCommandList,
- inputValue,
- setInputValue,
- } = useContext(InputSelectContext);
-
- return (
- <button
- type="button"
- onClick={() => {
- setOpenCommandList((prev) => !prev);
- setSelectedItem(null);
- setInputValue("");
- }}
- className="absolute inset-y-0 right-0 my-auto pr-3"
- >
- {inputValue.length > 0 ? (
- <X className="size-4 text-neutral-400 transition-all hover:text-neutral-700" />
- ) : (
- <ChevronDown
- className={cn(
- "size-4 text-neutral-400 transition-all hover:text-neutral-700",
- {
- "rotate-180 transform": openCommandList,
- },
- )}
- />
- )}
- </button>
- );
-}
-
-function SelectorList({ items }: { items: InputSelectItemProps[] }) {
- const { setSelectedItem, setOpenCommandList, setInputValue } =
- useContext(InputSelectContext);
-
- return items.map((item) => (
- <Command.Item
- key={item.id}
- value={item.value}
- disabled={item.disabled}
- onSelect={() => {
- setSelectedItem(item);
- setInputValue(item.value);
- setOpenCommandList(false);
- }}
- className="group flex cursor-pointer items-center justify-between rounded-md px-4 py-2 text-sm text-neutral-900 hover:bg-neutral-100 hover:text-neutral-900 active:bg-neutral-200 aria-disabled:cursor-not-allowed aria-disabled:opacity-75 aria-disabled:hover:bg-white aria-selected:bg-neutral-100 aria-selected:text-neutral-900"
- >
- <div className="flex items-center space-x-2">
- {item.icon ||
- (item.image && (
- <BlurImage
- src={item.image}
- alt={item.value}
- className="size-4 rounded-full"
- width={16}
- height={16}
- />
- ))}
- <p
- className={cn(
- "whitespace-nowrap py-0.5 text-sm",
- item.color && "rounded-md px-2",
- item.color === "red" && "bg-red-100 text-red-600",
- item.color === "yellow" && "bg-yellow-100 text-yellow-600",
- item.color === "green" && "bg-green-100 text-green-600",
- item.color === "blue" && "bg-blue-100 text-blue-600",
- item.color === "purple" && "bg-purple-100 text-purple-600",
- item.color === "brown" && "bg-brown-100 text-brown-600",
- )}
- >
- {item.value}
- </p>
- {item.label && (
- <Badge className="text-xs" variant="neutral">
- {item.label}
- </Badge>
- )}
- </div>
-
- <Check className="invisible h-5 w-5 text-neutral-500 aria-selected:visible" />
- </Command.Item>
- ));
-}