Keep account controls permanent and add system error pages
This commit is contained in:
1 parent
61b05abe44
commit
60b584b7c1
50 files changed
+1287
-56
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"id": "demo-account",
|
||||
"name": "Anna Volkova",
|
||||
"email": "anna@example.test",
|
||||
"status": "active",
|
||||
"banReason": null
|
||||
}
|
||||
@@ -6,6 +6,38 @@
|
||||
padding-top: 24px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
.integration-form[hidden],
|
||||
.page-heading[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.account-details {
|
||||
max-width: 640px;
|
||||
margin: 0 0 24px;
|
||||
}
|
||||
.account-details > div {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(100px, 0.5fr) minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.account-details dt {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.account-details dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.account-ban-reason {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
max-width: 64ch;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
.account-settings-note {
|
||||
margin-top: 20px;
|
||||
max-width: 60ch;
|
||||
}
|
||||
.integration-form .field {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
+322
-44
@@ -5,22 +5,40 @@ import {
|
||||
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;
|
||||
const notify = createNotifier($("#project-toast"), { t });
|
||||
const apiBase = new URL("./api/", import.meta.url);
|
||||
const abort = new AbortController();
|
||||
const { signal } = abort;
|
||||
const cleanups = [];
|
||||
|
||||
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", {
|
||||
@@ -37,36 +55,154 @@ $("#theme-toggle").addEventListener(
|
||||
() => {
|
||||
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) throw Error(`API: ${response.status}`);
|
||||
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();
|
||||
}
|
||||
const pageIds = new Set(["overview", "projects", "logs"]);
|
||||
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 = `<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) {
|
||||
pageRequest?.abort();
|
||||
const request = (pageRequest = new AbortController());
|
||||
const container = $("#page-data");
|
||||
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) {
|
||||
container.setAttribute("aria-busy", "false");
|
||||
: "Аккаунт и его настройки доступны внизу панели.";
|
||||
if (!id) return;
|
||||
if (!pageIds.has(id)) {
|
||||
displayError(404);
|
||||
return;
|
||||
}
|
||||
if (!allowedIds.has(id)) {
|
||||
displayError(403);
|
||||
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 (
|
||||
@@ -82,10 +218,10 @@ async function showPage(id) {
|
||||
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"),
|
||||
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);
|
||||
@@ -94,16 +230,29 @@ async function showPage(id) {
|
||||
container.append(list);
|
||||
if (!data.rows.length)
|
||||
container.textContent = "В этом разделе пока нет данных.";
|
||||
$(".integration-form").hidden = false;
|
||||
} 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);
|
||||
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");
|
||||
}
|
||||
@@ -115,15 +264,74 @@ const dock = mountDock({
|
||||
scrim: $(".dock-scrim"),
|
||||
t,
|
||||
});
|
||||
const accountMenu = mountAccountMenu($("#persistent-account"), {
|
||||
t,
|
||||
onNavigate: go,
|
||||
});
|
||||
const navigation = mountNavigation($(".nav-links"), {
|
||||
t,
|
||||
onActiveChange: showPage,
|
||||
onActiveChange: (id) => {
|
||||
if (!changingMenu && !fixed(current)) {
|
||||
current = id;
|
||||
}
|
||||
},
|
||||
onSelect: (id) => {
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set("page", id);
|
||||
history.pushState({}, "", url);
|
||||
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());
|
||||
@@ -131,22 +339,84 @@ async function refreshNavigation() {
|
||||
try {
|
||||
const data = await get("navigation.json", request.signal);
|
||||
if (disposed || request !== menuRequest) return;
|
||||
const preferred =
|
||||
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") ||
|
||||
navigation.activeId ||
|
||||
current ||
|
||||
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);
|
||||
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" });
|
||||
}
|
||||
}
|
||||
@@ -155,11 +425,15 @@ $("#refresh-navigation").addEventListener("click", refreshNavigation, {
|
||||
});
|
||||
window.addEventListener(
|
||||
"popstate",
|
||||
() => {
|
||||
try {
|
||||
navigation.setActive(new URL(location.href).searchParams.get("page"));
|
||||
} catch {
|
||||
refreshNavigation();
|
||||
() => 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 },
|
||||
@@ -189,22 +463,26 @@ $("#check-settings").addEventListener(
|
||||
}),
|
||||
{ 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",
|
||||
(e) => {
|
||||
if (!e.persisted) dispose();
|
||||
(event) => {
|
||||
if (!event.persisted) dispose();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
@@ -26,6 +26,7 @@
|
||||
<b>a/</b><span>anidev</span>
|
||||
</button>
|
||||
<nav class="nav-links" aria-label="Основная навигация"></nav>
|
||||
<div id="persistent-account"></div>
|
||||
</aside>
|
||||
<div class="main-column">
|
||||
<header class="app-header">
|
||||
|
||||
Reference in new issue
Block a user