import { applyTheme, iconSvg, createNotifier, mountCopyField, mountDock, mountNavigation, mountAccountMenu, errorPageMarkup, mountErrorPage, searchSelectMarkup, mountSearchSelect, } from "./anidev/runtime/index.js"; const $ = (selector) => document.querySelector(selector), t = (ru) => ru; const apiBase = new URL("./api/", import.meta.url); const abort = new AbortController(), { signal } = abort; const notify = createNotifier($("#project-toast"), { t }); const cleanups = []; const pageIds = new Set(["overview", "projects", "logs"]); let allowedIds = new Set(), serviceHome = null; const fixedIds = new Set(["account", "account-settings"]); let theme = "light", disposed = false, menuRequest, pageRequest, accountRequest, errorCleanup = () => {}, identity = null, accountError = null; let current = new URL(location.href).searchParams.get("page"), firstMenuLoad = true, changingMenu = false; const preview = (id) => id === "account-banned" ? "banned" : /^error-(\d{3}|offline|banned)$/.exec(id || "")?.[1]; const fixed = (id) => fixedIds.has(id) || Boolean(preview(id)); function renderTheme() { applyTheme({ theme }); $("#theme-toggle").innerHTML = iconSvg(theme === "light" ? "moon" : "sun", { size: 20, }); $("#theme-toggle").setAttribute( "aria-label", theme === "light" ? "Включить тёмную тему" : "Включить светлую тему", ); } renderTheme(); $("#theme-toggle").addEventListener( "click", () => { theme = theme === "light" ? "dark" : "light"; renderTheme(); if (current === "account-settings") showPage(current); }, { signal }, ); async function get(path, signal) { const response = await fetch(new URL(path, apiBase), { signal, credentials: "same-origin", headers: { Accept: "application/json" }, }); if (!response.ok) { const body = await response.json().catch(() => null), error = new Error(`API: ${response.status}`); error.status = response.status; error.code = body?.error?.code; error.requestId = body?.error?.requestId; if (error.code === "ACCOUNT_BANNED") error.reason = body?.error?.reason; throw error; } return response.json(); } function urlFor(id, push = false) { const url = new URL(location.href); if (id) url.searchParams.set("page", id); else url.searchParams.delete("page"); history[push ? "pushState" : "replaceState"]({}, "", url); } function displayError(status, { reason, requestId, retry } = {}) { errorCleanup(); errorCleanup = () => {}; $(".page-heading").hidden = true; $(".integration-form").hidden = true; const container = $("#page-data"); container.setAttribute("aria-busy", "false"); container.innerHTML = errorPageMarkup({ status, reason, requestId, t }); errorCleanup = mountErrorPage(container, { onRetry: retry, onHome: () => go(navigation.activeId || serviceHome), onAccount: () => go("account"), }); } function renderAccount(id) { const container = $("#page-data"); if (!identity && !accountError) { $("#page-title").textContent = "Аккаунт"; $("#page-description").textContent = "Загружаем данные аккаунта…"; container.setAttribute("aria-busy", "true"); return; } if (accountError) { displayError( accountError.status || (accountError instanceof TypeError ? "offline" : 500), { retry: async () => { await loadAccount(); showPage(current); }, }, ); return; } $("#page-title").textContent = id === "account" ? "Аккаунт" : "Настройки аккаунта"; $("#page-description").textContent = id === "account" ? "Личные данные и состояние аккаунта." : "Настройки общей панели доступны независимо от списка сервисов."; if (id === "account") { const list = document.createElement("dl"); list.className = "account-details"; for (const [label, value] of [ ["Имя", identity?.name || "Не указано"], ["Email", identity?.email || "Не указан"], ["Статус", identity?.status === "banned" ? "Заблокирован" : "Активен"], ]) { const row = document.createElement("div"), term = document.createElement("dt"), definition = document.createElement("dd"); term.textContent = label; definition.textContent = value; row.append(term, definition); list.append(row); } container.append(list); if (identity?.status === "banned") { const reason = document.createElement("p"); reason.className = "account-ban-reason"; reason.textContent = `Причина блокировки: ${identity.banReason || "Причина не указана. Уточните её у администратора."}`; container.append(reason); } const settings = document.createElement("button"); settings.textContent = "Настройки аккаунта"; settings.addEventListener("click", () => go("account-settings"), { once: true, }); container.append(settings); } else { container.innerHTML = `
В примере тема действует в текущей вкладке. Настройки на сервер не отправляются.
`; } } async function showPage(id) { pageRequest?.abort(); errorCleanup(); errorCleanup = () => {}; const request = (pageRequest = new AbortController()), container = $("#page-data"); container.replaceChildren(); container.setAttribute("aria-busy", "false"); $(".page-heading").hidden = false; $(".integration-form").hidden = true; accountMenu.setActive(id); if (fixedIds.has(id)) { renderAccount(id); return; } if (identity?.status === "banned") { displayError("banned", { reason: identity.banReason }); return; } if (preview(id)) { displayError(preview(id), { reason: preview(id) === "banned" ? "Повторное нарушение правил сервиса.\nЭто демонстрационный пример причины." : undefined, retry: () => notify("Это пример страницы ошибки. Реальный запрос не выполняется.", { type: "info", }), }); return; } $("#page-title").textContent = id ? "Загрузка…" : "Нет доступных разделов"; $("#page-description").textContent = id ? "Получаем данные раздела." : "Аккаунт и его настройки доступны внизу панели."; if (!id) return; if (!pageIds.has(id)) { displayError(404); return; } if (!allowedIds.has(id)) { displayError(403); return; } container.setAttribute("aria-busy", "true"); try { const data = await get(`pages/${id}.json`, request.signal); if (disposed || request !== pageRequest) return; if ( typeof data.title !== "string" || typeof data.description !== "string" || !Array.isArray(data.rows) ) throw Error("Invalid page response"); $("#page-title").textContent = data.title; $("#page-description").textContent = data.description; const list = document.createElement("div"); list.className = "resource-list"; for (const row of data.rows.slice(0, 100)) { if (typeof row.label !== "string" || typeof row.value !== "string") throw Error("Invalid row response"); const item = document.createElement("div"), label = document.createElement("strong"), value = document.createElement("span"); item.className = "resource-row"; label.textContent = row.label; value.textContent = row.value; item.append(label, value); list.append(item); } container.append(list); if (!data.rows.length) container.textContent = "В этом разделе пока нет данных."; $(".integration-form").hidden = false; } catch (error) { if (error.name === "AbortError" || disposed || request !== pageRequest) return; if (error.status === 403 && error.code === "ACCOUNT_BANNED") { accountError = null; identity = { ...identity, status: "banned", banReason: typeof error.reason === "string" ? error.reason : null, }; changingMenu = true; navigation.setItems([]); changingMenu = false; displayError("banned", { reason: identity.banReason, requestId: error.requestId, }); } else displayError( error.status || (error instanceof TypeError ? "offline" : 500), { requestId: error.requestId, retry: () => showPage(current) }, ); } finally { if (request === pageRequest) container.setAttribute("aria-busy", "false"); } } const dock = mountDock({ navigation: $(".navigation"), main: $(".main-column"), trigger: $(".dock-brand"), scrim: $(".dock-scrim"), t, }); const accountMenu = mountAccountMenu($("#persistent-account"), { t, onNavigate: go, }); const navigation = mountNavigation($(".nav-links"), { t, onActiveChange: (id) => { if (!changingMenu && !fixed(current)) { current = id; } }, onSelect: (id) => { current = id; urlFor(id, true); showPage(id); }, }); function go(id, push = true) { current = id; changingMenu = true; if (fixed(id)) navigation.clearActive(); else { try { navigation.setActive(id); } catch { navigation.clearActive(); } } changingMenu = false; urlFor(id, push); showPage(id); } async function loadAccount() { accountRequest?.abort(); const request = (accountRequest = new AbortController()); try { const data = await get("account.json", request.signal); if (disposed || request !== accountRequest) return; if ( !data || typeof data.id !== "string" || typeof data.name !== "string" || typeof data.email !== "string" || !["active", "banned"].includes(data.status) || (data.banReason != null && typeof data.banReason !== "string") ) throw Error("Invalid account response"); identity = data; accountError = null; accountMenu.update(data); } catch (error) { if ( error.name !== "AbortError" && !disposed && request === accountRequest ) { accountError = error; if (error.status === 403 && error.code === "ACCOUNT_BANNED") { identity = { ...identity, status: "banned", banReason: typeof error.reason === "string" ? error.reason : null, }; accountError = null; } } } } async function refreshNavigation() { menuRequest?.abort(); const request = (menuRequest = new AbortController()); $("#connection-status").textContent = "Обновляем доступные разделы…"; try { const data = await get("navigation.json", request.signal); if (disposed || request !== menuRequest) return; const reserved = (items) => Array.isArray(items) && items.some( (item) => fixedIds.has(item?.id) || item?.id === "account-banned" || String(item?.id).startsWith("error-") || (item?.children && reserved(item.children)), ); if (reserved(data.items)) throw Error("Reserved account/error route in API menu"); const requested = new URL(location.href).searchParams.get("page") || current || data.defaultPage; changingMenu = true; try { navigation.setItems(identity?.status === "banned" ? [] : data.items, { activeId: requested, }); serviceHome = navigation.activeId; allowedIds = new Set( (identity?.status === "banned" ? [] : data.items) .flatMap((item) => (item.disabled ? [] : item.children || [item])) .filter((item) => !item.disabled) .map((item) => item.id), ); if ( fixed(requested) || (firstMenuLoad && requested && requested !== navigation.activeId) ) { current = requested; navigation.clearActive(); } else current = navigation.activeId; } finally { changingMenu = false; } firstMenuLoad = false; urlFor(current); showPage(current); $("#connection-status").textContent = "Пример: данные получены из тестового API."; } catch (error) { if (error.name === "AbortError" || disposed || request !== menuRequest) return; if ( error.status === 401 || (error.status === 403 && error.code === "ACCOUNT_BANNED") ) { pageRequest?.abort(); accountError = null; if (error.status === 401) { identity = null; accountError = error; accountMenu.update({}); } else identity = { ...identity, status: "banned", banReason: typeof error.reason === "string" ? error.reason : null, }; changingMenu = true; navigation.setItems([]); changingMenu = false; allowedIds.clear(); serviceHome = null; if (fixedIds.has(current)) showPage(current); else displayError(error.status === 401 ? 401 : "banned", { reason: identity?.banReason, requestId: error.requestId, }); $("#connection-status").textContent = "Доступ к сервисам ограничен."; return; } $("#connection-status").textContent = "Не удалось обновить разделы. Попробуйте ещё раз; доступное меню сохранено."; if (firstMenuLoad) showPage(current); notify("Не удалось загрузить доступные разделы.", { type: "error" }); } } $("#refresh-navigation").addEventListener("click", refreshNavigation, { signal, }); window.addEventListener( "popstate", () => go(new URL(location.href).searchParams.get("page"), false), { signal }, ); $("#page-data").addEventListener( "change", (event) => { if (event.target.name === "account-theme") { theme = event.target.value; renderTheme(); } }, { signal }, ); const options = [ { value: "production", label: "Production" }, { value: "staging", label: "Staging" }, { value: "development", label: "Development" }, { value: "preview", label: "Preview" }, ]; $("#environment-control").innerHTML = searchSelectMarkup({ id: "project-environment", name: "environment", label: "Окружение", options, value: "production", t, }); cleanups.push(mountSearchSelect($("#project-environment"), { options, t })); $("[data-copy-input]").innerHTML = iconSvg("copy", { size: 16 }); cleanups.push(mountCopyField($(".copy-input"), { notify, t })); $("#check-settings").addEventListener( "click", () => notify("Поля заполнены. Пример не отправляет изменения на сервер.", { type: "info", }), { signal }, ); await loadAccount(); refreshNavigation(); function dispose() { if (disposed) return; disposed = true; menuRequest?.abort(); pageRequest?.abort(); accountRequest?.abort(); errorCleanup(); abort.abort(); cleanups.forEach((cleanup) => cleanup()); navigation.dispose(); accountMenu.dispose(); dock.dispose(); notify.dispose(); } window.addEventListener( "pagehide", (event) => { if (!event.persisted) dispose(); }, { signal }, );