import { searchSelectMarkup, mountSearchSelect, environmentOptions, } from "../components/search-select.js"; import { createNotifier } from "../components/toast.js"; import { mountCopyField } from "../components/copy-field.js"; import { breadcrumbsMarkup, mountBreadcrumbs, } from "../components/breadcrumbs.js"; import { contentDemoPages, contentDemoMarkup, mountContentDemo, contentBreadcrumbs, contentHref, createDemoDocuments, } from "../components/content-demo.js"; import { mountMobileDock, createMobileHistory, mobileDockQuery, } from "../components/mobile-dock.js"; import { themeControlMarkup, mountThemeControl, } from "../components/theme-control.js"; import { accountSubmenuMarkup, mountAccountSubmenu, } from "../components/account-submenu.js"; import { errorPageMarkup, errorStatuses, mountErrorPage, } from "../components/error-page.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(); const mobileHistory = createMobileHistory(); const documentFiles = createDemoDocuments(); let documentOwner = null; 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", "errors", "documents", "servers", "server", "statistics", ...accountPageIds, ].includes(params.get("page")) ? params.get("page") : "dashboard"; let panel = params.get("panel") === "user" || accountPageIds.includes(page) ? "user" : "admin"; let query = "", role = "all", userPage = 1, sortAsc = true, sortKey = "name", selected = new Set(), tab = "general", chartRange = "24h"; const pageNames = { documents: t("Документы", "Documents"), servers: t("Серверы", "Servers"), server: t("Сервер", "Server"), statistics: t("Статистика сервера", "Server statistics"), errors: t("Страницы ошибок", "Error pages"), 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", errors: "warning", documents: "document", statistics: "server", servers: "server", server: "server", }[id] || id, { className: "nav-icon", }, ); const wordmark = '
a/anidev
'; 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 panel === "user" ? ["dashboard", "documents"] : [ "dashboard", "users", "settings", "documents", "administration", "components", "tokens", ]; } function dockAccount() { return `
${accountSubmenuMarkup({ id: "account-sections", t, pageAttribute: "data-page", items: [ { id: "profile", label: t("Управление", "Management"), icon: "profile" }, { id: "security", label: t("Безопасность", "Security"), icon: "security", }, { id: "sessions", label: t("Устройства и сеансы", "Devices and sessions"), icon: "sessions", }, { id: "applications", label: t("Приложения", "Applications"), icon: "applications", }, ], })} ${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)) ? `` : ""} ${themeControlMarkup({ theme, t })}
`; } let administrationOpen = [ "ssh", "logs", "statistics", "servers", "server", ].includes(page); function navPage(id, label = pageNames[id]) { return ``; } function administrationNav() { const active = ["ssh", "logs", "statistics", "servers", "server"].includes( page, ); return ``; } 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 = ``; return ``; } const commandShortcut = /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘ K" : "Ctrl K"; function header() { const route = new URL(location.href), personal = panel === "user", root = { label: "anidev", href: contentHref({ page: "dashboard", panel: personal ? "user" : "admin", }), }; const items = contentDemoPages.includes(page) ? contentBreadcrumbs(page, { server: route.searchParams.get("server") || "edge-01", path: route.searchParams.get("path") || "/", t, }) : [ root, ...(page !== "dashboard" && page !== "profile" ? [ { label: personal ? t("Аккаунт", "Account") : t("Панель управления", "Control panel"), href: contentHref({ page: personal ? "profile" : "dashboard", panel, }), }, ] : []), { label: pageNames[page] }, ]; const breadcrumb = breadcrumbsMarkup({ items, t }); return `
${breadcrumb}
`; } const heading = (title, desc, actions = "") => `
ANIDEV://PRODUCTION/${page.toUpperCase()}

${title}

${desc}

${actions}
`; let dockHoverOpened = false; let dockCloseTimer; function bindDockHover() { if (!$(".dock-toggle")) return; const nav = $(".navigation"); nav.addEventListener("pointerenter", (e) => { if ( matchMedia(mobileDockQuery).matches || 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"); if (open) document .querySelectorAll("[data-search-popup]:popover-open") .forEach((popup) => popup.hidePopover()); $(".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 selectCleanups = []; let workspaceCleanup = () => {}, workspaceRender = 0; let initialRender = true; function render({ preserveDock = false } = {}) { workspaceCleanup(); selectCleanups.forEach((cleanup) => cleanup()); selectCleanups = []; workspaceCleanup = () => {}; const workspaceVersion = ++workspaceRender; const signedIn = identityAdapter.snapshot().status === "authenticated"; const owner = signedIn ? currentIdentity()?.sub : null; if (owner !== documentOwner) { documentFiles.clear(); for (const [path, file] of createDemoDocuments()) documentFiles.set(path, file); documentOwner = owner; } if ( accountPageIds.includes(page) || !currentIdentity()?.roles.some((role) => ["Master Admin", "SSO Admin"].includes(role), ) ) panel = "user"; document.body.dataset.panel = panel; document.body.dataset.session = signedIn ? "authenticated" : "guest"; const dockWasOpen = preserveDock && document.body.classList.contains("dock-open") && page !== "auth" && signedIn; const route = new URL(location.href); route.searchParams.delete("concept"); route.searchParams.set("page", page); route.searchParams.set("panel", panel); 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", "errors"].includes(page) ? accountUI.gate() : [ "users", "settings", "ssh", "logs", "statistics", "servers", "server", ].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: panel === "admin" ? dashboard : userOverview, users: userScreen, settings: settingsScreen, documents: () => contentDemoMarkup("documents", { heading, t }), servers: () => contentDemoMarkup("servers", { heading, t }), server: () => contentDemoMarkup("server", { heading, t, server: new URL(location.href).searchParams.get("server") || "edge-01", }), statistics: () => contentDemoMarkup("statistics", { heading, t, server: new URL(location.href).searchParams.get("server") || "edge-01", }), components: componentScreen, errors: errorScreen, tokens: tokenScreen, }[page]?.() || ""; $("#app").innerHTML = page === "auth" ? auth() : !signedIn ? `
${page === "identity" ? accountUI.renderPage("identity") : accountUI.gate()}
` : `
${nav()}
${header()}
${content}
`; bindForms(); accountUI.bind(page); bindDockHover(); if (dockWasOpen) setDockOpen(true, false); bindCharts(); if ($(".breadcrumbs")) selectCleanups.push( mountBreadcrumbs($(".breadcrumbs"), { onNavigate: visitContentURL }), ); if (contentDemoPages.includes(page) && $("[data-content-demo]")) workspaceCleanup = mountContentDemo($("[data-content-demo]"), { page, server: new URL(location.href).searchParams.get("server") || "edge-01", path: new URL(location.href).searchParams.get("path") || "/", files: documentFiles, onNavigate: visitContentURL, notify: toast, t, }); if ($(".navigation")) { const mobile = mountMobileDock($(".navigation"), { trigger: $(".dock-brand"), history: mobileHistory, t, getPage: (id) => { const allowed = [ "dashboard", "documents", ...accountPageIds, "components", "tokens", "errors", ...(panel === "admin" ? [ "users", "settings", "ssh", "logs", "statistics", "servers", "server", ] : []), ]; return allowed.includes(id) && pageNames[id] ? { id, label: pageNames[id], icon: { ssh: "terminal", logs: "document", errors: "warning", documents: "document", statistics: "server", servers: "server", server: "server", }[id] || id, } : null; }, onNavigate: navigate, onCloseMenu: () => setDockOpen(false, false), }); mobile.update(page, `${panel}:${currentIdentity()?.sub || "account"}`); selectCleanups.push(() => mobile.dispose()); } else { mobileHistory.current = null; mobileHistory.previous = null; mobileHistory.context = null; } if ($("#account-menu")) { const submenu = mountAccountSubmenu($("#account-menu")); selectCleanups.push(() => submenu.dispose()); const themeControl = mountThemeControl($("#account-menu"), { theme, onChange: (mode) => { theme = mode; tokens = tokensFor(concept.id, theme, rawAccent || undefined, density); document.documentElement.style.cssText = cssVars(tokens); document.body.dataset.theme = theme; const url = new URL(location.href); url.searchParams.set("theme", theme); history.replaceState({}, "", url); savePreferences(); document .querySelectorAll('[data-identity="theme"]') .forEach((button) => button.setAttribute( "aria-pressed", String(button.dataset.theme === theme), ), ); }, }); selectCleanups.push(() => themeControl.dispose()); $("#account-menu").addEventListener("keydown", (event) => { if (event.key === "Tab") { $("#account-menu").hidePopover(); $(".dock-account").focus(); } }); } if (page === "errors" && $("[data-error-status]")) { selectCleanups.push( mountErrorPage($("[data-error-status]"), { onRetry: () => toast( t( "Это пример страницы ошибки. Реальный запрос не выполняется.", "This is an error page preview. No request is sent.", ), ), onHome: () => { page = "components"; render(); }, onAccount: () => { page = "profile"; render(); }, }), ); $("#error-preview-status").addEventListener("change", (event) => { const url = new URL(location.href); url.searchParams.set("status", event.target.value); history.replaceState({}, "", url); render(); }); } document .querySelectorAll(".copy-input") .forEach((root) => selectCleanups.push(mountCopyField(root, { notify: toast, t })), ); document .querySelectorAll("[data-search-select]") .forEach((root) => selectCleanups.push( mountSearchSelect(root, { options: environmentOptions, t }), ), ); if ($("#log-workspace")) workspaceCleanup = mountLogs($("#log-workspace"), { t, escape, notify: toast, }); const sshRoot = $("#ssh-workspace"); if (sshRoot) mountSsh(sshRoot, { t, notify: toast }) .then((cleanup) => { if (workspaceVersion === workspaceRender) workspaceCleanup = cleanup; else cleanup(); }) .catch(() => { if (sshRoot.isConnected) sshRoot.querySelector("[data-terminal]").innerHTML = `

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

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

`; }); if (page === "users" && $("#user-search")) bindUsers(); } function chart() { 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 `
${chartRange === "24h" ? "00:00" : "21.11"}${chartRange === "24h" ? "06:00" : "23.11"}${chartRange === "24h" ? "12:00" : "25.11"}${chartRange === "24h" ? "18:00" : "27.11"}

${t("p95 · миллисекунды · ниже — лучше · тестовая выборка", "p95 · milliseconds · lower is better · sample dataset")}

${t("Числовые данные", "Numerical data")}
${values.map((v, i) => ``).join("")}
${t("Время UTC", "Time UTC")}p95 / ms
${chartRange === "24h" ? String(i).padStart(2, "0") + ":00" : 21 + i + ".11"}${v}
`; } 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"), ``)}
${t("Все системы работают штатно", "All systems operational")}${t("Проверено в 09:42 UTC · демонстрация", "Checked at 09:42 UTC · demo")}
${t("Доступность за 30 дней", "30-day availability")}
${number(99.98, 2)}%
${t("SLO 99.9% · в пределах цели", "SLO 99.9% · within target")}
${t("Активные сессии", "Active sessions")}
${number(1284)}
${t("SSO · за последние 15 минут", "SSO · last 15 minutes")}
${t("Задержка API, p95", "API latency, p95")}
34 ms
${t("Порог оповещения: 100 мс", "Alert threshold: 100 ms")}

${t("Время ответа API", "API response time")}

${chart()}

${t("Сервисы", "Services")}

3 / 3 ONLINE
${[ ["Identity", "18 ms"], ["License API", "34 ms"], ["Edge Gateway", "12 ms"], ] .map( ([name, time]) => `
${name}${time}${t("Работает", "Operational")}
`, ) .join( "", )}

eu-central-1 · ${t("проверка каждую минуту", "checked every minute")}

${t("Последние события", "Recent activity")}

UTC
${[ [ "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]) => `
${event}${who}
`, ) .join( "", )}

${t("Демонстрационные данные. Подключение к реальной инфраструктуре отсутствует.", "Demonstration data. No connection to live infrastructure.")}

`; } 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."), ``)}
${userResults()}
`; } 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 ? `
${t("Выбрано", "Selected")}: ${selected.size}
` : ""} ${ !filtered.length ? `

${t("Пользователи не найдены", "No users found")}

${t("Попробуйте другое имя или сбросьте фильтр.", "Try another name or reset the filter.")}

` : `
${visible .map( (u) => ``, ) .join("")}
${t("Участники Anidev Production", "Anidev Production members")}
selected.has(u.id)) ? "checked" : ""}>${t("Статус", "Status")}${t("Был в сети", "Last seen")}${t("Действия", "Actions")}
${escape( u.name .split(" ") .map((n) => n[0]) .join(""), )}
${escape(u.name)}${escape(u.email)}
${roleName(u.role)}${statusName(u.status)}${u.last}
` } `; } 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."))}
${["general", "security", "notifications"].map((v, i) => ``).join("")}

${tab === "general" ? t("Ваше пространство", "Your workspace") : tab === "security" ? t("Контроль доступа", "Access control") : t("Оповещения", "Notifications")}

${tab === "general" ? t("Эти данные видны участникам организации.", "These details are visible to organization members.") : t("Изменения применяются к этому демо.", "Changes apply to this demo.")}

${tab === "general" ? `` : tab === "security" ? `
` : `
`}
`; } function auth() { return `
${wordmark}
${t("Ваша инфраструктура.
Под вашим контролем.", "Your infrastructure.
Under your control.")}
ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}

${t("Вход в Anidev", "Sign in to Anidev")}

${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}

${t("или корпоративный аккаунт", "or your company account")}
© Anidev 2026
`; } function visitContentURL(url) { history.pushState({}, "", url); dispatchEvent(new PopStateEvent("popstate")); $("#content")?.focus({ preventScroll: true }); } function userOverview() { return ( heading( t("Обзор", "Overview"), t( "Личная панель Anidev. Управление аккаунтом доступно в нижней строке Dock.", "Your Anidev workspace. Account management is available at the bottom of the Dock.", ), ) + `

${t("Сеанс активен", "Session active")}

${escape(accountName())}

${t("Это демонстрация пользовательской панели. Административные разделы находятся в отдельном Dock.", "This is a user-panel preview. Administrative sections use a separate Dock.")}

` ); } function errorScreen() { const requested = new URL(location.href).searchParams.get("status") || "404"; const status = errorStatuses.find((value) => String(value) === requested) ?? 500; return `
${errorPageMarkup({ status, t, reason: t("Повторное нарушение правил сервиса.\nЭто демонстрационный пример причины блокировки.", "Repeated violations of service rules.\nThis is a sample suspension reason."), requestId: "demo-7f2c" })}`; } function componentScreen() { return `${heading(t("Библиотека компонентов", "Component library"), t("Единые компоненты и состояния Dock.", "Shared Dock components and states."), ``)}

${t("Кнопки", "Buttons")}

Hover · active · focus · disabled · loading

${t("Поля и списки", "Inputs & selects")}

${searchSelectMarkup({ id: "environment-search", name: "searchEnvironment", label: t("Окружение — с поиском", "Environment — searchable"), options: environmentOptions, value: "production", t })}

${t("Выбор и переключатели", "Selection controls")}

${t("Период хранения", "Retention period")}

${t("Группы чекбоксов", "Checkbox groups")}

${[ "horizontal", "vertical", ] .map( (orientation) => `
${orientation === "horizontal" ? t("Горизонтально", "Horizontal") : t("Вертикально", "Vertical")}
${[ ["email", "Email"], ["push", "Push"], ["sms", "SMS"], ] .map( ([value, label]) => ``, ) .join("")}
`, ) .join("")}

${t("Меню и обратная связь", "Overlays & feedback")}

${t("Скопировать идентификатор", "Copy identifier")}
${t("Действия проекта", "Project actions")}
${t("Контекстное меню: правая кнопка, Shift+F10 или Enter", "Context menu: right click, Shift+F10 or Enter")}

${t("Пустое состояние", "Empty state")}

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

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

${t("Ошибка и загрузка", "Error & skeleton")}

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

${t("Уведомления", "Notifications")}

${[ ["success", t("Успех", "Success")], ["info", t("Информация", "Information")], ["warning", t("Предупреждение", "Warning")], ["error", t("Ошибка", "Error")], ] .map( ([type, label]) => ``, ) .join("")}

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

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

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

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

${t("Терминал, логи, статистика сервера и документы.", "Terminal, logs, server statistics and documents.")}

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

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

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

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

${t("График", "Chart")}

${chart()}

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

`; } function tokenScreen() { return `${heading(t("Дизайн-токены", "Design tokens"), `${concept.name} / ${theme} / ${density}`, ``)}
${Object.entries( tokens, ) .map( ([key, value]) => `
${key}${value.startsWith("#") ? `` : ""}${escape(value)}
`, ) .join( "", )}
:root {\n${cssVars(tokens)}\n}

${t("Экспорт включает обе темы, JSON и CSS. Используется утверждённая палитра Dock.", "Export includes both themes, JSON and CSS. Uses the approved Dock palette.")}

`; } let dialogInitiator = null; function openDialog(title, body, cls = "") { if (document.body.classList.contains("dock-open")) setDockOpen(false, false); document .querySelectorAll("[data-search-popup]:popover-open") .forEach((popup) => popup.hidePopover()); const d = $("#dialog"); if (d.open) d.close(); dialogInitiator = document.activeElement; d.className = cls; d.innerHTML = `

${title}

${body}`; d.showModal(); return d; } function invite() { openDialog( t("Пригласить участника", "Invite a member"), `

${t("Приглашение будет добавлено в демонстрационный список. Письмо не отправляется.", "The invitation is added to the demo list. No email is sent.")}

`, ); $("#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), `

${escape(user.email)}

${accountUI.roleMarkup(id)}${accountUI.grantsMarkup(id)}
`, ); $("#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"), `
${Object.entries( pageNames, ) .map(([id, name]) => ``) .join( "", )}
${t("↑ ↓ — выбор · Enter — открыть · Esc — закрыть", "↑ ↓ to navigate · Enter to open · Esc to close")}`, ); $("#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"), ``, ); $("#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 = ``; 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 panelChanged = pageButton.dataset.panel && panel !== pageButton.dataset.panel; if (pageButton.dataset.panel) panel = pageButton.dataset.panel; const fromDock = Boolean(pageButton.closest(".navigation")); if (fromDock && page === pageButton.dataset.page && !panelChanged) { if (pageButton.closest(".account-menu")) { $("#account-menu").hidePopover(); $(".dock-account").focus({ preventScroll: true }); } return; } page = pageButton.dataset.page; if (["ssh", "logs", "statistics", "servers", "server"].includes(page)) administrationOpen = true; $("#dialog").close(); render({ preserveDock: fromDock && !matchMedia(mobileDockQuery).matches }); 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"), `

${t("Общих ресурсов пока нет.", "No shared resources yet.")}

`, "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?"), `

${t("Количество выбранных участников", "Selected members")}: ${selected.size}

`, ); }, "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"), `

ANIDEV / PRODUCTION

${t("Регион", "Region")}
eu-central-1
${t("Владелец", "Owner")}
Anna Volkova
${t("Создано", "Created")}
2026-01-14
`, "drawer", ), sessions: () => openDialog( t("Активные сессии", "Active sessions"), `

Windows · Edge · Moscow

${t("Текущая сессия · 09:42 UTC", "Current session · 09:42 UTC")}

`, ), revoke: () => { $("#dialog").close(); toast(t("Другие демо-сессии завершены", "Other demo sessions revoked")); }, recover: () => { openDialog( t("Восстановить доступ", "Reset password"), `

${t("Демо-форма. Письмо не отправляется.", "Demo form. No email is sent.")}

`, ); $("#recover-form").onsubmit = (e) => { e.preventDefault(); $("#dialog").close(); toast( t("Демо-запрос восстановления принят", "Demo reset request accepted"), ); }; }, sso: () => { openDialog( t("Корпоративный вход", "Company sign-in"), `

${t("Проверка демонстрационного домена. OAuth-провайдер не подключён.", "Demo domain validation. No OAuth provider is connected.")}

`, ); $("#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?"), `

${t("Демонстрация подтверждения опасного действия. Данные пространства сохранятся.", "Demonstration of destructive action confirmation. Workspace data is retained.")}

`, ), "confirm-delete": () => { $("#dialog").close(); toast(t("Тестовый проект удалён", "Demo project deleted")); }, rename: () => { openDialog( t("Переименовать проект", "Rename project"), `
`, ); $("#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"), `

${t("Ключ не даёт доступ к реальным сервисам.", "This key does not access real services.")}

`, ); $("#copy-key").onclick = () => copy(key); }, retry: () => { const box = button.closest(".error-state"); box.innerHTML = `${t("Журнал загружен · 3 события", "Log loaded · 3 events")}`; 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 ( identityAdapter.snapshot().status !== "authenticated" && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k" ) { e.preventDefault(); return; } if (e.key === "Escape" && $("[popover=auto]:popover-open")) { e.preventDefault(); const popup = [ ...document.querySelectorAll("[popover=auto]:popover-open"), ].at(-1); popup.hidePopover(); if (popup.classList.contains("account-submenu")) popup .closest("[data-account-parent]") .querySelector(".account-parent-link") .focus(); else $(".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", "statistics", "servers", "server"].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); panel = route.searchParams.get("panel") === "admin" ? "admin" : "user"; page = Object.keys(pageNames).includes(route.searchParams.get("page")) ? route.searchParams.get("page") : "dashboard"; if (["ssh", "logs", "statistics", "servers", "server"].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();