Skip to content

Modern Docker Management, Designed for Everyone

5.3 KB
Raw Blame
<script lang="ts">
	import { FitAddon } from '@xterm/addon-fit';
	import { Terminal } from '@xterm/xterm';
	import { mode } from 'mode-watcher';

	import '@xterm/xterm/css/xterm.css';
	import { untrack } from 'svelte';

	import { m } from '#lib/paraglide/messages.js';

	let {
		websocketUrl,
		height = '100%',
		onConnected,
		onDisconnected
	}: {
		websocketUrl: string;
		height?: string;
		onConnected?: () => void;
		onDisconnected?: () => void;
	} = $props();

	let container: HTMLDivElement | null = null;
	let terminal: Terminal | null = null;
	let fitAddon: FitAddon | null = null;
	let ws: WebSocket | null = null;
	let isReconnecting = false;
	let openedAt = 0;
	let resizeObserver: ResizeObserver | null = null;
	let fitFrame = 0;

	const darkTheme = {
		background: '#09090b',
		foreground: '#e4e4e7',
		cursor: '#e4e4e7',
		selectionBackground: 'rgba(96, 165, 250, 0.40)',
		selectionInactiveBackground: 'rgba(96, 165, 250, 0.25)',
		black: '#18181b',
		red: '#f87171',
		green: '#4ade80',
		yellow: '#facc15',
		blue: '#60a5fa',
		magenta: '#c084fc',
		cyan: '#22d3ee',
		white: '#e4e4e7',
		brightBlack: '#52525b',
		brightRed: '#fca5a5',
		brightGreen: '#86efac',
		brightYellow: '#fde047',
		brightBlue: '#93c5fd',
		brightMagenta: '#d8b4fe',
		brightCyan: '#67e8f9',
		brightWhite: '#fafafa'
	};

	const lightTheme = {
		background: '#ffffff',
		foreground: '#18181b',
		cursor: '#18181b',
		selectionBackground: 'rgba(59, 130, 246, 0.35)',
		selectionInactiveBackground: 'rgba(59, 130, 246, 0.25)',
		black: '#18181b',
		red: '#dc2626',
		green: '#16a34a',
		yellow: '#ca8a04',
		blue: '#2563eb',
		magenta: '#9333ea',
		cyan: '#0891b2',
		white: '#fafafa',
		brightBlack: '#71717a',
		brightRed: '#ef4444',
		brightGreen: '#22c55e',
		brightYellow: '#eab308',
		brightBlue: '#3b82f6',
		brightMagenta: '#a855f7',
		brightCyan: '#06b6d4',
		brightWhite: '#ffffff'
	};

	function initializeTerminal(node: HTMLDivElement) {
		container = node;

		if (terminal) {
			terminal.dispose();
		}

		terminal = new Terminal({
			cursorBlink: true,
			cursorStyle: 'underline',
			fontSize: 14,
			fontFamily: 'Mona Sans Mono, monospace',
			theme: mode.current === 'dark' ? darkTheme : lightTheme
		});

		fitAddon = new FitAddon();
		terminal.loadAddon(fitAddon);
		terminal.open(node);

		fitFrame = requestAnimationFrame(() => {
			if (fitAddon && node.offsetParent !== null) {
				fitAddon.fit();
			}
		});

		terminal.onData((data) => {
			if (ws && ws.readyState === WebSocket.OPEN) {
				ws.send(data);
			}
		});

		resizeObserver = new ResizeObserver(() => {
			handleResize();
		});
		resizeObserver.observe(node);
	}

	function connectWebSocket(url: string) {
		if (ws) {
			isReconnecting = true;
			ws.onopen = null;
			ws.onclose = null;
			ws.onerror = null;
			ws.onmessage = null;
			ws.close();
			ws = null;
		}

		isReconnecting = false;
		ws = new WebSocket(url);
		ws.binaryType = 'arraybuffer';

		ws.onopen = () => {
			openedAt = Date.now();
			onConnected?.();
		};

		ws.onmessage = (event) => {
			if (!terminal) return;
			if (event.data instanceof ArrayBuffer) {
				const uint8Array = new Uint8Array(event.data);
				const text = new TextDecoder().decode(uint8Array);
				terminal.write(text);
			} else {
				terminal.write(event.data);
			}
		};

		ws.onerror = () => {
			if (!isReconnecting && terminal) {
				terminal.writeln(`\r\n\x1b[31m${m.terminal_websocket_error()}\x1b[0m`);
			}
		};

		ws.onclose = (event) => {
			if (!isReconnecting && terminal) {
				// Surface the close code so reports of unexpected disconnects
				// carry the reason (server 1000/1006, proxy 1001, ...) — see #3536.
				console.warn('Terminal websocket closed', {
					code: event.code,
					reason: event.reason,
					wasClean: event.wasClean,
					durationMs: openedAt ? Date.now() - openedAt : null
				});
				const detail = event.reason ? `${event.code}: ${event.reason}` : `${event.code}`;
				terminal.writeln(`\r\n\x1b[33m${m.terminal_connection_closed()} (${detail})\x1b[0m`);
				onDisconnected?.();
			}
		};
	}

	function handleResize() {
		if (fitAddon && container && container.offsetParent !== null) {
			try {
				fitAddon.fit();
			} catch (e) {
				console.warn('Terminal resize failed:', e);
			}
		}
	}

	function attachTerminal(node: HTMLDivElement) {
		untrack(() => initializeTerminal(node));

		$effect(() => {
			if (websocketUrl) {
				terminal?.clear();
				connectWebSocket(websocketUrl);
			}
		});

		$effect(() => {
			if (terminal && mode.current) {
				terminal.options.theme = mode.current === 'dark' ? darkTheme : lightTheme;
			}
		});

		return () => {
			cancelAnimationFrame(fitFrame);
			resizeObserver?.disconnect();
			resizeObserver = null;
			isReconnecting = true;
			if (ws) {
				ws.onopen = null;
				ws.onclose = null;
				ws.onerror = null;
				ws.onmessage = null;
				ws.close();
				ws = null;
			}
			terminal?.dispose();
			terminal = null;
			fitAddon = null;
			container = null;
		};
	}
</script>

<svelte:window onresize={handleResize} />

<div {@attach attachTerminal} class="terminal-container h-(--terminal-height) w-full" style="--terminal-height: {height}"></div>

<style>
	:global(.terminal-container .xterm) {
		padding: 8px 12px;
	}

	:global(.terminal-container .xterm-viewport) {
		background-color: transparent !important;
	}

	:global(.terminal-container .xterm-screen) {
		background-color: transparent !important;
	}
</style>