Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

5.3 KB
Raw Blame
// [settings] navigation hook — route resolution for the two-pane settings
// layout. Uses the settingsRouteRegistry as the single source of truth so
// every registered route resolves without a parallel switch-statement.
import debug from 'debug';
import { useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { entryRoute, findEntryByRoute, SETTINGS_ROUTE_REGISTRY } from '../settingsRouteRegistry';

const log = debug('settings:nav');

// ---------------------------------------------------------------------------
// SettingsRoute type — derived from the registry so it stays in sync.
// ---------------------------------------------------------------------------

type SettingsRoute =
  | 'home'
  | 'agent-access'
  | 'account'
  | 'privacy'
  | 'billing'
  | 'developer-options'
  | 'llm'
  | 'voice'
  | 'tools'
  | 'recovery-phrase'
  | 'wallet-balances'
  | 'personality'
  | 'face'
  | 'theme'
  | 'appearance'
  | 'approval-history'
  | 'integrations'
  | 'composio-triggers'
  | 'sandbox-settings'
  | 'permissions'
  | 'usage'
  | 'security'
  | 'migration'
  | 'meetings'
  | 'embeddings'
  | 'search'
  | 'event-log'
  | 'tool-policy-diagnostics'
  | 'about';

interface BreadcrumbItem {
  label: string;
  onClick?: () => void;
}

interface SettingsNavigationHook {
  currentRoute: SettingsRoute;
  navigateToSettings: (route?: SettingsRoute | string) => void;
  navigateBack: () => void;
  closeSettings: () => void;
  breadcrumbs: BreadcrumbItem[];
}

// ---------------------------------------------------------------------------
// Route extraction
//
// Prior implementation used `path.includes()` which is fragile against
// substring collisions (e.g. '/settings/ai' matching '/settings/ai-debug').
// We now extract the slug via an exact-segment split so each path maps to
// exactly one route, then fall back to the registry for known routes.
// ---------------------------------------------------------------------------

/** Extract the settings sub-path from a full pathname. */
const extractSettingsSlug = (pathname: string): string => {
  // Strip the leading /settings/ and take the first path segment.
  // e.g. /settings/team/manage/123 → 'team'
  const match = /^\/settings\/(.+)$/.exec(pathname);
  if (!match) return '';
  return match[1];
};

const getCurrentRoute = (pathname: string): SettingsRoute => {
  const slug = extractSettingsSlug(pathname);
  if (!slug) return 'home';

  // --- exact first-segment lookup via registry ---
  const firstSegment = slug.split('/')[0];

  // Try to find the route by first segment first (most routes are single-segment).
  const entry = findEntryByRoute(firstSegment);
  if (entry) {
    log('getCurrentRoute: %s → %s', pathname, entry.id);
    return entry.id as SettingsRoute;
  }

  // A few routes have ids that don't match their URL segment (e.g. an entry with an explicit `route`).
  // Check all registry entries whose resolved route matches.
  const byRoute = SETTINGS_ROUTE_REGISTRY.find(e => entryRoute(e) === firstSegment);
  if (byRoute) {
    log('getCurrentRoute (via route alias): %s → %s', pathname, byRoute.id);
    return byRoute.id as SettingsRoute;
  }

  // Legacy redirect targets that don't have a registry entry.

  log('getCurrentRoute: unknown slug "%s", defaulting to home', firstSegment);
  return 'home';
};

export const useSettingsNavigation = (): SettingsNavigationHook => {
  const navigate = useNavigate();
  const location = useLocation();

  const goBackWithFallback = useCallback(
    (fallbackPath: string) => {
      const historyState = window.history.state as { idx?: number } | null;
      if (typeof historyState?.idx === 'number' && historyState.idx > 0) {
        navigate(-1);
        return;
      }
      navigate(fallbackPath);
    },
    [navigate]
  );

  const currentRoute = getCurrentRoute(location.pathname);

  const navigateToSettings = useCallback(
    (route: SettingsRoute | string = 'home') => {
      const target = route === 'home' ? '/settings' : `/settings/${route}`;
      navigate(target);
    },
    [navigate]
  );

  const navigateBack = useCallback(() => {
    if (currentRoute === 'home') {
      goBackWithFallback('/home');
      return;
    }
    goBackWithFallback('/settings');
  }, [currentRoute, goBackWithFallback]);

  const closeSettings = useCallback(() => {
    // Settings is a routed page, so "close" means leaving it: step back to
    // whatever the user was on, or land on /home for a deep link with no
    // history behind it. `replace` in the fallback so Back doesn't bounce
    // straight back into Settings.
    const historyState = window.history.state as { idx?: number } | null;
    if (typeof historyState?.idx === 'number' && historyState.idx > 0) {
      navigate(-1);
      return;
    }
    navigate('/home', { replace: true });
  }, [navigate]);

  // -------------------------------------------------------------------------
  // Breadcrumbs — derived from the registry.
  //
  // Breadcrumbs were replaced by the two-pane sidebar — the trail is no longer
  // rendered anywhere. The field is kept (always empty) so the ~50 panel call
  // sites keep compiling until the prop is mechanically removed.
  // -------------------------------------------------------------------------

  const breadcrumbs: BreadcrumbItem[] = [];

  return { currentRoute, navigateToSettings, navigateBack, closeSettings, breadcrumbs };
};