Skip to content

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

6.4 KB
Raw Blame
import React, { useState, useEffect } from "react";
import { Stack, Card, Badge, Text, Group } from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { useTranslation } from "react-i18next";
import {
  connectionModeService,
  ConnectionConfig,
} from "@editor/services/connectionModeService";
import { authService, UserInfo } from "@editor/services/authService";
import { OPEN_SIGN_IN_EVENT } from "@editor/constants/signInEvents";
import { useAuth } from "@editor/auth/UseSession";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";

export const ConnectionSettings: React.FC = () => {
  const { t } = useTranslation();
  const { signOut } = useAuth();
  const [config, setConfig] = useState<ConnectionConfig | null>(null);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(false);

  // Load current config on mount
  useEffect(() => {
    const loadConfig = async () => {
      const currentConfig = await connectionModeService.getCurrentConfig();
      setConfig(currentConfig);

      if (
        currentConfig.mode === "saas" ||
        currentConfig.mode === "selfhosted"
      ) {
        const user = await authService.getUserInfo();
        setUserInfo(user);
      }
    };

    loadConfig();

    const unsubscribe =
      connectionModeService.subscribeToModeChanges(loadConfig);
    return unsubscribe;
  }, []);

  const handleLogout = async () => {
    try {
      setLoading(true);
      // Save server URL before clearing so user can easily reconnect (self-hosted only)
      if (config?.mode === "selfhosted" && config?.server_config?.url) {
        localStorage.setItem("server_url", config.server_config.url);
      }
      // Use the proprietary signOut (which also fans out the SIGNED_OUT event
      // to the AuthProvider so the React tree sees the unauthenticated state)
      // and treat authService.logout() as a fallback if it errors. The previous
      // implementation only called authService.logout() directly, which cleared
      // the Tauri-stored token+user_info but left the proprietary AuthProvider's
      // session state stale - so the FileSidebar badge kept showing the prior
      // user's name until the next session check happened to fire.
      try {
        await signOut();
      } catch (signOutError) {
        console.warn(
          "[ConnectionSettings] signOut() failed, falling back to authService.logout()",
          signOutError,
        );
        await authService.logout();
      }
      if (!config?.require_sign_in) await connectionModeService.switchToLocal();

      // Reload config
      const newConfig = await connectionModeService.getCurrentConfig();
      setConfig(newConfig);
      setUserInfo(null);

      // Clear URL to home page so we don't return to settings after re-login
      window.history.replaceState({}, "", "/");
      // No reload needed — AppProviders remounts the SaaS provider tree via
      // connectionModeService subscription when mode changes to local.
    } catch (error) {
      console.error("Logout failed:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSignIn = () => {
    window.dispatchEvent(new CustomEvent(OPEN_SIGN_IN_EVENT));
  };

  if (!config) {
    return <Text>{t("common.loading", "Loading...")}</Text>;
  }

  return (
    <>
      <Card shadow="sm" padding="lg" radius="md" withBorder>
        <Stack gap="md">
          <Group justify="space-between">
            <Text fw={600}>
              {t("settings.connection.title", "Connection Mode")}
            </Text>
            <Badge
              color={
                config.mode === "saas"
                  ? "blue"
                  : config.mode === "local"
                    ? "white"
                    : "green"
              }
              variant="light"
            >
              {config.mode === "saas"
                ? t("settings.connection.mode.saas", "Stirling Cloud")
                : config.mode === "local"
                  ? t("settings.connection.mode.local", "Local Only")
                  : t("settings.connection.mode.selfhosted", "Self-Hosted")}
            </Badge>
          </Group>

          {config.mode === "local" && (
            <Text size="sm" c="dimmed">
              {t(
                "settings.connection.localDescription",
                "You are using the local backend without an account. Some tools requiring cloud processing or a self-hosted server are unavailable.",
              )}
            </Text>
          )}

          {(config.mode === "saas" || config.mode === "selfhosted") &&
            config.server_config && (
              <>
                <div>
                  <Text size="sm" fw={500}>
                    {t("settings.connection.server", "Server")}
                  </Text>
                  <Text
                    size="sm"
                    c="dimmed"
                    className={
                      config.mode === "saas"
                        ? undefined
                        : privateContentClassName
                    }
                  >
                    {config.mode === "saas"
                      ? "stirling.com"
                      : config.server_config.url}
                  </Text>
                </div>

                {userInfo && (
                  <div>
                    <Text size="sm" fw={500}>
                      {t("settings.connection.user", "Logged in as")}
                    </Text>
                    <Text
                      size="sm"
                      c="dimmed"
                      className={privateContentClassName}
                    >
                      {userInfo.username}
                      {userInfo.email && ` (${userInfo.email})`}
                    </Text>
                  </div>
                )}
              </>
            )}

          <Group mt="md">
            {config.mode === "local" ? (
              <Button onClick={handleSignIn} variant="secondary">
                {t("settings.connection.signIn", "Sign In")}
              </Button>
            ) : (
              <Button
                onClick={handleLogout}
                accent="danger"
                variant="secondary"
                disabled={loading}
              >
                {t("settings.connection.logout", "Log Out")}
              </Button>
            )}
          </Group>
        </Stack>
      </Card>
    </>
  );
};