Files

1090 lines
59 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { concepts, tokensFor, cssVars } from "../concepts/registry.js";
import {
createDemoIdentityAdapter,
identityStates,
} from "../patterns/demo-identity.js";
import {
createAccountUI,
accountPageIds,
} from "../components/account-pages.js";
const identityAdapter = createDemoIdentityAdapter();
const params = new URLSearchParams(location.search),
concept = concepts.find((c) => c.id === params.get("concept")) || concepts[0];
let theme = params.get("theme") === "dark" ? "dark" : "light",
density = params.get("density") || "normal",
locale = params.get("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) =>
({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[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",
...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 = {
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 icons = {
profile:
'<circle cx="12" cy="7" r="4"/><path d="M4 22v-3a8 8 0 0 1 16 0v3"/>',
security:
'<path d="m12 2 8 4v6c0 5-8 10-8 10S4 17 4 12V6Z"/><path d="m8 12 3 3 5-6"/>',
sessions:
'<rect x="2" y="3" width="16" height="12" rx="2"/><path d="M6 20h8M10 15v5"/><rect x="16" y="9" width="6" height="12" rx="1"/>',
applications:
'<rect x="3" y="3" width="7" height="7" rx="2"/><rect x="14" y="3" width="7" height="7" rx="2"/><rect x="3" y="14" width="7" height="7" rx="2"/><rect x="14" y="14" width="7" height="7" rx="2"/>',
appearance: '<circle cx="12" cy="12" r="9"/><path d="M12 3v18"/>',
identity:
'<rect x="3" y="4" width="18" height="16" rx="3"/><circle cx="8" cy="10" r="2"/><path d="M5 16a3 3 0 0 1 6 0M14 9h4M14 13h4"/>',
dashboard:
'<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>',
users:
'<circle cx="9" cy="8" r="3"/><path d="M3 21v-3a6 6 0 0 1 12 0v3M16 5a3 3 0 0 1 0 6M18 15a5 5 0 0 1 3 5"/>',
settings:
'<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="3"/><circle cx="16" cy="17" r="3"/>',
components:
'<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 10h18M10 10v11"/>',
tokens: '<path d="m8 4-6 8 6 8M16 4l6 8-6 8M14 2l-4 20"/>',
};
const icon = (id) =>
`<svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">${icons[id] || icons.dashboard}</svg>`;
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"));
}
}
let toastTimer;
function toast(message) {
$("#toast").textContent = message;
$("#toast").style.display = "block";
clearTimeout(toastTimer);
toastTimer = setTimeout(() => ($("#toast").style.display = "none"), 3500);
}
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", "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("users")}<span>${t("Аккаунт", "Account")}</span></button>
<button data-page="security">${icon("settings")}<span>${t("Настройки", "Settings")}</span></button>
<button data-page="applications">${icon("applications")}<span>${t("Приложения", "Applications")}</span></button>
<button data-action="shares">${icon("components")}<span>${t("Мои общие ресурсы", "My shares")}</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("users")}<span>${t("Сменить аккаунт", "Switch account")}</span></button>
<button class="account-separator" data-identity="logout"><svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M9 4H4v16h5M13 7l5 5-5 5M8 12h11"/></svg><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>`;
}
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">${concept.id === "dock" ? dockBrand : wordmark}<div class="workspace-label">ANIDEV / PRODUCTION</div><nav aria-label="${t("Основная навигация", "Main navigation")}" class="nav-links">${navigationPages()
.map(
(p) =>
`<button data-page="${p}" ${page === p ? 'aria-current="page"' : ""} title="${pageNames[p]}" aria-label="${pageNames[p]}">${icon(p)}<span>${pageNames[p]}</span></button>`,
)
.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>${concept.id === "dock" ? dockAccount() : ""}</aside>`;
}
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">${t("Найти команду", "Find a command")} <kbd>⌘ K</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 (concept.id !== "dock" || !$(".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]:popover-open")) {
dockHoverOpened = false;
setDockOpen(false, false);
}
}, 180);
});
}
function setDockOpen(open, returnFocus = true) {
if (!open) {
dockHoverOpened = false;
clearTimeout(dockCloseTimer);
}
const nav = $(".navigation");
if (!nav || concept.id !== "dock") 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;
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 render() {
dockHoverOpened = false;
clearTimeout(dockCloseTimer);
document.body.classList.remove("dock-open");
document.title = `Anidev / ${concept.name} / ${pageNames[page]}`;
const content = accountPageIds.includes(page)
? accountUI.renderPage(page)
: identityAdapter.snapshot().status !== "authenticated" &&
!["components", "tokens", "auth"].includes(page)
? accountUI.gate()
: ["dashboard", "users", "settings"].includes(page) &&
!currentIdentity()?.roles.some((r) =>
["Master Admin", "SSO Admin"].includes(r),
)
? accountUI.gate("access_denied")
: {
dashboard,
users: userScreen,
settings: settingsScreen,
components: componentScreen,
tokens: tokenScreen,
}[page]?.() || "";
$("#app").innerHTML =
page === "auth"
? auth()
: `<div class="shell">${nav()}${concept.id === "dock" ? `<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 (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="img" aria-label="${t("Задержка p95: от 30 до 43 мс. Текущая 34 мс.", "p95 latency: 30 to 43 ms. Current 34 ms.")}"><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><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 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("Единые состояния. Шесть способов выражения.", "Shared states. Six ways of expressing them."), `<button data-action="command">${t("Команды", "Commands")} ⌘K</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><select aria-label="${t("Окружение", "Environment")}"><option>Production</option><option>Staging</option></select><input aria-label="Disabled input" disabled value="Read only"></section>
<section class="specimen"><h2>Selection controls</h2><div class="form-row"><input id="check-demo" type="checkbox" checked><label for="check-demo">${t("Email-уведомления", "Email notifications")}</label></div><fieldset style="border:0;padding:0"><legend>${t("Период хранения", "Retention period")}</legend><div class="component-row"><label><input type="radio" name="retention" value="30" checked> 30 ${t("дней", "days")}</label><label><input type="radio" name="retention" value="90"> 90 ${t("дней", "days")}</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"><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"><h2>Status indicators</h2><div class="component-row"><span class="status">${t("Работает", "Operational")}</span><span class="status warn">${t("Недоступен", "Unavailable")}</span><span class="muted">${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>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="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. Акцент применяется к каждой концепции отдельно.", "Gallery export includes both themes, JSON and CSS. Each concept retains its own accent.")}</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")}">×</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) {
page = pageButton.dataset.page;
$("#dialog").close();
render();
$("#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]:popover-open")
.forEach((el) => el.hidePopover());
const actions = {
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"));
},
"dock-close": () => setDockOpen(false),
"mobile-menu": () => {
if (concept.id === "dock") {
setDockOpen(!document.body.classList.contains("dock-open"));
return;
}
const nav = $(".navigation");
nav.classList.toggle("open");
button.setAttribute("aria-expanded", nav.classList.contains("open"));
},
close: () => $("#dialog").close(),
invite,
command,
activity: () => $("#activity").scrollIntoView({ behavior: "smooth" }),
profile: () => navigate("profile"),
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]:popover-open")) {
e.preventDefault();
$("[popover]:popover-open").hidePopover();
$(".dock-account")?.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]"),
);
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;
$("#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();
if (parent !== window)
parent.postMessage({ type: "anidev-theme", theme }, location.origin);
},
});
if (identityStates.includes(params.get("identityState")))
identityAdapter.setScenario(params.get("identityState"));
addEventListener("storage", (e) => {
if (e.key === "anidev.identity.demo.v2") {
$("#dialog").close();
render();
}
});
render();