import { applyTheme, iconSvg, createNotifier, mountCopyField, mountDock, mountNavigation, searchSelectMarkup, mountSearchSelect, } from "./anidev/runtime/index.js"; const $ = (selector) => document.querySelector(selector), t = (ru) => ru; let theme = "light", disposed = false, menuRequest, pageRequest; const notify = createNotifier($("#project-toast"), { t }); const apiBase = new URL("./api/", import.meta.url); const abort = new AbortController(); const { signal } = abort; const cleanups = []; 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(); }, { 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) throw Error(`API: ${response.status}`); return response.json(); } const pageIds = new Set(["overview", "projects", "logs"]); async function showPage(id) { pageRequest?.abort(); const request = (pageRequest = new AbortController()); const container = $("#page-data"); container.replaceChildren(); $("#page-title").textContent = id ? "Загрузка…" : "Нет доступных разделов"; $("#page-description").textContent = id ? "Получаем данные раздела." : "Обратитесь к администратору за доступом."; if (!id) { container.setAttribute("aria-busy", "false"); return; } container.setAttribute("aria-busy", "true"); try { if (!pageIds.has(id)) throw Error("Section module is not installed"); 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"); item.className = "resource-row"; const label = document.createElement("strong"), value = document.createElement("span"); label.textContent = row.label; value.textContent = row.value; item.append(label, value); list.append(item); } container.append(list); if (!data.rows.length) container.textContent = "В этом разделе пока нет данных."; } catch (error) { if (error.name === "AbortError" || disposed || request !== pageRequest) return; $("#page-title").textContent = "Раздел недоступен"; $("#page-description").textContent = "Не удалось получить данные. Попробуйте ещё раз."; const retry = document.createElement("button"); retry.textContent = "Повторить"; retry.addEventListener("click", () => showPage(id), { once: true }); container.append(retry); } 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 navigation = mountNavigation($(".nav-links"), { t, onActiveChange: showPage, onSelect: (id) => { const url = new URL(location.href); url.searchParams.set("page", id); history.pushState({}, "", url); }, }); 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 preferred = new URL(location.href).searchParams.get("page") || navigation.activeId || data.defaultPage; navigation.setItems(data.items, { activeId: preferred }); const url = new URL(location.href); if (navigation.activeId) url.searchParams.set("page", navigation.activeId); else url.searchParams.delete("page"); history.replaceState({}, "", url); $("#connection-status").textContent = "Пример: данные получены из тестового API."; } catch (error) { if (error.name === "AbortError" || disposed || request !== menuRequest) return; $("#connection-status").textContent = "Не удалось обновить разделы. Попробуйте ещё раз; доступное меню сохранено."; notify("Не удалось загрузить доступные разделы.", { type: "error" }); } } $("#refresh-navigation").addEventListener("click", refreshNavigation, { signal, }); window.addEventListener( "popstate", () => { try { navigation.setActive(new URL(location.href).searchParams.get("page")); } catch { refreshNavigation(); } }, { 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 }, ); refreshNavigation(); function dispose() { if (disposed) return; disposed = true; menuRequest?.abort(); pageRequest?.abort(); abort.abort(); cleanups.forEach((cleanup) => cleanup()); navigation.dispose(); dock.dispose(); notify.dispose(); } window.addEventListener( "pagehide", (e) => { if (!e.persisted) dispose(); }, { signal }, );