Add SSH console and log reader workspaces
This commit is contained in:
1 parent
0561fb1596
commit
cd821abb51
68 files changed
+3227
-5
No files matched your search
@@ -0,0 +1,397 @@
|
||||
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."))}
|
||||
<section id="ssh-workspace" class="ssh-workspace" aria-label="${t("SSH-сессия", "SSH session")}">
|
||||
<div class="workspace-toolbar"><div class="workspace-context"><span class="status-badge status-badge--success" data-ssh-state>${glyph("check")} ${t("Демосессия", "Demo session")}</span><label class="workspace-host">${t("Сервер", "Server")}<select data-ssh-host aria-label="${t("Сервер SSH", "SSH server")}"><option>edge-01</option><option>worker-02</option></select></label><span class="workspace-meta">dev · :22</span></div><div class="workspace-actions"><button type="button" data-ssh="search" aria-label="${t("Поиск в консоли", "Search terminal")}">${glyph("search")}</button><button type="button" data-ssh="copy" aria-label="${t("Копировать выделение", "Copy selection")}">${glyph("copy")}</button><button type="button" data-ssh="paste" aria-label="${t("Вставить", "Paste")}">${glyph("upload")}</button><button type="button" data-ssh="fullscreen">${glyph("external-link")}<span>${t("Полный экран", "Fullscreen")}</span></button><button type="button" data-ssh="connect">${t("Отключиться", "Disconnect")}</button></div></div>
|
||||
<form class="ssh-find" hidden role="search"><label>${t("Поиск по выводу", "Search output")}<input type="search" data-ssh-query autocomplete="off"></label><button type="button" data-ssh="previous" aria-label="${t("Предыдущее совпадение", "Previous match")}">${glyph("chevron-up")}</button><button type="submit" aria-label="${t("Следующее совпадение", "Next match")}">${glyph("chevron-down")}</button><span data-search-result role="status"></span><button type="button" data-ssh="close-search" aria-label="${t("Закрыть поиск", "Close search")}">${glyph("close")}</button></form>
|
||||
<div class="ssh-terminal" data-terminal aria-label="${t("Терминал загружается", "Terminal loading")}"><p class="workspace-loading">${t("Подготовка терминала…", "Preparing terminal…")}</p></div>
|
||||
<div class="terminal-status"><button type="button" data-ssh="capture" aria-pressed="true">${glyph("terminal")}<span>${t("Ввод включён", "Input enabled")}</span></button><span data-keyboard-status>${t("Нажмите в терминале для ввода", "Click the terminal to type")}</span><span class="terminal-dimensions" data-terminal-size>—</span><span>UTF-8</span></div>
|
||||
<details class="terminal-help"><summary>${t("Клавиатура и управление", "Keyboard and controls")}</summary><div class="terminal-shortcuts"><p><kbd>Ctrl C / D / Z</kbd><span>${t("Прервать / EOF / приостановить", "Interrupt / EOF / suspend")}</span></p><p><kbd>Ctrl A / E / W / U / K / Y</kbd><span>${t("Редактирование строки", "Line editing")}</span></p><p><kbd>↑ / ↓ · Ctrl R · Tab</kbd><span>${t("История, поиск в истории, дополнение", "History, history search, completion")}</span></p><p><kbd>Alt B / F / D</kbd><span>${t("Перейти на слово / удалить слово", "Move by word / delete word")}</span></p><p><kbd>Ctrl Shift C / V</kbd><span>${t("Копировать выделение / вставить", "Copy selection / paste")}</span></p><p><kbd>Ctrl Shift F</kbd><span>${t("Поиск по выводу терминала", "Search terminal output")}</span></p><p><kbd>Ctrl Shift M</kbd><span>${t("Вернуть фокус интерфейсу", "Release focus to the interface")}</span></p></div><p class="workspace-note">${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.")}</p></details>
|
||||
</section><p class="workspace-note">${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.")}</p>`;
|
||||
}
|
||||
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(() => {});
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user