Files
anidev-design-system/examples/starter/app.js
T

781 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
applyTheme,
breadcrumbsMarkup,
mountBreadcrumbs,
iconSvg,
createNotifier,
mountCopyField,
mountDock,
mountMobileDock,
mountNavigation,
mountAccountMenu,
errorPageMarkup,
mountErrorPage,
searchSelectMarkup,
mountSearchSelect,
} from "./anidev/runtime/index.js";
import {
contentDemoPages,
contentDemoMarkup,
mountContentDemo,
contentBreadcrumbs,
contentHref,
createDemoDocuments,
} from "./anidev/components/content-demo.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 = [];
let syncAccountTheme = () => {};
const pageIds = new Set(["overview", "projects", "logs", ...contentDemoPages]);
const documentFiles = createDemoDocuments();
let contentCleanup = () => {},
breadcrumbCleanup = () => {};
let allowedIds = new Set(),
serviceHome = null;
let mobilePages = new Map();
const fixedIds = new Set([
"account",
"account-security",
"account-sessions",
"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() {
syncAccountTheme();
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);
}
let sessionCleanup = () => {};
function showSession(error = { status: 401 }) {
contentCleanup();
contentCleanup = () => {};
breadcrumbCleanup();
breadcrumbCleanup = () => {};
documentFiles.clear();
for (const [path, file] of createDemoDocuments())
documentFiles.set(path, file);
pageRequest?.abort();
pageRequest = undefined;
menuRequest?.abort();
menuRequest = undefined;
accountRequest?.abort();
accountRequest = undefined;
errorCleanup();
errorCleanup = () => {};
sessionCleanup();
sessionCleanup = () => {};
dock.close();
mobileDock.reset();
accountMenu.close();
notify.dismiss();
document.querySelectorAll("[popover]:popover-open").forEach((popup) => {
if (popup.matches(":popover-open")) popup.hidePopover();
});
document.querySelectorAll("dialog[open]").forEach((dialog) => dialog.close());
identity = null;
accountError = error;
changingMenu = true;
navigation.setItems([]);
changingMenu = false;
allowedIds.clear();
mobilePages.clear();
serviceHome = null;
accountMenu.update({});
$("#page-data").replaceChildren();
$(".integration-form").hidden = true;
document.body.dataset.session =
error.status === 401 ? "guest" : "unavailable";
$(".shell").inert = true;
$(".skip").href = "#session-screen";
const screen = $("#session-screen");
screen.innerHTML = errorPageMarkup({
status: error.status || (error instanceof TypeError ? "offline" : 500),
t,
});
sessionCleanup = mountErrorPage(screen, {
onAccount: () =>
notify("Это пример состояния входа. SSO пока не подключён.", {
type: "info",
title: "Вход в аккаунт",
}),
onRetry: async () => {
await loadAccount();
if (identity) refreshNavigation();
},
});
const login = screen.querySelector('[data-error-action="account"]');
if (login) login.textContent = "Войти";
}
function showShell() {
sessionCleanup();
sessionCleanup = () => {};
$("#session-screen").replaceChildren();
$(".shell").inert = false;
document.body.dataset.session = "authenticated";
$(".skip").href = "#content";
document.body.dataset.panel = identity.panel;
$(".breadcrumb").textContent =
identity.panel === "admin"
? "Anidev / Панель администратора"
: "Anidev / Панель пользователя";
}
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 = `<fieldset class="choice-fieldset"><legend>Тема панели</legend><div class="component-row"><label class="choice-pill"><input type="radio" name="account-theme" value="light" ${theme === "light" ? "checked" : ""}><span>Светлая</span></label><label class="choice-pill"><input type="radio" name="account-theme" value="dark" ${theme === "dark" ? "checked" : ""}><span>Тёмная</span></label></div></fieldset><p class="muted account-settings-note">В примере тема действует в текущей вкладке. Настройки на сервер не отправляются.</p>`;
}
}
async function showPage(id) {
if (!identity) {
if (accountError) showSession(accountError);
return;
}
pageRequest?.abort();
contentCleanup();
contentCleanup = () => {};
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);
renderBreadcrumbs(id);
mobileDock.update(id, `${identity.panel}:${identity.id || "account"}`);
if (["account", "account-settings"].includes(id)) {
renderAccount(id);
return;
}
if (["account-security", "account-sessions"].includes(id)) {
$("#page-title").textContent = "Загрузка…";
$("#page-description").textContent = "Получаем данные аккаунта.";
container.setAttribute("aria-busy", "true");
try {
const data = await get(
`account/${id === "account-security" ? "security" : "sessions"}.json`,
request.signal,
);
if (disposed || request !== pageRequest) return;
if (
typeof data.title !== "string" ||
typeof data.description !== "string" ||
!Array.isArray(data.rows)
)
throw Error("Invalid account section");
$("#page-title").textContent = data.title;
$("#page-description").textContent = data.description;
const list = document.createElement("dl");
list.className = "account-details";
for (const row of data.rows.slice(0, 100)) {
if (typeof row.label !== "string" || typeof row.value !== "string")
throw Error("Invalid account row");
const item = document.createElement("div"),
term = document.createElement("dt"),
value = document.createElement("dd");
term.textContent = row.label;
value.textContent = row.value;
item.append(term, value);
list.append(item);
}
container.append(list);
} catch (error) {
if (error.name !== "AbortError" && request === pageRequest && !disposed) {
if (error.status === 401) showSession(error);
else
displayError(error.status || 500, { retry: () => showPage(current) });
}
} finally {
if (request === pageRequest) container.setAttribute("aria-busy", "false");
}
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) &&
!(["server", "servers"].includes(id) && allowedIds.has("statistics"))
) {
displayError(403);
return;
}
if (contentDemoPages.includes(id)) {
$(".page-heading").hidden = true;
const url = new URL(location.href),
server = url.searchParams.get("server") || "edge-01",
path = url.searchParams.get("path") || "/";
container.innerHTML = contentDemoMarkup(id, {
server,
path,
t,
heading: (title, description) =>
`<div class="page-heading"><div><h1></h1><p></p></div></div>`,
});
const heading = container.querySelector(".page-heading");
if (heading) {
const names = {
documents: "Документы и код",
servers: "Серверы",
server,
statistics: `Статистика · ${server}`,
};
heading.querySelector("h1").textContent = names[id];
heading.querySelector("p").textContent =
"Демонстрационные данные · API пока не подключено.";
}
contentCleanup = mountContentDemo(
container.querySelector("[data-content-demo]"),
{
page: id,
server,
path,
files: documentFiles,
onNavigate: visitContentURL,
notify,
t,
},
);
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 === 401) {
showSession(error);
return;
}
if (error.status === 403 && error.code === "ACCOUNT_BANNED") {
accountError = null;
mobilePages.clear();
allowedIds.clear();
mobileDock.reset();
mobileDock.update(
"account-banned",
`${identity?.panel || "user"}:${identity?.id || "account"}`,
);
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,
theme,
onThemeChange: (mode) => {
theme = mode;
renderTheme();
if (current === "account-settings") showPage(current);
},
});
syncAccountTheme = () => accountMenu.setTheme(theme);
const mobileDock = mountMobileDock($(".navigation"), {
trigger: $(".dock-brand"),
t,
onNavigate: go,
onCloseMenu: () => dock.close(),
getPage: (id) => {
const personal = {
account: ["Управление", "profile"],
"account-security": ["Безопасность", "security"],
"account-sessions": ["Устройства и сеансы", "sessions"],
"account-settings": ["Настройки", "settings"],
};
if (personal[id])
return { id, label: personal[id][0], icon: personal[id][1] };
if (preview(id)) return { id, label: "Состояние", icon: "warning" };
return (
mobilePages.get(id) ||
(["servers", "server"].includes(id) && mobilePages.has("statistics")
? { id, label: id === "servers" ? "Серверы" : "Сервер", icon: "server" }
: null)
);
},
});
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);
}
function renderBreadcrumbs(id) {
breadcrumbCleanup();
const url = new URL(location.href);
const personalNames = {
account: "Управление",
"account-security": "Безопасность",
"account-sessions": "Устройства и сеансы",
"account-settings": "Настройки",
};
const items = contentDemoPages.includes(id)
? contentBreadcrumbs(id, {
server: url.searchParams.get("server") || "edge-01",
path: url.searchParams.get("path") || "/",
rootPage: "overview",
t,
})
: [
{ label: "anidev", href: contentHref({ page: "overview" }) },
{ label: personalNames[id] || mobilePages.get(id)?.label || "Панель" },
];
$(".breadcrumb").innerHTML = breadcrumbsMarkup({ items, t });
breadcrumbCleanup = mountBreadcrumbs($(".breadcrumbs"), {
onNavigate: visitContentURL,
});
}
function visitContentURL(url) {
history.pushState({}, "", url);
go(url.searchParams.get("page") || "overview", false);
}
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?.status === "guest") {
showSession({ status: 401 });
return;
}
if (
!data ||
typeof data.id !== "string" ||
typeof data.name !== "string" ||
typeof data.email !== "string" ||
!["active", "banned"].includes(data.status) ||
(data.panel !== undefined && !["user", "admin"].includes(data.panel)) ||
(data.banReason != null && typeof data.banReason !== "string")
)
throw Error("Invalid account response");
if (identity?.id !== data.id) {
documentFiles.clear();
for (const [path, file] of createDemoDocuments())
documentFiles.set(path, file);
}
identity = { ...data, panel: data.panel || "user" };
accountError = null;
accountMenu.update(data);
showShell();
} catch (error) {
if (
error.name !== "AbortError" &&
!disposed &&
request === accountRequest
) {
accountError = error;
if (error.status === 403 && error.code === "ACCOUNT_BANNED") {
identity = {
...identity,
status: "banned",
panel: "user",
banReason: typeof error.reason === "string" ? error.reason : null,
};
accountError = null;
showShell();
} else showSession(error);
}
}
}
async function refreshNavigation() {
if (!identity) return;
menuRequest?.abort();
const request = (menuRequest = new AbortController());
$("#connection-status").textContent = "Обновляем доступные разделы…";
try {
const response = await get("navigation.json", request.signal);
if (disposed || request !== menuRequest) return;
const data = response.panels ? response.panels[identity.panel] : response;
if (!data) throw Error("Panel navigation not configured");
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),
);
mobilePages = new Map(
(identity?.status === "banned" ? [] : data.items)
.flatMap((item) => (item.disabled ? [] : item.children || [item]))
.filter((item) => !item.disabled)
.map((item) => [
item.id,
{ id: item.id, label: item.label, icon: item.icon },
]),
);
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) {
showSession(error);
return;
} else
identity = {
...identity,
status: "banned",
banReason: typeof error.reason === "string" ? error.reason : null,
};
changingMenu = true;
navigation.setItems([]);
changingMenu = false;
allowedIds.clear();
mobilePages.clear();
mobileDock.reset();
mobileDock.update(
"account-banned",
`${identity?.panel || "user"}:${identity?.id || "account"}`,
);
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();
if (identity) refreshNavigation();
function dispose() {
if (disposed) return;
disposed = true;
menuRequest?.abort();
pageRequest?.abort();
accountRequest?.abort();
errorCleanup();
sessionCleanup();
contentCleanup();
breadcrumbCleanup();
abort.abort();
cleanups.forEach((cleanup) => cleanup());
navigation.dispose();
accountMenu.dispose();
mobileDock.dispose();
dock.dispose();
notify.dispose();
}
window.addEventListener(
"pagehide",
(event) => {
if (!event.persisted) dispose();
},
{ signal },
);