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:
'
${desc}
${t("p95 · миллисекунды · ниже — лучше · тестовая выборка", "p95 · milliseconds · lower is better · sample dataset")}
| ${t("Время UTC", "Time UTC")} | p95 / ms |
|---|---|
| ${chartRange === "24h" ? String(i).padStart(2, "0") + ":00" : 21 + i + ".11"} | ${v} |
eu-central-1 · ${t("проверка каждую минуту", "checked every minute")}
${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."), ``)}${t("Попробуйте другое имя или сбросьте фильтр.", "Try another name or reset the filter.")}
| 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} |
${tab === "general" ? t("Эти данные видны участникам организации.", "These details are visible to organization members.") : t("Изменения применяются к этому демо.", "Changes apply to this demo.")}
${t("Создайте ключ для подключения сервиса.", "Create a key to connect your service.")}
${t("Не удалось загрузить журнал.", "Could not load the log.")}
${t("Состояние выражено текстом, а не только цветом.", "Status uses text as well as color.")}
${t("Таблицы, пагинация и фильтры — на экране «Пользователи»; вкладки — в настройках; форма входа — в авторизации.", "Tables, pagination and filters: Users. Tabs: Settings. Sign-in form: Authentication.")}
${key}${value.startsWith("#") ? `` : ""}${escape(value)}:root {\n${cssVars(tokens)}\n}${t("Экспорт включает обе темы, JSON и CSS. Используется утверждённая палитра Dock.", "Export includes both themes, JSON and CSS. Uses the approved Dock palette.")}
${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)}
`, ); $("#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"), `${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
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();