Skip to content

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

2.8 KB
Raw Blame
import { useCallback, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
  PORTAL_BASENAME,
  PORTAL_REVIEW_PATH,
} from "@editor/routes/portalBasename";

export type ViewId =
  | "home"
  | "users"
  | "sources"
  | "integrations"
  | "policies"
  | "pipelines"
  | "documents"
  | "review"
  | "infrastructure"
  | "usage"
  | "docs"
  | "settings";

export const VIEW_PATHS: Record<ViewId, string> = {
  home: "/",
  users: "/users",
  sources: "/sources",
  integrations: "/integrations",
  policies: "/policies",
  pipelines: "/pipelines",
  documents: "/documents",
  // Shared with the notification action that deep-links here, which cannot import portal code.
  review: PORTAL_REVIEW_PATH,
  infrastructure: "/infrastructure",
  usage: "/usage",
  docs: "/docs",
  settings: "/settings",
};

/**
 * The portal is mounted as a route-set under this base path inside the editor
 * app (see the admin-route seam). VIEW_PATHS stay expressed as logical portal
 * paths; this facade adds/strips the base so components keep navigating by
 * ViewId without knowing where the portal is mounted. The constant lives in
 * core so portal-free build flavors can reference the mount point too.
 */
export { PORTAL_BASENAME };

/** Logical view path -> full app path (e.g. "/users" -> "/processor/users"). */
export function toPortalPath(viewPath: string): string {
  return `${PORTAL_BASENAME}${viewPath === "/" ? "" : viewPath}`;
}

const PATH_TO_VIEW: Record<string, ViewId> = Object.fromEntries(
  (Object.entries(VIEW_PATHS) as Array<[ViewId, string]>).map(
    ([view, path]) => [path, view],
  ),
);

function deriveActiveView(pathname: string): ViewId {
  // Strip the portal base, then match against the logical VIEW_PATHS.
  let inner = pathname.startsWith(PORTAL_BASENAME)
    ? pathname.slice(PORTAL_BASENAME.length)
    : pathname;
  if (inner === "") inner = "/";
  // Exact match first; otherwise treat the first segment as the view.
  if (PATH_TO_VIEW[inner]) return PATH_TO_VIEW[inner];
  const firstSegment = "/" + inner.split("/").filter(Boolean)[0];
  return PATH_TO_VIEW[firstSegment] ?? "home";
}

interface ViewContextValue {
  activeView: ViewId;
  setActiveView: (view: ViewId) => void;
}

/**
 * Facade over react-router so components navigate by `ViewId` (activeView /
 * setActiveView) while URLs stay the source of truth. There is no
 * <ViewProvider> — the router is the provider; App.tsx supplies <BrowserRouter>.
 */
export function useView(): ViewContextValue {
  const { pathname } = useLocation();
  const navigate = useNavigate();
  const activeView = useMemo(() => deriveActiveView(pathname), [pathname]);
  const setActiveView = useCallback(
    (view: ViewId) => navigate(toPortalPath(VIEW_PATHS[view])),
    [navigate],
  );
  return { activeView, setActiveView };
}