import React, { Suspense, lazy, useEffect, useRef, useState, useMemo, } from "react"; import type { GuacamoleConnectionConfig } from "@/ui/desktop/apps/features/guacamole/GuacamoleDisplay.tsx"; import type { SSHHost } from "@/types"; import { useTabs } from "@/ui/desktop/navigation/tabs/TabContext.tsx"; import { ResizablePanelGroup, ResizablePanel, ResizableHandle, } from "@/components/ui/resizable.tsx"; import { useSidebar } from "@/components/ui/sidebar.tsx"; import { RefreshCcw } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button.tsx"; import { TERMINAL_THEMES, DEFAULT_TERMINAL_CONFIG, } from "@/constants/terminal-themes"; import { useTheme } from "@/components/theme-provider"; import { SimpleLoader } from "@/ui/desktop/navigation/animations/SimpleLoader.tsx"; import { useTranslation } from "react-i18next"; const Terminal = lazy(() => import("@/ui/desktop/apps/features/terminal/Terminal.tsx").then((module) => ({ default: module.Terminal, })), ); const ServerView = lazy(() => import("@/ui/desktop/apps/features/server-stats/ServerStats.tsx").then( (module) => ({ default: module.ServerStats, }), ), ); const FileManager = lazy(() => import("@/ui/desktop/apps/features/file-manager/FileManager.tsx").then( (module) => ({ default: module.FileManager, }), ), ); const GuacamoleDisplay = lazy(() => import("@/ui/desktop/apps/features/guacamole/GuacamoleDisplay.tsx").then( (module) => ({ default: module.GuacamoleDisplay, }), ), ); const TunnelManager = lazy(() => import("@/ui/desktop/apps/features/tunnel/TunnelManager.tsx").then( (module) => ({ default: module.TunnelManager, }), ), ); const DockerManager = lazy(() => import("@/ui/desktop/apps/features/docker/DockerManager.tsx").then( (module) => ({ default: module.DockerManager, }), ), ); const NetworkGraphCard = lazy(() => import("@/ui/desktop/apps/dashboard/cards/NetworkGraphCard").then( (module) => ({ default: module.NetworkGraphCard, }), ), ); interface TabData { id: number; type: string; title: string; terminalRef?: { current?: { fit?: () => void; notifyResize?: () => void; refresh?: () => void; }; }; hostConfig?: SSHHost; connectionConfig?: GuacamoleConnectionConfig; [key: string]: unknown; } type LayoutNode = | number // leaf: index into layoutTabs[] | { direction: "horizontal" | "vertical"; children: LayoutNode[] }; const SPLIT_LAYOUTS: Record = { 2: { direction: "horizontal", children: [0, 1] }, 3: { direction: "vertical", children: [{ direction: "horizontal", children: [0, 1] }, 2], }, 4: { direction: "vertical", children: [ { direction: "horizontal", children: [0, 1] }, { direction: "horizontal", children: [2, 3] }, ], }, 5: { direction: "vertical", children: [ { direction: "horizontal", children: [0, 1] }, { direction: "horizontal", children: [2, 3, 4] }, ], }, 6: { direction: "vertical", children: [ { direction: "horizontal", children: [0, 1, 2] }, { direction: "horizontal", children: [3, 4, 5] }, ], }, }; interface TerminalViewProps { isTopbarOpen?: boolean; rightSidebarOpen?: boolean; rightSidebarWidth?: number; } export function AppView({ isTopbarOpen = true, rightSidebarOpen = false, rightSidebarWidth = 400, }: TerminalViewProps): React.ReactElement { const { tabs, currentTab, allSplitScreenTab, removeTab, updateTab, addTab, previewTerminalTheme, } = useTabs() as { tabs: TabData[]; currentTab: number; allSplitScreenTab: number[]; removeTab: (id: number) => void; updateTab: (tabId: number, updates: Partial>) => void; addTab: (tab: Omit) => number; previewTerminalTheme: string | null; }; const { state: sidebarState } = useSidebar(); const { theme: appTheme } = useTheme(); const { t: translate } = useTranslation(); const isDarkMode = useMemo(() => { if (appTheme === "dark") return true; if (appTheme === "dracula") return true; if (appTheme === "gentlemansChoice") return true; if (appTheme === "midnightEspresso") return true; if (appTheme === "catppuccinMocha") return true; if (appTheme === "light") return false; return window.matchMedia("(prefers-color-scheme: dark)").matches; }, [appTheme]); const terminalTabs = useMemo( () => tabs.filter( (tab: TabData) => tab.type === "terminal" || tab.type === "server_stats" || tab.type === "file_manager" || tab.type === "rdp" || tab.type === "vnc" || tab.type === "telnet" || tab.type === "tunnel" || tab.type === "docker" || tab.type === "network_graph", ), [tabs], ); const containerRef = useRef(null); const panelRefs = useRef>({}); const [panelRects, setPanelRects] = useState>( {}, ); const [resetKey, setResetKey] = useState(0); const previousStylesRef = useRef>({}); const updatePanelRects = React.useCallback(() => { const next: Record = {}; Object.entries(panelRefs.current).forEach(([id, el]) => { if (el) next[id] = el.getBoundingClientRect(); }); setPanelRects(next); }, []); const fitActiveAndNotify = React.useCallback(() => { const visibleIds: number[] = []; if (allSplitScreenTab.length === 0) { if (currentTab) visibleIds.push(currentTab); } else { const splitIds = allSplitScreenTab as number[]; visibleIds.push(currentTab, ...splitIds.filter((i) => i !== currentTab)); } const operations = terminalTabs .filter((t: TabData) => visibleIds.includes(t.id)) .map((t: TabData) => t.terminalRef?.current) .filter((ref) => ref?.fit); requestAnimationFrame(() => { operations.forEach((ref) => { ref.fit?.(); ref.notifyResize?.(); ref.refresh?.(); }); }); }, [allSplitScreenTab, currentTab, terminalTabs]); const layoutScheduleRef = useRef(null); const scheduleMeasureAndFit = React.useCallback(() => { if (layoutScheduleRef.current) cancelAnimationFrame(layoutScheduleRef.current); layoutScheduleRef.current = requestAnimationFrame(() => { updatePanelRects(); fitActiveAndNotify(); }); }, [updatePanelRects, fitActiveAndNotify]); const hideThenFit = React.useCallback(() => { requestAnimationFrame(() => { updatePanelRects(); fitActiveAndNotify(); }); }, [updatePanelRects, fitActiveAndNotify]); const prevStateRef = useRef({ terminalTabsLength: terminalTabs.length, currentTab, splitScreenTabsStr: allSplitScreenTab.join(","), terminalTabIds: terminalTabs.map((t) => t.id).join(","), }); useEffect(() => { const prev = prevStateRef.current; const currentTabIds = terminalTabs.map((t) => t.id).join(","); const lengthChanged = prev.terminalTabsLength !== terminalTabs.length; const currentTabChanged = prev.currentTab !== currentTab; const splitChanged = prev.splitScreenTabsStr !== allSplitScreenTab.join(","); const tabIdsChanged = prev.terminalTabIds !== currentTabIds; const isJustReorder = !lengthChanged && tabIdsChanged && !currentTabChanged && !splitChanged; if ( (lengthChanged || currentTabChanged || splitChanged) && !isJustReorder ) { hideThenFit(); } prevStateRef.current = { terminalTabsLength: terminalTabs.length, currentTab, splitScreenTabsStr: allSplitScreenTab.join(","), terminalTabIds: currentTabIds, }; }, [ currentTab, terminalTabs.length, allSplitScreenTab.join(","), terminalTabs, hideThenFit, ]); useEffect(() => { scheduleMeasureAndFit(); }, [ scheduleMeasureAndFit, allSplitScreenTab.length, isTopbarOpen, sidebarState, resetKey, rightSidebarOpen, rightSidebarWidth, ]); useEffect(() => { const roContainer = containerRef.current ? new ResizeObserver(() => { updatePanelRects(); fitActiveAndNotify(); }) : null; if (containerRef.current && roContainer) roContainer.observe(containerRef.current); return () => roContainer?.disconnect(); }, [updatePanelRects, fitActiveAndNotify]); useEffect(() => { const onWinResize = () => { updatePanelRects(); fitActiveAndNotify(); }; window.addEventListener("resize", onWinResize); return () => window.removeEventListener("resize", onWinResize); }, [updatePanelRects, fitActiveAndNotify]); const HEADER_H = 28; const terminalIdMapRef = useRef>(new Set()); useEffect(() => { terminalTabs.forEach((t) => terminalIdMapRef.current.add(t.id)); }, [terminalTabs]); const renderTerminalsLayer = () => { const styles: Record = {}; const layoutTabs = allSplitScreenTab .map((tabId) => terminalTabs.find((tab: TabData) => tab.id === tabId)) .filter((t): t is TabData => t !== null && t !== undefined); const mainTab = terminalTabs.find((tab: TabData) => tab.id === currentTab); if (allSplitScreenTab.length === 0 && mainTab) { const isFileManagerTab = mainTab.type === "file_manager" || mainTab.type === "tunnel" || mainTab.type === "docker" || mainTab.type === "network_graph"; const newStyle = { position: "absolute" as const, top: isFileManagerTab ? 0 : 4, left: isFileManagerTab ? 0 : 4, right: isFileManagerTab ? 0 : 4, bottom: isFileManagerTab ? 0 : 4, zIndex: 20, display: "block" as const, pointerEvents: "auto" as const, opacity: 1, }; styles[mainTab.id] = newStyle; previousStylesRef.current[mainTab.id] = newStyle; } else { layoutTabs.forEach((t: TabData) => { const rect = panelRects[String(t.id)]; const parentRect = containerRef.current?.getBoundingClientRect(); if (rect && parentRect) { const newStyle = { position: "absolute" as const, top: rect.top - parentRect.top + HEADER_H + 4, left: rect.left - parentRect.left + 4, width: rect.width - 8, height: rect.height - HEADER_H - 8, zIndex: 20, display: "block" as const, pointerEvents: "auto" as const, opacity: 1, }; styles[t.id] = newStyle; previousStylesRef.current[t.id] = newStyle; } }); } const sortedTerminalTabs = [...terminalTabs].sort((a, b) => a.id - b.id); return (
{sortedTerminalTabs.map((t: TabData) => { const hasStyle = !!styles[t.id]; const isVisible = hasStyle || (allSplitScreenTab.length === 0 && t.id === currentTab); const effectiveVisible = isVisible; const previousStyle = previousStylesRef.current[t.id]; const isFileManagerTab = t.type === "file_manager" || t.type === "tunnel" || t.type === "docker" || t.type === "network_graph"; const standardStyle = { position: "absolute" as const, top: isFileManagerTab ? 0 : 4, left: isFileManagerTab ? 0 : 4, right: isFileManagerTab ? 0 : 4, bottom: isFileManagerTab ? 0 : 4, }; const finalStyle: React.CSSProperties = hasStyle ? { ...styles[t.id], overflow: "hidden" } : effectiveVisible ? { ...(previousStyle || standardStyle), opacity: 1, pointerEvents: "auto", zIndex: 20, display: "block", overflow: "hidden", } : ({ ...(previousStyle || standardStyle), opacity: 0, pointerEvents: "none", zIndex: 0, display: "none", overflow: "hidden", } as React.CSSProperties); const isTerminal = t.type === "terminal"; const terminalConfig = { ...DEFAULT_TERMINAL_CONFIG, ...t.hostConfig?.terminalConfig, }; let themeColors; const activeTerminalTheme = t.id === currentTab && previewTerminalTheme ? previewTerminalTheme : terminalConfig.theme; if (activeTerminalTheme === "termix") { themeColors = isDarkMode ? TERMINAL_THEMES.termixDark.colors : TERMINAL_THEMES.termixLight.colors; } else { themeColors = TERMINAL_THEMES[activeTerminalTheme]?.colors || TERMINAL_THEMES.termixDark.colors; } const backgroundColor = themeColors.background; return (
} > {t.type === "terminal" ? ( 0} onClose={() => removeTab(t.id)} onTitleChange={(title) => updateTab(t.id, { title })} onOpenFileManager={ (t.hostConfig as any)?.enableFileManager ? (path?: string) => addTab({ type: "file_manager", title: t.title, hostConfig: path ? { ...t.hostConfig!, defaultPath: path, } : t.hostConfig, }) : undefined } previewTheme={ t.id === currentTab ? previewTerminalTheme : null } /> ) : t.type === "server_stats" ? ( ) : t.type === "rdp" || t.type === "vnc" || t.type === "telnet" ? ( t.connectionConfig ? ( removeTab(t.id)} onError={(err) => { toast.error(err); removeTab(t.id); }} /> ) : (
Missing connection configuration
) ) : t.type === "network_graph" ? ( ) : t.type === "tunnel" ? ( ) : t.type === "docker" ? ( removeTab(t.id)} /> ) : ( removeTab(t.id)} /> )}
); })}
); }; const ResetButton = ({ onClick }: { onClick: () => void }) => ( ); const handleReset = () => { setResetKey((k) => k + 1); requestAnimationFrame(() => scheduleMeasureAndFit()); }; const renderSplitOverlays = () => { const layoutTabs = allSplitScreenTab .map((tabId) => terminalTabs.find((tab: TabData) => tab.id === tabId)) .filter((t): t is TabData => t !== null && t !== undefined); if (allSplitScreenTab.length === 0) return null; const layout = SPLIT_LAYOUTS[layoutTabs.length]; if (!layout) return null; const handleStyle = { pointerEvents: "auto", zIndex: 12, background: "var(--border-base)", } as React.CSSProperties; const commonGroupProps: { onLayout: () => void; onResize: () => void; } = { onLayout: scheduleMeasureAndFit, onResize: scheduleMeasureAndFit, }; const renderNode = ( node: LayoutNode, path: string, siblingCount: number, orderIndex: number, isRoot: boolean, ): React.ReactNode => { const defaultSize = Math.round(100 / siblingCount); if (typeof node === "number") { const tab = layoutTabs[node]; if (!tab) return null; return (
{ panelRefs.current[String(tab.id)] = el; }} className="h-full w-full flex flex-col relative" >
{tab.title} {node === 1 && }
); } const groupKey = isRoot ? String(resetKey) : `${path}-${resetKey}`; const groupId = isRoot ? `main-${node.direction}` : `group-${path}`; const groupContent = ( {node.children.flatMap((child, i) => { const childPath = isRoot ? String(i) : `${path}-${i}`; const panel = renderNode( child, childPath, node.children.length, i + 1, false, ); if (i === 0) return [panel]; return [ , panel, ]; })} ); if (isRoot) return groupContent; return ( {groupContent} ); }; return (
{renderNode(layout, "", 1, 1, true)}
); }; const currentTabData = tabs.find((tab: TabData) => tab.id === currentTab); const isFileManager = currentTabData?.type === "file_manager"; const isTunnel = currentTabData?.type === "tunnel"; const isDocker = currentTabData?.type === "docker"; const isTerminal = currentTabData?.type === "terminal"; const isSplitScreen = allSplitScreenTab.length > 0; const terminalConfig = { ...DEFAULT_TERMINAL_CONFIG, ...currentTabData?.hostConfig?.terminalConfig, }; let containerThemeColors; if (terminalConfig.theme === "termix") { containerThemeColors = isDarkMode ? TERMINAL_THEMES.termixDark.colors : TERMINAL_THEMES.termixLight.colors; } else { containerThemeColors = TERMINAL_THEMES[terminalConfig.theme]?.colors || TERMINAL_THEMES.termixDark.colors; } const terminalBackgroundColor = containerThemeColors.background; const topMarginPx = isTopbarOpen ? 74 : 26; const leftMarginPx = sidebarState === "collapsed" ? 26 : 8; const bottomMarginPx = 8; let containerBackground = "var(--color-canvas)"; if ((isFileManager || isTunnel || isDocker) && !isSplitScreen) { containerBackground = "var(--color-deepest)"; } else if (isTerminal) { containerBackground = terminalBackgroundColor; } return (
{renderTerminalsLayer()} {renderSplitOverlays()}
); }