Skip to content

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

1.9 KB
Raw Blame
import { clearNotificationReadState } from "@editor/hooks/useNotifications";
import { clearConnectedAccounts } from "@editor/hooks/useConnectedAccounts";
import { connectionModeService } from "@editor/services/connectionModeService";
import { suspendWorkbenchSession } from "@editor/services/workbenchSession";

type SignOutFn = () => Promise<void>;

interface AccountLogoutDeps {
  signOut: SignOutFn;
  redirectToLogin: () => void;
}

/**
 * Desktop-specific logout: mirrors Connection Settings flow to avoid stale state.
 */
export function useAccountLogout() {
  return async ({
    signOut,
    redirectToLogin,
  }: AccountLogoutDeps): Promise<void> => {
    try {
      // The tab outlives the session; the next person to sign in here must not
      // inherit this workbench. Suspends writing too - signing out unmounts the
      // editor, and its flush would otherwise write the record straight back.
      suspendWorkbenchSession();
      // Same reason: the next person's own failures must not arrive pre-read.
      clearNotificationReadState();
      clearConnectedAccounts();
      await signOut();

      const currentConfig = await connectionModeService.getCurrentConfig();
      // Save server URL before clearing so user can easily reconnect (self-hosted only)
      if (
        currentConfig.mode === "selfhosted" &&
        currentConfig.server_config?.url
      ) {
        localStorage.setItem("server_url", currentConfig.server_config.url);
      }
      if (!currentConfig.require_sign_in)
        await connectionModeService.switchToLocal();

      window.history.replaceState({}, "", "/");
      // No reload needed — AppProviders remounts the SaaS provider tree via
      // connectionModeService subscription when mode changes to local.
      return;
    } catch (err) {
      console.warn(
        "[Desktop AccountLogout] Desktop-specific logout failed, falling back to redirect",
        err,
      );
    }

    redirectToLogin();
  };
}