Skip to content

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

5.4 KB
Raw Blame
import { useEffect } from "react";
import { Navigate, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "@editor/auth/UseSession";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
import { useSuppressQuickNavRail } from "@editor/contexts/QuickNavHostContext";
import { AppRoot } from "@editor/components/layout/AppRoot";
import { useBackendProbe } from "@editor/hooks/useBackendProbe";
import { EDITOR_BASENAME } from "@editor/routes/editorBasename";
import AuthLayout from "@editor/routes/authShared/AuthLayout";
import LoginHeader from "@editor/routes/login/LoginHeader";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";

/**
 * Landing component - Smart router based on authentication status
 *
 * If login is disabled: Show the app directly (anonymous mode)
 * If user is authenticated: Show the app
 * If user is not authenticated: Show Login or redirect to /login
 */
export default function Landing() {
  const { session, loading: authLoading } = useAuth();
  const { config, loading: configLoading, refetch } = useAppConfig();
  const backendProbe = useBackendProbe();
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useTranslation();

  // The probe gates only the signed-out backend-down screen: a session means
  // /auth/me already answered.
  const loading = authLoading || (configLoading && !config);
  const probePending = backendProbe.loading;

  // The backend-down screen is not the app. Loading is: it resolves in a moment.
  useSuppressQuickNavRail(!session && backendProbe.status !== "up");

  // Periodically probe while backend isn't up so the screen can auto-advance when it comes online
  useEffect(() => {
    if (backendProbe.status === "up" || backendProbe.loginDisabled) {
      return;
    }
    const tick = async () => {
      const result = await backendProbe.probe();
      if (result.status === "up") {
        await refetch();
        if (result.loginDisabled) {
          navigate(EDITOR_BASENAME, { replace: true });
        }
      }
    };
    const intervalId = window.setInterval(() => {
      void tick();
    }, 5000);
    return () => window.clearInterval(intervalId);
  }, [
    backendProbe.status,
    backendProbe.loginDisabled,
    backendProbe.probe,
    navigate,
    refetch,
  ]);

  // Show loading while checking auth and config
  if (loading || (!session && probePending)) {
    return (
      <div
        style={{
          minHeight: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-3"></div>
          <div className="text-gray-600">
            {t("common.loading", "Loading...")}
          </div>
        </div>
      </div>
    );
  }

  // If login is disabled, show app directly (anonymous mode)
  if (config?.enableLogin === false || backendProbe.loginDisabled) {
    console.debug("[Landing] Login disabled - showing app in anonymous mode");
    return <AppRoot />;
  }

  // If backend is not up yet and user is not authenticated, show a branded status screen
  if (!session && backendProbe.status !== "up") {
    const backendTitle = t("backendStartup.notFoundTitle", "Backend not found");
    const handleRetry = async () => {
      const result = await backendProbe.probe();
      if (result.status === "up") {
        await refetch();
        navigate(EDITOR_BASENAME, { replace: true });
      }
    };
    return (
      <AuthLayout>
        <LoginHeader title={backendTitle} />
        <div
          className="auth-section"
          style={{
            padding: "1.5rem",
            marginTop: "1rem",
            borderRadius: "0.75rem",
            backgroundColor:
              "color-mix(in srgb, var(--c-primary) 8%, transparent)",
            border:
              "1px solid color-mix(in srgb, var(--c-primary) 20%, transparent)",
          }}
        >
          <p style={{ margin: "0 0 0.75rem 0", color: "var(--c-text)" }}>
            {t(
              "backendStartup.unreachable",
              "The application cannot currently connect to the backend. Verify the backend status and network connectivity, then try again.",
            )}
          </p>
          <Button
            type="button"
            onClick={handleRetry}
            className="auth-cta-button px-4 py-[0.75rem] rounded-[0.625rem] text-base font-semibold mt-5 border-0 cursor-pointer"
            style={{ width: "fit-content" }}
          >
            {t("backendStartup.retry", "Retry")}
          </Button>
        </div>
      </AuthLayout>
    );
  }

  // If we have a session, show the main app
  // Note: First login password change is now handled by the onboarding flow
  if (session) {
    return <AppRoot />;
  }

  // No session - redirect to login page. The URL always shows /login when not
  // authenticated, and carries where we came from so signing in returns there
  // (going to /editor and logging in lands back on /editor, not the role
  // router). Also passed as router state; the query is what survives a reload.
  const returnTo = encodeURIComponent(
    location.pathname + location.search + location.hash,
  );
  return config?.enableLogin === true && !backendProbe.loginDisabled ? (
    <Navigate
      to={`/login?from=${returnTo}`}
      replace
      state={{ from: location }}
    />
  ) : (
    <AppRoot />
  );
}