import { iconSvg } from "../icons/icons.js";
import { createDemoPty } from "../patterns/demo-pty.js";
const glyph = (name) => iconSvg(name, { size: 16 });
export function sshScreen({ t, heading }) {
return `${heading(t("SSH-консоль", "SSH console"), t("Терминал сервера с полноценной обработкой клавиатуры.", "Server terminal with full terminal keyboard handling."))}
${t("Подготовка терминала…", "Preparing terminal…")} Ctrl C / D / Z${t("Прервать / EOF / приостановить", "Interrupt / EOF / suspend")} Ctrl A / E / W / U / K / Y${t("Редактирование строки", "Line editing")} ↑ / ↓ · Ctrl R · Tab${t("История, поиск в истории, дополнение", "History, history search, completion")} Alt B / F / D${t("Перейти на слово / удалить слово", "Move by word / delete word")} Ctrl Shift C / V${t("Копировать выделение / вставить", "Copy selection / paste")} Ctrl Shift F${t("Поиск по выводу терминала", "Search terminal output")} Ctrl Shift M${t("Вернуть фокус интерфейсу", "Release focus to the interface")} ${t("Tab, Esc, Home/End, Delete, PgUp/PgDn и F1–F12 передаются терминалу. Для браузерных сочетаний используйте полный экран с Keyboard Lock, если он поддерживается. Часть системных клавиш остаётся за ОС; удержание Esc возвращает управление браузеру.", "Tab, Esc, Home/End, Delete, PgUp/PgDn and F1–F12 go to the terminal. Use fullscreen with Keyboard Lock for browser shortcuts where supported. Some keys stay with the OS; hold Esc to return control to the browser.")}${t("Клавиатура и управление", "Keyboard and controls")}
${t("Локальная демосессия: help, top, less gateway.log, tail -f gateway.log. Подключения к серверу и выполнения команд на вашем компьютере нет.", "Local demo session: help, top, less gateway.log, tail -f gateway.log. No server connection or commands run on your computer.")}
`; } export async function mountSsh( root, { t, notify, createTransport = createDemoPty } = {}, ) { const [{ Terminal }, { FitAddon }, { SearchAddon }] = await Promise.all([ import("../vendor/xterm/xterm.js"), import("../vendor/xterm/addon-fit.js"), import("../vendor/xterm/addon-search.js"), ]); if (!root.isConnected) return () => {}; const $ = (s) => root.querySelector(s), host = $("[data-terminal]"), abort = new AbortController(), signal = abort.signal; const term = new Terminal({ fontFamily: '"Cascadia Mono",Consolas,"Liberation Mono",monospace', fontSize: 14, lineHeight: 1.35, cursorBlink: !matchMedia("(prefers-reduced-motion: reduce)").matches, cursorStyle: "block", scrollback: 5000, screenReaderMode: true, allowProposedApi: false, theme: { background: "#000000", foreground: "#e3f2f3", cursor: "#77cbbb", cursorAccent: "#000000", selectionBackground: "#3b5f69", black: "#182a32", red: "#ffaaa2", green: "#9dd2ae", yellow: "#e8c889", blue: "#9cc5f1", magenta: "#d4b8e4", cyan: "#77cbbb", white: "#e3f2f3", brightBlack: "#a5bec5", }, }); const fit = new FitAddon(), search = new SearchAddon(); term.loadAddon(fit); term.loadAddon(search); host.replaceChildren(); term.open(host); host.setAttribute("role", "group"); host.setAttribute("aria-label", t("SSH-терминал", "SSH terminal")); term.textarea.setAttribute( "aria-label", t( "SSH-терминал. Ctrl Shift M — выйти из перехвата.", "SSH terminal. Ctrl Shift M releases keyboard capture.", ), ); let transport, connected = false, capture = true, disposed = false, raf = 0, locked = false; const announce = (message) => { if (!disposed) notify(message); }; function unlock() { navigator.keyboard?.unlock?.(); locked = false; } function keyboardStatus() { if (disposed) return; const focused = document.activeElement === term.textarea; $("[data-keyboard-status]").textContent = locked ? t("Keyboard Lock включён", "Keyboard Lock active") : focused && capture ? t( "Клавиши → SSH · Ctrl Shift M — выйти", "Keys → SSH · Ctrl Shift M to release", ) : t("Фокус вне терминала", "Terminal is not focused"); } async function lock() { if ( document.fullscreenElement !== root || !capture || !connected || !navigator.keyboard?.lock ) return; try { await navigator.keyboard.lock(); if ( disposed || document.fullscreenElement !== root || !capture || !connected || document.activeElement !== term.textarea ) { unlock(); return; } locked = true; } catch { locked = false; } keyboardStatus(); } function state() { const badge = $("[data-ssh-state]"); badge.classList.toggle("status-badge--success", connected); badge.innerHTML = glyph(connected ? "check" : "close") + " " + (connected ? t("Демосессия", "Demo session") : t("Отключено", "Disconnected")); $('[data-ssh="connect"]').textContent = connected ? t("Отключиться", "Disconnect") : t("Подключить", "Connect"); $('[data-ssh="paste"]').disabled = !connected; term.options.disableStdin = !capture || !connected; keyboardStatus(); } function refit() { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => { if (disposed || !root.isConnected) return; try { fit.fit(); $("[data-terminal-size]").textContent = `${term.cols} × ${term.rows}`; transport?.resize(term.cols, term.rows); } catch {} }); } function connect() { transport?.dispose(); term.reset(); connected = true; transport = createTransport({ host: $("[data-ssh-host]").value, cols: term.cols, rows: term.rows, write: (data) => { if (!disposed) term.write(data); }, onClose: () => { connected = false; unlock(); state(); }, }); state(); refit(); } function setCapture(enabled) { capture = enabled; const button = $('[data-ssh="capture"]'); button.setAttribute("aria-pressed", String(enabled)); button.querySelector("span").textContent = enabled ? t("Ввод включён", "Input enabled") : t("Ввод выключен", "Input disabled"); state(); if (enabled) { term.focus(); lock(); } else { unlock(); button.focus(); } } async function copy() { if (!term.hasSelection()) { announce( t("Сначала выделите текст в терминале", "Select terminal text first"), ); return; } try { await navigator.clipboard.writeText(term.getSelection()); announce(t("Выделение скопировано", "Selection copied")); } catch { announce( t( "Копирование недоступно в этом браузере", "Copying is unavailable in this browser", ), ); } } async function pasteClipboard() { try { const text = await navigator.clipboard.readText(); if (disposed || !connected) return; term.paste(text); term.focus(); } catch { announce( t("Используйте Ctrl Shift V для вставки", "Use Ctrl Shift V to paste"), ); } } function find(previous = false) { const query = $("[data-ssh-query]").value; if (!query) { $("[data-search-result]").textContent = ""; search.clearDecorations(); return; } const found = previous ? search.findPrevious(query) : search.findNext(query); $("[data-search-result]").textContent = found ? t("Найдено", "Match found") : t("Нет совпадений", "No matches"); } function openSearch() { unlock(); $(".ssh-find").hidden = false; $("[data-ssh-query]").focus(); refit(); } function closeSearch() { $(".ssh-find").hidden = true; search.clearDecorations(); refit(); term.focus(); } term.attachCustomKeyEventHandler((event) => { if (!capture || !connected) return false; event.stopPropagation(); if (event.type !== "keydown") return true; const key = event.key.toLowerCase(), ctrl = event.ctrlKey && !event.altKey && !event.metaKey; if (ctrl && event.shiftKey && key === "m") { event.preventDefault(); setCapture(false); return false; } if ( (ctrl && event.shiftKey && key === "c") || (event.metaKey && key === "c") ) { event.preventDefault(); copy(); return false; } if ( (ctrl && event.shiftKey && key === "v") || (event.metaKey && key === "v") || (event.shiftKey && key === "insert") ) return false; // Native paste event is handled by xterm; do not cancel the browser paste. if (ctrl && event.shiftKey && key === "f") { event.preventDefault(); openSearch(); return false; } if (event.metaKey && key === "a") { event.preventDefault(); term.selectAll(); return false; } return true; }); const data = term.onData((value) => { if (connected && capture) transport?.send(value); }); const resize = term.onResize(({ cols, rows }) => { $("[data-terminal-size]").textContent = `${cols} × ${rows}`; }); const observer = new ResizeObserver(refit); observer.observe(host); term.textarea.addEventListener( "focus", () => { keyboardStatus(); if (document.fullscreenElement === root) lock(); }, { signal }, ); term.textarea.addEventListener( "blur", () => { unlock(); keyboardStatus(); }, { signal }, ); $("[data-ssh-host]").addEventListener( "change", () => { connect(); term.focus(); }, { signal }, ); root.addEventListener( "click", async (event) => { const action = event.target.closest("[data-ssh]")?.dataset.ssh; if (!action) return; if (action === "connect") { if (connected) transport.close(); else { connect(); term.focus(); } } if (action === "capture") setCapture(!capture); if (action === "copy") copy(); if (action === "paste") pasteClipboard(); if (action === "search") openSearch(); if (action === "close-search") closeSearch(); if (action === "previous") find(true); if (action === "fullscreen") { try { if (document.fullscreenElement === root) { unlock(); await document.exitFullscreen(); } else { await root.requestFullscreen(); term.focus(); await lock(); } } catch { announce( t("Полноэкранный режим недоступен", "Fullscreen is unavailable"), ); } } }, { signal }, ); $(".ssh-find").addEventListener( "submit", (e) => { e.preventDefault(); find(); }, { signal }, ); $("[data-ssh-query]").addEventListener("input", () => find(), { signal }); $(".ssh-find").addEventListener( "keydown", (e) => { e.stopPropagation(); if (e.key === "Escape") { e.preventDefault(); closeSearch(); } if (e.key === "Enter" && e.shiftKey) { e.preventDefault(); find(true); } }, { signal }, ); document.addEventListener( "fullscreenchange", () => { if (document.fullscreenElement !== root) unlock(); $('[data-ssh="fullscreen"] span').textContent = document.fullscreenElement === root ? t("Выйти из экрана", "Exit fullscreen") : t("Полный экран", "Fullscreen"); keyboardStatus(); refit(); }, { signal }, ); connect(); return () => { disposed = true; abort.abort(); unlock(); cancelAnimationFrame(raf); observer.disconnect(); transport?.dispose(); data.dispose(); resize.dispose(); term.dispose(); if (document.fullscreenElement === root) document.exitFullscreen().catch(() => {}); }; }