import { concepts, tokensFor, cssVars } from "../concepts/registry.js"; import { createDemoIdentityAdapter, identityStates, } from "../patterns/demo-identity.js"; import { createAccountUI, accountPageIds, } from "../components/account-pages.js"; import { exportSystem } from "../components/export-system.js"; const identityAdapter = createDemoIdentityAdapter(); let preferences = {}; try { preferences = JSON.parse( localStorage.getItem("anidev.preferences") || localStorage.getItem("anidev.lab") || "{}", ) || {}; } catch {} const params = new URLSearchParams(location.search), concept = concepts[0]; params.delete("concept"); let theme = (params.get("theme") || preferences.theme) === "dark" ? "dark" : "light", density = ["compact", "normal", "relaxed"].includes( params.get("density") || preferences.density, ) ? params.get("density") || preferences.density : "compact", locale = (params.get("locale") || preferences.locale) === "en" ? "en" : "ru"; const rawAccent = params.get("accent"), accent = /^#[0-9a-f]{6}$/i.test(rawAccent) ? rawAccent : theme === "dark" ? concept.darkAccent || concept.accent : concept.accent; let tokens = tokensFor(concept.id, theme, accent, density); document.documentElement.style.cssText = cssVars(tokens); document.documentElement.lang = locale; document.body.dataset.concept = concept.id; document.body.dataset.theme = theme; const t = (ru, en) => (locale === "ru" ? ru : en); const number = (v, digits = 0) => new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits, }).format(v); const $ = (s) => document.querySelector(s), escape = (s) => String(s).replace( /[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'", })[c], ); const initialUsers = [ { id: 1, name: "Anna Volkova", email: "anna@anidev.ru", role: "admin", status: "active", last: "09:42", }, { id: 2, name: "Mikhail Orlov", email: "mikhail@anidev.ru", role: "developer", status: "active", last: "09:38", }, { id: 3, name: "Elena Kim", email: "elena@anidev.ru", role: "viewer", status: "active", last: "09:21", }, { id: 4, name: "Denis Petrov", email: "denis@anidev.ru", role: "developer", status: "invited", last: "—", }, { id: 5, name: "Sofia Morozova", email: "sofia@anidev.ru", role: "viewer", status: "suspended", last: "26.11", }, { id: 6, name: "Pavel Sokolov", email: "pavel@anidev.ru", role: "developer", status: "active", last: "08:56", }, { id: 7, name: "Maria Ivanova", email: "maria@anidev.ru", role: "admin", status: "active", last: "08:40", }, { id: 8, name: "Alex Chen", email: "alex@anidev.ru", role: "viewer", status: "active", last: "08:32", }, ]; let users; try { users = JSON.parse(localStorage.getItem("anidev.users") || "null") || structuredClone(initialUsers); } catch { users = structuredClone(initialUsers); } let settings; try { settings = JSON.parse(localStorage.getItem("anidev.settings") || "null") || { name: "Anidev Production", slug: "anidev-prod", region: "eu", email: "ops@anidev.ru", mfa: true, audit: true, }; } catch { settings = { name: "Anidev Production", slug: "anidev-prod", region: "eu", email: "ops@anidev.ru", mfa: true, audit: true, }; } let page = [ "dashboard", "users", "settings", "auth", "components", "tokens", ...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: '', security: '', sessions: '', applications: '', appearance: '', identity: '', dashboard: '', users: '', settings: '', components: '', tokens: '', }; const icon = (id) => ``; 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")); } } let toastTimer; function toast(message) { const notification = $("#toast"); notification.popover = "manual"; notification.textContent = message; if (notification.matches(":popover-open")) notification.hidePopover(); notification.showPopover(); clearTimeout(toastTimer); toastTimer = setTimeout(() => { notification.hidePopover(); }, 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 ``; } function nav() { const dockBrand = ``; return ``; } function header() { return `
`; } 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 ( e.pointerType !== "mouse" || !matchMedia("(hover: hover) and (pointer: fine)").matches ) return; clearTimeout(dockCloseTimer); if (!document.body.classList.contains("dock-open")) { dockHoverOpened = true; setDockOpen(true, false); } }); nav.addEventListener("pointerenter", () => clearTimeout(dockCloseTimer)); nav.addEventListener("pointerleave", (e) => { if (nav.contains(e.relatedTarget)) return; if (dockHoverOpened) dockCloseTimer = setTimeout(() => { if (!$("[popover=auto]:popover-open")) { dockHoverOpened = false; setDockOpen(false, false); } }, 180); }); } function setDockOpen(open, returnFocus = true) { if (!open) { dockHoverOpened = false; clearTimeout(dockCloseTimer); } const nav = $(".navigation"); if (!nav) return; document.body.classList.toggle("dock-open", open); const toggle = $(".dock-toggle"); toggle.setAttribute("aria-expanded", String(open)); toggle.setAttribute( "aria-label", open ? t("Свернуть меню", "Collapse navigation") : t("Развернуть меню", "Expand navigation"), ); toggle.title = toggle.getAttribute("aria-label"); $(".main-column").inert = open; 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 initialRender = true; function render({ preserveDock = false } = {}) { const dockWasOpen = preserveDock && document.body.classList.contains("dock-open") && page !== "auth"; const route = new URL(location.href); route.searchParams.delete("concept"); route.searchParams.set("page", page); route.searchParams.set("theme", theme); route.searchParams.set("locale", locale); if (route.href !== location.href) { history[ initialRender || route.searchParams.get("page") === new URL(location.href).searchParams.get("page") ? "replaceState" : "pushState" ]({}, "", route); } initialRender = false; clearTimeout(dockCloseTimer); if (!dockWasOpen) { dockHoverOpened = false; document.body.classList.remove("dock-open"); } document.title = `Anidev / ${concept.name} / ${pageNames[page]}`; 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() : `
${nav()}
${header()}
${content}
`; bindForms(); accountUI.bind(page); bindDockHover(); if (dockWasOpen) setDockOpen(true, false); bindCharts(); 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 componentScreen() { return `${heading(t("Библиотека компонентов", "Component library"), t("Единые состояния. Шесть способов выражения.", "Shared states. Six ways of expressing them."), ``)}

Buttons

Hover · active · focus · disabled · loading

Inputs & selects

Selection controls

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

Overlays & feedback

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

Empty state

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

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

Error & skeleton

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

Status indicators

${t("Работает", "Operational")}${t("Недоступен", "Unavailable")}${t("Ожидает", "Pending")}

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

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); 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 fromDock = Boolean(pageButton.closest(".navigation")); if (fromDock && page === pageButton.dataset.page) return; page = pageButton.dataset.page; $("#dialog").close(); render({ preserveDock: fromDock }); if (fromDock && document.body.classList.contains("dock-open")) { $(".nav-links [aria-current=page]")?.focus({ preventScroll: true }); } else $("#content")?.focus(); return; } const sorter = e.target.closest("[data-sort]"); if (sorter) { sortAsc = sortKey === sorter.dataset.sort ? !sortAsc : true; sortKey = sorter.dataset.sort; refreshUsers(); return; } const edit = e.target.closest("[data-edit]"); if (edit) { editUser(Number(edit.dataset.edit)); return; } const tabButton = e.target.closest("[data-tab]"); if (tabButton) { tab = tabButton.dataset.tab; render(); $("#tab-" + tab).focus(); return; } const button = e.target.closest("[data-action]"), action = button?.dataset.action; if (!e.target.closest(".context-menu")) $(".context-menu")?.remove(); if (!action) return; document .querySelectorAll("[popover=auto]:popover-open") .forEach((el) => el.hidePopover()); const actions = { 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")); }, "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 (e.key === "Escape" && $("[popover=auto]:popover-open")) { e.preventDefault(); $("[popover=auto]: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(); savePreferences(); }, }); if (identityStates.includes(params.get("identityState"))) identityAdapter.setScenario(params.get("identityState")); addEventListener("storage", (e) => { if (e.key === "anidev.identity.demo.v2") { $("#dialog").close(); render(); } }); addEventListener("popstate", () => { const route = new URL(location.href); page = Object.keys(pageNames).includes(route.searchParams.get("page")) ? route.searchParams.get("page") : "dashboard"; 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();