Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

9.5 KB
Raw Blame
import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { signInAnonymously } from "@editor/auth/supabase";
import { useAuth } from "@editor/auth/UseSession";
import { useTranslation } from "@editor/hooks/useTranslation";
import { useDocumentMeta } from "@editor/hooks/useDocumentMeta";
import { getBaseUrl, withBasePath } from "@editor/constants/app";
import { rememberPendingDestination } from "@editor/services/pendingDestination";
import { nextPathOf } from "@editor/routes/authShared/nextPath";
import { TEAM_PATH } from "@editor/routes/teamPath";
import AuthLayout from "@editor/routes/authShared/AuthLayout";
import "@editor/auth/ui/auth.css";
import "@editor/routes/authShared/saas-auth.css";
import { alert } from "@editor/components/toast";
import { Button } from "@editor/ui/Button";

// Import signup components
import ErrorMessage from "@editor/auth/ui/ErrorMessage";
import OAuthButtons from "@editor/routes/login/OAuthButtons";
import SignupForm from "@editor/routes/signup/SignupForm";
import {
  useSignupFormValidation,
  SignupFieldErrors,
} from "@editor/routes/signup/SignupFormValidation";
import { useAuthService } from "@editor/routes/signup/AuthService";
import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";

export default function Signup() {
  const navigate = useNavigate();
  const location = useLocation();
  const { session, loading, refreshSession } = useAuth();
  const { t } = useTranslation();
  const [isSigningUp, setIsSigningUp] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [name, setName] = useState(undefined as string | undefined);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [agree, setAgree] = useState(true);
  const [fieldErrors, setFieldErrors] = useState<SignupFieldErrors>({});
  const next = new URLSearchParams(location.search).get("next");
  // Skipping makes a guest, and a guest cannot buy Team.
  const buyingTeam = nextPathOf(next) === TEAM_PATH;

  // Stashed rather than threaded onward: Supabase builds the confirmation link and
  // it cannot carry a `next`.
  useEffect(() => {
    rememberPendingDestination(next);
  }, [next]);

  // Check if we were redirected here with an auto-auth error
  useEffect(() => {
    const state = location.state as { autoAuthError?: string } | null;
    if (state?.autoAuthError) {
      setError(
        t("signup.unableToAccessTool", "Unable to access tool: {{error}}", {
          error: state.autoAuthError,
        }),
      );
    }
  }, [location.state]);

  // Redirect back to original tool URL once session appears (after auto-anon completes)
  useEffect(() => {
    if (!loading && session) {
      const state = location.state as {
        from?: { pathname?: string; search?: string; hash?: string };
      } | null;
      const from = state?.from;
      if (
        from?.pathname &&
        from.pathname !== "/signup" &&
        from.pathname !== "/login"
      ) {
        const target = `${from.pathname}${from.search ?? ""}${from.hash ?? ""}`;
        console.log("[Signup] Session detected, redirecting back to:", target);
        navigate(target, { replace: true });
      }
    }
  }, [loading, session, location.state, navigate]);

  const handleAnonymousSignIn = async () => {
    try {
      setIsSigningUp(true);
      setError(null);

      console.log("[Signup] Initiating anonymous sign-in...");
      const { data } = await signInAnonymously();

      if (data.user) {
        console.log(
          "[Signup] Anonymous sign-in successful, refreshing session...",
        );

        // Refresh session to ensure backend endpoints are properly synchronized
        await refreshSession();

        console.log("[Signup] Session refreshed, redirecting to home page");
        // Redirect to home page after successful anonymous login and session refresh
        navigate("/");
      }
    } catch (err) {
      console.error("[Signup] Anonymous sign-in unexpected error:", err);
      setError(
        t("signup.unexpectedError", "Unexpected error: {{message}}", {
          message:
            err instanceof Error
              ? err.message
              : t("signup.unknownError", "Unknown error"),
        }),
      );
    } finally {
      setIsSigningUp(false);
    }
  };

  const baseUrl = getBaseUrl();

  useDocumentMeta({
    title: `${t("signup.title", "Create an account")} - Stirling PDF`,
    description: t(
      "app.description",
      "A free, private PDF editor you can run on any infrastructure.",
    ),
    ogTitle: `${t("signup.title", "Create an account")} - Stirling PDF`,
    ogDescription: t(
      "app.description",
      "A free, private PDF editor you can run on any infrastructure.",
    ),
    ogImage: `${baseUrl}/og_images/saas/app.png`,
    ogUrl: `${window.location.origin}${window.location.pathname}`,
  });

  const { validateSignupForm } = useSignupFormValidation();
  const { signUp, signInWithProvider } = useAuthService();

  const handleSignUp = async () => {
    const validation = validateSignupForm(
      email,
      password,
      confirmPassword,
      name,
    );
    if (!validation.isValid) {
      setError(validation.error);
      setFieldErrors(validation.fieldErrors || {});
      return;
    }

    try {
      setIsSigningUp(true);
      setError(null);
      setFieldErrors({});

      const result = await signUp(email, password, name);

      if (result.requiresEmailConfirmation) {
        alert({
          alertType: "success",
          title: t("signup.checkEmailConfirmation"),
          location: "top-right",
          isPersistentPopup: true,
        });
      } else {
        alert({
          alertType: "success",
          title: t("signup.accountCreatedSuccessfully"),
          location: "top-right",
          durationMs: 3000,
        });
        setTimeout(() => navigate(`/login${location.search}`), 2000);
      }
    } catch (err) {
      console.error("[Signup] Unexpected error:", err);
      setError(
        err instanceof Error
          ? err.message
          : t("signup.unexpectedError", "Unexpected error: {{message}}", {
              message: t("signup.unknownError", "Unknown error"),
            }),
      );
    } finally {
      setIsSigningUp(false);
    }
  };

  const handleProviderSignIn = async (
    provider: "github" | "google" | "apple" | "azure",
  ) => {
    try {
      setIsSigningUp(true);
      setError(null);
      await signInWithProvider(provider);
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : t("signup.unexpectedError", "Unexpected error: {{message}}", {
              message: t("signup.unknownError", "Unknown error"),
            }),
      );
    } finally {
      setIsSigningUp(false);
    }
  };

  return (
    <AuthLayout>
      {/* Centered logo */}
      <div className="auth-logo-block">
        <img
          src={loginHeader}
          alt="Stirling PDF"
          className="auth-logo-header auth-logo-header--light"
        />
        <img
          src={withBasePath("/modern-logo/LoginDarkModeHeader.svg")}
          alt="Stirling PDF"
          className="auth-logo-header auth-logo-header--dark"
        />
      </div>

      <ErrorMessage error={error} />

      {/* OAuth providers */}
      <div>
        <OAuthButtons
          onProviderClick={handleProviderSignIn}
          isSubmitting={isSigningUp}
          layout="fullwidth"
          labelPrefix={`${t("signup.signUpWith", "Sign up with")} `}
        />
      </div>

      {/* Sign-up form — always visible (no expander toggle) */}
      <div style={{ marginTop: "2.5rem", paddingBottom: "0.5rem" }}>
        <SignupForm
          name={name}
          email={email}
          password={password}
          confirmPassword={confirmPassword}
          agree={agree}
          setName={setName}
          setEmail={setEmail}
          setPassword={setPassword}
          setConfirmPassword={setConfirmPassword}
          setAgree={setAgree}
          onSubmit={handleSignUp}
          isSubmitting={isSigningUp}
          fieldErrors={fieldErrors}
        />
      </div>

      {/* Already have an account — pushed to the bottom */}
      <div
        style={{
          textAlign: "center",
          marginTop: "auto",
          paddingTop: "1rem",
        }}
      >
        <Button
          variant="tertiary"
          onClick={() => navigate(`/login${location.search}`)}
          style={{
            background: "none",
            border: "none",
            cursor: "pointer",
            fontSize: "0.875rem",
            color: "var(--c-accent-text)",
          }}
        >
          {t("signup.alreadyHaveAccount", "I already have an account")}
        </Button>
      </div>

      {/* Skip — small + muted, at the very bottom */}
      {!buyingTeam && (
        <div style={{ textAlign: "center", margin: "0.5rem 0 0.25rem" }}>
          <Button
            variant="tertiary"
            onClick={handleAnonymousSignIn}
            disabled={isSigningUp}
            style={{
              background: "none",
              border: "none",
              cursor: "pointer",
              fontSize: "0.8125rem",
              fontWeight: 500,
              color: "var(--c-text-subtle)",
            }}
          >
            {isSigningUp
              ? t("login.signingIn", "Signing in...")
              : `${t("signup.skip", "Skip")} →`}
          </Button>
        </div>
      )}
    </AuthLayout>
  );
}