1370 lines
70 KiB
JavaScript
1370 lines
70 KiB
JavaScript
import { createNotifier } from "../components/toast.js";
|
||
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 {
|
||
createDemoIdentityAdapter,
|
||
identityStates,
|
||
} from "../patterns/demo-identity.js";
|
||
import {
|
||
createAccountUI,
|
||
accountPageIds,
|
||
} from "../components/account-pages.js";
|
||
import { exportSystem } from "../components/export-system.js";
|
||
const identityAdapter = createDemoIdentityAdapter();
|
||
let preferences = {};
|
||
try {
|
||
preferences =
|
||
JSON.parse(
|
||
localStorage.getItem("anidev.preferences") ||
|
||
localStorage.getItem("anidev.lab") ||
|
||
"{}",
|
||
) || {};
|
||
} catch {}
|
||
const params = new URLSearchParams(location.search),
|
||
concept = concepts[0];
|
||
params.delete("concept");
|
||
let theme =
|
||
(params.get("theme") || preferences.theme) === "dark" ? "dark" : "light",
|
||
density = ["compact", "normal", "relaxed"].includes(
|
||
params.get("density") || preferences.density,
|
||
)
|
||
? params.get("density") || preferences.density
|
||
: "compact",
|
||
locale = (params.get("locale") || preferences.locale) === "en" ? "en" : "ru";
|
||
const rawAccent = params.get("accent"),
|
||
accent = /^#[0-9a-f]{6}$/i.test(rawAccent)
|
||
? rawAccent
|
||
: theme === "dark"
|
||
? concept.darkAccent || concept.accent
|
||
: concept.accent;
|
||
let tokens = tokensFor(concept.id, theme, accent, density);
|
||
document.documentElement.style.cssText = cssVars(tokens);
|
||
document.documentElement.lang = locale;
|
||
document.body.dataset.concept = concept.id;
|
||
document.body.dataset.theme = theme;
|
||
const t = (ru, en) => (locale === "ru" ? ru : en);
|
||
const number = (v, digits = 0) =>
|
||
new Intl.NumberFormat(locale, {
|
||
minimumFractionDigits: digits,
|
||
maximumFractionDigits: digits,
|
||
}).format(v);
|
||
const $ = (s) => document.querySelector(s),
|
||
escape = (s) =>
|
||
String(s).replace(
|
||
/[&<>"']/g,
|
||
(c) =>
|
||
({
|
||
"&": "&",
|
||
"<": "<",
|
||
">": ">",
|
||
'"': """,
|
||
"'": "'",
|
||
})[c],
|
||
);
|
||
const initialUsers = [
|
||
{
|
||
id: 1,
|
||
name: "Anna Volkova",
|
||
email: "anna@anidev.ru",
|
||
role: "admin",
|
||
status: "active",
|
||
last: "09:42",
|
||
},
|
||
{
|
||
id: 2,
|
||
name: "Mikhail Orlov",
|
||
email: "mikhail@anidev.ru",
|
||
role: "developer",
|
||
status: "active",
|
||
last: "09:38",
|
||
},
|
||
{
|
||
id: 3,
|
||
name: "Elena Kim",
|
||
email: "elena@anidev.ru",
|
||
role: "viewer",
|
||
status: "active",
|
||
last: "09:21",
|
||
},
|
||
{
|
||
id: 4,
|
||
name: "Denis Petrov",
|
||
email: "denis@anidev.ru",
|
||
role: "developer",
|
||
status: "invited",
|
||
last: "—",
|
||
},
|
||
{
|
||
id: 5,
|
||
name: "Sofia Morozova",
|
||
email: "sofia@anidev.ru",
|
||
role: "viewer",
|
||
status: "suspended",
|
||
last: "26.11",
|
||
},
|
||
{
|
||
id: 6,
|
||
name: "Pavel Sokolov",
|
||
email: "pavel@anidev.ru",
|
||
role: "developer",
|
||
status: "active",
|
||
last: "08:56",
|
||
},
|
||
{
|
||
id: 7,
|
||
name: "Maria Ivanova",
|
||
email: "maria@anidev.ru",
|
||
role: "admin",
|
||
status: "active",
|
||
last: "08:40",
|
||
},
|
||
{
|
||
id: 8,
|
||
name: "Alex Chen",
|
||
email: "alex@anidev.ru",
|
||
role: "viewer",
|
||
status: "active",
|
||
last: "08:32",
|
||
},
|
||
];
|
||
let users;
|
||
try {
|
||
users =
|
||
JSON.parse(localStorage.getItem("anidev.users") || "null") ||
|
||
structuredClone(initialUsers);
|
||
} catch {
|
||
users = structuredClone(initialUsers);
|
||
}
|
||
let settings;
|
||
try {
|
||
settings = JSON.parse(localStorage.getItem("anidev.settings") || "null") || {
|
||
name: "Anidev Production",
|
||
slug: "anidev-prod",
|
||
region: "eu",
|
||
email: "ops@anidev.ru",
|
||
mfa: true,
|
||
audit: true,
|
||
};
|
||
} catch {
|
||
settings = {
|
||
name: "Anidev Production",
|
||
slug: "anidev-prod",
|
||
region: "eu",
|
||
email: "ops@anidev.ru",
|
||
mfa: true,
|
||
audit: true,
|
||
};
|
||
}
|
||
let page = [
|
||
"dashboard",
|
||
"users",
|
||
"settings",
|
||
"auth",
|
||
"components",
|
||
"tokens",
|
||
"ssh",
|
||
"logs",
|
||
...accountPageIds,
|
||
].includes(params.get("page"))
|
||
? params.get("page")
|
||
: "dashboard";
|
||
let query = "",
|
||
role = "all",
|
||
userPage = 1,
|
||
sortAsc = true,
|
||
sortKey = "name",
|
||
selected = new Set(),
|
||
tab = "general",
|
||
chartRange = "24h";
|
||
const pageNames = {
|
||
ssh: t("SSH-консоль", "SSH console"),
|
||
logs: t("Журнал событий", "Log reader"),
|
||
dashboard: t("Обзор", "Overview"),
|
||
users: t("Пользователи", "Users"),
|
||
settings: t("Настройки", "Settings"),
|
||
auth: t("Авторизация", "Sign in"),
|
||
components: t("Компоненты", "Components"),
|
||
tokens: t("Токены", "Tokens"),
|
||
profile: t("Аккаунт", "Account"),
|
||
security: t("Безопасность", "Security"),
|
||
sessions: t("Устройства и сеансы", "Devices and sessions"),
|
||
applications: t("Приложения", "Applications"),
|
||
appearance: t("Оформление", "Appearance"),
|
||
identity: t("Состояния входа", "Sign-in states"),
|
||
};
|
||
const icon = (id) =>
|
||
iconSvg(
|
||
{ ssh: "terminal", logs: "document", administration: "server" }[id] || id,
|
||
{
|
||
className: "nav-icon",
|
||
},
|
||
);
|
||
const wordmark = '<div class="wordmark"><b>a/</b><span>anidev</span></div>';
|
||
function persist() {
|
||
try {
|
||
localStorage.setItem("anidev.users", JSON.stringify(users));
|
||
localStorage.setItem("anidev.settings", JSON.stringify(settings));
|
||
} catch {
|
||
toast(t("Хранилище браузера недоступно", "Browser storage unavailable"));
|
||
}
|
||
}
|
||
const toast = createNotifier($("#toast"), { t });
|
||
function currentIdentity() {
|
||
return identityAdapter.snapshot().account;
|
||
}
|
||
function accountName() {
|
||
const a = currentIdentity();
|
||
return a
|
||
? `${a.firstName} ${a.lastName}`
|
||
: t("Нет активного входа", "No active sign-in");
|
||
}
|
||
function accountInitials() {
|
||
const a = currentIdentity();
|
||
return a ? (a.firstName[0] || "") + (a.lastName[0] || "") : "a/";
|
||
}
|
||
function navigationPages() {
|
||
return accountPageIds.includes(page)
|
||
? ["profile", "security", "sessions", "applications", "appearance"]
|
||
: [
|
||
"dashboard",
|
||
"users",
|
||
"settings",
|
||
"administration",
|
||
"components",
|
||
"tokens",
|
||
];
|
||
}
|
||
function dockAccount() {
|
||
return `<div class="dock-account-area"><div id="account-menu" class="account-menu" popover="auto" aria-label="${t("Меню аккаунта", "Account menu")}">
|
||
<button autofocus data-page="profile">${icon("profile")}<span>${t("Аккаунт", "Account")}</span></button>
|
||
${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)) ? `<button data-page="dashboard">${icon("dashboard")}<span>${t("Панель управления", "Control panel")}</span></button>` : ""}
|
||
<button class="account-separator" data-identity="switch">${icon("switch-account")}<span>${t("Сменить аккаунт", "Switch account")}</span></button>
|
||
<button class="account-separator" data-identity="logout">${icon("logout")}<span>${t("Выйти из SSO", "Sign out of SSO")}</span></button></div>
|
||
<button class="dock-account" popovertarget="account-menu" aria-label="${escape(t("Меню аккаунта ", "Account menu ") + accountName())}"><span class="avatar">${currentIdentity()?.avatar ? `<img src="${escape(currentIdentity().avatar)}" alt="">` : escape(accountInitials())}</span><span class="account-identity"><b>${escape(accountName())}</b><small>${escape(currentIdentity()?.username || "Anidev Identity")}</small></span><span class="account-more" aria-hidden="true">···</span></button></div>`;
|
||
}
|
||
let administrationOpen = ["ssh", "logs"].includes(page);
|
||
function navPage(id, label = pageNames[id]) {
|
||
return `<button data-page="${id}" ${page === id ? 'aria-current="page"' : ""} title="${label}" aria-label="${label}">${icon(id)}<span>${label}</span></button>`;
|
||
}
|
||
function administrationNav() {
|
||
const active = ["ssh", "logs"].includes(page);
|
||
return `<div class="nav-group" data-nav-group="administration"><button type="button" class="nav-group-toggle" data-action="administration-toggle" aria-expanded="false" aria-controls="administration-submenu" data-active="${active}" title="${t("Администрирование", "Administration")}" aria-label="${t("Администрирование", "Administration")}">${icon("administration")}<span class="nav-group-label">${t("Администрирование", "Administration")}${iconSvg("chevron-down", { size: 16, className: "nav-chevron" })}</span></button><div class="nav-submenu-container" id="administration-submenu" aria-hidden="true" inert><div class="nav-submenu-clip"><div class="nav-submenu-list">${navPage("ssh")}${navPage("logs", t("Логи", "Logs"))}</div></div></div></div>`;
|
||
}
|
||
function syncAdministration() {
|
||
const group = $("[data-nav-group=administration]");
|
||
if (!group) return;
|
||
const expanded =
|
||
administrationOpen && document.body.classList.contains("dock-open");
|
||
group.classList.toggle("is-expanded", expanded);
|
||
group
|
||
.querySelector(".nav-group-toggle")
|
||
.setAttribute("aria-expanded", String(expanded));
|
||
group
|
||
.querySelector(".nav-submenu-container")
|
||
.setAttribute("aria-hidden", String(!expanded));
|
||
group.querySelector(".nav-submenu-container").inert = !expanded;
|
||
}
|
||
function setAdministration(open, focusChild = false) {
|
||
if (open && !document.body.classList.contains("dock-open")) {
|
||
dockHoverOpened = false;
|
||
setDockOpen(true, false);
|
||
}
|
||
administrationOpen = open;
|
||
syncAdministration();
|
||
if (open && focusChild) $("#administration-submenu button")?.focus();
|
||
}
|
||
function nav() {
|
||
const dockBrand = `<button class="dock-toggle dock-brand wordmark" data-action="dock-toggle" aria-expanded="false" aria-controls="dock-navigation" aria-label="${t("Развернуть меню Anidev", "Expand Anidev navigation")}" title="${t("Навигация Anidev", "Anidev navigation")}"><b>a/</b><span>anidev</span></button>`;
|
||
return `<aside class="navigation" id="dock-navigation">${dockBrand}<div class="workspace-label">ANIDEV / PRODUCTION</div><nav aria-label="${t("Основная навигация", "Main navigation")}" class="nav-links">${navigationPages()
|
||
.map((id) => (id === "administration" ? administrationNav() : navPage(id)))
|
||
.join(
|
||
"",
|
||
)}</nav><div class="nav-bottom">eu-central-1<br>Workspace / Pro<br><button data-page="auth" style="font-size:12px;margin-top:15px">${t("Выйти", "Sign out")}</button></div>${dockAccount()}</aside>`;
|
||
}
|
||
const commandShortcut = /Mac|iPhone|iPad/.test(navigator.platform)
|
||
? "⌘ K"
|
||
: "Ctrl K";
|
||
function header() {
|
||
return `<header class="app-header"><button class="mobile-menu" data-action="mobile-menu" aria-label="${t("Открыть навигацию", "Open navigation")}" aria-expanded="false">☰</button><div class="breadcrumb">Anidev <span aria-hidden="true">/</span> ${accountPageIds.includes(page) ? t("Личный кабинет", "My account") : "Production"} <span aria-hidden="true">/</span> ${pageNames[page]}</div><div class="header-actions"><button class="command-trigger" data-action="command" data-shortcut="${commandShortcut}" aria-label="${t("Найти команду", "Find a command")} (${commandShortcut})">${t("Найти команду", "Find a command")} <kbd>${commandShortcut}</kbd></button><button class="avatar" data-action="profile" aria-label="${escape(accountName())}">${escape(accountInitials())}</button></div></header>`;
|
||
}
|
||
const heading = (title, desc, actions = "") =>
|
||
`<div class="page-heading"><div><div class="overline">ANIDEV://PRODUCTION/${page.toUpperCase()}</div><h1>${title}</h1><p>${desc}</p></div><div class="heading-actions">${actions}</div></div>`;
|
||
let dockHoverOpened = false;
|
||
let dockCloseTimer;
|
||
function bindDockHover() {
|
||
if (!$(".dock-toggle")) return;
|
||
const nav = $(".navigation");
|
||
nav.addEventListener("pointerenter", (e) => {
|
||
if (
|
||
e.pointerType !== "mouse" ||
|
||
!matchMedia("(hover: hover) and (pointer: fine)").matches
|
||
)
|
||
return;
|
||
clearTimeout(dockCloseTimer);
|
||
if (!document.body.classList.contains("dock-open")) {
|
||
dockHoverOpened = true;
|
||
setDockOpen(true, false);
|
||
}
|
||
});
|
||
nav.addEventListener("pointerenter", () => clearTimeout(dockCloseTimer));
|
||
nav.addEventListener("pointerleave", (e) => {
|
||
if (nav.contains(e.relatedTarget)) return;
|
||
if (dockHoverOpened)
|
||
dockCloseTimer = setTimeout(() => {
|
||
if (!$("[popover=auto]:popover-open")) {
|
||
dockHoverOpened = false;
|
||
setDockOpen(false, false);
|
||
}
|
||
}, 180);
|
||
});
|
||
}
|
||
function setDockOpen(open, returnFocus = true) {
|
||
if (!open) {
|
||
dockHoverOpened = false;
|
||
clearTimeout(dockCloseTimer);
|
||
}
|
||
const nav = $(".navigation");
|
||
if (!nav) return;
|
||
document.body.classList.toggle("dock-open", open);
|
||
const toggle = $(".dock-toggle");
|
||
toggle.setAttribute("aria-expanded", String(open));
|
||
toggle.setAttribute(
|
||
"aria-label",
|
||
open
|
||
? t("Свернуть меню", "Collapse navigation")
|
||
: t("Развернуть меню", "Expand navigation"),
|
||
);
|
||
toggle.title = toggle.getAttribute("aria-label");
|
||
$(".main-column").inert = open;
|
||
syncAdministration();
|
||
if (open) {
|
||
nav.setAttribute("role", "dialog");
|
||
nav.setAttribute("aria-modal", "true");
|
||
nav.setAttribute("aria-label", t("Навигация", "Navigation"));
|
||
} else {
|
||
nav.removeAttribute("role");
|
||
nav.removeAttribute("aria-modal");
|
||
if (returnFocus) toggle.focus();
|
||
}
|
||
}
|
||
function savePreferences() {
|
||
try {
|
||
localStorage.setItem(
|
||
"anidev.preferences",
|
||
JSON.stringify({ theme, density, locale }),
|
||
);
|
||
} 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") &&
|
||
page !== "auth";
|
||
const route = new URL(location.href);
|
||
route.searchParams.delete("concept");
|
||
route.searchParams.set("page", page);
|
||
route.searchParams.set("theme", theme);
|
||
route.searchParams.set("locale", locale);
|
||
if (route.href !== location.href) {
|
||
history[
|
||
initialRender ||
|
||
route.searchParams.get("page") ===
|
||
new URL(location.href).searchParams.get("page")
|
||
? "replaceState"
|
||
: "pushState"
|
||
]({}, "", route);
|
||
}
|
||
initialRender = false;
|
||
clearTimeout(dockCloseTimer);
|
||
if (!dockWasOpen) {
|
||
dockHoverOpened = false;
|
||
document.body.classList.remove("dock-open");
|
||
}
|
||
document.title = `Anidev / ${concept.name} / ${pageNames[page]}`;
|
||
$(".skip").textContent = t("К содержимому", "Skip to content");
|
||
const content = accountPageIds.includes(page)
|
||
? accountUI.renderPage(page)
|
||
: identityAdapter.snapshot().status !== "authenticated" &&
|
||
!["components", "tokens", "auth"].includes(page)
|
||
? accountUI.gate()
|
||
: ["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,
|
||
components: componentScreen,
|
||
tokens: tokenScreen,
|
||
}[page]?.() || "";
|
||
$("#app").innerHTML =
|
||
page === "auth"
|
||
? auth()
|
||
: `<div class="shell">${nav()}<button class="dock-scrim" data-action="dock-close" tabindex="-1" aria-label="${t("Закрыть меню", "Close navigation")}" aria-hidden="true"></button><div class="main-column">${header()}<main id="content" tabindex="-1">${content}</main></div></div>`;
|
||
bindForms();
|
||
accountUI.bind(page);
|
||
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 =
|
||
`<div class="error-state"><h2>${t("Терминал не загрузился", "Terminal did not load")}</h2><p>${t("Обновите страницу, чтобы повторить загрузку.", "Reload the page to try again.")}</p></div>`;
|
||
});
|
||
if (page === "users" && $("#user-search")) bindUsers();
|
||
}
|
||
function chart() {
|
||
const values =
|
||
chartRange === "24h"
|
||
? [
|
||
32, 30, 34, 33, 35, 42, 38, 34, 33, 32, 37, 35, 38, 41, 43, 39, 36,
|
||
35, 37, 40, 38, 34, 32, 34,
|
||
]
|
||
: [34, 38, 36, 41, 37, 35, 34];
|
||
const points = values
|
||
.map((v, i) => `${(i * 500) / (values.length - 1)},${145 - (v - 25) * 5}`)
|
||
.join(" ");
|
||
return `<div class="chart" role="group" aria-label="${t("Задержка p95: от 30 до 43 мс. Текущая 34 мс.", "p95 latency: 30 to 43 ms. Current 34 ms.")}"><div class="chart-plot" tabindex="0" role="slider" aria-label="${t("Точка графика p95", "p95 chart point")}" aria-valuemin="0" aria-valuemax="${values.length - 1}" aria-valuenow="${values.length - 1}" data-values="${values.join(",")}" data-range="${chartRange}"><svg viewBox="0 0 500 150" preserveAspectRatio="none" aria-hidden="true"><path class="chart-grid" d="M0 20H500M0 75H500M0 130H500"/><polygon class="chart-area" points="0,150 ${points} 500,150"/><polyline class="chart-line" points="${points}"/></svg><span class="chart-guide" hidden></span><span class="chart-dot" hidden></span><div class="chart-tooltip" role="tooltip" hidden></div></div><div class="axis-labels"><span>${chartRange === "24h" ? "00:00" : "21.11"}</span><span>${chartRange === "24h" ? "06:00" : "23.11"}</span><span>${chartRange === "24h" ? "12:00" : "25.11"}</span><span>${chartRange === "24h" ? "18:00" : "27.11"}</span></div></div><p class="chart-legend">${t("p95 · миллисекунды · ниже — лучше · тестовая выборка", "p95 · milliseconds · lower is better · sample dataset")}</p><details class="chart-data"><summary>${t("Числовые данные", "Numerical data")}</summary><div class="chart-data-scroll"><table><thead><tr><th>${t("Время UTC", "Time UTC")}</th><th>p95 / ms</th></tr></thead><tbody>${values.map((v, i) => `<tr><td>${chartRange === "24h" ? String(i).padStart(2, "0") + ":00" : 21 + i + ".11"}</td><td>${v}</td></tr>`).join("")}</tbody></table></div></details>`;
|
||
}
|
||
function bindCharts() {
|
||
document.querySelectorAll(".chart-plot").forEach((plot) => {
|
||
const values = plot.dataset.values.split(",").map(Number);
|
||
const tooltip = plot.querySelector(".chart-tooltip");
|
||
const dot = plot.querySelector(".chart-dot");
|
||
const guide = plot.querySelector(".chart-guide");
|
||
let selected = values.length - 1;
|
||
const label = (index) =>
|
||
plot.dataset.range === "24h"
|
||
? `${String(index).padStart(2, "0")}:00 UTC`
|
||
: `${21 + index}.11`;
|
||
const text = (index) =>
|
||
`${label(index)} · ${values[index]} ${t("мс", "ms")}`;
|
||
plot.setAttribute("aria-valuetext", text(selected));
|
||
function show(index) {
|
||
selected = Math.max(0, Math.min(values.length - 1, index));
|
||
const x = (selected / (values.length - 1)) * plot.clientWidth;
|
||
tooltip.textContent = text(selected);
|
||
tooltip.hidden = dot.hidden = guide.hidden = false;
|
||
tooltip.style.left = `${Math.max(0, Math.min(x - tooltip.offsetWidth / 2, plot.clientWidth - tooltip.offsetWidth))}px`;
|
||
dot.style.left = guide.style.left = `${x}px`;
|
||
dot.style.top = `${((145 - (values[selected] - 25) * 5) / 150) * 100}%`;
|
||
plot.setAttribute("aria-valuenow", String(selected));
|
||
plot.setAttribute("aria-valuetext", text(selected));
|
||
}
|
||
function hide() {
|
||
tooltip.hidden = dot.hidden = guide.hidden = true;
|
||
}
|
||
function point(event) {
|
||
const rect = plot.getBoundingClientRect();
|
||
show(
|
||
Math.round(
|
||
((event.clientX - rect.left) / rect.width) * (values.length - 1),
|
||
),
|
||
);
|
||
}
|
||
plot.addEventListener("pointermove", point);
|
||
plot.addEventListener("pointerdown", point);
|
||
plot.addEventListener("pointerleave", hide);
|
||
plot.addEventListener("focus", () => show(selected));
|
||
plot.addEventListener("blur", hide);
|
||
plot.addEventListener("keydown", (event) => {
|
||
const moves = {
|
||
ArrowLeft: selected - 1,
|
||
ArrowDown: selected - 1,
|
||
ArrowRight: selected + 1,
|
||
ArrowUp: selected + 1,
|
||
Home: 0,
|
||
End: values.length - 1,
|
||
};
|
||
if (event.key === "Escape") {
|
||
hide();
|
||
return;
|
||
}
|
||
if (event.key in moves) {
|
||
event.preventDefault();
|
||
show(moves[event.key]);
|
||
}
|
||
});
|
||
});
|
||
}
|
||
function dashboard() {
|
||
return `${heading(t("Обзор инфраструктуры", "Infrastructure overview"), t("Production · 27 ноября 2026", "Production · November 27, 2026"), `<button data-action="activity">${t("Журнал событий", "Activity log")}</button><button class="primary" data-action="invite">${t("Пригласить участника", "Invite member")}</button>`)}
|
||
<div class="health-line"><strong>${t("Все системы работают штатно", "All systems operational")}</strong><span>${t("Проверено в 09:42 UTC · демонстрация", "Checked at 09:42 UTC · demo")}</span></div>
|
||
<section class="metrics" aria-label="${t("Ключевые показатели", "Key metrics")}"><div class="metric"><div class="metric-label">${t("Доступность за 30 дней", "30-day availability")}</div><div class="metric-value">${number(99.98, 2)}<span style="font-size:.5em">%</span></div><div class="metric-note">${t("SLO 99.9% · в пределах цели", "SLO 99.9% · within target")}</div></div><div class="metric"><div class="metric-label">${t("Активные сессии", "Active sessions")}</div><div class="metric-value">${number(1284)}</div><div class="metric-note">${t("SSO · за последние 15 минут", "SSO · last 15 minutes")}</div></div><div class="metric"><div class="metric-label">${t("Задержка API, p95", "API latency, p95")}</div><div class="metric-value">34 <span style="font-size:.5em">ms</span></div><div class="metric-note">${t("Порог оповещения: 100 мс", "Alert threshold: 100 ms")}</div></div></section>
|
||
<div class="dashboard-grid"><section class="panel"><div class="section-title"><h2>${t("Время ответа API", "API response time")}</h2><select id="chart-range" aria-label="${t("Период графика", "Chart period")}" style="min-height:30px;font-size:12px;padding:4px 7px"><option value="24h" ${chartRange === "24h" ? "selected" : ""}>24 ${t("часа", "hours")}</option><option value="7d" ${chartRange === "7d" ? "selected" : ""}>7 ${t("дней", "days")}</option></select></div>${chart()}</section><section class="panel"><div class="section-title"><h2>${t("Сервисы", "Services")}</h2><span>3 / 3 ONLINE</span></div><div class="services">${[
|
||
["Identity", "18 ms"],
|
||
["License API", "34 ms"],
|
||
["Edge Gateway", "12 ms"],
|
||
]
|
||
.map(
|
||
([name, time]) =>
|
||
`<div class="service"><span>${name}</span><small>${time}</small><span class="status">${t("Работает", "Operational")}</span></div>`,
|
||
)
|
||
.join(
|
||
"",
|
||
)}</div><p class="chart-legend">eu-central-1 · ${t("проверка каждую минуту", "checked every minute")}</p></section></div>
|
||
<section class="activity" id="activity"><div class="section-title"><h2>${t("Последние события", "Recent activity")}</h2><span>UTC</span></div>${[
|
||
[
|
||
"09:42",
|
||
t("Обновлена политика доступа", "Access policy updated"),
|
||
"Anna Volkova",
|
||
],
|
||
[
|
||
"09:38",
|
||
t("Выпущена лицензия AN-2048", "License AN-2048 issued"),
|
||
"License API",
|
||
],
|
||
[
|
||
"09:21",
|
||
t("Успешная авторизация через SSO", "Successful SSO authentication"),
|
||
"Elena Kim",
|
||
],
|
||
]
|
||
.map(
|
||
([time, event, who]) =>
|
||
`<div class="activity-row"><time>${time}</time><span>${event}</span><span>${who}</span></div>`,
|
||
)
|
||
.join(
|
||
"",
|
||
)}</section><p class="compact-note">${t("Демонстрационные данные. Подключение к реальной инфраструктуре отсутствует.", "Demonstration data. No connection to live infrastructure.")}</p>`;
|
||
}
|
||
const roleName = (r) =>
|
||
({
|
||
admin: t("Администратор", "Administrator"),
|
||
developer: t("Разработчик", "Developer"),
|
||
viewer: t("Наблюдатель", "Viewer"),
|
||
})[r];
|
||
const statusName = (s) =>
|
||
({
|
||
active: t("Активен", "Active"),
|
||
invited: t("Приглашён", "Invited"),
|
||
suspended: t("Заблокирован", "Suspended"),
|
||
})[s];
|
||
function filteredUsers() {
|
||
return users
|
||
.filter(
|
||
(u) =>
|
||
(u.name + " " + u.email).toLowerCase().includes(query.toLowerCase()) &&
|
||
(role === "all" || u.role === role),
|
||
)
|
||
.sort((a, b) => a[sortKey].localeCompare(b[sortKey]) * (sortAsc ? 1 : -1));
|
||
}
|
||
function userScreen() {
|
||
return `${heading(t("Пользователи", "Users"), t("Участники рабочего пространства и их доступ.", "Workspace members and their access."), `<button data-action="reset-users">${t("Сбросить демо", "Reset demo")}</button><button class="primary" data-action="invite">${t("Пригласить участника", "Invite member")}</button>`)}<div class="page-body"><div class="toolbar"><input class="search" id="user-search" type="search" placeholder="${t("Поиск по имени или email", "Search name or email")}" aria-label="${t("Поиск пользователей", "Search users")}" value="${escape(query)}"><select id="role-filter" aria-label="${t("Фильтр по роли", "Filter role")}"><option value="all">${t("Все роли", "All roles")}</option>${["admin", "developer", "viewer"].map((r) => `<option value="${r}" ${role === r ? "selected" : ""}>${roleName(r)}</option>`).join("")}</select><button data-action="download-users">CSV</button></div><div id="user-results">${userResults()}</div></div>`;
|
||
}
|
||
function userResults() {
|
||
const filtered = filteredUsers();
|
||
userPage = Math.max(
|
||
1,
|
||
Math.min(userPage, Math.ceil(filtered.length / 5) || 1),
|
||
);
|
||
const visible = filtered.slice((userPage - 1) * 5, userPage * 5);
|
||
return `${selected.size ? `<div class="selection-bar"><span>${t("Выбрано", "Selected")}: ${selected.size}</span><button class="danger" data-action="bulk-suspend">${t("Заблокировать", "Suspend")}</button><button data-action="clear-selection">${t("Снять выбор", "Clear selection")}</button></div>` : ""}
|
||
${
|
||
!filtered.length
|
||
? `<div class="empty-state"><h3>${t("Пользователи не найдены", "No users found")}</h3><p>${t("Попробуйте другое имя или сбросьте фильтр.", "Try another name or reset the filter.")}</p><button data-action="clear-filters">${t("Сбросить фильтры", "Reset filters")}</button></div>`
|
||
: `<div class="table-wrap"><table><caption style="position:absolute;width:1px;height:1px;overflow:hidden">${t("Участники Anidev Production", "Anidev Production members")}</caption><thead><tr><th style="width:35px"><input type="checkbox" id="select-all" aria-label="${t("Выбрать текущую страницу", "Select current page")}" ${visible.every((u) => selected.has(u.id)) ? "checked" : ""}></th><th aria-sort="${sortKey === "name" ? (sortAsc ? "ascending" : "descending") : "none"}"><button class="row-action" data-sort="name">${t("Участник", "Member")} ${sortKey === "name" ? (sortAsc ? "↑" : "↓") : ""}</button></th><th aria-sort="${sortKey === "role" ? (sortAsc ? "ascending" : "descending") : "none"}"><button class="row-action" data-sort="role">${t("Роль", "Role")}</button></th><th>${t("Статус", "Status")}</th><th>${t("Был в сети", "Last seen")}</th><th><span class="muted">${t("Действия", "Actions")}</span></th></tr></thead><tbody>${visible
|
||
.map(
|
||
(u) =>
|
||
`<tr><td><input type="checkbox" data-select="${u.id}" aria-label="${t("Выбрать", "Select")} ${escape(u.name)}" ${selected.has(u.id) ? "checked" : ""}></td><td><div class="person"><span class="avatar">${escape(
|
||
u.name
|
||
.split(" ")
|
||
.map((n) => n[0])
|
||
.join(""),
|
||
)}</span><div>${escape(u.name)}<small>${escape(u.email)}</small></div></div></td><td>${roleName(u.role)}</td><td><span class="status ${u.status === "suspended" ? "warn" : ""}">${statusName(u.status)}</span></td><td><small>${u.last}</small></td><td><button class="row-action" data-edit="${u.id}" aria-label="${t("Изменить", "Edit")} ${escape(u.name)}">${t("Изменить", "Edit")}</button></td></tr>`,
|
||
)
|
||
.join("")}</tbody></table></div>`
|
||
}
|
||
<div class="pagination"><span>${filtered.length ? t("Показано", "Showing") + " " + ((userPage - 1) * 5 + 1) + "–" + Math.min(userPage * 5, filtered.length) + " / " + filtered.length : t("Нет результатов", "No results")}</span><div><button data-action="prev" ${userPage === 1 ? "disabled" : ""}>${t("Назад", "Previous")}</button><button data-action="next" ${userPage * 5 >= filtered.length ? "disabled" : ""}>${t("Далее", "Next")}</button></div></div>`;
|
||
}
|
||
function refreshUsers() {
|
||
const search = $("#user-search");
|
||
if (search) search.value = query;
|
||
const filter = $("#role-filter");
|
||
if (filter) filter.value = role;
|
||
$("#user-results").innerHTML = userResults();
|
||
bindSelection();
|
||
}
|
||
function bindUsers() {
|
||
$("#user-search").oninput = (e) => {
|
||
query = e.target.value;
|
||
userPage = 1;
|
||
refreshUsers();
|
||
};
|
||
$("#role-filter").onchange = (e) => {
|
||
role = e.target.value;
|
||
userPage = 1;
|
||
refreshUsers();
|
||
};
|
||
bindSelection();
|
||
}
|
||
function bindSelection() {
|
||
const all = $("#select-all");
|
||
if (all) {
|
||
const visible = filteredUsers().slice((userPage - 1) * 5, userPage * 5);
|
||
all.indeterminate =
|
||
visible.some((u) => selected.has(u.id)) &&
|
||
!visible.every((u) => selected.has(u.id));
|
||
all.onchange = (e) => {
|
||
visible.forEach((u) =>
|
||
e.target.checked ? selected.add(u.id) : selected.delete(u.id),
|
||
);
|
||
refreshUsers();
|
||
};
|
||
}
|
||
document.querySelectorAll("[data-select]").forEach(
|
||
(el) =>
|
||
(el.onchange = () => {
|
||
const id = Number(el.dataset.select);
|
||
el.checked ? selected.add(id) : selected.delete(id);
|
||
refreshUsers();
|
||
}),
|
||
);
|
||
}
|
||
function settingsScreen() {
|
||
return `${heading(t("Настройки пространства", "Workspace settings"), t("Идентификация, безопасность и уведомления.", "Identity, security and notifications."))}<div class="page-body"><div class="tabs" role="tablist" aria-label="${t("Раздел настроек", "Settings section")}">${["general", "security", "notifications"].map((v, i) => `<button role="tab" id="tab-${v}" aria-controls="settings-panel" data-tab="${v}" aria-selected="${tab === v}" tabindex="${tab === v ? "0" : "-1"}">${[t("Основные", "General"), t("Безопасность", "Security"), t("Уведомления", "Notifications")][i]}</button>`).join("")}</div><section id="settings-panel" role="tabpanel" aria-labelledby="tab-${tab}" class="settings-layout"><div class="settings-copy"><h2>${tab === "general" ? t("Ваше пространство", "Your workspace") : tab === "security" ? t("Контроль доступа", "Access control") : t("Оповещения", "Notifications")}</h2><p>${tab === "general" ? t("Эти данные видны участникам организации.", "These details are visible to organization members.") : t("Изменения применяются к этому демо.", "Changes apply to this demo.")}</p></div><form id="settings-form">${tab === "general" ? `<label class="field">${t("Название", "Workspace name")}<input name="name" required maxlength="60" value="${escape(settings.name)}"></label><label class="field">${t("Идентификатор", "Workspace slug")}<input name="slug" required pattern="[a-z0-9-]+" value="${escape(settings.slug)}"><small>${t("Строчные латинские буквы, цифры и дефис.", "Lowercase letters, numbers and hyphens.")}</small></label><label class="field">${t("Регион данных", "Data region")}<select name="region"><option value="eu" ${settings.region === "eu" ? "selected" : ""}>Europe / Frankfurt</option><option value="us" ${settings.region === "us" ? "selected" : ""}>US / Virginia</option></select></label>` : tab === "security" ? `<div class="form-row"><label for="mfa"><b>${t("Двухфакторная авторизация", "Two-factor authentication")}</b><small style="display:block">${t("Обязательна для всех участников", "Required for all members")}</small></label><input class="switch" type="checkbox" role="switch" name="mfa" id="mfa" ${settings.mfa ? "checked" : ""}></div><div class="form-row"><label for="audit">${t("Журналировать действия", "Record audit events")}</label><input class="switch" type="checkbox" role="switch" name="audit" id="audit" ${settings.audit ? "checked" : ""}></div><button type="button" data-action="sessions">${t("Управление сессиями", "Manage sessions")}</button>` : `<label class="field">${t("Email для оповещений", "Alert email")}<input type="email" name="email" required value="${escape(settings.email)}"></label><div class="form-row"><input type="checkbox" id="incidents" checked><label for="incidents">${t("Инциденты и недоступность сервисов", "Incidents and service outages")}</label></div>`}<div class="form-footer"><button type="reset">${t("Отменить", "Cancel")}</button><button class="primary" type="submit">${t("Сохранить изменения", "Save changes")}</button></div></form></section></div>`;
|
||
}
|
||
function auth() {
|
||
return `<main id="content" class="auth-layout" style="max-width:none;padding:0"><section class="auth-brand">${wordmark}<div class="auth-statement">${t("Ваша инфраструктура.<br>Под вашим контролем.", "Your infrastructure.<br>Under your control.")}</div><small>ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}</small></section><section class="auth-main"><form id="auth-form" class="auth-form"><h1>${t("Вход в Anidev", "Sign in to Anidev")}</h1><p>${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}</p><label class="field">${t("Username или email", "Username or email")}<input name="email" type="text" autocomplete="username" placeholder="anna.volkova" required></label><label class="field">${t("Пароль", "Password")}<input name="password" type="password" autocomplete="current-password" minlength="8" required aria-describedby="password-hint"><small id="password-hint">${t("Демо: anna.volkova или mikhail.orlov; пароль от 8 символов.", "Demo: anna.volkova or mikhail.orlov; password of 8+ characters.")}</small></label><div class="form-row"><input id="remember" type="checkbox"><label for="remember">${t("Запомнить меня", "Remember me")}</label><button class="row-action" type="button" data-action="recover">${t("Забыли пароль?", "Forgot password?")}</button></div><p class="error-text" id="auth-error" role="alert"></p><button class="primary" type="submit">${t("Войти", "Sign in")}</button><div class="auth-divider">${t("или корпоративный аккаунт", "or your company account")}</div><button type="button" class="sso" data-action="sso">${t("Войти через SSO", "Continue with SSO")}</button><div class="auth-foot"><span>© Anidev 2026</span><button class="row-action" type="button" data-page="dashboard">${t("Вернуться к обзору", "Back to overview")}</button></div></form></section></main>`;
|
||
}
|
||
function componentScreen() {
|
||
return `${heading(t("Библиотека компонентов", "Component library"), t("Единые компоненты и состояния Dock.", "Shared Dock components and states."), `<button data-action="command">${t("Команды", "Commands")} ${commandShortcut}</button>`)}<div class="page-body"><div class="library">
|
||
<section class="specimen"><h2>Buttons</h2><div class="component-row"><button class="primary" data-action="demo-save">${t("Сохранить", "Save")}</button><button data-action="toast">${t("Вторичная", "Secondary")}</button><button class="danger" data-action="delete">${t("Удалить", "Delete")}</button><button disabled>Disabled</button><button aria-busy="true" disabled>${t("Загрузка…", "Loading…")}</button></div><small>Hover · active · focus · disabled · loading</small></section>
|
||
<section class="specimen"><h2>Inputs & selects</h2><label class="field">${t("Имя проекта", "Project name")}<input placeholder="Anidev Production"></label><label class="field">Email<input aria-invalid="true" aria-describedby="sample-error" value="invalid-email"><small class="error-text" id="sample-error">${t("Введите корректный email", "Enter a valid email")}</small></label><div class="sample-control-row"><select aria-label="${t("Окружение", "Environment")}"><option>Production</option><option>Staging</option></select><input aria-label="${t("Только для чтения", "Read-only field")}" readonly value="Read only"></div></section>
|
||
<section class="specimen selection-specimen"><h2>Selection controls</h2><div class="form-row"><label class="choice-pill" for="check-demo"><input id="check-demo" type="checkbox" checked><span>${t("Email-уведомления", "Email notifications")}</span></label></div><fieldset style="border:0;padding:0"><legend>${t("Период хранения", "Retention period")}</legend><div class="component-row"><label class="choice-pill"><input type="radio" name="retention" value="30" checked><span>30 ${t("дней", "days")}</span></label><label class="choice-pill"><input type="radio" name="retention" value="90"><span>90 ${t("дней", "days")}</span></label></div></fieldset><div class="form-row"><label for="switch-demo">${t("Автообновление", "Auto refresh")}</label><input id="switch-demo" class="switch" role="switch" type="checkbox" checked></div></section>
|
||
<section class="specimen grouped-choice-specimen"><h2>${t("Группы чекбоксов", "Checkbox groups")}</h2>${[
|
||
"horizontal",
|
||
"vertical",
|
||
]
|
||
.map(
|
||
(orientation) =>
|
||
`<fieldset class="choice-fieldset"><legend>${orientation === "horizontal" ? t("Горизонтально", "Horizontal") : t("Вертикально", "Vertical")}</legend><div class="choice-group ${orientation === "vertical" ? "choice-group--vertical" : ""}" data-choice-group="${orientation}">${[
|
||
["email", "Email"],
|
||
["push", "Push"],
|
||
["sms", "SMS"],
|
||
]
|
||
.map(
|
||
([value, label]) =>
|
||
`<label class="choice-group-option"><input type="checkbox" name="channels-${orientation}" value="${value}" ${value !== "sms" ? "checked" : ""}><span>${label}</span></label>`,
|
||
)
|
||
.join("")}</div></fieldset>`,
|
||
)
|
||
.join("")}</section>
|
||
<section class="specimen"><h2>Overlays & feedback</h2><div class="component-row"><button data-action="invite">Modal</button><button data-action="drawer">Drawer</button><button data-action="toast">Toast</button><span class="tooltip-wrap"><button aria-describedby="demo-tooltip">Tooltip</button><span class="tooltip" id="demo-tooltip" role="tooltip">${t("Скопировать идентификатор", "Copy identifier")}</span></span></div><details><summary>${t("Действия проекта", "Project actions")}</summary><div class="dropdown"><button data-action="rename">${t("Переименовать", "Rename")}</button><button data-action="download-users">${t("Экспорт CSV", "Export CSV")}</button><button class="danger" data-action="delete">${t("Удалить", "Delete")}</button></div></details><div class="context-target" tabindex="0" role="button" aria-haspopup="menu" style="margin-top:15px">${t("Контекстное меню: правая кнопка, Shift+F10 или Enter", "Context menu: right click, Shift+F10 or Enter")}</div></section>
|
||
<section class="specimen"><h2>Empty state</h2><div class="empty-state"><h3>${t("Пока нет API-ключей", "No API keys yet")}</h3><p>${t("Создайте ключ для подключения сервиса.", "Create a key to connect your service.")}</p><button data-action="create-key">${t("Создать ключ", "Create key")}</button></div></section>
|
||
<section class="specimen"><h2>Error & skeleton</h2><div class="error-state" role="status"><p>${t("Не удалось загрузить журнал.", "Could not load the log.")}</p><button data-action="retry">${t("Повторить", "Retry")}</button></div><div aria-label="${t("Загрузка данных", "Loading data")}" aria-busy="true" style="margin-top:20px"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></div></section>
|
||
<section class="specimen toast-specimen"><h2>${t("Уведомления", "Notifications")}</h2><div class="component-row">${[
|
||
["success", t("Успех", "Success")],
|
||
["info", t("Информация", "Information")],
|
||
["warning", t("Предупреждение", "Warning")],
|
||
["error", t("Ошибка", "Error")],
|
||
]
|
||
.map(
|
||
([type, label]) => `<button data-action="toast-${type}">${label}</button>`,
|
||
)
|
||
.join("")}</div></section>
|
||
<section class="specimen status-specimen"><h2>${t("Статусы", "Status indicators")}</h2><div class="component-row status-examples"><span class="status-badge status-badge--success">${iconSvg("check", { size: 16 })}${t("Работает", "Operational")}</span><span class="status-badge status-badge--danger">${iconSvg("close", { size: 16 })}${t("Недоступен", "Unavailable")}</span><span class="status-badge status-badge--pending">${iconSvg("more-horizontal", { size: 16 })}${t("Ожидает", "Pending")}</span></div><p class="muted" style="font-size:13px">${t("Состояние выражено текстом, а не только цветом.", "Status uses text as well as color.")}</p></section>
|
||
<section class="specimen"><h2>${t("Рабочие области", "Workspaces")}</h2><p class="muted">${t("SSH-терминал и ридер логов в стиле Dock.", "SSH terminal and log reader in Dock style.")}</p><div class="component-row"><button data-page="ssh">${t("SSH-консоль", "SSH console")}</button><button data-page="logs">${t("Log-ридер", "Log reader")}</button></div></section>
|
||
<section class="specimen"><h2>${t("Иконки Anidev", "Anidev icons")}</h2><div class="component-row icon-specimen">${["profile", "security", "sessions", "applications", "settings", "copy", "key", "bell"].map(icon).join("")}</div><p class="muted">${t("64 SVG · сетка 24×24 · контур 1.5px", "64 SVGs · 24×24 grid · 1.5px stroke")}</p><a href="${new URL("../icons/", import.meta.url).pathname}" data-icon-catalog>${t("Открыть пак иконок →", "Open icon pack →")}</a></section>
|
||
<section class="specimen"><h2>Chart</h2>${chart()}</section></div><p class="compact-note">${t("Таблицы, пагинация и фильтры — на экране «Пользователи»; вкладки — в настройках; форма входа — в авторизации.", "Tables, pagination and filters: Users. Tabs: Settings. Sign-in form: Authentication.")}</p></div>`;
|
||
}
|
||
function tokenScreen() {
|
||
return `${heading(t("Дизайн-токены", "Design tokens"), `${concept.name} / ${theme} / ${density}`, `<button data-action="download-system">${t("Экспорт системы", "Export system")}</button><button data-action="copy-json">${t("Копировать JSON", "Copy JSON")}</button><button class="primary" data-action="copy-css">${t("Копировать CSS", "Copy CSS")}</button>`)}<div class="page-body"><div class="tokens-list">${Object.entries(
|
||
tokens,
|
||
)
|
||
.map(
|
||
([key, value]) =>
|
||
`<div class="token-row"><code>${key}</code><span class="token-value">${value.startsWith("#") ? `<i class="color-chip" style="background:${value}"></i>` : ""}${escape(value)}</span></div>`,
|
||
)
|
||
.join(
|
||
"",
|
||
)}</div><pre class="code-block">:root {\n${cssVars(tokens)}\n}</pre><p class="compact-note">${t("Экспорт включает обе темы, JSON и CSS. Используется утверждённая палитра Dock.", "Export includes both themes, JSON and CSS. Uses the approved Dock palette.")}</p></div>`;
|
||
}
|
||
let dialogInitiator = null;
|
||
function openDialog(title, body, cls = "") {
|
||
if (document.body.classList.contains("dock-open")) setDockOpen(false, false);
|
||
const d = $("#dialog");
|
||
if (d.open) d.close();
|
||
dialogInitiator = document.activeElement;
|
||
d.className = cls;
|
||
d.innerHTML = `<div class="dialog-heading"><h2 id="dialog-title">${title}</h2><button class="close" data-action="close" aria-label="${t("Закрыть", "Close")}">${iconSvg("close", { size: 20 })}</button></div>${body}`;
|
||
d.showModal();
|
||
return d;
|
||
}
|
||
function invite() {
|
||
openDialog(
|
||
t("Пригласить участника", "Invite a member"),
|
||
`<p>${t("Приглашение будет добавлено в демонстрационный список. Письмо не отправляется.", "The invitation is added to the demo list. No email is sent.")}</p><form id="invite-form"><label class="field">${t("Имя", "Name")}<input name="name" required maxlength="80" autocomplete="name"></label><label class="field">Email<input name="email" type="email" required autocomplete="email"></label><label class="field">${t("Роль", "Role")}<select name="role">${["developer", "viewer", "admin"].map((r) => `<option value="${r}">${roleName(r)}</option>`).join("")}</select></label><p id="invite-error" class="error-text" role="alert"></p><div class="form-footer"><button type="button" data-action="close">${t("Отмена", "Cancel")}</button><button class="primary" type="submit">${t("Добавить приглашение", "Add invitation")}</button></div></form>`,
|
||
);
|
||
$("#invite-form").onsubmit = (e) => {
|
||
e.preventDefault();
|
||
const f = new FormData(e.target),
|
||
email = f.get("email").trim().toLowerCase();
|
||
if (users.some((u) => u.email.toLowerCase() === email)) {
|
||
$("#invite-error").textContent = t(
|
||
"Этот email уже добавлен.",
|
||
"This email already exists.",
|
||
);
|
||
return;
|
||
}
|
||
users.push({
|
||
id: Date.now(),
|
||
name: f.get("name").trim(),
|
||
email,
|
||
role: f.get("role"),
|
||
status: "invited",
|
||
last: "—",
|
||
});
|
||
persist();
|
||
$("#dialog").close();
|
||
if (page === "users") refreshUsers();
|
||
toast(t("Приглашение добавлено в демо", "Invitation added to demo"));
|
||
};
|
||
}
|
||
function editUser(id) {
|
||
const user = users.find((u) => u.id === id);
|
||
if (!user) return;
|
||
openDialog(
|
||
escape(user.name),
|
||
`<p>${escape(user.email)}</p><form id="edit-user"><label class="field">${t("Роль в пространстве", "Workspace role")}<select name="role">${["admin", "developer", "viewer"].map((r) => `<option value="${r}" ${user.role === r ? "selected" : ""}>${roleName(r)}</option>`).join("")}</select></label><label class="field">${t("Статус", "Status")}<select name="status">${["active", "invited", "suspended"].map((s) => `<option value="${s}" ${user.status === s ? "selected" : ""}>${statusName(s)}</option>`).join("")}</select></label>${accountUI.roleMarkup(id)}${accountUI.grantsMarkup(id)}<div class="form-footer"><button type="button" data-action="close">${t("Отмена", "Cancel")}</button><button type="submit" class="primary">${t("Сохранить", "Save")}</button></div></form>`,
|
||
);
|
||
$("#dialog").classList.add("identity-editor-dialog");
|
||
accountUI.bindGrants(id, () => editUser(id));
|
||
$("#edit-user").onsubmit = (e) => {
|
||
e.preventDefault();
|
||
const data = new FormData(e.target);
|
||
user.role = data.get("role");
|
||
user.status = data.get("status");
|
||
identityAdapter.setUserRoles(id, data.getAll("ssoRole"));
|
||
persist();
|
||
$("#dialog").close();
|
||
refreshUsers();
|
||
toast(t("Доступ обновлён", "Access updated"));
|
||
};
|
||
}
|
||
function command() {
|
||
openDialog(
|
||
t("Команды", "Commands"),
|
||
`<input id="command-search" type="search" placeholder="${t("Найти экран…", "Find a page…")}" aria-label="${t("Поиск команд", "Search commands")}" style="width:100%"><div class="command-list">${Object.entries(
|
||
pageNames,
|
||
)
|
||
.map(([id, name]) => `<button data-page="${id}">${name}</button>`)
|
||
.join(
|
||
"",
|
||
)}<button data-action="invite">${t("Пригласить участника", "Invite member")}</button></div><small>${t("↑ ↓ — выбор · Enter — открыть · Esc — закрыть", "↑ ↓ to navigate · Enter to open · Esc to close")}</small>`,
|
||
);
|
||
$("#command-search").oninput = (e) =>
|
||
document
|
||
.querySelectorAll(".command-list button")
|
||
.forEach(
|
||
(b) =>
|
||
(b.hidden = !b.textContent
|
||
.toLowerCase()
|
||
.includes(e.target.value.toLowerCase())),
|
||
);
|
||
}
|
||
function download(name, text, type = "text/plain") {
|
||
const url = URL.createObjectURL(new Blob(["\ufeff", text], { type }));
|
||
const a = document.createElement("a");
|
||
a.href = url;
|
||
a.download = name;
|
||
a.click();
|
||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||
}
|
||
async function copy(text) {
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
toast(t("Скопировано", "Copied"));
|
||
} catch {
|
||
openDialog(
|
||
t("Скопируйте вручную", "Copy manually"),
|
||
`<textarea readonly aria-label="Copy" style="width:100%;height:220px">${escape(text)}</textarea>`,
|
||
);
|
||
$("#dialog textarea").select();
|
||
}
|
||
}
|
||
function bindForms() {
|
||
if ($("#settings-form"))
|
||
$("#settings-form").onsubmit = (e) => {
|
||
e.preventDefault();
|
||
const f = new FormData(e.target);
|
||
if (tab === "general") {
|
||
settings.name = f.get("name").trim();
|
||
settings.slug = f.get("slug");
|
||
settings.region = f.get("region");
|
||
} else if (tab === "security") {
|
||
settings.mfa = f.has("mfa");
|
||
settings.audit = f.has("audit");
|
||
} else {
|
||
settings.email = f.get("email");
|
||
settings.incidents = $("#incidents").checked;
|
||
}
|
||
persist();
|
||
toast(t("Настройки сохранены", "Settings saved"));
|
||
};
|
||
if ($("#settings-form"))
|
||
$("#settings-form").onreset = (e) => {
|
||
e.preventDefault();
|
||
render();
|
||
};
|
||
if ($("#incidents") && settings.incidents !== undefined)
|
||
$("#incidents").checked = settings.incidents;
|
||
if ($("#auth-form"))
|
||
$("#auth-form").onsubmit = async (e) => {
|
||
e.preventDefault();
|
||
const identityRevision = identityAdapter.snapshot().revision;
|
||
const b = e.target.querySelector("[type=submit]");
|
||
b.disabled = true;
|
||
b.setAttribute("aria-busy", "true");
|
||
b.textContent = t("Вход…", "Signing in…");
|
||
await new Promise((r) => setTimeout(r, 450));
|
||
if (identityAdapter.snapshot().revision !== identityRevision) return;
|
||
if (new FormData(e.target).get("password") === "wrong-password") {
|
||
e.target.elements.password.value = "";
|
||
$("#auth-error").textContent = t(
|
||
"Неверный пароль. Попробуйте другой пароль для демо.",
|
||
"Incorrect password. Try another password for this demo.",
|
||
);
|
||
e.target.elements.password.setAttribute("aria-invalid", "true");
|
||
b.disabled = false;
|
||
b.removeAttribute("aria-busy");
|
||
b.textContent = t("Войти", "Sign in");
|
||
return;
|
||
}
|
||
identityAdapter.signIn(new FormData(e.target).get("email"));
|
||
page = "profile";
|
||
render();
|
||
toast(t("Демонстрационный вход выполнен", "Demo sign-in complete"));
|
||
};
|
||
if ($("#chart-range"))
|
||
$("#chart-range").onchange = (e) => {
|
||
chartRange = e.target.value;
|
||
render();
|
||
};
|
||
const target = $(".context-target");
|
||
if (target) {
|
||
target.oncontextmenu = (e) => {
|
||
e.preventDefault();
|
||
contextMenu(e.clientX, e.clientY);
|
||
};
|
||
target.onkeydown = (e) => {
|
||
if ((e.shiftKey && e.key === "F10") || e.key === "Enter") {
|
||
e.preventDefault();
|
||
const r = target.getBoundingClientRect();
|
||
contextMenu(r.left, r.top);
|
||
}
|
||
};
|
||
}
|
||
}
|
||
function contextMenu(x, y) {
|
||
$(".context-menu")?.remove();
|
||
const menu = document.createElement("div");
|
||
menu.className = "context-menu";
|
||
menu.setAttribute("role", "menu");
|
||
menu.innerHTML = `<button role="menuitem" data-action="copy-id">${t("Копировать ID", "Copy ID")}</button><button role="menuitem" data-action="drawer">${t("Подробности", "Details")}</button>`;
|
||
document.body.append(menu);
|
||
menu.style.left = Math.min(x, innerWidth - 200) + "px";
|
||
menu.style.top = Math.min(y, innerHeight - 130) + "px";
|
||
menu.querySelector("button").focus();
|
||
}
|
||
document.addEventListener("click", async (e) => {
|
||
if (await accountUI.handleClick(e)) return;
|
||
const pageButton = e.target.closest("[data-page]");
|
||
if (pageButton) {
|
||
const fromDock = Boolean(pageButton.closest(".navigation"));
|
||
if (fromDock && page === pageButton.dataset.page) return;
|
||
page = pageButton.dataset.page;
|
||
if (["ssh", "logs"].includes(page)) administrationOpen = true;
|
||
$("#dialog").close();
|
||
render({ preserveDock: fromDock });
|
||
if (fromDock && document.body.classList.contains("dock-open")) {
|
||
$(".nav-links [aria-current=page]")?.focus({ preventScroll: true });
|
||
} else $("#content")?.focus();
|
||
return;
|
||
}
|
||
const sorter = e.target.closest("[data-sort]");
|
||
if (sorter) {
|
||
sortAsc = sortKey === sorter.dataset.sort ? !sortAsc : true;
|
||
sortKey = sorter.dataset.sort;
|
||
refreshUsers();
|
||
return;
|
||
}
|
||
const edit = e.target.closest("[data-edit]");
|
||
if (edit) {
|
||
editUser(Number(edit.dataset.edit));
|
||
return;
|
||
}
|
||
const tabButton = e.target.closest("[data-tab]");
|
||
if (tabButton) {
|
||
tab = tabButton.dataset.tab;
|
||
render();
|
||
$("#tab-" + tab).focus();
|
||
return;
|
||
}
|
||
const button = e.target.closest("[data-action]"),
|
||
action = button?.dataset.action;
|
||
if (!e.target.closest(".context-menu")) $(".context-menu")?.remove();
|
||
if (!action) return;
|
||
document
|
||
.querySelectorAll("[popover=auto]:popover-open")
|
||
.forEach((el) => el.hidePopover());
|
||
const actions = {
|
||
"toast-success": () =>
|
||
toast(t("Изменения сохранены.", "Changes saved."), { type: "success" }),
|
||
"toast-info": () =>
|
||
toast(
|
||
t(
|
||
"В журнале появилось новое событие.",
|
||
"A new event is available in the log.",
|
||
),
|
||
{ type: "info" },
|
||
),
|
||
"toast-warning": () =>
|
||
toast(
|
||
t(
|
||
"Срок действия сессии скоро истечёт.",
|
||
"Your session will expire soon.",
|
||
),
|
||
{ type: "warning" },
|
||
),
|
||
"toast-error": () =>
|
||
toast(
|
||
t(
|
||
"Не удалось выполнить операцию. Попробуйте ещё раз.",
|
||
"The operation failed. Please try again.",
|
||
),
|
||
{ type: "error" },
|
||
),
|
||
shares: () =>
|
||
openDialog(
|
||
t("Мои общие ресурсы", "My shares"),
|
||
`<p>${t("Общих ресурсов пока нет.", "No shared resources yet.")}</p><button data-action="close">${t("Закрыть", "Close")}</button>`,
|
||
"drawer",
|
||
),
|
||
"switch-account": () => accountUI.switchAccount(),
|
||
"dock-toggle": () => {
|
||
if (dockHoverOpened) {
|
||
dockHoverOpened = false;
|
||
return;
|
||
}
|
||
setDockOpen(!document.body.classList.contains("dock-open"));
|
||
},
|
||
"administration-toggle": () =>
|
||
setAdministration(
|
||
!administrationOpen || !document.body.classList.contains("dock-open"),
|
||
),
|
||
"dock-close": () => setDockOpen(false),
|
||
"mobile-menu": () =>
|
||
setDockOpen(!document.body.classList.contains("dock-open")),
|
||
close: () => $("#dialog").close(),
|
||
invite,
|
||
command,
|
||
activity: () => $("#activity").scrollIntoView({ behavior: "smooth" }),
|
||
profile: () => navigate("profile"),
|
||
"download-system": async () => {
|
||
button.disabled = true;
|
||
try {
|
||
await exportSystem(
|
||
{ page, theme, density, locale, accent: rawAccent || undefined },
|
||
toast,
|
||
);
|
||
} catch {
|
||
toast(
|
||
t(
|
||
"Экспорт не удался. Повторите попытку.",
|
||
"Export failed. Try again.",
|
||
),
|
||
);
|
||
} finally {
|
||
button.disabled = false;
|
||
}
|
||
},
|
||
prev: () => {
|
||
userPage--;
|
||
refreshUsers();
|
||
},
|
||
next: () => {
|
||
userPage++;
|
||
refreshUsers();
|
||
},
|
||
"clear-filters": () => {
|
||
query = "";
|
||
role = "all";
|
||
userPage = 1;
|
||
refreshUsers();
|
||
},
|
||
"clear-selection": () => {
|
||
selected.clear();
|
||
refreshUsers();
|
||
},
|
||
"bulk-suspend": () => {
|
||
openDialog(
|
||
t("Заблокировать участников?", "Suspend members?"),
|
||
`<p>${t("Количество выбранных участников", "Selected members")}: ${selected.size}</p><div class="form-footer"><button data-action="close">${t("Отмена", "Cancel")}</button><button class="primary" data-action="confirm-suspend">${t("Заблокировать", "Suspend")}</button></div>`,
|
||
);
|
||
},
|
||
"confirm-suspend": () => {
|
||
users
|
||
.filter((u) => selected.has(u.id))
|
||
.forEach((u) => (u.status = "suspended"));
|
||
selected.clear();
|
||
persist();
|
||
$("#dialog").close();
|
||
refreshUsers();
|
||
toast(t("Доступ заблокирован", "Access suspended"));
|
||
},
|
||
"reset-users": () => {
|
||
users = structuredClone(initialUsers);
|
||
selected.clear();
|
||
query = "";
|
||
role = "all";
|
||
userPage = 1;
|
||
persist();
|
||
render();
|
||
toast(t("Тестовые данные восстановлены", "Demo data restored"));
|
||
},
|
||
"download-users": () => {
|
||
const csv = [
|
||
"Name,Email,Role,Status",
|
||
...filteredUsers().map((u) =>
|
||
[u.name, u.email, u.role, u.status]
|
||
.map((v) => '"' + String(v).replaceAll('"', '""') + '"')
|
||
.join(","),
|
||
),
|
||
].join("\r\n");
|
||
download("anidev-users.csv", csv, "text/csv;charset=utf-8");
|
||
},
|
||
toast: () =>
|
||
toast(t("Изменения сохранены в демонстрации", "Demo changes saved")),
|
||
"demo-save": async () => {
|
||
button.disabled = true;
|
||
button.setAttribute("aria-busy", "true");
|
||
const old = button.textContent;
|
||
button.textContent = t("Сохранение…", "Saving…");
|
||
await new Promise((r) => setTimeout(r, 500));
|
||
button.disabled = false;
|
||
button.removeAttribute("aria-busy");
|
||
button.textContent = old;
|
||
toast(t("Сохранено", "Saved"));
|
||
},
|
||
drawer: () =>
|
||
openDialog(
|
||
t("Сведения о пространстве", "Workspace details"),
|
||
`<p>ANIDEV / PRODUCTION</p><dl><dt>${t("Регион", "Region")}</dt><dd>eu-central-1</dd><dt>${t("Владелец", "Owner")}</dt><dd>Anna Volkova</dd><dt>${t("Создано", "Created")}</dt><dd>2026-01-14</dd></dl><div class="form-footer"><button data-action="close">${t("Закрыть", "Close")}</button></div>`,
|
||
"drawer",
|
||
),
|
||
sessions: () =>
|
||
openDialog(
|
||
t("Активные сессии", "Active sessions"),
|
||
`<p>Windows · Edge · Moscow</p><p>${t("Текущая сессия · 09:42 UTC", "Current session · 09:42 UTC")}</p><button data-action="revoke">${t("Завершить другие демо-сессии", "Revoke other demo sessions")}</button>`,
|
||
),
|
||
revoke: () => {
|
||
$("#dialog").close();
|
||
toast(t("Другие демо-сессии завершены", "Other demo sessions revoked"));
|
||
},
|
||
recover: () => {
|
||
openDialog(
|
||
t("Восстановить доступ", "Reset password"),
|
||
`<p>${t("Демо-форма. Письмо не отправляется.", "Demo form. No email is sent.")}</p><form id="recover-form"><label class="field">Email<input type="email" name="email" required></label><button class="primary" type="submit">${t("Продолжить", "Continue")}</button></form>`,
|
||
);
|
||
$("#recover-form").onsubmit = (e) => {
|
||
e.preventDefault();
|
||
$("#dialog").close();
|
||
toast(
|
||
t("Демо-запрос восстановления принят", "Demo reset request accepted"),
|
||
);
|
||
};
|
||
},
|
||
sso: () => {
|
||
openDialog(
|
||
t("Корпоративный вход", "Company sign-in"),
|
||
`<p>${t("Проверка демонстрационного домена. OAuth-провайдер не подключён.", "Demo domain validation. No OAuth provider is connected.")}</p><form id="sso-form"><label class="field">${t("Рабочий email", "Work email")}<input type="email" required></label><button class="primary" type="submit">${t("Войти в демо", "Enter demo")}</button></form>`,
|
||
);
|
||
$("#sso-form").onsubmit = (e) => {
|
||
e.preventDefault();
|
||
$("#dialog").close();
|
||
page = "dashboard";
|
||
render();
|
||
toast(t("Демо SSO-вход выполнен", "Demo SSO sign-in complete"));
|
||
};
|
||
},
|
||
delete: () =>
|
||
openDialog(
|
||
t("Удалить тестовый проект?", "Delete demo project?"),
|
||
`<p>${t("Демонстрация подтверждения опасного действия. Данные пространства сохранятся.", "Demonstration of destructive action confirmation. Workspace data is retained.")}</p><div class="form-footer"><button data-action="close">${t("Отмена", "Cancel")}</button><button class="danger" data-action="confirm-delete">${t("Удалить", "Delete")}</button></div>`,
|
||
),
|
||
"confirm-delete": () => {
|
||
$("#dialog").close();
|
||
toast(t("Тестовый проект удалён", "Demo project deleted"));
|
||
},
|
||
rename: () => {
|
||
openDialog(
|
||
t("Переименовать проект", "Rename project"),
|
||
`<form id="rename-form"><label class="field">${t("Название", "Name")}<input name="name" required value="${escape(settings.name)}"></label><button class="primary" type="submit">${t("Сохранить", "Save")}</button></form>`,
|
||
);
|
||
$("#rename-form").onsubmit = (e) => {
|
||
e.preventDefault();
|
||
settings.name = new FormData(e.target).get("name").trim();
|
||
persist();
|
||
$("#dialog").close();
|
||
toast(t("Название сохранено: ", "Name saved: ") + settings.name);
|
||
};
|
||
},
|
||
"create-key": () => {
|
||
const key = "an_demo_" + crypto.randomUUID().replaceAll("-", "");
|
||
openDialog(
|
||
t("Тестовый API-ключ", "Demo API key"),
|
||
`<p>${t("Ключ не даёт доступ к реальным сервисам.", "This key does not access real services.")}</p><input aria-label="API key" readonly value="${key}" style="width:100%"><button id="copy-key" style="margin-top:15px">${t("Копировать", "Copy")}</button>`,
|
||
);
|
||
$("#copy-key").onclick = () => copy(key);
|
||
},
|
||
retry: () => {
|
||
const box = button.closest(".error-state");
|
||
box.innerHTML = `<span class="status">${t("Журнал загружен · 3 события", "Log loaded · 3 events")}</span>`;
|
||
box.style.borderColor = "var(--color-border)";
|
||
},
|
||
"copy-id": () => {
|
||
copy("ws_anidev_prod");
|
||
$(".context-menu")?.remove();
|
||
},
|
||
"copy-json": () => copy(JSON.stringify(tokens, null, 2)),
|
||
"copy-css": () => copy(":root {\n" + cssVars(tokens) + "\n}"),
|
||
};
|
||
if (actions[action]) await actions[action]();
|
||
document.querySelectorAll("details[open]").forEach((el) => {
|
||
if (!el.contains(e.target) || action) el.open = false;
|
||
});
|
||
});
|
||
document.addEventListener("keydown", (e) => {
|
||
if (e.key === "Escape" && $("[popover=auto]:popover-open")) {
|
||
e.preventDefault();
|
||
$("[popover=auto]:popover-open").hidePopover();
|
||
$(".dock-account")?.focus();
|
||
return;
|
||
}
|
||
const groupTarget = e.target.closest?.("[data-nav-group=administration]");
|
||
if (
|
||
groupTarget &&
|
||
document.body.classList.contains("dock-open") &&
|
||
!e.ctrlKey &&
|
||
!e.altKey &&
|
||
!e.metaKey
|
||
) {
|
||
if (e.key === "ArrowRight" && e.target.closest(".nav-group-toggle")) {
|
||
e.preventDefault();
|
||
setAdministration(true, true);
|
||
return;
|
||
}
|
||
if (e.key === "ArrowLeft" || (e.key === "Escape" && administrationOpen)) {
|
||
e.preventDefault();
|
||
setAdministration(false);
|
||
$(".nav-group-toggle").focus();
|
||
return;
|
||
}
|
||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||
e.preventDefault();
|
||
const items = [
|
||
groupTarget.querySelector(".nav-group-toggle"),
|
||
...(administrationOpen
|
||
? groupTarget.querySelectorAll("[data-page]")
|
||
: []),
|
||
];
|
||
const at = items.indexOf(e.target),
|
||
next =
|
||
(at + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length;
|
||
items[next].focus();
|
||
return;
|
||
}
|
||
}
|
||
if (document.body.classList.contains("dock-open")) {
|
||
if (e.key === "Escape") {
|
||
e.preventDefault();
|
||
setDockOpen(false);
|
||
return;
|
||
}
|
||
if (e.key === "Tab") {
|
||
const items = [...$(".navigation").querySelectorAll("button")].filter(
|
||
(el) => el.getClientRects().length && !el.closest("[popover], [inert]"),
|
||
);
|
||
const first = items[0],
|
||
last = items.at(-1);
|
||
if (e.shiftKey && document.activeElement === first) {
|
||
e.preventDefault();
|
||
last.focus();
|
||
} else if (!e.shiftKey && document.activeElement === last) {
|
||
e.preventDefault();
|
||
first.focus();
|
||
}
|
||
}
|
||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k")
|
||
setDockOpen(false, false);
|
||
}
|
||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
|
||
e.preventDefault();
|
||
command();
|
||
}
|
||
if (e.key === "Escape") {
|
||
if ($(".context-menu")) {
|
||
$(".context-menu").remove();
|
||
$(".context-target")?.focus();
|
||
}
|
||
document
|
||
.querySelectorAll("details[open]")
|
||
.forEach((el) => (el.open = false));
|
||
}
|
||
const tabs = [...document.querySelectorAll("[role=tab]")];
|
||
if (
|
||
tabs.includes(e.target) &&
|
||
["ArrowLeft", "ArrowRight", "Home", "End"].includes(e.key)
|
||
) {
|
||
e.preventDefault();
|
||
const index = tabs.indexOf(e.target);
|
||
const next =
|
||
e.key === "Home"
|
||
? 0
|
||
: e.key === "End"
|
||
? tabs.length - 1
|
||
: (index + (e.key === "ArrowRight" ? 1 : -1) + tabs.length) %
|
||
tabs.length;
|
||
tab = tabs[next].dataset.tab;
|
||
render();
|
||
$("#tab-" + tab).focus();
|
||
}
|
||
if (
|
||
$("#dialog").open &&
|
||
$(".command-list") &&
|
||
["ArrowDown", "ArrowUp", "Enter"].includes(e.key)
|
||
) {
|
||
const buttons = [
|
||
...document.querySelectorAll(".command-list button:not([hidden])"),
|
||
];
|
||
if (!buttons.length) return;
|
||
const index = buttons.indexOf(document.activeElement);
|
||
if (e.key === "Enter" && document.activeElement === $("#command-search")) {
|
||
e.preventDefault();
|
||
buttons[0].click();
|
||
} else if (e.key !== "Enter") {
|
||
e.preventDefault();
|
||
buttons[
|
||
(index + (e.key === "ArrowDown" ? 1 : -1) + buttons.length) %
|
||
buttons.length
|
||
].focus();
|
||
}
|
||
}
|
||
const menu = $(".context-menu");
|
||
if (menu && ["ArrowDown", "ArrowUp"].includes(e.key)) {
|
||
e.preventDefault();
|
||
const buttons = [...menu.querySelectorAll("button")];
|
||
buttons[
|
||
(buttons.indexOf(document.activeElement) +
|
||
(e.key === "ArrowDown" ? 1 : -1) +
|
||
buttons.length) %
|
||
buttons.length
|
||
].focus();
|
||
}
|
||
});
|
||
$("#dialog").addEventListener("close", () => {
|
||
if (dialogInitiator?.isConnected) dialogInitiator.focus();
|
||
});
|
||
$("#dialog").addEventListener("click", (e) => {
|
||
if (e.target === $("#dialog")) {
|
||
const r = e.target.getBoundingClientRect();
|
||
if (
|
||
e.clientX < r.left ||
|
||
e.clientX > r.right ||
|
||
e.clientY < r.top ||
|
||
e.clientY > r.bottom
|
||
)
|
||
e.target.close();
|
||
}
|
||
});
|
||
// Refresh shared fixture edits in both comparison panes, preserving each pane's layout.
|
||
addEventListener("storage", (e) => {
|
||
if (e.key === "anidev.users") {
|
||
try {
|
||
users = JSON.parse(e.newValue);
|
||
if (page === "users") refreshUsers();
|
||
} catch {}
|
||
}
|
||
if (e.key === "anidev.settings") {
|
||
try {
|
||
settings = JSON.parse(e.newValue);
|
||
if (page === "settings") render();
|
||
} catch {}
|
||
}
|
||
});
|
||
function navigate(next) {
|
||
page = next;
|
||
if (["ssh", "logs"].includes(page)) administrationOpen = true;
|
||
$("#dialog").close();
|
||
render();
|
||
$("#content")?.focus();
|
||
}
|
||
const accountUI = createAccountUI({
|
||
adapter: identityAdapter,
|
||
t,
|
||
escape,
|
||
heading,
|
||
icon,
|
||
openDialog,
|
||
toast,
|
||
render,
|
||
navigate,
|
||
setTheme: (mode) => {
|
||
theme = mode;
|
||
tokens = tokensFor(concept.id, theme, rawAccent || undefined, density);
|
||
document.documentElement.style.cssText = cssVars(tokens);
|
||
document.body.dataset.theme = theme;
|
||
render();
|
||
savePreferences();
|
||
},
|
||
});
|
||
if (identityStates.includes(params.get("identityState")))
|
||
identityAdapter.setScenario(params.get("identityState"));
|
||
addEventListener("storage", (e) => {
|
||
if (e.key === "anidev.identity.demo.v2") {
|
||
$("#dialog").close();
|
||
render();
|
||
}
|
||
});
|
||
addEventListener("popstate", () => {
|
||
const route = new URL(location.href);
|
||
page = Object.keys(pageNames).includes(route.searchParams.get("page"))
|
||
? route.searchParams.get("page")
|
||
: "dashboard";
|
||
if (["ssh", "logs"].includes(page)) administrationOpen = true;
|
||
theme = route.searchParams.get("theme") === "dark" ? "dark" : "light";
|
||
tokens = tokensFor("dock", theme, rawAccent || undefined, density);
|
||
document.documentElement.style.cssText = cssVars(tokens);
|
||
document.body.dataset.theme = theme;
|
||
initialRender = true;
|
||
$("#dialog").close();
|
||
render();
|
||
});
|
||
render();
|