Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

17.7 KB
Raw Blame
"use client";

import { Button, Input, LogoBadge } from "@cap/ui";
import {
	faArrowLeft,
	faEnvelope,
	faExclamationCircle,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { captureException } from "@sentry/nextjs";
import { AnimatePresence, motion } from "framer-motion";
import Cookies from "js-cookie";
import { LucideArrowUpRight } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";
import {
	Suspense,
	useCallback,
	useEffect,
	useId,
	useRef,
	useState,
	useTransition,
} from "react";
import { toast } from "sonner";
import { getOrganizationSSOData } from "@/actions/organization/get-organization-sso-data";
import { trackEvent } from "@/app/utils/analytics";
import { usePublicEnv } from "@/utils/public-env";
import { getEmailCodeCooldownSeconds, requestEmailCode } from "../auth-email";
import {
	clearOnboardingNextPath,
	rememberOnboardingNextPath,
} from "../onboarding-next";
import { getSafeNextPath } from "../safe-next";
import { SsoErrorNotice } from "../sso-error-notice";

const MotionInput = motion(Input);
const MotionLogoBadge = motion(LogoBadge);
const MotionLink = motion(Link);
const MotionButton = motion(Button);

export function SignupForm() {
	const searchParams = useSearchParams();
	const router = useRouter();
	const next = searchParams?.get("next");
	const [email, setEmail] = useState("");
	const [loading, setLoading] = useState(false);
	const [emailSent, setEmailSent] = useState(false);
	const [oauthError, setOauthError] = useState(false);
	const [showOrgInput, setShowOrgInput] = useState(
		Boolean(
			searchParams?.get("organizationId") ||
				searchParams?.get("connection_id") ||
				searchParams?.get("error") === "SsoMissingProfileAttributes" ||
				searchParams?.get("sso") === "1",
		),
	);
	const [ssoIdentifier, setSsoIdentifier] = useState("");
	const [ssoLoading, startSsoTransition] = useTransition();
	const [organizationName, setOrganizationName] = useState<string | null>(null);
	const [lastEmailSentTime, setLastEmailSentTime] = useState<number | null>(
		null,
	);
	const workosSignInStarted = useRef(false);
	const workosSignInPending = useRef(false);
	const signupFormMounted = useRef(false);
	const theme = Cookies.get("theme") || "light";
	const getNextPath = useCallback(
		() => (next ? getSafeNextPath(next, window.location.origin) : null),
		[next],
	);

	useEffect(() => {
		const nextPath = getNextPath();
		if (nextPath) rememberOnboardingNextPath(nextPath);
		else clearOnboardingNextPath();
	}, [getNextPath]);

	useEffect(() => {
		signupFormMounted.current = true;
		return () => {
			signupFormMounted.current = false;
		};
	}, []);

	useEffect(() => {
		document.body.className = theme === "dark" ? "dark" : "light";
		return () => {
			document.body.className = "light";
		};
	}, [theme]);

	useEffect(() => {
		const error = searchParams?.get("error");

		const handleErrors = () => {
			if (error === "OAuthAccountNotLinked") {
				setOauthError(true);
				return toast.error(
					"This email already has a Cap account. Sign in using your original sign-in method.",
				);
			} else if (error === "SsoMissingProfileAttributes") {
				setShowOrgInput(true);
				return;
			} else if (error === "SignupBlocked") {
				return;
			} else if (error === "SsoSessionExpired") {
				setShowOrgInput(true);
				return toast.error(
					"Your SSO sign-in session expired. Enter your work email or domain to start again.",
				);
			} else if (error === "SsoSignInFailed") {
				setShowOrgInput(true);
				return toast.error(
					"SSO sign-in could not be completed. Start again with your work email or domain, or contact your organization's administrator.",
				);
			} else if (error === "profile_not_allowed_outside_organization") {
				return toast.error(
					"Your email domain is not authorized for SSO access. Please use your work email or contact your administrator.",
				);
			} else if (error === "signin_consent_denied") {
				return toast.error(
					"SSO sign-in was canceled. Only continue if you recognize your organization's identity provider.",
				);
			} else if (error) {
				return toast.error(
					"Sign-in could not be completed. Please try again, or contact your organization's administrator if you use SSO.",
				);
			}
		};
		handleErrors();
	}, [searchParams]);

	useEffect(() => {
		const pendingPriceId = localStorage.getItem("pendingPriceId");
		const pendingQuantity = localStorage.getItem("pendingQuantity") ?? "1";
		if (emailSent && pendingPriceId) {
			localStorage.removeItem("pendingPriceId");
			localStorage.removeItem("pendingQuantity");

			// Wait a bit to ensure the user is created
			setTimeout(async () => {
				const response = await fetch(`/api/settings/billing/subscribe`, {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
					},
					body: JSON.stringify({
						priceId: pendingPriceId,
						quantity: parseInt(pendingQuantity, 10),
					}),
				});
				const data = await response.json();

				if (data.url) {
					window.location.href = data.url;
				}
			}, 2000);
		}
	}, [emailSent]);

	const handleGoogleSignIn = () => {
		const nextPath = getNextPath();
		trackEvent("auth_started", {
			method: "google",
			is_signup: true,
			auth_surface: "signup",
		});
		signIn("google", {
			...(nextPath ? { callbackUrl: nextPath } : {}),
		}).catch((error) => {
			captureException(error, {
				tags: { auth_provider: "google", auth_surface: "signup" },
			});
			toast.error(
				"Could not start sign-in. Check your connection and try again.",
			);
		});
	};

	const handleWorkosSignIn = useCallback(
		(identifier: string, connectionId?: string) => {
			if (workosSignInPending.current) return;
			workosSignInPending.current = true;
			setOrganizationName(null);

			startSsoTransition(async () => {
				try {
					const data = await getOrganizationSSOData(
						identifier,
						connectionId,
						getNextPath() ?? "/dashboard",
					);
					if (!signupFormMounted.current) return;
					setOrganizationName(data.name);
					trackEvent("auth_started", {
						method: "workos",
						is_signup: true,
						auth_surface: "signup",
					});
					await signIn(
						"workos",
						{ callbackUrl: getNextPath() ?? "/dashboard" },
						{
							connection: data.connectionId,
						},
					);
				} catch {
					if (!signupFormMounted.current) return;
					setOrganizationName(null);
					setSsoIdentifier(identifier);
					setShowOrgInput(true);
					toast.error(
						"SSO is not available for this organization yet. Check your work email or domain, or contact your administrator.",
					);
				} finally {
					workosSignInPending.current = false;
				}
			});
		},
		[getNextPath],
	);

	useEffect(() => {
		if (searchParams?.get("error")) return;
		const organizationId = searchParams?.get("organizationId");
		const connectionId = searchParams?.get("connection_id");
		if (!organizationId && !connectionId) return;
		if (workosSignInStarted.current) return;
		workosSignInStarted.current = true;
		setShowOrgInput(true);
		setSsoIdentifier(organizationId ?? "");
		handleWorkosSignIn(organizationId ?? "", connectionId ?? undefined);
	}, [handleWorkosSignIn, searchParams]);

	const handleOrganizationLookup = (e: React.FormEvent) => {
		e.preventDefault();
		const identifier = ssoIdentifier.trim();
		if (!identifier) {
			toast.error("Enter your work email or domain.");
			return;
		}
		handleWorkosSignIn(identifier);
	};

	return (
		<motion.div
			layout
			transition={{
				layout: { duration: 0.3, ease: "easeInOut" },
				height: { duration: 0.3, ease: "easeInOut" },
			}}
			className="overflow-hidden relative w-[calc(100%-5%)] p-[28px] max-w-[432px] bg-gray-3 border border-gray-5 rounded-2xl"
		>
			<motion.button
				type="button"
				layout="position"
				key="back-button"
				initial={{ opacity: 0, display: "none" }}
				animate={{
					opacity: showOrgInput ? 1 : 0,
					display: showOrgInput ? "flex" : "none",
					transition: { duration: 0.1, delay: 0.2 },
				}}
				onClick={() => setShowOrgInput(false)}
				disabled={ssoLoading}
				className="absolute overflow-hidden top-5 rounded-full left-5 z-20 hover:bg-gray-1 gap-2 items-center py-1.5 px-3 text-gray-12 bg-transparent border border-gray-4 transition-colors duration-300 cursor-pointer"
			>
				<FontAwesomeIcon className="w-2" icon={faArrowLeft} />
				<motion.p layout="position" className="text-xs text-inherit">
					Back
				</motion.p>
			</motion.button>
			<MotionLink layout="position" className="flex mx-auto size-fit" href="/">
				<MotionLogoBadge layout="position" className="w-[72px] h-[72px]" />
			</MotionLink>
			<motion.div
				layout="position"
				className="flex flex-col justify-center items-center my-7 text-left"
			>
				<motion.h1
					key="title"
					layout="position"
					className="text-2xl font-semibold text-gray-12"
				>
					Sign up to Cap
				</motion.h1>
				<motion.p
					key="subtitle"
					layout="position"
					className="text-[16px] text-gray-10"
				>
					Beautiful screen recordings, owned by you.
				</motion.p>
			</motion.div>
			<motion.div layout="position" className="flex flex-col space-y-3">
				<SsoErrorNotice error={searchParams?.get("error")} />
				<Suspense
					fallback={
						<>
							<Button disabled={true} variant="primary" />
							<Button disabled={true} variant="destructive" />
							<div className="mx-auto w-3/4 h-5 rounded-lg bg-gray-1" />
						</>
					}
				>
					<motion.div layout className="flex flex-col space-y-3">
						<AnimatePresence mode="wait" initial={false}>
							<motion.div
								key={showOrgInput ? "sso-wrapper" : "email-wrapper"}
								layout
								initial={{ height: 0, opacity: 0 }}
								animate={{ height: "auto", opacity: 1 }}
								exit={{ height: 0, opacity: 0 }}
								transition={{
									duration: 0.25,
									ease: "easeInOut",
									opacity: { delay: 0.05 },
								}}
								className="px-1"
							>
								{showOrgInput ? (
									<motion.div
										key="sso"
										layout
										className="min-w-fit"
										initial={{ opacity: 0, y: 10 }}
										animate={{ opacity: 1, y: 0, transition: { delay: 0.1 } }}
										exit={{ opacity: 0, y: -10, transition: { duration: 0.1 } }}
										transition={{ duration: 0.2, ease: "easeInOut" }}
									>
										<SignupWithSSO
											handleOrganizationLookup={handleOrganizationLookup}
											identifier={ssoIdentifier}
											setIdentifier={setSsoIdentifier}
											organizationName={organizationName}
											loading={ssoLoading}
										/>
									</motion.div>
								) : (
									<motion.form
										key="email"
										layout
										initial={{ opacity: 0, y: 10 }}
										animate={{
											opacity: 1,
											y: 0,
											transition: { duration: 0.1 },
										}}
										exit={{
											opacity: 0,
											y: -10,
											transition: { duration: 0.15 },
										}}
										transition={{
											duration: 0.2,
											ease: "easeInOut",
											opacity: { delay: 0.05 },
										}}
										noValidate
										onSubmit={async (e) => {
											e.preventDefault();

											const remainingSeconds =
												getEmailCodeCooldownSeconds(lastEmailSentTime);
											if (remainingSeconds > 0) {
												toast.error(
													`Please wait ${remainingSeconds} seconds before requesting a new code.`,
												);
												return;
											}

											setLoading(true);
											try {
												const nextPath = getNextPath();
												const normalizedEmail = await requestEmailCode({
													email,
													next: nextPath,
													isSignup: true,
													authSurface: "signup",
												});
												if (!normalizedEmail) return;

												const sentAt = Date.now();
												setEmailSent(true);
												setLastEmailSentTime(sentAt);
												const params = new URLSearchParams({
													email: normalizedEmail,
													...(nextPath && { next: nextPath }),
													lastSent: sentAt.toString(),
												});
												router.push(`/verify-otp?${params.toString()}`);
											} catch {
												setEmailSent(false);
												toast.error(
													"Sign up is taking longer than expected. Check your connection or browser extensions, then try again.",
												);
											} finally {
												setLoading(false);
											}
										}}
										className="flex flex-col space-y-3"
									>
										<NormalSignup
											setShowOrgInput={setShowOrgInput}
											email={email}
											emailSent={emailSent}
											setEmail={setEmail}
											loading={loading}
											oauthError={oauthError}
											handleGoogleSignIn={handleGoogleSignIn}
										/>
									</motion.form>
								)}
							</motion.div>
						</AnimatePresence>
						<motion.p
							layout="position"
							className="pt-3 text-xs text-center text-gray-9"
						>
							Already have an account?{" "}
							<Link
								href="/login"
								className="text-xs font-semibold text-blue-9 hover:text-blue-8"
							>
								Log in here
							</Link>
						</motion.p>
						<motion.p
							layout="position"
							className="text-xs text-center text-gray-9"
						>
							By typing your email and clicking continue, you acknowledge that
							you have both read and agree to Cap's{" "}
							<Link
								href="/terms"
								target="_blank"
								className="text-xs font-semibold text-gray-12 hover:text-blue-300"
							>
								Terms of Service
							</Link>{" "}
							and{" "}
							<Link
								href="/privacy"
								target="_blank"
								className="text-xs font-semibold text-gray-12 hover:text-blue-300"
							>
								Privacy Policy
							</Link>
							.
						</motion.p>
					</motion.div>
				</Suspense>
			</motion.div>
		</motion.div>
	);
}

const SignupWithSSO = ({
	handleOrganizationLookup,
	identifier,
	setIdentifier,
	organizationName,
	loading,
}: {
	handleOrganizationLookup: (e: React.FormEvent) => void;
	identifier: string;
	setIdentifier: (identifier: string) => void;
	organizationName: string | null;
	loading: boolean;
}) => {
	const identifierInputId = useId();

	return (
		<motion.form
			layout
			onSubmit={handleOrganizationLookup}
			className="relative space-y-2"
		>
			<label htmlFor={identifierInputId} className="text-sm text-gray-12">
				Work email or domain
			</label>
			<MotionInput
				id={identifierInputId}
				name="organization"
				placeholder="[email protected] or company.com"
				autoComplete="username"
				autoCapitalize="none"
				autoCorrect="off"
				required
				value={identifier}
				disabled={loading}
				onChange={(e) => setIdentifier(e.target.value)}
				className="w-full max-w-full"
			/>
			<p className="text-xs leading-5 text-gray-10" aria-live="polite">
				{organizationName
					? `Signing in to ${organizationName}…`
					: "Your organization must have SSO set up before you can continue."}
			</p>
			<div>
				<Button
					type="submit"
					variant="dark"
					className="w-full max-w-full"
					disabled={loading}
					spinner={loading}
				>
					{loading ? "Connecting to SSO…" : "Continue with SSO"}
				</Button>
			</div>
		</motion.form>
	);
};

const NormalSignup = ({
	setShowOrgInput,
	email,
	emailSent,
	setEmail,
	loading,
	oauthError,
	handleGoogleSignIn,
}: {
	setShowOrgInput: (show: boolean) => void;
	email: string;
	emailSent: boolean;
	setEmail: (email: string) => void;
	loading: boolean;
	oauthError: boolean;
	handleGoogleSignIn: () => void;
}) => {
	const publicEnv = usePublicEnv();
	const emailInputId = useId();

	return (
		<motion.div>
			<motion.div layout className="flex flex-col space-y-3">
				<MotionInput
					id={emailInputId}
					name="email"
					autoFocus
					type="email"
					placeholder={emailSent ? "" : "[email protected]"}
					autoComplete="email"
					required
					value={email}
					disabled={emailSent || loading}
					onChange={(e) => {
						setEmail(e.target.value.toLowerCase());
					}}
				/>
				<MotionButton
					variant="dark"
					type="submit"
					disabled={loading || emailSent}
					spinner={loading}
					icon={
						loading ? undefined : (
							<FontAwesomeIcon className="mr-1 size-4" icon={faEnvelope} />
						)
					}
				>
					{loading ? "Sending code..." : "Sign up with email"}
				</MotionButton>
			</motion.div>
			{(publicEnv.googleAuthAvailable || publicEnv.workosAuthAvailable) && (
				<>
					<div className="flex gap-4 items-center my-4">
						<span className="flex-1 h-px bg-gray-5" />
						<p className="text-sm text-center text-gray-10">OR</p>
						<span className="flex-1 h-px bg-gray-5" />
					</div>
					<motion.div
						layout
						className="flex flex-col gap-3 justify-center items-center"
					>
						{!oauthError && (
							<MotionButton
								variant="gray"
								type="button"
								className="flex gap-2 justify-center items-center w-full text-sm"
								onClick={handleGoogleSignIn}
								disabled={loading}
							>
								<Image src="/google.svg" alt="Google" width={16} height={16} />
								Sign up with Google
							</MotionButton>
						)}

						{oauthError && (
							<div className="flex gap-3 items-center p-3 bg-red-400 rounded-xl border border-red-600">
								<FontAwesomeIcon
									className="text-gray-50 size-8"
									icon={faExclamationCircle}
								/>
								<p className="text-xs leading-5 text-gray-50">
									It looks like you've previously used this email to sign up via
									email. Please enter your email below to receive a sign up
									link.
								</p>
							</div>
						)}
						<MotionButton
							variant="gray"
							type="button"
							className="w-full"
							layout
							onClick={() => setShowOrgInput(true)}
							disabled={loading}
						>
							<LucideArrowUpRight size={20} />
							Sign up with SAML SSO
						</MotionButton>
					</motion.div>
				</>
			)}
		</motion.div>
	);
};