import { useDesignSandbox } from "@/context/DesignSandboxContext"; import { DesignSandboxSidebar } from "./DesignSandboxSidebar"; import { BoardDialogs } from "./BoardDialogs"; import { CloudTrialGate } from "./CloudTrialGate"; import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext"; import { PluginAppShellOverlays } from "./PluginAppShellOverlays"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, } from "react"; import { useQuery } from "@tanstack/react-query"; import { Outlet, useLocation, useNavigate, useNavigationType, useParams, } from "@/lib/router"; import { Sidebar } from "./Sidebar.production"; import { CompanySettingsSidebar } from "./CompanySettingsSidebar.production"; import { CompanySettingsNav } from "./access/CompanySettingsNav"; import { AppsSidebar } from "./AppsSidebar.production"; import { appsRouteHasRail } from "../pages/apps/apps-rail"; import { AppDetailSidebar } from "./AppConnectionSidebar.production"; import { BreadcrumbBar } from "./BreadcrumbBar.production"; import { PropertiesPanel } from "./PropertiesPanel"; import { CommandPalette } from "./CommandPalette"; import { KeyboardShortcutsCheatsheet } from "./KeyboardShortcutsCheatsheet"; import { ToastViewport } from "./ToastViewport"; import { MobileBottomNav } from "./MobileBottomNav"; import { WorktreeBanner } from "./WorktreeBanner"; import { DevRestartBanner } from "./DevRestartBanner"; import { StandaloneBrowserControls } from "./StandaloneBrowserControls"; import { RouteErrorBoundary } from "./RouteErrorBoundary"; import { SidebarShell } from "./SidebarShell.production"; import { SecondarySidebar } from "./SecondarySidebar.production"; import { SidebarAccountMenu } from "./SidebarAccountMenu.production"; import { useDialogActions } from "../context/DialogContext"; import { usePanel } from "../context/PanelContext"; import { useCompany } from "../context/CompanyContext"; import { useSidebar } from "../context/SidebarContext"; import { useKeyboardShortcuts } from "../hooks/useKeyboardShortcuts"; import { useCompanyPageMemory } from "../hooks/useCompanyPageMemory"; import { useMobileNavVisibility } from "../hooks/useMobileNavVisibility"; import { useMobileVisualViewport } from "../hooks/useMobileVisualViewport"; import { healthApi } from "../api/health"; import { resolveArchivedCompanyBounce, shouldSyncCompanySelectionFromRoute, } from "../lib/company-selection"; import { useOptionalToastActions } from "../context/ToastContext"; import { applyMainContentScrollTop, NavigationScrollMemory, resetNavigationScroll, shouldResetScrollOnNavigation, } from "../lib/navigation-scroll"; import { queryKeys } from "../lib/queryKeys"; import { scheduleMainContentFocus } from "../lib/main-content-focus"; import { pinDocumentScrollToZero } from "../lib/pin-document-scroll"; import { cn } from "../lib/utils"; import { classifyShellRoute } from "../lib/shell-navigation"; import { NotFoundPage } from "../pages/NotFound"; import { PluginSlotMount, resolveRouteSidebarSlot, usePluginSlots, } from "../plugins/slots"; function getCompanyRouteSegment( pathname: string, companyPrefix: string | undefined, ): string | null { return ( getCompanyPathSegments(pathname, companyPrefix)[0]?.toLowerCase() ?? null ); } function getCompanyPathSegments( pathname: string, companyPrefix: string | undefined, ): string[] { if (!companyPrefix) return []; const segments = pathname.split("/").filter(Boolean); if (segments.length < 2) return []; if (segments[0]?.toUpperCase() !== companyPrefix.toUpperCase()) return []; return segments.slice(1); } const RESERVED_APP_SUBPATHS = new Set([ "plugin", "category", "browse", "connections", "connect", "chat", "review", "attention", "gateways", "advanced", "app", ]); export function Layout() { const designSandbox = useDesignSandbox(); const { sidebarOpen, setSidebarOpen, toggleSidebar, isMobile, } = useSidebar(); const { openNewIssue, openOnboarding } = useDialogActions(); const { togglePanelVisible } = usePanel(); // Optional: Layout also renders in harnesses without a ToastProvider. const pushToast = useOptionalToastActions()?.pushToast ?? null; const { companies, loading: companiesLoading, selectedCompany, selectedCompanyId, selectionSource, setSelectedCompanyId, } = useCompany(); const { companyPrefix, pluginRoutePath: matchedPluginRoutePath } = useParams<{ companyPrefix: string; pluginRoutePath?: string; }>(); const navigate = useNavigate(); const location = useLocation(); const navigationType = useNavigationType(); const isTaskDetailRoute = classifyShellRoute(location.pathname, companyPrefix).isTaskDetail; const isCompanySettingsRoute = [ "/company/settings", "/company/export", "/company/import", ].some((settingsPath) => location.pathname.includes(settingsPath)); const companyPathSegments = getCompanyPathSegments( location.pathname, companyPrefix, ); const isToolsRoute = companyPathSegments[0]?.toLowerCase() === "tools"; const isAppsRoute = companyPathSegments[0]?.toLowerCase() === "apps"; const appDetailConnectionId = isAppsRoute && companyPathSegments[1] && !RESERVED_APP_SUBPATHS.has(companyPathSegments[1].toLowerCase()) ? companyPathSegments[1] : null; const appDetailApplicationId = isAppsRoute && companyPathSegments[1]?.toLowerCase() === "app" && companyPathSegments[2] ? companyPathSegments[2] : null; const onboardingTriggered = useRef(false); const previousPathname = useRef(null); const mainContentRef = useRef(null); const scrollMemory = useRef(new NavigationScrollMemory()); const activeScrollKey = useRef(location.key); const mobileNavVisible = useMobileNavVisibility(isMobile, location.pathname); const mobileViewportRef = useMobileVisualViewport(true); const [shortcutsOpen, setShortcutsOpen] = useState(false); const matchedCompany = useMemo(() => { if (!companyPrefix) return null; const requestedPrefix = companyPrefix.toUpperCase(); return ( companies.find( (company) => company.issuePrefix.toUpperCase() === requestedPrefix, ) ?? null ); }, [companies, companyPrefix]); const hasUnknownCompanyPrefix = Boolean(companyPrefix) && !companiesLoading && companies.length > 0 && !matchedCompany; const pluginRoutePath = useMemo( () => matchedPluginRoutePath?.toLowerCase() ?? getCompanyRouteSegment(location.pathname, companyPrefix), [companyPrefix, location.pathname, matchedPluginRoutePath], ); const routeSidebarCompanyId = matchedCompany?.id ?? null; const routeSidebarCompanyPrefix = matchedCompany?.issuePrefix ?? null; const { slots: routeSidebarSlots } = usePluginSlots({ slotTypes: ["page", "routeSidebar"], companyId: routeSidebarCompanyId, enabled: Boolean(routeSidebarCompanyId && pluginRoutePath), }); const routeSidebarSlot = useMemo( () => resolveRouteSidebarSlot(routeSidebarSlots, pluginRoutePath), [pluginRoutePath, routeSidebarSlots], ); const sidebarContext = useMemo( () => ({ companyId: routeSidebarCompanyId, companyPrefix: routeSidebarCompanyPrefix, }), [routeSidebarCompanyId, routeSidebarCompanyPrefix], ); const secondarySidebar = isCompanySettingsRoute ? ( ) : appDetailConnectionId ? ( ) : appDetailApplicationId ? ( ) : appsRouteHasRail(companyPathSegments, true) ? ( ) : routeSidebarSlot ? ( ) : null; const hasSecondarySidebar = secondarySidebar != null; const { data: health } = useQuery({ queryKey: queryKeys.health, queryFn: () => healthApi.get(), refetchInterval: (query) => { const data = query.state.data as { devServer?: { enabled?: boolean } } | undefined; return data?.devServer?.enabled ? 2000 : false; }, refetchIntervalInBackground: false, }); useEffect(() => { if (companiesLoading || onboardingTriggered.current) return; if (health?.deploymentMode === "authenticated") return; // Cloud provisions the single company for a stack, and POST /companies is a // 403 floor there — auto-opening the wizard could only dead-end. if (health?.cloud) return; if (companies.length === 0) { onboardingTriggered.current = true; openOnboarding(); } }, [ companies, companiesLoading, openOnboarding, health?.cloud, health?.deploymentMode, ]); useEffect(() => { if (!companyPrefix || companiesLoading || companies.length === 0) return; if (!matchedCompany) { const fallback = (selectedCompanyId ? companies.find((company) => company.id === selectedCompanyId) : null) ?? companies[0] ?? null; if (fallback && selectedCompanyId !== fallback.id) { setSelectedCompanyId(fallback.id, { source: "route_sync" }); } return; } if (companyPrefix !== matchedCompany.issuePrefix) { const suffix = location.pathname.replace(/^\/[^/]+/, ""); navigate(`/${matchedCompany.issuePrefix}${suffix}${location.search}`, { replace: true, }); return; } // Stale state (remembered paths, history, bookmarks, restored tabs) // deposits users into archived companies long after archiving; a cold // arrival bounces to an active company instead of dwelling there. // Deliberate visits (the company is already the selection) stay put. const bounce = resolveArchivedCompanyBounce({ matchedCompany, selectedCompanyId, companies, }); if (bounce) { pushToast?.({ title: `${matchedCompany.name} is archived`, body: `Switched to ${bounce.name}.`, tone: "info", dedupeKey: `archived-company-bounce:${matchedCompany.id}`, }); setSelectedCompanyId(bounce.id, { source: "route_sync" }); navigate(`/${bounce.issuePrefix}/dashboard`, { replace: true }); return; } if ( shouldSyncCompanySelectionFromRoute({ selectionSource, selectedCompanyId, routeCompanyId: matchedCompany.id, }) ) { setSelectedCompanyId(matchedCompany.id, { source: "route_sync" }); } }, [ companyPrefix, companies, companiesLoading, matchedCompany, location.pathname, location.search, navigate, pushToast, selectionSource, selectedCompanyId, setSelectedCompanyId, ]); const togglePanel = togglePanelVisible; const openSearch = useCallback(() => { document.dispatchEvent( new KeyboardEvent("keydown", { key: "k", metaKey: true, bubbles: true, cancelable: true, }), ); }, []); useCompanyPageMemory(); useKeyboardShortcuts({ onNewIssue: () => openNewIssue(), onSearch: openSearch, onToggleSidebar: toggleSidebar, onTogglePanel: togglePanel, onShowShortcuts: () => setShortcutsOpen(true), onGoToInbox: () => navigate("/inbox"), }); // Swipe gesture to open/close sidebar on mobile useEffect(() => { if (!isMobile) return; const EDGE_ZONE = 30; // px from left edge to start open-swipe const MIN_DISTANCE = 50; // minimum horizontal swipe distance const MAX_VERTICAL = 75; // max vertical drift before we ignore let startX = 0; let startY = 0; const onTouchStart = (e: TouchEvent) => { const t = e.touches[0]!; startX = t.clientX; startY = t.clientY; }; const onTouchEnd = (e: TouchEvent) => { const t = e.changedTouches[0]!; const dx = t.clientX - startX; const dy = Math.abs(t.clientY - startY); if (dy > MAX_VERTICAL) return; // vertical scroll, ignore // Swipe right from left edge → open if (!sidebarOpen && startX < EDGE_ZONE && dx > MIN_DISTANCE) { setSidebarOpen(true); return; } // Swipe left when open → close if (sidebarOpen && dx < -MIN_DISTANCE) { setSidebarOpen(false); } }; document.addEventListener("touchstart", onTouchStart, { passive: true }); document.addEventListener("touchend", onTouchEnd, { passive: true }); return () => { document.removeEventListener("touchstart", onTouchStart); document.removeEventListener("touchend", onTouchEnd); }; }, [isMobile, sidebarOpen, setSidebarOpen]); useEffect(() => { const previousOverflow = document.body.style.overflow; document.body.style.overflow = isMobile ? "visible" : "clip"; return () => { document.body.style.overflow = previousOverflow; }; }, [isMobile]); // `scrollIntoView` walks every ancestor scroll container. On a long thread // the post-submit `scrollIntoView` on the new comment reaches `` and // animates `documentElement.scrollTop` via the browser's internal scroll // algorithm, which bypasses the CSS `overflow` on the root element and // visually shifts the entire shell (sidebar included) off-screen. Pin // both roots to scrollTop=0 on every scroll tick. useEffect(() => { if (isMobile) return; return pinDocumentScrollToZero(); }, [isMobile]); useEffect(() => { if (typeof document === "undefined") return; const mainContent = mainContentRef.current; return scheduleMainContentFocus(mainContent); }, [location.pathname]); // Continuously record the scroll offset of the active history entry so a // later back/forward navigation can restore it (see NavigationScrollMemory). useEffect(() => { const main = mainContentRef.current; if (!main) return; const recordScroll = () => { scrollMemory.current.remember(activeScrollKey.current, main.scrollTop); }; main.addEventListener("scroll", recordScroll, { passive: true }); return () => main.removeEventListener("scroll", recordScroll); }, []); useLayoutEffect(() => { const main = mainContentRef.current; const shouldResetScroll = shouldResetScrollOnNavigation({ previousPathname: previousPathname.current, pathname: location.pathname, navigationType, state: location.state, }); previousPathname.current = location.pathname; const isHistoryPop = navigationType === "POP"; const restoredScrollTop = isHistoryPop ? scrollMemory.current.recall(location.key) : 0; activeScrollKey.current = location.key; if (isHistoryPop) { applyMainContentScrollTop(main, restoredScrollTop); // Cached page content can finish laying out a frame after commit; re-apply // once it has so the restored offset isn't clamped to a shorter interim height. const raf = requestAnimationFrame(() => applyMainContentScrollTop(main, restoredScrollTop), ); return () => cancelAnimationFrame(raf); } if (shouldResetScroll) { resetNavigationScroll(main); } }, [location.key, location.pathname, location.state, navigationType]); return (
Skip to Main Content
{isMobile && sidebarOpen && (
{isMobile && }
); }