Files
Termix/src/ui/desktop/navigation/AppView.tsx
T
Luke Gustafson 2768f11dfc v2.2.0 (#738)
* Improve Docker container list UI

* Rework SSH tunnel forwarding

* Update macOS Electron packaging

* Optimize frontend bundle splitting

* Add beta version update status

* Add client tunnel preset management

* Secure cookie authentication flows

* Add client tunnel bridge support

* Preserve sessions on restart

* Update runtime to Node 24

* Add client remote tunnel support

* Fix stale frontend cache handling

* Fix Docker image platforms for Node 24

* Fix Electron packaging workflows

* Fix client auth cache after upgrades

* chore: cleanup files

* fix: npm i error

* Fix OIDC auth cookie readiness

* Fix Docker npm ci config

* Add react-is peer dependency

* Fix Electron auth and cache handling

* Improve terminal clipboard and refresh actions

* feat: add API keys

* feat: improve lazy loading with loading spinners

* feat: Introduce FolderTree component with lazy-loading and motion animations for improved file manager UX (#735)

* feat: integrate FolderTree component with lazy-loading for file manager sidebar

- Add motion animation library (v12.38.0) for smooth UI transitions
- Create new FolderTree component with advanced keyboard navigation support
- Refactor kbd component: introduce KbdKey and KbdSeparator subcomponents
- Implement lazy-loading strategy for directory tree in FileManagerSidebar
- Refactor FileManagerSidebar with improved code organization and better separation of concerns
- Update keyboard shortcut displays across CommandPalette, FileViewer, and Dashboard
- Change React/ReactDOM dependency flags from dev to devOptional in package-lock.json

BREAKING CHANGE: KbdGroup component has been replaced. Use <Kbd><KbdKey>...</KbdKey><KbdSeparator /></Kbd> instead.

- Improves UX with smooth animations and better folder navigation
- Reduces initial load time through lazy-loading subdirectories
- Enhances accessibility with ARIA labels and keyboard navigation
- Maintains dark mode support and proper styling

* fix: incorrect use of the theme system and linked file manger sidebar with current folder

---------

Co-authored-by: suryacagur <suryacagur.dev@gmail.com>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>

* Enhance VNC token generation to include optional username parameter and refactor username input handling in HostGeneralTab (#733)

* Fix Docker build info generation

* Remove unused node-fetch dependency

* feat: prompt user for SSH key passphrase on use (#715)

When an encrypted SSH key has no stored passphrase, show a lightweight
dialog prompting the user to enter it at connection time instead of
failing with a parse error. Supports both desktop and mobile terminals.

Closes Termix-SSH/Support#354

* fix: prevent session crash when uploading to permission-denied directory (#716)

- Wrap writeFile sftp.stat callback in try-catch to prevent uncaught
  exceptions from escaping the callback into the event loop
- Add missing stream.stderr error handler in writeFile fallback to
  prevent unhandled error events from crashing the process
- Remove bogus activeOperations decrement in both writeFile and
  uploadFile fallback methods (counter was never incremented)
- Add res.headersSent checks in fallback disconnect paths to prevent
  ERR_HTTP_HEADERS_SENT crashes

Closes Termix-SSH/Support#652

* feat: add LOG_TIMESTAMP_FORMAT env var for 24h/ISO log timestamps (#718)

Support LOG_TIMESTAMP_FORMAT environment variable with values:
- "24h": 24-hour format (14:58:45)
- "iso": ISO 8601 format (2026-04-25T14:58:45.000Z)
- default: locale format (2:58:45 PM)

Closes Termix-SSH/Support#650

* feat: open file manager at terminal current working directory (#719)

* feat: open file manager at terminal current working directory

When right-clicking in the terminal and selecting "Open File Manager
Here", query the current working directory via a separate SSH exec
channel and pass it as the initial path to the file manager tab.

Closes Termix-SSH/Support#649

* chore: sync package-lock.json with node-fetch and deps

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: remove undefined TerminalContextMenu from bad merge resolution

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>

* fix: show reconnect overlay when SSH server reboots (#720)

When the remote server reboots, the SSH connection closes while the
stream is still active. The close handler only sent the "disconnected"
message when sshStream was null, so the frontend never received the
disconnect notification and hung with a blinking cursor.

Change the else-if condition to always send the "disconnected" message
regardless of stream state.

Closes Termix-SSH/Support#648

* feat: support read-only Docker container mode (#721)

Move nginx runtime files (config, pid, logs, temp dirs) from /app/nginx/
to /tmp/nginx/ so the container can run with read_only: true. Template
files remain in /app/nginx/ as read-only assets.

Users can now harden the container with:
  read_only: true
  tmpfs:
    - /tmp

Closes Termix-SSH/Support#647

* fix: allow editing host folder without re-entering password (#722)

When editing an existing host, the password field is stripped by the
backend for security. The form validation treated the empty password
as invalid, disabling the Update Host button even for non-auth changes
like folder assignment.

Use an "existing_password" sentinel (mirroring the existing
"existing_key" pattern) to represent an unchanged password during
editing, skip validation for it, and omit it from the update payload.

Closes Termix-SSH/Support#645

* fix: auto-close tab on graceful SSH disconnect (exit/Ctrl+D) (#723)

Distinguish between graceful shell exit and unexpected disconnection
using the stream close event's exit code. When the shell exits normally
(code != null), send "session_ended" instead of "disconnected". The
frontend auto-closes the tab on session_ended, and shows the reconnect
overlay only on unexpected disconnections.

Closes Termix-SSH/Support#643

* fix: reattach existing SSH session on WebSocket reconnect (#724)

WebSocket reconnection was always creating a new SSH connection with
full authentication instead of reattaching to the existing SSH session.
The condition `!isReconnectingRef.current` prevented session reattach
during reconnection, causing repeated password auth attempts that
trigger SSHGuard/fail2ban blocking.

Remove the guard so reconnection tries to reattach the persisted
session first. If the session has expired, the backend sends
sessionExpired and the frontend falls back to a new connection.

Closes Termix-SSH/Support#644

* fix: prevent browser crash when uploading large files (>100MB) (#725)

The file-to-base64 conversion used a byte-by-byte string concatenation
loop (String.fromCharCode + btoa), which allocated ~3x the file size
in intermediate strings, causing the browser tab to OOM on files over
~100MB.

Replace with FileReader.readAsDataURL which delegates base64 encoding
to the browser engine natively, avoiding the intermediate allocations.

Closes Termix-SSH/Support#577

* fix: support SSH multi-factor auth with publickey + password (#726)

When sshd requires AuthenticationMethods publickey,password, the
connection failed because the key auth branch only set privateKey
without also setting password. After publickey partial auth succeeded,
ssh2 sent keyboard-interactive (due to tryKeyboard:true) instead of
password, which the server rejected.

Pass the credential password alongside the private key so ssh2 can
complete the password step after publickey succeeds.

Closes Termix-SSH/Support#629

* feat(oidc): add OIDC_ALLOW_REGISTRATION env to bypass allow_registration for OIDC (#727)

The `allow_registration` setting blocks both password-based and OIDC user
creation. Admins who want to close password registration but still onboard
new users via a trusted IdP (with the existing `OIDC_ALLOWED_USERS` whitelist)
have no way to do that today.

Introduce an `OIDC_ALLOW_REGISTRATION` env var. When set to `true`, the OIDC
callback skips the `allow_registration` settings check while still honoring
the `OIDC_ALLOWED_USERS` whitelist. Password registration via `POST
/users/create` continues to respect `allow_registration`.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* perf: lazy load locales, file previews, and decouple startup imports (#729)

* perf: lazy load locale bundles

* perf: lazy load file preview modules

* perf: avoid eager api client load on startup

* chore: remove dead code, tighten types, fix lint warnings (#730)

* chore: clean up low-risk lint warnings

* chore: tighten utility types

* chore: preserve backend error causes

* chore: simplify command palette host state

* chore: remove unused frontend code

* chore: prune stale frontend state

* chore: trim unused navigation code

* chore: prune unused user settings props

* chore: trim unused sidebar state

* chore: remove stale host editor imports

* chore: tighten shared frontend types

* chore: narrow desktop helper types

* chore: type network topology data

* chore: type connection log errors

* chore: use typed tab context

* chore: type api client error metadata

* chore: tighten terminal config types

* chore: type host proxy chains

* chore: type host editor form data

* chore: use typed host viewer fields

* chore: format app builder patch script

* Fix client auth cache after upgrades

* chore: fix pr checks after dev merge

* fix: remove duplicate session-expired useEffect in FullScreenAppWrapper

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Xenthys <x@dis.gg>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: npm package warnings

* feat: reconnect after file manager disconnects

* feat: add docs button in api keys

* feat: change colors for server tunnels

* fix: fetch password from API for Copy Password button (#736)

* chore: update readme's

* feat: improve c2s UI in user profile

* feat: improve ssh key detection and move open file manager at path for terminal button

* fix: restore missing getHostPassword import in Tab.tsx (#737)

* fix: security related fixes

* feat: improve alert code

* Fix Electron clipboard handling

* fix: untranslated alert text

---------

Co-authored-by: Xenthys <x@dis.gg>
Co-authored-by: PT Kelana Tech Solutions <ptkelanatechsolutions@gmail.com>
Co-authored-by: suryacagur <suryacagur.dev@gmail.com>
Co-authored-by: zimmra <28514085+zimmra@users.noreply.github.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Fuad <funtik1229@yandex.ru>
2026-05-06 15:12:07 -05:00

751 lines
24 KiB
TypeScript

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<number, LayoutNode> = {
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<Omit<TabData, "id">>) => void;
addTab: (tab: Omit<TabData, "id">) => 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<HTMLDivElement | null>(null);
const panelRefs = useRef<Record<string, HTMLDivElement | null>>({});
const [panelRects, setPanelRects] = useState<Record<string, DOMRect | null>>(
{},
);
const [resetKey, setResetKey] = useState<number>(0);
const previousStylesRef = useRef<Record<number, React.CSSProperties>>({});
const updatePanelRects = React.useCallback(() => {
const next: Record<string, DOMRect | null> = {};
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<number | null>(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<Set<number>>(new Set());
useEffect(() => {
terminalTabs.forEach((t) => terminalIdMapRef.current.add(t.id));
}, [terminalTabs]);
const renderTerminalsLayer = () => {
const styles: Record<number, React.CSSProperties> = {};
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 (
<div className="absolute inset-0 z-[1]">
{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 (
<div key={t.id} style={finalStyle}>
<div
className="absolute inset-0 rounded-md overflow-hidden"
style={{
backgroundColor: isTerminal
? backgroundColor
: "var(--bg-base)",
}}
>
<Suspense
fallback={
<SimpleLoader
visible={true}
message={translate("common.loading")}
backgroundColor={
isTerminal ? backgroundColor : "var(--bg-base)"
}
/>
}
>
{t.type === "terminal" ? (
<Terminal
key={`term-${t.id}-${t.instanceId || ""}`}
ref={t.terminalRef}
hostConfig={t.hostConfig}
isVisible={effectiveVisible}
title={t.title}
showTitle={false}
splitScreen={allSplitScreenTab.length > 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" ? (
<ServerView
key={`stats-${t.id}-${t.instanceId || ""}`}
hostConfig={t.hostConfig}
title={t.title}
isVisible={effectiveVisible}
isTopbarOpen={isTopbarOpen}
embedded
/>
) : t.type === "rdp" ||
t.type === "vnc" ||
t.type === "telnet" ? (
t.connectionConfig ? (
<GuacamoleDisplay
key={`guac-${t.id}-${t.instanceId || ""}`}
connectionConfig={t.connectionConfig}
isVisible={effectiveVisible}
onDisconnect={() => removeTab(t.id)}
onError={(err) => {
toast.error(err);
removeTab(t.id);
}}
/>
) : (
<div className="flex items-center justify-center h-full text-red-500">
Missing connection configuration
</div>
)
) : t.type === "network_graph" ? (
<NetworkGraphCard
key={`netgraph-${t.id}-${t.instanceId || ""}`}
isTopbarOpen={isTopbarOpen}
rightSidebarOpen={rightSidebarOpen}
rightSidebarWidth={rightSidebarWidth}
embedded={false}
/>
) : t.type === "tunnel" ? (
<TunnelManager
key={`tunnel-${t.id}-${t.instanceId || ""}`}
hostConfig={t.hostConfig}
title={t.title}
isVisible={effectiveVisible}
isTopbarOpen={isTopbarOpen}
embedded
/>
) : t.type === "docker" ? (
<DockerManager
key={`docker-${t.id}-${t.instanceId || ""}`}
hostConfig={t.hostConfig}
title={t.title}
isVisible={effectiveVisible}
isTopbarOpen={isTopbarOpen}
embedded
onClose={() => removeTab(t.id)}
/>
) : (
<FileManager
key={`filemgr-${t.id}-${t.instanceId || ""}`}
embedded
initialHost={t.hostConfig}
onClose={() => removeTab(t.id)}
/>
)}
</Suspense>
</div>
</div>
);
})}
</div>
);
};
const ResetButton = ({ onClick }: { onClick: () => void }) => (
<Button
type="button"
variant="ghost"
onClick={onClick}
aria-label="Reset split sizes"
className="absolute top-0 right-0 h-[28px] w-[28px] !rounded-none border-l-1 border-b-1 border-edge-panel bg-surface hover:bg-surface-hover text-foreground flex items-center justify-center p-0"
>
<RefreshCcw className="h-4 w-4" />
</Button>
);
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 (
<ResizablePanel
key={`panel-${tab.id}`}
id={`panel-${tab.id}`}
defaultSize={defaultSize}
minSize={20}
className="!overflow-hidden h-full w-full"
order={orderIndex}
>
<div
ref={(el) => {
panelRefs.current[String(tab.id)] = el;
}}
className="h-full w-full flex flex-col relative"
>
<div className="bg-surface text-foreground text-[13px] h-[28px] leading-[28px] px-[10px] border-b border-edge-panel tracking-[1px] m-0 pointer-events-auto z-[11] relative">
{tab.title}
{node === 1 && <ResetButton onClick={handleReset} />}
</div>
</div>
</ResizablePanel>
);
}
const groupKey = isRoot ? String(resetKey) : `${path}-${resetKey}`;
const groupId = isRoot ? `main-${node.direction}` : `group-${path}`;
const groupContent = (
<ResizablePanelGroup
key={groupKey}
direction={node.direction}
className="h-full w-full"
id={groupId}
{...commonGroupProps}
>
{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 [
<ResizableHandle
key={`handle-${childPath}`}
style={handleStyle}
/>,
panel,
];
})}
</ResizablePanelGroup>
);
if (isRoot) return groupContent;
return (
<ResizablePanel
key={`container-${path}`}
id={`container-${path}`}
defaultSize={defaultSize}
minSize={20}
className="!overflow-hidden h-full w-full"
order={orderIndex}
>
{groupContent}
</ResizablePanel>
);
};
return (
<div className="absolute inset-0 z-[10] pointer-events-none">
{renderNode(layout, "", 1, 1, true)}
</div>
);
};
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 (
<div
ref={containerRef}
className="border-2 border-edge rounded-lg overflow-hidden overflow-x-hidden relative"
style={{
background: containerBackground,
marginLeft: leftMarginPx,
marginRight: rightSidebarOpen
? `calc(var(--right-sidebar-width, ${rightSidebarWidth}px) + 8px)`
: 17,
marginTop: topMarginPx,
marginBottom: bottomMarginPx,
height: `calc(100vh - ${topMarginPx + bottomMarginPx}px)`,
transition:
"margin-left 200ms linear, margin-right 200ms linear, margin-top 200ms linear",
}}
>
{renderTerminalsLayer()}
{renderSplitOverlays()}
</div>
);
}