diff --git a/DESIGN.md b/DESIGN.md index 1b346c5..424a1f9 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -41,3 +41,9 @@ SSO Service не изменяется, реальные почта, OAuth и Web icons/icons.js — общий источник 64 линейных иконок. Сетка 24×24, stroke 1.5, круглые окончания и соединения, currentColor. Отдельные SVG, sprite и обзорные листы генерируются scripts/build-icons.mjs. Не рисуйте локальные варианты тех же значков внутри компонентов. Каталог расположен в icons/index.html; ссылка есть на странице компонентов. В Dock SVG занимает 24×24, первый трек кнопки — 50px. Иконки, логотип и аватар имеют общую центральную ось в свёрнутом меню и сохраняют её при расширении. Фокус — внутренняя обводка 2px, не обрезается краем панели. Пункты меню не смещаются по вертикали при нажатии. У диалогов центрированная SVG-кнопка закрытия. Рамки пустых/ошибочных состояний, контекстных областей и кода используют единый radius-control. + +## Операционные рабочие области + +SSH-консоль и log-ридер — собственные страницы Dock, а также образцы на странице компонентов. Терминал имеет чёрный фон #000 в обеих темах; текст и ANSI-палитра рассчитаны на этот фон. Обрамление и инструменты используют выбранную тему Dock. Площадь терминала автоматически пересчитывает количество строк и колонок. Перехват клавиатуры ограничен фокусом терминала, предусмотрен доступный выход Ctrl+Shift+M. + +Log-ридер использует моноширинные строки, явные уровни DEBUG/INFO/WARN/ERROR, фильтры и отдельную панель события. На мобильном метаданные переносятся над сообщением, без горизонтального скролла всей страницы. Открытие события останавливает следование, чтобы поток не сдвигал выбранные данные. diff --git a/README.md b/README.md index 20f0ec8..67b38e6 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,14 @@ node scripts/serve.mjs 64 иконки в общей сетке 24×24: отдельные SVG, sprite, JS-модуль, manifest и обзорные листы обеих тем. Каталог поддерживает поиск, разделы, размеры 16/20/24/32/48px и копирование SVG. Пак подключён к навигации и входит в экспорт системы. Исходник — icons/icons.js; сборка: `npm run icons:build`, проверка: `npm run test:icons`. +## SSH-консоль и log-ридер + +[SSH-консоль](http://127.0.0.1:4173/?page=ssh) · [Log-ридер](http://127.0.0.1:4173/?page=logs). + +Рабочие демо-экраны доступны из Dock и страницы компонентов. SSH использует xterm.js, чёрный фон в обеих темах, поиск, resize, буфер обмена, fullscreen и Keyboard Lock по поддержке браузера. Ctrl+Shift+M возвращает фокус интерфейсу. Log-ридер поддерживает фильтры, поиск, паузу/follow, детали JSON, локальные файлы и экспорт. [Контракт и подключение backend](patterns/WORKSPACES.md). + +Для просмотра npm install не требуется: MIT runtime включён в vendor/xterm. Восстановление зависимостей: `npm ci`; обновление vendored-копий: `npm run terminal:vendor`; проверка: `npm run test:workspaces`. Реальные SSH-соединения и серверные команды в демо не выполняются. + ## Возможности Самостоятельный сайт Dock на весь экран, без внешней панели просмотра и iframe. Разделы открываются собственной навигацией, URL поддерживают перезагрузку и Back/Forward. Светлая/тёмная тема выбирается в личном кабинете и сохраняется. Параметры locale/density/accent доступны в URL; внешних регуляторов нет. Компоненты и токены — собственные страницы Dock. Экспорт находится на странице токенов. Старый /playground/ перенаправляет на корень с сохранением параметров. diff --git a/components/CONTRACT.md b/components/CONTRACT.md index a288731..5401fc8 100644 --- a/components/CONTRACT.md +++ b/components/CONTRACT.md @@ -10,6 +10,8 @@ Бейджи статуса: status-badge — подпись, декоративная SVG 16px, мягкий семантический фон и рамка. Success — check, danger — close, pending — more-horizontal. Это информационные метки; без hover, фокуса и курсора кнопки. Минимальная высота 28px, контраст подписи не ниже 4.5:1 в обеих темах. Образец находится в компонентах. +Рабочие области: SSH — xterm.js, black surface, resize, управляющие коды, history/completion, clipboard, поиск, fullscreen и Keyboard Lock с fallback. Перехват действует только в активном терминале; Ctrl+Shift+M возвращает фокус панели, выключенный ввод не перехватывает Tab. Log reader — текст/level/source-фильтры, пауза с очередью, follow, ограниченные окна строк, детали JSON, безопасное чтение файлов и экспорт. Контракт транспорта, ограничения браузера и cleanup описаны в patterns/WORKSPACES.md. + Исполняемые образцы: экран Components; таблица и фильтры — Users; вкладки — Settings; вход — Authentication. Основная стилизация в `system.css`. | Компонент | Состояния и взаимодействия | diff --git a/components/export-system.js b/components/export-system.js index 13183f1..e1c8a1f 100644 --- a/components/export-system.js +++ b/components/export-system.js @@ -105,6 +105,19 @@ export async function exportSystem( "icons/anidev-dock-icons.zip", ...iconNames.map((name) => `icons/svg/${name}.svg`), "components/system.css", + "components/workspaces.css", + "components/ssh-console.js", + "components/log-reader.js", + "patterns/demo-pty.js", + "patterns/WORKSPACES.md", + "vendor/xterm/xterm.js", + "vendor/xterm/xterm.css", + "vendor/xterm/addon-fit.js", + "vendor/xterm/addon-search.js", + "vendor/xterm/xterm.LICENSE", + "vendor/xterm/addon-fit.LICENSE", + "vendor/xterm/addon-search.LICENSE", + "vendor/xterm/manifest.json", "components/export-system.js", "components/account-pages.js", "patterns/demo-identity.js", diff --git a/components/log-reader.js b/components/log-reader.js new file mode 100644 index 0000000..9c05314 --- /dev/null +++ b/components/log-reader.js @@ -0,0 +1,471 @@ +import { iconSvg } from "../icons/icons.js"; +const glyph = (name) => iconSvg(name, { size: 16 }); +export const logLevels = ["DEBUG", "INFO", "WARN", "ERROR"]; +export function parseLogText(text) { + return text + .split(/\r?\n/) + .filter((s) => s.trim()) + .map((line, i) => { + try { + const data = JSON.parse(line); + if (data && typeof data === "object" && !Array.isArray(data)) { + const raw = String( + data.level || data.severity || "INFO", + ).toUpperCase(), + level = + raw === "WARNING" + ? "WARN" + : logLevels.includes(raw) + ? raw + : "INFO"; + return { + id: i + 1, + time: String(data.timestamp || data.time || ""), + level, + source: String(data.source || data.service || "file"), + message: String(data.message || data.msg || line), + fields: data, + raw: line, + }; + } + } catch {} + const match = line.match( + /^(\S+)\s+(DEBUG|INFO|WARN|WARNING|ERROR)\s+(\S+)\s+(.*)$/i, + ); + return { + id: i + 1, + time: match?.[1] || "", + level: match + ? match[2].toUpperCase() === "WARNING" + ? "WARN" + : match[2].toUpperCase() + : "INFO", + source: match?.[3] || "file", + message: match?.[4] || line, + fields: { line: i + 1 }, + raw: line, + }; + }); +} +function demoRecord(id) { + const level = + id % 19 === 0 + ? "ERROR" + : id % 11 === 0 + ? "WARN" + : id % 5 === 0 + ? "DEBUG" + : "INFO", + source = ["gateway", "identity", "worker"][id % 3]; + return { + id, + time: new Date( + Date.UTC(2026, 11, 1, 12, 8, Math.floor(id / 3)), + ).toISOString(), + level, + source, + message: + level === "ERROR" + ? "Upstream timeout: retry scheduled" + : level === "WARN" + ? "Rate limit approached for tenant demo" + : level === "DEBUG" + ? "Connection pool reused" + : source === "identity" + ? "Session verified successfully" + : source === "worker" + ? "Background job completed" + : "HTTP request completed", + fields: { + request_id: `demo-${String(id).padStart(5, "0")}`, + duration_ms: 12 + (id % 47), + status: level === "ERROR" ? 504 : 200, + }, + raw: null, + }; +} +export function logsScreen({ t, heading }) { + return `${heading(t("Журнал событий", "Log reader"), t("Поиск, фильтрация и чтение потока без потери контекста.", "Search, filter and inspect a stream without losing context."))} +
+
${glyph("check")} ${t("Демопоток", "Demo stream")}anidev / production.log
+ +
    + +

    ${t("Поток демонстрационный. Поддерживаются локальные .log, .txt и JSONL до 8 МБ. Храним последние 2000 событий; в окне — до 150 строк. Ctrl F — поиск, Ctrl End — последние события.", "This is a demo stream. Open local .log, .txt and JSONL files up to 8 MB. The latest 2,000 events are retained; up to 150 lines are rendered. Ctrl F searches, Ctrl End jumps to the latest events.")}

    `; +} +export function mountLogs(root, { t, escape: e, notify }) { + const $ = (s) => root.querySelector(s), + abort = new AbortController(), + signal = abort.signal; + let records = Array.from({ length: 96 }, (_, i) => demoRecord(i + 1)), + id = 96, + paused = false, + pending = [], + follow = true, + windowEnd = Infinity, + selected = null, + unseen = 0, + mode = "demo", + disposed = false, + rendering = false; + const viewport = $(".log-viewport"), + list = $(".log-lines"); + const rowText = (r) => + `${r.time} ${r.level} ${r.source} ${r.message} ${JSON.stringify(r.fields)}`; + function filtered() { + const query = $("[data-log-query]").value.toLowerCase(), + level = $("[data-log-level]").value, + source = $("[data-log-source]").value; + return records.filter( + (r) => + (!level || r.level === level) && + (!source || r.source === source) && + (!query || rowText(r).toLowerCase().includes(query)), + ); + } + function highlight(text) { + const query = $("[data-log-query]").value; + if (!query) return e(text); + let start = 0, + result = "", + at; + while ( + (at = text.toLowerCase().indexOf(query.toLowerCase(), start)) !== -1 + ) { + result += + e(text.slice(start, at)) + + "" + + e(text.slice(at, at + query.length)) + + ""; + start = at + query.length; + } + return result + e(text.slice(start)); + } + function sources() { + const select = $("[data-log-source]"), + value = select.value; + select.innerHTML = + `` + + [...new Set(records.map((r) => r.source))] + .sort() + .map((source) => ``) + .join(""); + select.value = value; + } + function status() { + const badge = $("[data-log-state]"); + badge.classList.toggle("status-badge--success", mode === "demo" && !paused); + badge.innerHTML = + glyph(mode === "file" ? "file" : paused ? "more-horizontal" : "check") + + " " + + (mode === "file" + ? t("Файл", "File") + : paused + ? t("Пауза", "Paused") + : t("Демопоток", "Demo stream")); + $('[data-log="pause"]').textContent = paused + ? t("Продолжить", "Resume") + : t("Пауза", "Pause"); + $('[data-log="pause"]').disabled = mode === "file"; + $('[data-log="demo"]').hidden = mode === "demo"; + $('[data-log="follow"]').setAttribute("aria-pressed", String(follow)); + $("[data-log-unseen]").hidden = unseen === 0; + $("[data-log-unseen]").textContent = String(unseen); + if (paused && pending.length) + $("[data-log-count]").textContent = t( + `На паузе · новых событий: ${pending.length}`, + `Paused · ${pending.length} new events`, + ); + } + function details(record, focus = false) { + selected = record?.id ?? null; + const panel = $(".log-details"); + panel.hidden = !record; + root.classList.toggle("has-log-details", Boolean(record)); + if (!record) return; + $("[data-log-details-summary]").textContent = + `${record.time} · ${record.level} · ${record.source}`; + $("[data-log-json]").textContent = JSON.stringify( + { + timestamp: record.time, + level: record.level, + source: record.source, + message: record.message, + ...record.fields, + }, + null, + 2, + ); + if (focus) $('[data-log="close-details"]').focus(); + } + function render() { + if (disposed) return; + const matches = filtered(), + end = Math.min(matches.length, windowEnd), + start = Math.max(0, end - 150), + visible = matches.slice(start, end); + rendering = true; + list.innerHTML = visible + .map( + (r, i) => + `
  1. `, + ) + .join(""); + $(".log-empty").hidden = visible.length > 0; + $("[data-log-count]").textContent = t( + `${visible.length ? start + 1 : 0}–${end} из ${matches.length} · всего ${records.length}`, + `${visible.length ? start + 1 : 0}–${end} of ${matches.length} · ${records.length} total`, + ); + $('[data-log="older"]').disabled = start === 0; + $('[data-log="newer"]').disabled = end === matches.length; + $('[data-log="download"]').disabled = matches.length === 0; + if (selected && !visible.some((r) => r.id === selected)) details(null); + status(); + if (follow) viewport.scrollTop = viewport.scrollHeight; + requestAnimationFrame(() => { + rendering = false; + }); + } + function filter() { + windowEnd = Infinity; + selected = null; + details(null); + render(); + } + function newest() { + follow = true; + windowEnd = Infinity; + unseen = 0; + render(); + } + function closeDetails() { + const old = selected; + details(null); + render(); + root.querySelector(`[data-record="${old}"]`)?.focus(); + } + sources(); + render(); + const timer = setInterval(() => { + if (disposed || mode !== "demo") return; + const record = demoRecord(++id); + if (paused) { + pending.push(record); + pending = pending.slice(-2000); + status(); + return; + } + records.push(record); + records = records.slice(-2000); + if (follow) render(); + else { + unseen++; + status(); + } + }, 1300); + root.addEventListener( + "click", + async (event) => { + const row = event.target.closest("[data-record]"); + if (row) { + follow = false; + const record = records.find((r) => r.id === Number(row.dataset.record)); + details(record, true); + render(); + return; + } + const action = event.target.closest("[data-log]")?.dataset.log; + if (!action) return; + if (action === "pause") { + paused = !paused; + if (!paused) { + records = [...records, ...pending].slice(-2000); + pending = []; + } + render(); + } + if (action === "follow") newest(); + if (action === "older") { + follow = false; + windowEnd = Math.max(150, Math.min(filtered().length, windowEnd) - 150); + render(); + } + if (action === "newer") { + const count = filtered().length; + windowEnd = Math.min(count, windowEnd + 150); + if (windowEnd === count) windowEnd = Infinity; + render(); + } + if (action === "clear") { + records = []; + pending = []; + unseen = 0; + selected = null; + details(null); + render(); + } + if (action === "reset") { + $("[data-log-query]").value = ""; + $("[data-log-level]").value = ""; + $("[data-log-source]").value = ""; + filter(); + } + if (action === "close-details") closeDetails(); + if (action === "demo") { + mode = "demo"; + paused = false; + pending = []; + records = Array.from({ length: 96 }, (_, i) => demoRecord(i + 1)); + id = 96; + follow = true; + windowEnd = Infinity; + unseen = 0; + $("[data-log-file]").textContent = "anidev / production.log"; + sources(); + details(null); + render(); + } + if (action === "copy") { + try { + await navigator.clipboard.writeText($("[data-log-json]").textContent); + notify(t("JSON скопирован", "JSON copied")); + } catch { + notify(t("Копирование недоступно", "Copying is unavailable")); + } + } + if (action === "download") { + const content = + filtered() + .map( + (r) => + r.raw || + `${r.time} ${r.level} ${r.source} ${r.message} ${JSON.stringify(r.fields)}`, + ) + .join("\n") + "\n", + url = URL.createObjectURL( + new Blob([content], { type: "text/plain;charset=utf-8" }), + ), + a = document.createElement("a"); + a.href = url; + a.download = "anidev-filtered.log"; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } + }, + { signal }, + ); + for (const name of ["query", "level", "source"]) + $(`[data-log-${name}]`).addEventListener( + name === "query" ? "input" : "change", + filter, + { signal }, + ); + $(".log-filters").addEventListener("submit", (e) => e.preventDefault(), { + signal, + }); + viewport.addEventListener( + "scroll", + () => { + if (rendering) return; + if ( + viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop > + 32 + ) { + follow = false; + status(); + } + }, + { signal }, + ); + root.addEventListener( + "keydown", + (event) => { + const formField = event.target.matches("input,select,textarea"); + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "f") { + event.preventDefault(); + event.stopPropagation(); + $("[data-log-query]").focus(); + return; + } + if (!formField && event.ctrlKey && event.key === "End") { + event.preventDefault(); + newest(); + return; + } + if (event.key === "Escape" && !$(".log-details").hidden) { + event.preventDefault(); + event.stopPropagation(); + closeDetails(); + return; + } + if (formField || !event.target.closest(".log-viewport")) return; + const buttons = [...root.querySelectorAll(".log-row")], + index = buttons.indexOf(document.activeElement); + let next; + if (event.key === "ArrowDown") + next = Math.min(buttons.length - 1, index + 1); + if (event.key === "ArrowUp") next = Math.max(0, index - 1); + if (event.key === "Home") next = 0; + if (event.key === "End") next = buttons.length - 1; + if (next !== undefined) { + event.preventDefault(); + buttons.forEach((b) => (b.tabIndex = -1)); + if (buttons[next]) { + buttons[next].tabIndex = 0; + buttons[next].focus(); + } + } + }, + { signal }, + ); + $("[data-log-input]").addEventListener( + "change", + async (event) => { + const file = event.target.files?.[0]; + if (!file) return; + if (file.size > 8 * 1024 * 1024) { + notify( + t("Максимальный размер файла — 8 МБ", "Maximum file size is 8 MB"), + ); + event.target.value = ""; + return; + } + try { + const parsed = parseLogText(await file.text()); + if (disposed) return; + mode = "file"; + paused = true; + pending = []; + records = parsed.slice(-2000); + id = records.at(-1)?.id || 0; + follow = true; + windowEnd = Infinity; + selected = null; + unseen = 0; + $("[data-log-file]").textContent = file.name; + $("[data-log-query]").value = ""; + $("[data-log-level]").value = ""; + $("[data-log-source]").value = ""; + sources(); + details(null); + render(); + if (parsed.length > 2000) + notify( + t( + "Показаны последние 2000 событий файла", + "Showing the latest 2,000 file events", + ), + ); + } catch { + notify(t("Не удалось прочитать файл", "Could not read the file")); + } + event.target.value = ""; + }, + { signal }, + ); + return () => { + disposed = true; + clearInterval(timer); + abort.abort(); + }; +} diff --git a/components/ssh-console.js b/components/ssh-console.js new file mode 100644 index 0000000..318373f --- /dev/null +++ b/components/ssh-console.js @@ -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."))} +
    +
    ${glyph("check")} ${t("Демосессия", "Demo session")}dev · :22
    + +

    ${t("Подготовка терминала…", "Preparing terminal…")}

    +
    ${t("Нажмите в терминале для ввода", "Click the terminal to type")}—UTF-8
    +
    ${t("Клавиатура и управление", "Keyboard and controls")}

    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("Локальная демосессия: 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(() => {}); + }; +} diff --git a/components/system.css b/components/system.css index 6ddf1a0..87d19fe 100644 --- a/components/system.css +++ b/components/system.css @@ -1,3 +1,4 @@ +@import url("./workspaces.css"); * { box-sizing: border-box; } diff --git a/components/workspaces.css b/components/workspaces.css new file mode 100644 index 0000000..abecc41 --- /dev/null +++ b/components/workspaces.css @@ -0,0 +1,553 @@ +@import url("../vendor/xterm/xterm.css"); +.ssh-workspace, +.log-workspace { + border: 1px solid var(--color-border); + border-radius: 12px; + background: var(--color-surface); + overflow: hidden; + min-width: 0; +} +.workspace-toolbar, +.workspace-context, +.workspace-actions { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} +.workspace-toolbar { + justify-content: space-between; + padding: 12px 14px; + border-bottom: 1px solid var(--color-border); +} +.workspace-context { + gap: 14px; + min-width: 0; +} +.workspace-actions { + gap: 6px; +} +.workspace-actions button, +.workspace-actions .file-button, +.log-footer button, +.ssh-find button, +.log-details button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + min-height: 34px; + padding: 7px 10px; + font-size: 12px; +} +.workspace-actions button > svg, +.workspace-actions .file-button > svg, +.log-footer svg, +.ssh-find button > svg, +.log-details button > svg { + flex-shrink: 0; +} +.workspace-host { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: var(--color-muted); +} +.workspace-host select { + font: + 13px Consolas, + monospace; + min-height: 32px; + padding: 5px 8px; +} +.workspace-meta { + font: + 12px/1.5 Consolas, + monospace; + color: var(--color-muted); + overflow-wrap: anywhere; +} +.workspace-note { + font-size: 12px; + line-height: 1.6; + color: var(--color-muted); + margin: 14px 0 0; + max-width: 100ch; +} +.workspace-loading { + padding: 24px; + color: var(--color-muted); +} +.ssh-terminal { + height: clamp(340px, 57dvh, 650px); + padding: 0; + background: #000; + color: #e3f2f3; + color-scheme: dark; + min-width: 0; +} +.ssh-terminal .xterm { + height: 100%; + padding: 14px 12px 10px; +} +.ssh-terminal .workspace-loading { + color: #a5bec5; +} +.ssh-terminal .xterm:focus-visible { + outline: none; +} +.ssh-terminal:focus-within { + outline: 2px solid #77cbbb; + outline-offset: -2px; +} +.ssh-terminal .xterm .xterm-viewport { + scrollbar-gutter: auto; +} +.terminal-status { + display: flex; + align-items: center; + gap: 14px; + flex-wrap: wrap; + padding: 9px 14px; + border-top: 1px solid var(--color-border); + font: + 11px/1.5 Consolas, + monospace; + color: var(--color-muted); +} +.terminal-status button { + display: inline-flex; + align-items: center; + gap: 7px; + font: 12px var(--font-body); + min-height: 30px; + padding: 5px 8px; +} +.terminal-status button[aria-pressed="true"] { + color: var(--color-accent); +} +.terminal-dimensions { + margin-left: auto; +} +.terminal-help { + border-top: 1px solid var(--color-border); + padding: 4px 14px; +} +.terminal-help summary { + border: 0; + padding: 9px 0; + font-size: 12px; + color: var(--color-muted); +} +.terminal-shortcuts { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px 24px; + padding: 12px 0; +} +.terminal-shortcuts p { + display: flex; + flex-direction: column; + gap: 5px; + margin: 0; + font-size: 12px; + color: var(--color-muted); +} +.terminal-shortcuts kbd { + color: var(--color-text); + font: + 12px Consolas, + monospace; +} +.terminal-help .workspace-note { + margin: 0 0 14px; +} +.ssh-find { + display: flex; + gap: 6px; + align-items: flex-end; + flex-wrap: wrap; + padding: 10px 14px; + border-bottom: 1px solid var(--color-border); + background: var(--color-bg); +} +.ssh-find[hidden], +.log-details[hidden], +.log-empty[hidden], +.log-workspace [hidden] { + display: none; +} +.ssh-find label { + display: grid; + gap: 4px; + flex: 1; + min-width: 130px; + font-size: 12px; +} +.ssh-find input { + width: 100%; + min-height: 34px; + font-size: 13px; +} +.ssh-find [role="status"] { + font-size: 12px; + color: var(--color-muted); + align-self: center; +} +.ssh-workspace:fullscreen { + border: 0; + border-radius: 0; + padding: 8px; + background: var(--color-surface); + display: flex; + flex-direction: column; +} +.ssh-workspace:fullscreen .ssh-terminal { + flex: 1; + height: auto; + min-height: 0; +} +.ssh-workspace:fullscreen .terminal-help { + max-height: 30dvh; + overflow: auto; +} +.log-filters { + display: grid; + grid-template-columns: minmax(180px, 1fr) 150px 180px auto; + align-items: end; + gap: 12px; + padding: 14px; + border-bottom: 1px solid var(--color-border); +} +.log-filters label { + display: grid; + gap: 5px; + font-size: 12px; + min-width: 0; +} +.log-filters input, +.log-filters select { + width: 100%; + font-size: 13px; + min-height: 36px; +} +.log-reset { + font-size: 12px; + min-height: 36px; +} +.log-layout { + display: grid; + grid-template-columns: minmax(0, 1fr); +} +.has-log-details .log-layout { + grid-template-columns: minmax(0, 1fr) 320px; +} +.log-main { + min-width: 0; +} +.log-column-labels, +.log-row { + display: grid; + grid-template-columns: 38px 108px 64px 86px minmax(0, 1fr); + gap: 10px; + align-items: start; +} +.log-column-labels { + padding: 10px 14px; + color: var(--color-muted); + font-size: 11px; + border-bottom: 1px solid var(--color-border); +} +.log-viewport { + height: clamp(340px, 57dvh, 650px); + overflow: auto; + scrollbar-gutter: stable; + outline-offset: -2px; +} +.log-lines { + list-style: none; + padding: 0; + margin: 0; +} +.log-row { + width: 100%; + border: 0; + border-bottom: 1px solid + color-mix(in srgb, var(--color-border) 55%, transparent); + border-radius: 0; + text-align: left; + background: transparent; + padding: 9px 14px; + font: + 12px/1.6 Consolas, + "Cascadia Mono", + monospace; + min-height: 36px; +} +.log-row:hover:not(:disabled), +.log-row:focus-visible { + background: var(--color-row-hover); +} +.log-row:focus-visible { + outline: 2px solid var(--color-accent); + outline-offset: -2px; +} +.log-row.is-selected { + background: var(--color-row-active); +} +.log-row mark { + background: color-mix(in srgb, var(--color-accent) 24%, var(--color-surface)); + color: var(--color-text); + border-radius: 2px; +} +.log-number, +.log-row time { + color: var(--color-muted); +} +.log-number { + text-align: right; + font-size: 11px; +} +.log-level { + font-size: 10px; + line-height: 18px; + padding: 1px 5px; + border: 1px solid var(--color-border); + border-radius: 4px; + justify-self: start; +} +.log-level--info { + color: var(--color-accent); + background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface)); +} +.log-level--debug { + color: var(--color-muted); +} +.log-level--warn { + color: var(--color-text); + border-style: dashed; + font-weight: bold; +} +.log-level--error { + color: var(--color-danger); + background: color-mix(in srgb, var(--color-danger) 9%, var(--color-surface)); + border-color: color-mix( + in srgb, + var(--color-danger) 35%, + var(--color-surface) + ); + font-weight: bold; +} +.log-source { + color: var(--color-accent); + overflow-wrap: anywhere; +} +.log-message { + white-space: pre-wrap; + overflow-wrap: anywhere; + min-width: 0; +} +.log-details { + padding: 14px; + border-left: 1px solid var(--color-border); + background: var(--color-bg); + min-width: 0; +} +.log-details-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.log-details-heading h2 { + margin: 0; + font-size: 15px; +} +.log-details > p { + font-size: 11px; + color: var(--color-muted); + overflow-wrap: anywhere; + margin: 12px 0; +} +.log-details pre { + font: + 12px/1.7 Consolas, + monospace; + white-space: pre-wrap; + overflow-wrap: anywhere; + margin: 16px 0; + max-height: 350px; + overflow: auto; +} +.log-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + padding: 10px 14px; + border-top: 1px solid var(--color-border); + font-size: 12px; + color: var(--color-muted); +} +.log-paging { + display: flex; + gap: 4px; +} +.log-footer [data-log="follow"][aria-pressed="true"] { + color: var(--color-accent); + border-color: var(--color-accent); +} +.log-footer [data-log-unseen] { + border-radius: 999px; + background: var(--color-accent); + color: var(--color-on-accent); + padding: 0 5px; + font-size: 10px; +} +.log-empty { + padding: 48px 20px; + text-align: center; +} +.log-empty h2 { + margin-bottom: 8px; +} +.log-empty p { + font-size: 13px; + color: var(--color-muted); +} +@media (max-width: 1100px) { + .has-log-details .log-layout { + grid-template-columns: minmax(0, 1fr); + } + .log-details { + border-left: 0; + border-top: 1px solid var(--color-border); + } + .has-log-details .log-viewport { + max-height: 35dvh; + } + .log-filters { + grid-template-columns: minmax(0, 1fr) 120px 130px; + } + .log-reset { + grid-column: 3; + } + .log-column-labels, + .log-row { + grid-template-columns: 30px 102px 60px 75px minmax(0, 1fr); + gap: 8px; + } +} +@media (max-width: 600px) { + .workspace-toolbar { + padding: 10px; + gap: 12px; + } + .workspace-context { + gap: 8px; + } + .workspace-actions { + width: 100%; + } + .workspace-actions [data-ssh="fullscreen"] span { + display: none; + } + .workspace-host { + gap: 5px; + } + .workspace-meta { + font-size: 11px; + } + .ssh-terminal { + padding: 0; + height: 53dvh; + min-height: 330px; + } + .terminal-status { + gap: 8px; + padding: 8px 10px; + } + .terminal-status [data-keyboard-status] { + order: 4; + flex-basis: 100%; + font: + 10px/1.5 Consolas, + monospace; + } + .terminal-help { + padding-inline: 10px; + } + .terminal-shortcuts { + grid-template-columns: 1fr; + } + .ssh-find { + padding: 10px; + } + .log-filters { + grid-template-columns: 1fr 1fr; + padding: 10px; + gap: 10px; + } + .log-search { + grid-column: 1/-1; + } + .log-reset { + grid-column: auto; + justify-self: start; + } + .log-column-labels { + display: none; + } + .log-row { + grid-template-columns: 28px 1fr auto; + gap: 4px 8px; + padding: 10px; + font-size: 11px; + } + .log-number { + grid-row: 1/3; + } + .log-row time { + grid-column: 2; + } + .log-level { + grid-column: 3; + grid-row: 1; + } + .log-source { + grid-column: 2; + grid-row: 2; + } + .log-message { + grid-column: 2/-1; + grid-row: 3; + } + .log-footer { + padding: 10px; + gap: 10px; + } + .log-footer > span { + flex-basis: 100%; + } + .log-viewport { + height: 54dvh; + min-height: 300px; + } + .log-details { + padding: 12px; + } + .workspace-note { + font-size: 11px; + } +} + +@media (max-width: 600px) { + .ssh-terminal .xterm { + padding: 12px 8px; + } +} +body[data-concept="dock"] .log-workspace .log-row:active { + transform: none; +} diff --git a/package-lock.json b/package-lock.json index 9080a1b..df8b20b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,10 +7,36 @@ "": { "name": "anidev-design-system", "version": "0.1.0", + "dependencies": { + "@xterm/addon-fit": "0.11.0", + "@xterm/addon-search": "0.16.0", + "@xterm/xterm": "6.0.0" + }, "devDependencies": { "playwright": "^1.58.0" } }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/addon-search": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-search/-/addon-search-0.16.0.tgz", + "integrity": "sha512-9OeuBFu0/uZJPu+9AHKY6g/w0Czyb/Ut0A5t79I4ULoU4IfU5BEpPFVGQxP4zTTMdfZEYkVIRYbHBX1xWwjeSA==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, "node_modules/playwright": { "version": "1.65.1", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", diff --git a/package.json b/package.json index 9b5db5e..cf3ca64 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,8 @@ "private": true, "type": "module", "scripts": { + "terminal:vendor": "node scripts/vendor-terminal.mjs", + "test:workspaces": "node tests/workspaces.mjs", "icons:build": "node scripts/build-icons.mjs && python scripts/package-icons.py", "test:icons": "node tests/icons.mjs", "dev": "node scripts/serve.mjs", @@ -17,5 +19,10 @@ }, "devDependencies": { "playwright": "^1.58.0" + }, + "dependencies": { + "@xterm/addon-fit": "0.11.0", + "@xterm/addon-search": "0.16.0", + "@xterm/xterm": "6.0.0" } } diff --git a/patterns/WORKSPACES.md b/patterns/WORKSPACES.md new file mode 100644 index 0000000..e90de90 --- /dev/null +++ b/patterns/WORKSPACES.md @@ -0,0 +1,25 @@ +# SSH console and log reader + +Both workspaces use the approved Dock layout and local demo data. The terminal surface is pure black (#000) in both UI themes; its foreground and ANSI colors remain light enough for that surface. No SSH login, private key or host command execution is implemented. + +## Terminal + +`components/ssh-console.js` mounts xterm.js 6.0.0, addon-fit 0.11.0 and addon-search 0.16.0. The official MIT distributions and licenses are copied into `vendor/xterm/` by `node scripts/vendor-terminal.mjs`; there is no CDN dependency. `patterns/demo-pty.js` supplies a local shell fixture with line editing, history, completion, signals, an alternate-screen pager/top and streaming output. + +Replace the `createTransport` option of `mountSsh` to connect a project backend. The factory receives `{host, cols, rows, write, onClose}` and returns `{send(data), resize(cols, rows), close(), dispose()}`. Forward `Terminal.onData` unchanged to the server PTY; forward server output to `write`. Input includes control characters and escape sequences, not just printable text. Resize the actual server PTY. The backend owns SSH host validation, authentication, authorization, credentials and session lifetime. The demo adapter never evaluates JavaScript or invokes a host shell. + +Keyboard events are intercepted only by a focused, enabled terminal. xterm encodes arrows, Home/End, Delete, Tab/Shift+Tab, F1–F12, Ctrl and Alt sequences. Ctrl+C/D/Z are terminal signals, not app commands. Ctrl+K goes to the terminal instead of the Dock command palette. Ctrl+Shift+C copies a selection; Ctrl+Shift+V and Shift+Insert use the browser's native paste event. macOS Cmd+C/V/A preserve copy/paste/select-all. The toolbar also provides clipboard actions. Bracketed paste is enabled by the PTY; the demo flattens pasted newlines and waits for Enter rather than auto-executing pasted commands. + +Ctrl+Shift+F opens output search. Ctrl+Shift+M disables input and focuses the toolbar so Tab can leave the terminal. Enable input again with the button. Focus loss and unmount release Keyboard Lock. The fullscreen action requests Keyboard Lock only if supported; denial falls back to regular terminal key capture. Browser/OS-reserved combinations cannot be guaranteed in an ordinary tab. Holding Esc remains the browser's fullscreen escape route. Terminal events do not bubble into app shortcuts. Components outside the terminal retain native keyboard behavior. + +References: [xterm Terminal API](https://xtermjs.org/docs/api/terminal/classes/terminal/), [Keyboard Lock and its fullscreen/OS limitations](https://developer.chrome.com/docs/capabilities/web-apis/keyboard-lock). + +## Log reader + +`components/log-reader.js` provides level/source/literal-text filters, highlighted matches, stream pause/resume with a bounded backlog, follow mode, older/newer windows, event JSON, clipboard and filtered `.log` export. Opening an event or scrolling up stops following; the follow button or Ctrl+End jumps to the latest data. Ctrl+F focuses the local search. Arrow keys move through rows and Enter opens an event; Escape closes details and restores row focus. + +Open local `.log`, `.txt` and JSONL files up to 8 MB. File contents stay in the browser. Text and JSON fields are escaped before rendering. At most 2,000 records and a separate 2,000-event paused backlog are retained; at most 150 rows are rendered at once. Search/export operate on retained records, not only the visible page. `parseLogText` supports JSONL and `timestamp LEVEL source message` text. Malformed JSON is treated as plain text. File mode stops the synthetic feed; the demo stream button explicitly returns to demo data. + +Both mount functions return cleanup handlers. The app disposes them on every route change, including observers, timers, event listeners, terminal instances and keyboard lock. Loading an async terminal after navigation cannot revive a disposed page. Replacing the demo feed with a real source should retain these limits and cleanup rules. + +The xterm runtime is an intentional dependency: a real terminal parser/keyboard encoder replaces ad-hoc key handling. No framework or CDN was added. The vendor manifest records exact package versions and the MIT licenses are distributed alongside the runtime. diff --git a/patterns/demo-pty.js b/patterns/demo-pty.js new file mode 100644 index 0000000..a0d961e --- /dev/null +++ b/patterns/demo-pty.js @@ -0,0 +1,523 @@ +// In-browser PTY fixture. No command here is executed on the host computer. +export function createDemoPty({ + write, + onClose, + host = "edge-01", + rows = 24, + cols = 80, +}) { + let line = "", + cursor = 0, + history = ["uptime", "ls", "systemctl status gateway"], + index = history.length, + kill = "", + closed = false; + let running = null, + timer = null, + pagerOffset = 0, + search = null, + suspended = false, + queued = "", + escapeBuffer = "", + paste = false, + pasteBuffer = ""; + const prompt = () => + `\x1b[38;5;37mdev@${host}\x1b[0m:\x1b[34m~/anidev\x1b[0m$ `; + const emit = (s) => { + if (suspended) queued += s; + else write(s); + }; + let paintedCursor = 0; + const promptLength = () => `dev@${host}:~/anidev$ `.length; + function putPrompt() { + emit(prompt()); + paintedCursor = promptLength(); + } + function paint(text, length, offset) { + const oldRow = Math.floor(paintedCursor / Math.max(1, cols)); + emit("\r" + (oldRow ? `\x1b[${oldRow}A` : "") + "\x1b[J" + text); + const endRow = Math.floor(length / Math.max(1, cols)), + targetRow = Math.floor(offset / Math.max(1, cols)); + emit(length && length % cols === 0 ? "\r\n" : "\r"); + if (endRow > targetRow) emit(`\x1b[${endRow - targetRow}A`); + if (offset % cols) emit(`\x1b[${offset % cols}C`); + paintedCursor = offset; + } + function redraw() { + paint( + prompt() + line, + promptLength() + line.length, + promptLength() + cursor, + ); + } + function stop() { + clearInterval(timer); + timer = null; + if (running === "top" || running === "less") emit("\x1b[?1049l"); + running = null; + } + function close() { + if (closed) return; + stop(); + closed = true; + emit("\r\nConnection to " + host + " closed.\r\n"); + onClose?.(); + } + function historyMove(delta) { + index = Math.max(0, Math.min(history.length, index + delta)); + line = history[index] || ""; + cursor = line.length; + redraw(); + } + function wordLeft() { + while (cursor && /\s/.test(line[cursor - 1])) cursor--; + while (cursor && !/\s/.test(line[cursor - 1])) cursor--; + } + function wordRight() { + while (cursor < line.length && !/\s/.test(line[cursor])) cursor++; + while (cursor < line.length && /\s/.test(line[cursor])) cursor++; + } + function remove(a, b) { + kill = line.slice(a, b); + line = line.slice(0, a) + line.slice(b); + cursor = a; + } + function insert(s) { + line = line.slice(0, cursor) + s + line.slice(cursor); + cursor += s.length; + redraw(); + } + const commands = [ + "help", + "ls", + "pwd", + "whoami", + "hostname", + "date", + "uptime", + "clear", + "echo", + "history", + "cat", + "top", + "less", + "tail", + "systemctl", + "exit", + ]; + const logLines = Array.from( + { length: 160 }, + (_, i) => + `${String(i + 1).padStart(3)} 12:08:${String(i % 60).padStart(2, "0")} ${i % 17 === 0 ? "WARN " : "INFO "} gateway request_id=demo-${i + 1} status=${i % 17 === 0 ? "429" : "200"} duration=${12 + (i % 38)}ms`, + ); + function pager() { + emit( + "\x1b[H\x1b[2J" + + logLines + .slice(pagerOffset, pagerOffset + Math.max(3, rows - 2)) + .join("\r\n") + + `\r\n\x1b[7m demo gateway.log ${pagerOffset + 1}/${logLines.length} · arrows / PgUp / PgDn · q to exit \x1b[0m`, + ); + } + function top() { + emit( + "\x1b[H\x1b[2Jtop — " + + host + + " demo PTY\r\nTasks: 5 total, 1 running CPU 4.2% Memory 184M / 2G\r\n\r\n\x1b[7m PID USER CPU% MEM% COMMAND \x1b[0m\r\n 842 anidev 2.4 1.8 gateway\r\n 901 anidev 1.1 2.3 identity\r\n 722 postgres 0.6 3.2 postgres\r\n 611 redis 0.1 0.4 redis-server\r\n\r\nq / Ctrl+C — exit · Ctrl+Z — suspend\r\n", + ); + } + function execute() { + const input = line.trim(); + cursor = line.length; + redraw(); + emit("\r\n"); + paintedCursor = 0; + line = ""; + cursor = 0; + if (!input) { + putPrompt(); + return; + } + history.push(input); + history = history.slice(-100); + index = history.length; + const [cmd, ...args] = input.split(/\s+/); + switch (cmd) { + case "help": + emit( + "Demo commands\r\n ls, pwd, whoami, hostname, date, uptime, echo, history\r\n systemctl status gateway · cat gateway.log · less gateway.log\r\n top · tail -f gateway.log · clear · exit\r\n\r\nEditing: arrows, Home/End, Ctrl+A/E/W/U/K/Y, Alt+B/F/D\r\nHistory: Up/Down, Ctrl+P/N/R · Tab completion\r\nSignals: Ctrl+C interrupt, Ctrl+D EOF, Ctrl+Z suspend\r\nClipboard: Ctrl+Shift+C / Ctrl+Shift+V\r\n", + ); + break; + case "ls": + emit( + "\x1b[34mconfig/ deploy/ logs/\x1b[0m gateway.log README.md\r\n", + ); + break; + case "pwd": + emit("/home/dev/anidev\r\n"); + break; + case "whoami": + emit("dev\r\n"); + break; + case "hostname": + emit(host + "\r\n"); + break; + case "date": + emit(new Date().toISOString() + "\r\n"); + break; + case "uptime": + emit( + "12:08:42 up 18 days, 4:32, 2 users, load average: 0.08, 0.12, 0.10\r\n", + ); + break; + case "echo": + emit(args.join(" ") + "\r\n"); + break; + case "history": + emit( + history + .map((s, i) => `${String(i + 1).padStart(3)} ${s}`) + .join("\r\n") + "\r\n", + ); + break; + case "clear": + emit("\x1b[2J\x1b[H"); + break; + case "systemctl": + emit( + "\x1b[32m●\x1b[0m gateway.service — Anidev Gateway\r\n Loaded: loaded; enabled\r\n Active: \x1b[32mactive (running)\x1b[0m\r\n Main PID: 842 (gateway)\r\n Memory: 38.2M\r\n", + ); + break; + case "cat": + emit( + (args[0] === "gateway.log" + ? logLines.slice(-12).join("\r\n") + : "# Anidev workspace\r\nLocal demonstration of a remote PTY.") + + "\r\n", + ); + break; + case "top": + running = "top"; + emit("\x1b[?1049h"); + top(); + timer = setInterval(top, 2000); + return; + case "less": + running = "less"; + pagerOffset = 0; + emit("\x1b[?1049h"); + pager(); + return; + case "tail": + running = "tail"; + emit(logLines.slice(-4).join("\r\n") + "\r\n"); + let tick = 0; + timer = setInterval( + () => + emit( + `12:09:${String(tick++ % 60).padStart(2, "0")} INFO gateway demo request status=200 duration=18ms\r\n`, + ), + 1100, + ); + return; + case "exit": + close(); + return; + default: + emit(`${cmd}: not available in this demo. Type help.\r\n`); + } + putPrompt(); + } + function completion(reverse = false) { + const stem = line.slice(0, cursor), + matches = commands.filter((s) => s.startsWith(stem)); + if (matches.length === 1) { + line = matches[0] + " " + line.slice(cursor); + cursor = matches[0].length + 1; + redraw(); + } else if (matches.length > 1) { + cursor = line.length; + redraw(); + emit( + "\r\n" + + (reverse ? [...matches].reverse() : matches).join(" ") + + "\r\n", + ); + paintedCursor = 0; + redraw(); + } + } + function sequence(s) { + if (running === "less") { + if (["\x1b[B", "\x1b[6~"].includes(s)) + pagerOffset = Math.min( + logLines.length - 3, + pagerOffset + (s === "\x1b[B" ? 1 : rows - 3), + ); + else if (["\x1b[A", "\x1b[5~"].includes(s)) + pagerOffset = Math.max( + 0, + pagerOffset - (s === "\x1b[A" ? 1 : rows - 3), + ); + else if (["\x1b[H", "\x1b[1~"].includes(s)) pagerOffset = 0; + else if (["\x1b[F", "\x1b[4~"].includes(s)) + pagerOffset = Math.max(0, logLines.length - rows + 2); + pager(); + return; + } + const before = cursor; + switch (s) { + case "\x1b[A": + historyMove(-1); + return; + case "\x1b[B": + historyMove(1); + return; + case "\x1b[D": + cursor = Math.max(0, cursor - 1); + break; + case "\x1b[C": + cursor = Math.min(line.length, cursor + 1); + break; + case "\x1b[H": + case "\x1bOH": + case "\x1b[1~": + cursor = 0; + break; + case "\x1b[F": + case "\x1bOF": + case "\x1b[4~": + cursor = line.length; + break; + case "\x1b[3~": + line = line.slice(0, cursor) + line.slice(cursor + 1); + break; + case "\x1bb": + case "\x1b[1;5D": + wordLeft(); + break; + case "\x1bf": + case "\x1b[1;5C": + wordRight(); + break; + case "\x1bd": + wordRight(); + remove(before, cursor); + break; + case "\x1b\x7f": + wordLeft(); + remove(cursor, before); + break; + case "\x1b[Z": + completion(true); + return; + } + redraw(); + } + function char(c) { + if (c === "\x11") { + suspended = false; + write(queued); + queued = ""; + return; + } + if (c === "\x13") { + suspended = true; + return; + } + if (c === "\x03" || c === "\x1a") { + suspended = false; + queued = ""; + const active = running; + stop(); + line = ""; + cursor = 0; + search = null; + emit( + c === "\x03" + ? "^C\r\n" + : `^Z\r\n${active ? "[1]+ Stopped (demo)\r\n" : ""}`, + ); + putPrompt(); + return; + } + if (running) { + if (c === "q" || c === "\x1b") { + stop(); + putPrompt(); + } else if (running === "less") { + if (c === "j" || c === " ") + pagerOffset = Math.min( + logLines.length - 3, + pagerOffset + (c === " " ? rows - 3 : 1), + ); + if (c === "k") pagerOffset = Math.max(0, pagerOffset - 1); + pager(); + } + return; + } + if (search !== null) { + if (c === "\r") { + line = [...history].reverse().find((s) => s.includes(search)) || ""; + cursor = line.length; + search = null; + redraw(); + return; + } + if (c === "\x1b") { + search = null; + redraw(); + return; + } + if (c === "\x7f") search = search.slice(0, -1); + else if (c >= " ") search += c; + const match = + [...history].reverse().find((s) => s.includes(search)) || ""; + emit(`\r\x1b[2K(reverse-i-search) '${search}': ${match}`); + return; + } + const before = cursor; + switch (c) { + case "\r": + case "\n": + execute(); + return; + case "\t": + completion(); + return; + case "\x7f": + case "\b": + if (cursor) { + line = line.slice(0, cursor - 1) + line.slice(cursor); + cursor--; + } + break; + case "\x01": + cursor = 0; + break; + case "\x05": + cursor = line.length; + break; + case "\x02": + cursor = Math.max(0, cursor - 1); + break; + case "\x06": + cursor = Math.min(line.length, cursor + 1); + break; + case "\x04": + if (!line) { + close(); + return; + } + line = line.slice(0, cursor) + line.slice(cursor + 1); + break; + case "\x0b": + remove(cursor, line.length); + break; + case "\x15": + remove(0, cursor); + break; + case "\x17": + wordLeft(); + remove(cursor, before); + break; + case "\x19": + insert(kill); + return; + case "\x0c": + emit("\x1b[2J\x1b[H"); + paintedCursor = 0; + break; + case "\x10": + historyMove(-1); + return; + case "\x0e": + historyMove(1); + return; + case "\x12": + search = ""; + emit("\r\x1b[2K(reverse-i-search) '': "); + return; + case "\x14": + if (cursor > 0 && line.length > 1) { + const at = Math.min(cursor, line.length - 1); + line = + line.slice(0, at - 1) + + line[at] + + line[at - 1] + + line.slice(at + 1); + cursor = Math.min(line.length, at + 1); + } + break; + default: + if (c >= " ") { + insert(c); + return; + } + } + redraw(); + } + function send(data) { + if (closed) return; + // A bracketed paste is inserted as text; pasted newlines never auto-execute commands. + if (paste) { + pasteBuffer += data; + const end = pasteBuffer.indexOf("\x1b[201~"); + if (end < 0) return; + const rest = pasteBuffer.slice(end + 6), + text = pasteBuffer + .slice(0, end) + .replace(/[\r\n]+/g, " ") + .replace(/[\x00-\x1f\x7f]/g, ""); + paste = false; + pasteBuffer = ""; + insert(text); + if (rest) send(rest); + return; + } + const start = data.indexOf("\x1b[200~"); + if (start >= 0) { + if (start) send(data.slice(0, start)); + paste = true; + pasteBuffer = ""; + send(data.slice(start + 6)); + return; + } + data = escapeBuffer + data; + escapeBuffer = ""; + for (let i = 0; i < data.length;) { + if (data[i] === "\x1b" && i + 1 < data.length) { + const match = data + .slice(i) + .match(/^\x1b(?:\[[0-9;?]*[A-Za-z~]|O[A-Za-z]|[^\[O])/); + if (match) { + sequence(match[0]); + i += match[0].length; + continue; + } + escapeBuffer = data.slice(i); + break; + } + char(data[i++]); + } + } + emit( + "\x1b[?2004h\x1b[36manidev / SSH workspace\x1b[0m\r\nUbuntu 24.04 LTS · xterm-256color · demo PTY\r\nType \x1b[36mhelp\x1b[0m, try \x1b[36mtop\x1b[0m or \x1b[36mless gateway.log\x1b[0m.\r\n\r\n" + + prompt(), + ); + paintedCursor = promptLength(); + return { + send, + resize(c, r) { + cols = c; + rows = r; + if (running === "less") pager(); + if (running === "top") top(); + }, + close, + dispose() { + clearInterval(timer); + closed = true; + }, + }; +} diff --git a/playground/frame.js b/playground/frame.js index 8ce8bea..d212fef 100644 --- a/playground/frame.js +++ b/playground/frame.js @@ -1,3 +1,5 @@ +import { sshScreen, mountSsh } from "../components/ssh-console.js"; +import { logsScreen, mountLogs } from "../components/log-reader.js"; import { iconSvg } from "../icons/icons.js"; import { concepts, tokensFor, cssVars } from "../concepts/registry.js"; import { @@ -161,6 +163,8 @@ let page = [ "auth", "components", "tokens", + "ssh", + "logs", ...accountPageIds, ].includes(params.get("page")) ? params.get("page") @@ -174,6 +178,8 @@ let query = "", tab = "general", chartRange = "24h"; const pageNames = { + ssh: t("SSH-консоль", "SSH console"), + logs: t("Журнал событий", "Log reader"), dashboard: t("Обзор", "Overview"), users: t("Пользователи", "Users"), settings: t("Настройки", "Settings"), @@ -187,7 +193,10 @@ const pageNames = { appearance: t("Оформление", "Appearance"), identity: t("Состояния входа", "Sign-in states"), }; -const icon = (id) => iconSvg(id, { className: "nav-icon" }); +const icon = (id) => + iconSvg({ ssh: "terminal", logs: "document" }[id] || id, { + className: "nav-icon", + }); const wordmark = '
    a/anidev
    '; function persist() { try { @@ -225,7 +234,7 @@ function accountInitials() { function navigationPages() { return accountPageIds.includes(page) ? ["profile", "security", "sessions", "applications", "appearance"] - : ["dashboard", "users", "settings", "components", "tokens"]; + : ["dashboard", "users", "settings", "ssh", "logs", "components", "tokens"]; } function dockAccount() { return `
    @@ -319,8 +328,13 @@ function savePreferences() { ); } catch {} } +let workspaceCleanup = () => {}, + workspaceRender = 0; let initialRender = true; function render({ preserveDock = false } = {}) { + workspaceCleanup(); + workspaceCleanup = () => {}; + const workspaceVersion = ++workspaceRender; const dockWasOpen = preserveDock && document.body.classList.contains("dock-open") && @@ -352,12 +366,14 @@ function render({ preserveDock = false } = {}) { : identityAdapter.snapshot().status !== "authenticated" && !["components", "tokens", "auth"].includes(page) ? accountUI.gate() - : ["dashboard", "users", "settings"].includes(page) && + : ["dashboard", "users", "settings", "ssh", "logs"].includes(page) && !currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r), ) ? accountUI.gate("access_denied") : { + ssh: () => sshScreen({ t, heading }), + logs: () => logsScreen({ t, heading }), dashboard, users: userScreen, settings: settingsScreen, @@ -373,6 +389,24 @@ function render({ preserveDock = false } = {}) { bindDockHover(); if (dockWasOpen) setDockOpen(true, false); bindCharts(); + if ($("#log-workspace")) + workspaceCleanup = mountLogs($("#log-workspace"), { + t, + escape, + notify: toast, + }); + const sshRoot = $("#ssh-workspace"); + if (sshRoot) + mountSsh(sshRoot, { t, notify: toast }) + .then((cleanup) => { + if (workspaceVersion === workspaceRender) workspaceCleanup = cleanup; + else cleanup(); + }) + .catch(() => { + if (sshRoot.isConnected) + sshRoot.querySelector("[data-terminal]").innerHTML = + `

    ${t("Терминал не загрузился", "Terminal did not load")}

    ${t("Обновите страницу, чтобы повторить загрузку.", "Reload the page to try again.")}

    `; + }); if (page === "users" && $("#user-search")) bindUsers(); } function chart() { @@ -598,6 +632,7 @@ function componentScreen() {

    Empty state

    ${t("Пока нет API-ключей", "No API keys yet")}

    ${t("Создайте ключ для подключения сервиса.", "Create a key to connect your service.")}

    Error & skeleton

    ${t("Не удалось загрузить журнал.", "Could not load the log.")}

    ${t("Статусы", "Status indicators")}

    ${iconSvg("check", { size: 16 })}${t("Работает", "Operational")}${iconSvg("close", { size: 16 })}${t("Недоступен", "Unavailable")}${iconSvg("more-horizontal", { size: 16 })}${t("Ожидает", "Pending")}

    ${t("Состояние выражено текстом, а не только цветом.", "Status uses text as well as color.")}

    +

    ${t("Рабочие области", "Workspaces")}

    ${t("SSH-терминал и ридер логов в стиле Dock.", "SSH terminal and log reader in Dock style.")}

    ${t("Иконки Anidev", "Anidev icons")}

    ${["profile", "security", "sessions", "applications", "settings", "copy", "key", "bell"].map(icon).join("")}

    ${t("64 SVG · сетка 24×24 · контур 1.5px", "64 SVGs · 24×24 grid · 1.5px stroke")}

    ${t("Открыть пак иконок →", "Open icon pack →")}

    Chart

    ${chart()}

    ${t("Таблицы, пагинация и фильтры — на экране «Пользователи»; вкладки — в настройках; форма входа — в авторизации.", "Tables, pagination and filters: Users. Tabs: Settings. Sign-in form: Authentication.")}

    `; } diff --git a/references/QA.md b/references/QA.md index 55d4962..b000a9d 100644 --- a/references/QA.md +++ b/references/QA.md @@ -104,3 +104,18 @@ SVG ZIP содержит 70 файлов. Экспорт системы соде В образце Status indicators вместо трёх разрозненных цветных подписей — компактные бейджи с иконками check/close/more-horizontal, мягкой заливкой и семантической рамкой. Состояние передаётся символом и текстом; декоративные SVG скрыты от скринридера. Стиль вынесен в отдельный status-badge и не меняет служебные текстовые сообщения статуса. Проверены 12 сочетаний: light/dark, RU/EN, ширины 1440/768/390. Контраст текста на фактическом смешанном фоне >=4.5:1, высота >=28px, центры SVG совпадают с центрами меток, горизонтального переполнения и ошибок JavaScript нет. Скриншоты обеих тем desktop/tablet/mobile просмотрены: references/status-badges. npm run check проходит. + + +## SSH-консоль и log-ридер / 01.12.2026 + +Добавлены собственные страницы ssh/logs, пункты Dock и образец Workspaces в компонентах. SSH использует xterm.js 6.0.0, addon-fit 0.11.0, addon-search 0.16.0, локальные ESM-дистрибутивы и MIT-лицензии в vendor/xterm. Это frontend-демо с локальной PTY, не настоящая SSH-сессия; реализация транспорта вынесена в контракт. Фон #000 проверен в обеих темах. После корректировки padding renderer полностью помещается в viewport терминала. + +Целевая suite: 83/83. Из них 24 сочетания двух страниц, двух тем, RU/EN и трёх размеров (1440×1000, 768×1024, 390×844); остальные — управляющие коды, реальные команды демо, перенос длинных строк, история/дополнение/редактирование, Ctrl+C/D/Z, alternate screen top/less, tail, поиск, отключение/reconnect, освобождение фокуса и отсутствие перехвата Tab при отключённом вводе. Проверены Ctrl A/B/C/D/E/F/K/L/N/P/Q/R/S/T/U/V/W/Y/Z, Alt B/F/D, стрелки, Home/End/Delete/PgUp/PgDn/Esc/Tab/Shift+Tab и F1–F12 на границе транспорта. Ctrl+K не открывает command palette при вводе в терминале; вне терминала сочетание работает. Буфер обмена и bracketed paste проверены. + +Keyboard Lock: нативный fullscreen проверен; вызовы lock/unlock и отказ разрешения проверены через тестовую реализацию API. Это проверка жизненного цикла, а не утверждение, что браузер/ОС физически отдают все зарезервированные клавиши. Ограничения и способ выхода указаны в справке консоли и patterns/WORKSPACES.md. + +Log reader: фильтры уровня/сервиса/текста, подсветка, пустое состояние, очередь паузы, follow/unseen, JSONL/plain-text parser, детали/возврат фокуса, окно 150 строк и cap 2000, экспорт всех 500 отфильтрованных строк при видимом окне 150. Проверен текст с HTML: не исполняется. Открытие локального файла выключает демопоток. Открытие деталей выключает follow. + +Повторены Core 50/50, standalone site 35/35, Dock 10/10 и feedback/scroll 24/24. Всего текущего прохода 202; ошибок JavaScript нет. npm run check проходит. Скриншоты обеих тем и трёх размеров просмотрены в references/workspaces. Это не полный аудит доступности. + +Экспорт 110 файлов: CRC всех записей и вложенного SVG ZIP проверены; присутствуют оба компонента, CSS, PTY fixture, xterm runtime и лицензии. Распакованный экспорт запущен на отдельном loopback-сервере: ввод в SSH, чёрный фон и фильтры логов работают без репозитория/CDN, ошибок JavaScript нет. QA-сервер закрыт после проверки. diff --git a/references/approved-dock/gallery-mobile.png b/references/approved-dock/gallery-mobile.png index d2fe282..960e115 100644 Binary files a/references/approved-dock/gallery-mobile.png and b/references/approved-dock/gallery-mobile.png differ diff --git a/references/approved-dock/rows-dark-desktop.png b/references/approved-dock/rows-dark-desktop.png index 192b216..8e2e366 100644 Binary files a/references/approved-dock/rows-dark-desktop.png and b/references/approved-dock/rows-dark-desktop.png differ diff --git a/references/approved-dock/rows-light-desktop.png b/references/approved-dock/rows-light-desktop.png index 04d24dd..5b87f0f 100644 Binary files a/references/approved-dock/rows-light-desktop.png and b/references/approved-dock/rows-light-desktop.png differ diff --git a/references/dock-revision/dark-desktop-account.png b/references/dock-revision/dark-desktop-account.png index 786fa2f..6f01608 100644 Binary files a/references/dock-revision/dark-desktop-account.png and b/references/dock-revision/dark-desktop-account.png differ diff --git a/references/dock-revision/dark-desktop-collapsed.png b/references/dock-revision/dark-desktop-collapsed.png index dd6671f..d01125e 100644 Binary files a/references/dock-revision/dark-desktop-collapsed.png and b/references/dock-revision/dark-desktop-collapsed.png differ diff --git a/references/dock-revision/dark-desktop-expanded.png b/references/dock-revision/dark-desktop-expanded.png index e3f92bc..e5ed2fb 100644 Binary files a/references/dock-revision/dark-desktop-expanded.png and b/references/dock-revision/dark-desktop-expanded.png differ diff --git a/references/dock-revision/dark-mobile-account.png b/references/dock-revision/dark-mobile-account.png index 2ed8b68..7e4241c 100644 Binary files a/references/dock-revision/dark-mobile-account.png and b/references/dock-revision/dark-mobile-account.png differ diff --git a/references/dock-revision/dark-mobile-collapsed.png b/references/dock-revision/dark-mobile-collapsed.png index bcc6a39..0565ba5 100644 Binary files a/references/dock-revision/dark-mobile-collapsed.png and b/references/dock-revision/dark-mobile-collapsed.png differ diff --git a/references/dock-revision/dark-mobile-expanded.png b/references/dock-revision/dark-mobile-expanded.png index fee5589..79d8b70 100644 Binary files a/references/dock-revision/dark-mobile-expanded.png and b/references/dock-revision/dark-mobile-expanded.png differ diff --git a/references/dock-revision/dark-tablet-account.png b/references/dock-revision/dark-tablet-account.png index 69b6b15..62fa254 100644 Binary files a/references/dock-revision/dark-tablet-account.png and b/references/dock-revision/dark-tablet-account.png differ diff --git a/references/dock-revision/dark-tablet-collapsed.png b/references/dock-revision/dark-tablet-collapsed.png index 63b78bc..63020d7 100644 Binary files a/references/dock-revision/dark-tablet-collapsed.png and b/references/dock-revision/dark-tablet-collapsed.png differ diff --git a/references/dock-revision/dark-tablet-expanded.png b/references/dock-revision/dark-tablet-expanded.png index 5514d1c..0bafab3 100644 Binary files a/references/dock-revision/dark-tablet-expanded.png and b/references/dock-revision/dark-tablet-expanded.png differ diff --git a/references/dock-revision/light-desktop-account.png b/references/dock-revision/light-desktop-account.png index be1c91c..ae13614 100644 Binary files a/references/dock-revision/light-desktop-account.png and b/references/dock-revision/light-desktop-account.png differ diff --git a/references/dock-revision/light-desktop-collapsed.png b/references/dock-revision/light-desktop-collapsed.png index 7aca9ba..dae57ab 100644 Binary files a/references/dock-revision/light-desktop-collapsed.png and b/references/dock-revision/light-desktop-collapsed.png differ diff --git a/references/dock-revision/light-desktop-expanded.png b/references/dock-revision/light-desktop-expanded.png index 10d041f..9d3feee 100644 Binary files a/references/dock-revision/light-desktop-expanded.png and b/references/dock-revision/light-desktop-expanded.png differ diff --git a/references/dock-revision/light-mobile-account.png b/references/dock-revision/light-mobile-account.png index 46ca9e0..e1c317b 100644 Binary files a/references/dock-revision/light-mobile-account.png and b/references/dock-revision/light-mobile-account.png differ diff --git a/references/dock-revision/light-mobile-collapsed.png b/references/dock-revision/light-mobile-collapsed.png index efe8712..6d19d6b 100644 Binary files a/references/dock-revision/light-mobile-collapsed.png and b/references/dock-revision/light-mobile-collapsed.png differ diff --git a/references/dock-revision/light-mobile-expanded.png b/references/dock-revision/light-mobile-expanded.png index 02e1cf1..2159909 100644 Binary files a/references/dock-revision/light-mobile-expanded.png and b/references/dock-revision/light-mobile-expanded.png differ diff --git a/references/dock-revision/light-tablet-account.png b/references/dock-revision/light-tablet-account.png index 2c70142..95382db 100644 Binary files a/references/dock-revision/light-tablet-account.png and b/references/dock-revision/light-tablet-account.png differ diff --git a/references/dock-revision/light-tablet-collapsed.png b/references/dock-revision/light-tablet-collapsed.png index 3977f57..bf38b96 100644 Binary files a/references/dock-revision/light-tablet-collapsed.png and b/references/dock-revision/light-tablet-collapsed.png differ diff --git a/references/dock-revision/light-tablet-expanded.png b/references/dock-revision/light-tablet-expanded.png index 37bfea2..f4dd05a 100644 Binary files a/references/dock-revision/light-tablet-expanded.png and b/references/dock-revision/light-tablet-expanded.png differ diff --git a/references/gallery.png b/references/gallery.png index 0413729..bc3ae07 100644 Binary files a/references/gallery.png and b/references/gallery.png differ diff --git a/references/qa-summary.json b/references/qa-summary.json index 8bc2a69..a55963f 100644 --- a/references/qa-summary.json +++ b/references/qa-summary.json @@ -11,7 +11,10 @@ "totalPassed": 316, "failed": 0, "errors": [], - "export": "97 files; 64 SVG icons; nested 70-file icon ZIP; CRC verified; standalone profile/catalog verified", + "export": "110 files; SSH/log workspaces; vendored xterm and licenses; nested icon ZIP; CRC and standalone runtime verified", "iconChecksPassed": 91, - "polishScenariosPassed": 8 + "polishScenariosPassed": 8, + "workspacesPassed": 83, + "lastWorkspaceRunPassed": 202, + "lastWorkspaceDate": "2026-12-01" } diff --git a/references/site/dark-desktop.png b/references/site/dark-desktop.png index 9ad54ca..048b08d 100644 Binary files a/references/site/dark-desktop.png and b/references/site/dark-desktop.png differ diff --git a/references/site/dark-mobile.png b/references/site/dark-mobile.png index 1be81bf..2f245da 100644 Binary files a/references/site/dark-mobile.png and b/references/site/dark-mobile.png differ diff --git a/references/site/light-desktop.png b/references/site/light-desktop.png index cc8688a..9d3eae1 100644 Binary files a/references/site/light-desktop.png and b/references/site/light-desktop.png differ diff --git a/references/site/light-mobile.png b/references/site/light-mobile.png index 5a2be12..0614c83 100644 Binary files a/references/site/light-mobile.png and b/references/site/light-mobile.png differ diff --git a/references/site/navigation-dark-desktop.png b/references/site/navigation-dark-desktop.png index c449e4b..1c84820 100644 Binary files a/references/site/navigation-dark-desktop.png and b/references/site/navigation-dark-desktop.png differ diff --git a/references/site/navigation-dark-mobile.png b/references/site/navigation-dark-mobile.png index 4407b3f..0ee03d9 100644 Binary files a/references/site/navigation-dark-mobile.png and b/references/site/navigation-dark-mobile.png differ diff --git a/references/site/navigation-light-desktop.png b/references/site/navigation-light-desktop.png index 3e24e43..f525e7d 100644 Binary files a/references/site/navigation-light-desktop.png and b/references/site/navigation-light-desktop.png differ diff --git a/references/site/navigation-light-mobile.png b/references/site/navigation-light-mobile.png index 8cdb156..174d357 100644 Binary files a/references/site/navigation-light-mobile.png and b/references/site/navigation-light-mobile.png differ diff --git a/references/workspaces/logs-dark-desktop.png b/references/workspaces/logs-dark-desktop.png new file mode 100644 index 0000000..ee840ae Binary files /dev/null and b/references/workspaces/logs-dark-desktop.png differ diff --git a/references/workspaces/logs-dark-mobile.png b/references/workspaces/logs-dark-mobile.png new file mode 100644 index 0000000..367d990 Binary files /dev/null and b/references/workspaces/logs-dark-mobile.png differ diff --git a/references/workspaces/logs-dark-tablet.png b/references/workspaces/logs-dark-tablet.png new file mode 100644 index 0000000..656a6a2 Binary files /dev/null and b/references/workspaces/logs-dark-tablet.png differ diff --git a/references/workspaces/logs-light-desktop.png b/references/workspaces/logs-light-desktop.png new file mode 100644 index 0000000..a163ce8 Binary files /dev/null and b/references/workspaces/logs-light-desktop.png differ diff --git a/references/workspaces/logs-light-mobile.png b/references/workspaces/logs-light-mobile.png new file mode 100644 index 0000000..5b7a2be Binary files /dev/null and b/references/workspaces/logs-light-mobile.png differ diff --git a/references/workspaces/logs-light-tablet.png b/references/workspaces/logs-light-tablet.png new file mode 100644 index 0000000..163fda8 Binary files /dev/null and b/references/workspaces/logs-light-tablet.png differ diff --git a/references/workspaces/qa.json b/references/workspaces/qa.json new file mode 100644 index 0000000..4ab985e --- /dev/null +++ b/references/workspaces/qa.json @@ -0,0 +1,6 @@ +{ + "passed": 83, + "errors": [], + "keyboardScope": "Encoding verified for events delivered to xterm. Browser/OS-reserved combinations require fullscreen Keyboard Lock and platform permission; native OS interception is not guaranteed.", + "checks": "Both themes, RU/EN, three widths; black terminal; size fit; editing/signals/history/completion/alternate screen; control/Alt/navigation/F1-F12 encoding; focus escape and app hotkeys; bracketed paste; log filtering/pause/follow/file/XSS/windows/details/export; teardown on route changes" +} diff --git a/references/workspaces/ssh-dark-desktop.png b/references/workspaces/ssh-dark-desktop.png new file mode 100644 index 0000000..6ddf262 Binary files /dev/null and b/references/workspaces/ssh-dark-desktop.png differ diff --git a/references/workspaces/ssh-dark-mobile.png b/references/workspaces/ssh-dark-mobile.png new file mode 100644 index 0000000..f113b27 Binary files /dev/null and b/references/workspaces/ssh-dark-mobile.png differ diff --git a/references/workspaces/ssh-dark-tablet.png b/references/workspaces/ssh-dark-tablet.png new file mode 100644 index 0000000..87b9165 Binary files /dev/null and b/references/workspaces/ssh-dark-tablet.png differ diff --git a/references/workspaces/ssh-light-desktop.png b/references/workspaces/ssh-light-desktop.png new file mode 100644 index 0000000..be11dbc Binary files /dev/null and b/references/workspaces/ssh-light-desktop.png differ diff --git a/references/workspaces/ssh-light-mobile.png b/references/workspaces/ssh-light-mobile.png new file mode 100644 index 0000000..9a4f382 Binary files /dev/null and b/references/workspaces/ssh-light-mobile.png differ diff --git a/references/workspaces/ssh-light-tablet.png b/references/workspaces/ssh-light-tablet.png new file mode 100644 index 0000000..9e4d4f3 Binary files /dev/null and b/references/workspaces/ssh-light-tablet.png differ diff --git a/scripts/vendor-terminal.mjs b/scripts/vendor-terminal.mjs new file mode 100644 index 0000000..dc801e1 --- /dev/null +++ b/scripts/vendor-terminal.mjs @@ -0,0 +1,36 @@ +import { readFile, writeFile, mkdir } from "node:fs/promises"; +const root = new URL("../", import.meta.url), + out = new URL("vendor/xterm/", root); +await mkdir(out, { recursive: true }); +const packages = [ + ["@xterm/xterm", "xterm"], + ["@xterm/addon-fit", "addon-fit"], + ["@xterm/addon-search", "addon-search"], +]; +const manifest = []; +for (const [pkg, name] of packages) { + const dir = new URL(`node_modules/${pkg}/`, root), + meta = JSON.parse(await readFile(new URL("package.json", dir), "utf8")); + const source = await readFile(new URL(meta.module, dir), "utf8"); + await writeFile( + new URL(name + ".js", out), + source.replace(/^\/\/# sourceMappingURL=.*$/gm, ""), + ); + await writeFile( + new URL(name + ".LICENSE", out), + await readFile(new URL("LICENSE", dir)), + ); + manifest.push({ package: pkg, version: meta.version, license: meta.license }); +} +await writeFile( + new URL("xterm.css", out), + await readFile(new URL("node_modules/@xterm/xterm/css/xterm.css", root)), +); +await writeFile( + new URL("manifest.json", out), + JSON.stringify(manifest, null, 2) + "\n", +); +console.log( + "Vendored terminal runtime:", + manifest.map((p) => `${p.package}@${p.version}`).join(", "), +); diff --git a/tests/workspaces.mjs b/tests/workspaces.mjs new file mode 100644 index 0000000..ced23ba --- /dev/null +++ b/tests/workspaces.mjs @@ -0,0 +1,619 @@ +import { chromium } from "playwright"; +import assert from "node:assert/strict"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { parseLogText } from "../components/log-reader.js"; +const base = process.env.BASE_URL || "http://127.0.0.1:4173"; +const browser = await chromium.launch({ + executablePath: + process.env.PLAYWRIGHT_EXECUTABLE_PATH || + "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", + headless: true, +}); +const context = await browser.newContext({ acceptDownloads: true }); +const p = await context.newPage(); +const errors = []; +p.on("pageerror", (e) => errors.push(e.message)); +let passed = 0; +await mkdir("references/workspaces", { recursive: true }); +async function check(name, run) { + await run(); + passed++; + console.log("PASS", name); +} +const url = (page, theme = "dark", locale = "ru") => + `${base}/?page=${page}&theme=${theme}&locale=${locale}`; +const screen = () => p.locator(".xterm-rows").innerText(); +const terminal = () => p.locator(".xterm-helper-textarea"); +async function command(text) { + await terminal().focus(); + await p.keyboard.type(text); + await p.keyboard.press("Enter"); + await p.waitForTimeout(80); +} +try { + for (const page of process.env.SKIP_MATRIX ? [] : ["ssh", "logs"]) + for (const theme of ["light", "dark"]) + for (const locale of ["ru", "en"]) + for (const [device, width, height] of [ + ["desktop", 1440, 1000], + ["tablet", 768, 1024], + ["mobile", 390, 844], + ]) { + await check(`${page}/${theme}/${locale}/${device}`, async () => { + await p.setViewportSize({ width, height }); + await p.goto(url(page, theme, locale)); + await p + .locator(page === "ssh" ? ".xterm-rows" : ".log-row") + .first() + .waitFor(); + await p.waitForTimeout(180); + assert.ok( + await p.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + ); + if (page === "ssh") { + assert.equal( + await p + .locator(".ssh-terminal") + .evaluate((e) => getComputedStyle(e).backgroundColor), + "rgb(0, 0, 0)", + ); + const box = await p.locator(".ssh-terminal").boundingBox(), + canvas = await p.locator(".xterm-screen").boundingBox(); + assert.ok( + canvas.y + canvas.height <= box.y + box.height + 0.5, + JSON.stringify({ box, canvas }), + ); + } + if (locale === "en") + assert.equal( + /[А-Яа-яЁё]/.test(await p.locator("#content").innerText()), + false, + ); + if (locale === "ru") + await p.screenshot({ + path: `references/workspaces/${page}-${theme}-${device}.png`, + fullPage: true, + }); + }); + } + await p.setViewportSize({ width: 1440, height: 1000 }); + await p.goto(url("ssh")); + await terminal().waitFor({ state: "attached" }); + await check( + "demo commands, cursor editing, line kill/yank and history", + async () => { + await command("whoami"); + assert.match(await screen(), /\ndev\n/); + await terminal().focus(); + await p.keyboard.type("echo ac"); + await p.keyboard.press("ArrowLeft"); + await p.keyboard.type("b"); + await p.keyboard.press("End"); + await p.keyboard.press("Enter"); + await p.waitForTimeout(80); + assert.match(await screen(), /\nabc\n/); + await p.keyboard.type("bad text"); + await p.keyboard.press("Control+u"); + await p.keyboard.type("echo killed"); + await p.keyboard.press("Control+u"); + await p.keyboard.press("Control+y"); + await p.keyboard.press("Enter"); + await p.waitForTimeout(80); + assert.match(await screen(), /\nkilled\n/); + await p.keyboard.press("ArrowUp"); + await p.keyboard.press("Enter"); + await p.waitForTimeout(80); + assert.ok((await screen()).match(/killed/g).length >= 4); + await p.keyboard.type("who"); + await p.keyboard.press("Tab"); + await p.keyboard.press("Enter"); + await p.waitForTimeout(80); + assert.match(await screen(), /whoami/); + }, + ); + await check("signals, streaming process and alternate screen", async () => { + await command("top"); + assert.match(await screen(), /PID USER/); + await p.keyboard.press("Control+c"); + await p.waitForTimeout(80); + assert.doesNotMatch(await screen(), /Tasks: 5 total/); + await command("less gateway.log"); + assert.match(await screen(), /demo gateway.log/); + await p.keyboard.press("PageDown"); + await p.waitForTimeout(80); + assert.match(await screen(), /gateway request_id/); + await p.keyboard.press("q"); + await command("tail -f gateway.log"); + await p.waitForTimeout(1200); + assert.match(await screen(), /demo request/); + await p.keyboard.press("Control+z"); + await p.waitForTimeout(80); + assert.match(await screen(), /Stopped \(demo\)/); + }); + await check( + "search and keyboard escape hatch; app shortcuts outside terminal", + async () => { + await terminal().focus(); + await p.keyboard.press("Control+Shift+f"); + await p.locator("[data-ssh-query]").fill("gateway"); + assert.equal(await p.locator(".ssh-find").isVisible(), true); + await p.keyboard.press("Escape"); + assert.equal(await p.locator(".ssh-find").isVisible(), false); + await p.keyboard.press("Control+k"); + assert.equal(await p.locator("#dialog").evaluate((e) => e.open), false); + await p.keyboard.press("Control+Shift+m"); + assert.equal( + await p.locator("[data-ssh=capture]").getAttribute("aria-pressed"), + "false", + ); + assert.notEqual( + await p.evaluate(() => document.activeElement?.className), + "xterm-helper-textarea", + ); + await terminal().focus(); + await p.keyboard.press("Tab"); + assert.notEqual( + await p.evaluate(() => document.activeElement?.className), + "xterm-helper-textarea", + ); + await p.keyboard.press("Control+k"); + await p.locator("#command-search").waitFor(); + await p.keyboard.press("Escape"); + await p.locator("[data-ssh=capture]").click(); + assert.equal( + await p.locator("[data-ssh=capture]").getAttribute("aria-pressed"), + "true", + ); + }, + ); + await check("EOF and reconnect", async () => { + await terminal().focus(); + await p.keyboard.press("Control+u"); + await p.keyboard.press("Control+d"); + await p.waitForTimeout(80); + assert.match(await p.locator("[data-ssh-state]").innerText(), /Отключено/); + await p.locator("[data-ssh=connect]").click(); + await p.waitForTimeout(80); + assert.match(await screen(), /dev@edge-01/); + }); + await check("wrapped command editing on a narrow terminal", async () => { + await p.setViewportSize({ width: 390, height: 844 }); + await p.waitForTimeout(100); + await command("clear"); + const text = "abcdefghijklmnopqrst".repeat(7); + await command("echo " + text); + assert.ok((await screen()).replace(/\s/g, "").includes(text)); + await p.setViewportSize({ width: 1440, height: 1000 }); + }); + await check( + "transport boundary receives terminal control sequences", + async () => { + await p.goto(url("components")); + await p.evaluate(async () => { + const { sshScreen, mountSsh } = + await import("/components/ssh-console.js"); + const container = document.createElement("div"); + container.id = "keyboard-fixture"; + container.innerHTML = sshScreen({ + t: (ru, en) => en, + heading: () => "", + }); + document.querySelector("#content").append(container); + window.terminalInput = []; + window.fixtureDispose = await mountSsh( + container.querySelector("#ssh-workspace"), + { + t: (ru, en) => en, + notify: () => {}, + createTransport: ({ write, onClose }) => { + write("\x1b[?2004hREADY\r\n$ "); + return { + send(data) { + window.terminalInput.push(data); + }, + resize() {}, + close: onClose, + dispose() { + window.fixtureTransportDisposed = true; + }, + }; + }, + }, + ); + }); + await p.locator("#keyboard-fixture .xterm-helper-textarea").focus(); + const controls = { + a: 1, + b: 2, + c: 3, + d: 4, + e: 5, + f: 6, + k: 11, + l: 12, + n: 14, + p: 16, + q: 17, + r: 18, + s: 19, + t: 20, + u: 21, + v: 22, + w: 23, + y: 25, + z: 26, + }; + for (const [key, code] of Object.entries(controls)) { + await p.evaluate(() => (window.terminalInput = [])); + await p + .locator("#keyboard-fixture .xterm-helper-textarea") + .dispatchEvent("keydown", { + key, + code: "Key" + key.toUpperCase(), + keyCode: key.toUpperCase().charCodeAt(0), + which: key.toUpperCase().charCodeAt(0), + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + assert.equal( + await p.evaluate(() => window.terminalInput.join("")), + String.fromCharCode(code), + `Ctrl+${key}`, + ); + passed++; + } + for (const [key, code, value] of [ + ["ArrowUp", "ArrowUp", "\x1b[A"], + ["ArrowDown", "ArrowDown", "\x1b[B"], + ["ArrowLeft", "ArrowLeft", "\x1b[D"], + ["ArrowRight", "ArrowRight", "\x1b[C"], + ["Home", "Home", "\x1b[H"], + ["End", "End", "\x1b[F"], + ["Delete", "Delete", "\x1b[3~"], + ["PageUp", "PageUp", "\x1b[5~"], + ["PageDown", "PageDown", "\x1b[6~"], + ["Escape", "Escape", "\x1b"], + ["Tab", "Tab", "\t"], + ]) { + await p.evaluate(() => (window.terminalInput = [])); + await p + .locator("#keyboard-fixture .xterm-helper-textarea") + .dispatchEvent("keydown", { + key, + code, + keyCode: { + ArrowUp: 38, + ArrowDown: 40, + ArrowLeft: 37, + ArrowRight: 39, + Home: 36, + End: 35, + Delete: 46, + PageUp: 33, + PageDown: 34, + Escape: 27, + Tab: 9, + }[key], + bubbles: true, + cancelable: true, + }); + assert.equal( + await p.evaluate(() => window.terminalInput.join("")), + value, + key, + ); + passed++; + } + for (const [key, value] of [ + ["b", "\x1bb"], + ["f", "\x1bf"], + ["d", "\x1bd"], + ]) { + await p.evaluate(() => (window.terminalInput = [])); + await p + .locator("#keyboard-fixture .xterm-helper-textarea") + .dispatchEvent("keydown", { + key, + code: "Key" + key.toUpperCase(), + keyCode: key.toUpperCase().charCodeAt(0), + which: key.toUpperCase().charCodeAt(0), + altKey: true, + bubbles: true, + cancelable: true, + }); + assert.equal( + await p.evaluate(() => window.terminalInput.join("")), + value, + ); + passed++; + } + for (const [n, value] of [ + [1, "\x1bOP"], + [2, "\x1bOQ"], + [3, "\x1bOR"], + [4, "\x1bOS"], + [5, "\x1b[15~"], + [6, "\x1b[17~"], + [7, "\x1b[18~"], + [8, "\x1b[19~"], + [9, "\x1b[20~"], + [10, "\x1b[21~"], + [11, "\x1b[23~"], + [12, "\x1b[24~"], + ]) { + await p.evaluate(() => (window.terminalInput = [])); + await p + .locator("#keyboard-fixture .xterm-helper-textarea") + .dispatchEvent("keydown", { + key: `F${n}`, + code: `F${n}`, + keyCode: 111 + n, + bubbles: true, + cancelable: true, + }); + assert.equal( + await p.evaluate(() => window.terminalInput.join("")), + value, + ); + passed++; + } + await p.evaluate(() => (window.terminalInput = [])); + await p + .locator("#keyboard-fixture .xterm-helper-textarea") + .dispatchEvent("keydown", { + key: "Tab", + code: "Tab", + keyCode: 9, + shiftKey: true, + bubbles: true, + cancelable: true, + }); + assert.equal( + await p.evaluate(() => window.terminalInput.join("")), + "\x1b[Z", + ); + passed++; + assert.equal(await p.locator("#dialog").evaluate((e) => e.open), false); + }, + ); + await check( + "fullscreen keyboard-lock lifecycle and permission fallback", + async () => { + await p.evaluate(() => { + window.lockFixture = { locks: 0, unlocks: 0, denied: false }; + Object.defineProperty(navigator, "keyboard", { + configurable: true, + value: { + async lock() { + window.lockFixture.locks++; + if (window.lockFixture.denied) throw Error("Permission denied"); + }, + unlock() { + window.lockFixture.unlocks++; + }, + }, + }); + }); + await p.locator("#keyboard-fixture [data-ssh=fullscreen]").click(); + await p.waitForFunction( + () => document.fullscreenElement?.id === "ssh-workspace", + ); + await p.waitForTimeout(100); + assert.ok(await p.evaluate(() => window.lockFixture.locks > 0)); + assert.match( + await p.locator("#keyboard-fixture [data-keyboard-status]").innerText(), + /Keyboard Lock/, + ); + await p.locator("#keyboard-fixture [data-ssh=capture]").click(); + assert.ok(await p.evaluate(() => window.lockFixture.unlocks > 0)); + await p.evaluate(() => (window.lockFixture.denied = true)); + await p.locator("#keyboard-fixture [data-ssh=capture]").click(); + await p.waitForTimeout(100); + assert.doesNotMatch( + await p.locator("#keyboard-fixture [data-keyboard-status]").innerText(), + /Keyboard Lock/, + ); + await p.locator("#keyboard-fixture [data-ssh=fullscreen]").click(); + await p.waitForFunction(() => !document.fullscreenElement); + await p.locator("#keyboard-fixture .xterm-helper-textarea").focus(); + }, + ); + await check( + "clipboard and bracketed paste at transport boundary", + async () => { + await context.grantPermissions(["clipboard-read", "clipboard-write"], { + origin: base, + }); + const input = p.locator("#keyboard-fixture .xterm-helper-textarea"); + await input.focus(); + await input.dispatchEvent("keydown", { + key: "a", + code: "KeyA", + keyCode: 65, + metaKey: true, + bubbles: true, + cancelable: true, + }); + await p.keyboard.press("Control+Shift+c"); + await p.waitForTimeout(100); + assert.match( + await p.evaluate(() => navigator.clipboard.readText()), + /READY/, + ); + await p.evaluate(() => { + window.terminalInput = []; + const dt = new DataTransfer(); + dt.setData("text/plain", "echo one\necho two"); + document + .querySelector("#keyboard-fixture .xterm-helper-textarea") + .dispatchEvent( + new ClipboardEvent("paste", { + clipboardData: dt, + bubbles: true, + cancelable: true, + }), + ); + }); + const data = await p.evaluate(() => window.terminalInput.join("")); + assert.ok(data.startsWith("\x1b[200~")); + assert.ok(data.endsWith("\x1b[201~")); + assert.match(data, /echo one/); + assert.match(data, /echo two/); + await p.evaluate(() => { + window.fixtureDispose(); + document.querySelector("#keyboard-fixture").remove(); + }); + }, + ); + await p.goto(url("logs")); + await p.locator(".log-row").first().waitFor(); + await check( + "log filters, literal search and local find shortcut", + async () => { + await p.locator("[data-log=pause]").click(); + await p.locator("[data-log-level]").selectOption("ERROR"); + assert.ok((await p.locator(".log-row").count()) > 0); + for (const r of await p.locator(".log-level").all()) + assert.equal(await r.innerText(), "ERROR"); + await p.locator("[data-log=reset]").click(); + await p.locator("[data-log-source]").selectOption("gateway"); + for (const r of await p.locator(".log-source").all()) + assert.equal(await r.innerText(), "gateway"); + await p.locator("[data-log-query]").fill("HTTP"); + assert.ok((await p.locator("mark").count()) > 0); + await p.locator("[data-log-query]").fill("no-such-event"); + assert.equal(await p.locator(".log-empty").isVisible(), true); + await p.locator("[data-log=reset]").click(); + await p.locator(".log-viewport").focus(); + await p.keyboard.press("Control+f"); + assert.equal( + await p + .locator("[data-log-query]") + .evaluate((e) => e === document.activeElement), + true, + ); + }, + ); + await check("pause backlog, follow mode and jump to newest", async () => { + const count = await p.locator(".log-row").count(); + await p.waitForTimeout(1400); + assert.equal(await p.locator(".log-row").count(), count); + assert.match( + await p.locator("[data-log-count]").innerText(), + /новых событий/, + ); + await p.locator("[data-log=pause]").click(); + assert.ok((await p.locator(".log-row").count()) > count); + await p.locator(".log-viewport").evaluate((e) => (e.scrollTop = 0)); + await p.waitForTimeout(100); + assert.equal( + await p.locator("[data-log=follow]").getAttribute("aria-pressed"), + "false", + ); + await p.waitForTimeout(1400); + assert.equal(await p.locator("[data-log-unseen]").isVisible(), true); + await p.locator("[data-log=follow]").click(); + assert.equal( + await p.locator("[data-log=follow]").getAttribute("aria-pressed"), + "true", + ); + }); + await check( + "file parsing, bounded windows, event JSON and filtered export", + async () => { + const lines = Array.from({ length: 2200 }, (_, i) => + JSON.stringify({ + timestamp: "2026-12-01T12:00:00Z", + level: i % 4 === 0 ? "ERROR" : "INFO", + source: "fixture", + message: + i === 2199 ? "" : `event ${i + 1}`, + request_id: `file-${i + 1}`, + }), + ).join("\n"); + await p.locator("[data-log-input]").setInputFiles({ + name: "events.jsonl", + mimeType: "application/json", + buffer: Buffer.from(lines), + }); + await p.waitForTimeout(100); + assert.equal(await p.locator(".log-row").count(), 150); + assert.equal(await p.locator("[data-log=pause]").isDisabled(), true); + assert.match(await p.locator("[data-log-count]").innerText(), /2000/); + assert.equal(await p.locator("img[src=x]").count(), 0); + const first = Number( + await p.locator(".log-row").first().getAttribute("data-record"), + ); + await p.locator("[data-log=older]").click(); + assert.equal( + Number(await p.locator(".log-row").first().getAttribute("data-record")), + first - 150, + ); + await p.locator("[data-log=follow]").click(); + await p.locator(".log-row").last().click(); + assert.equal( + await p.locator("[data-log=follow]").getAttribute("aria-pressed"), + "false", + ); + assert.match( + await p.locator("[data-log-json]").innerText(), + / 0); + }, + ); + await check( + "text/JSON parser preserves text and normalizes warning levels", + async () => { + const parsed = parseLogText( + 'not json