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,115 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
let sequence = 0;
|
||||
/** Fixed account controls live outside the API-driven service navigation. */
|
||||
export function mountAccountMenu(
|
||||
root,
|
||||
{ onNavigate, t = (ru) => ru, name = "", email = "" } = {},
|
||||
) {
|
||||
if (typeof onNavigate !== "function")
|
||||
throw new TypeError("Account menu needs onNavigate");
|
||||
const abort = new AbortController(),
|
||||
{ signal } = abort,
|
||||
id = `anidev-account-${++sequence}`;
|
||||
root.classList.add("dock-account-area");
|
||||
root.dataset.fixedAccount = "";
|
||||
root.innerHTML = `<div id="${id}" class="account-menu" popover="auto" role="menu" aria-label="${t("Меню аккаунта", "Account menu")}"><button type="button" role="menuitem" data-account-page="account">${iconSvg("profile", { size: 20 })}<span>${t("Аккаунт", "Account")}</span></button><button type="button" role="menuitem" data-account-page="account-settings">${iconSvg("settings", { size: 20 })}<span>${t("Настройки аккаунта", "Account settings")}</span></button></div><button type="button" class="dock-account" popovertarget="${id}" aria-haspopup="menu" aria-expanded="false" aria-controls="${id}" aria-label="${t("Открыть меню аккаунта", "Open account menu")}"><span class="avatar">${iconSvg("profile", { size: 20 })}</span><span class="account-identity"><b></b><small></small></span><span class="account-more" aria-hidden="true">···</span></button>`;
|
||||
const popup = root.querySelector(".account-menu"),
|
||||
trigger = root.querySelector(".dock-account");
|
||||
function update(identity = {}) {
|
||||
root.querySelector(".account-identity b").textContent =
|
||||
identity.name || t("Аккаунт", "Account");
|
||||
root.querySelector(".account-identity small").textContent =
|
||||
identity.email || t("Личные настройки", "Personal settings");
|
||||
}
|
||||
update({ name, email });
|
||||
const close = (restore = false) => {
|
||||
if (popup.matches(":popover-open")) popup.hidePopover();
|
||||
if (restore) trigger.focus({ preventScroll: true });
|
||||
};
|
||||
popup.addEventListener(
|
||||
"toggle",
|
||||
() =>
|
||||
trigger.setAttribute(
|
||||
"aria-expanded",
|
||||
String(popup.matches(":popover-open")),
|
||||
),
|
||||
{ signal },
|
||||
);
|
||||
popup.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const target = event.target.closest("[data-account-page]");
|
||||
if (target) {
|
||||
close(true);
|
||||
onNavigate(target.dataset.accountPage);
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
popup.addEventListener(
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (event.key === "Tab") close(true);
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close(true);
|
||||
}
|
||||
if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
const items = [...popup.querySelectorAll("button")],
|
||||
current = items.indexOf(document.activeElement);
|
||||
const index =
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? items.length - 1
|
||||
: (current +
|
||||
(event.key === "ArrowDown" ? 1 : -1) +
|
||||
items.length) %
|
||||
items.length;
|
||||
items[index].focus();
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
trigger.addEventListener(
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (["ArrowDown", "ArrowUp"].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
popup.showPopover();
|
||||
const buttons = popup.querySelectorAll("button");
|
||||
buttons[event.key === "ArrowDown" ? 0 : buttons.length - 1].focus();
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
const shell = root.closest(".navigation");
|
||||
shell?.addEventListener(
|
||||
"anidev:dockchange",
|
||||
(event) => {
|
||||
if (!event.detail.open) close();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return {
|
||||
update,
|
||||
close,
|
||||
setActive(id) {
|
||||
popup.querySelectorAll("[data-account-page]").forEach((button) => {
|
||||
if (button.dataset.accountPage === id)
|
||||
button.setAttribute("aria-current", "page");
|
||||
else button.removeAttribute("aria-current");
|
||||
});
|
||||
trigger.dataset.active = String(
|
||||
["account", "account-settings"].includes(id),
|
||||
);
|
||||
},
|
||||
dispose() {
|
||||
close();
|
||||
abort.abort();
|
||||
trigger.removeAttribute("popovertarget");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
const escape = (value) =>
|
||||
String(value).replace(
|
||||
/[&<>"']/g,
|
||||
(c) =>
|
||||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[
|
||||
c
|
||||
],
|
||||
);
|
||||
const states = {
|
||||
400: [
|
||||
"Запрос не выполнен",
|
||||
"Invalid request",
|
||||
"Проверьте введённые данные и попробуйте ещё раз.",
|
||||
"Check the submitted data and try again.",
|
||||
"warning",
|
||||
["home"],
|
||||
],
|
||||
401: [
|
||||
"Нужно войти в аккаунт",
|
||||
"Sign-in required",
|
||||
"Сеанс завершён или вход ещё не выполнен.",
|
||||
"Your session has ended or you have not signed in yet.",
|
||||
"lock",
|
||||
["account"],
|
||||
],
|
||||
403: [
|
||||
"Нет доступа",
|
||||
"Access denied",
|
||||
"У аккаунта нет прав на этот раздел. Обратитесь к администратору.",
|
||||
"Your account cannot access this section. Contact an administrator.",
|
||||
"lock",
|
||||
["account", "home"],
|
||||
],
|
||||
404: [
|
||||
"Страница не найдена",
|
||||
"Page not found",
|
||||
"Возможно, адрес изменился или страница больше не существует.",
|
||||
"The address may have changed or the page may no longer exist.",
|
||||
"search",
|
||||
["home"],
|
||||
],
|
||||
408: [
|
||||
"Время ожидания истекло",
|
||||
"Request timed out",
|
||||
"Сервер не успел обработать запрос. Попробуйте ещё раз.",
|
||||
"The server did not finish the request in time. Try again.",
|
||||
"refresh",
|
||||
["retry", "home"],
|
||||
],
|
||||
409: [
|
||||
"Данные изменились",
|
||||
"Data conflict",
|
||||
"Обновите страницу и проверьте актуальные данные перед повторной отправкой.",
|
||||
"Refresh the page and check the latest data before submitting again.",
|
||||
"warning",
|
||||
["retry", "home"],
|
||||
],
|
||||
410: [
|
||||
"Страница удалена",
|
||||
"Page removed",
|
||||
"Этот ресурс больше недоступен. Перейдите к доступным разделам.",
|
||||
"This resource is no longer available. Open an available section.",
|
||||
"archive",
|
||||
["home"],
|
||||
],
|
||||
422: [
|
||||
"Проверьте данные",
|
||||
"Check your data",
|
||||
"Некоторые значения не прошли проверку. Вернитесь к форме и исправьте их.",
|
||||
"Some values failed validation. Return to the form and correct them.",
|
||||
"warning",
|
||||
["home"],
|
||||
],
|
||||
429: [
|
||||
"Слишком много запросов",
|
||||
"Too many requests",
|
||||
"Подождите немного, прежде чем повторять действие.",
|
||||
"Wait a little before trying again.",
|
||||
"warning",
|
||||
["retry", "home"],
|
||||
],
|
||||
500: [
|
||||
"Внутренняя ошибка сервера",
|
||||
"Internal server error",
|
||||
"Не удалось обработать запрос. Попробуйте позже; если ошибка повторяется, сообщите администратору.",
|
||||
"The request could not be processed. Try later; if this persists, contact an administrator.",
|
||||
"error",
|
||||
["retry", "home"],
|
||||
],
|
||||
502: [
|
||||
"Нет ответа от сервиса",
|
||||
"Bad gateway",
|
||||
"Промежуточный сервер получил некорректный ответ. Попробуйте ещё раз позже.",
|
||||
"The gateway received an invalid response. Try again later.",
|
||||
"server",
|
||||
["retry", "home"],
|
||||
],
|
||||
503: [
|
||||
"Сервис временно недоступен",
|
||||
"Service unavailable",
|
||||
"Сервис перегружен или находится на обслуживании. Попробуйте позже.",
|
||||
"The service is overloaded or under maintenance. Try again later.",
|
||||
"server",
|
||||
["retry", "home"],
|
||||
],
|
||||
504: [
|
||||
"Сервис не ответил вовремя",
|
||||
"Gateway timeout",
|
||||
"Время ожидания ответа от сервиса истекло. Попробуйте позже.",
|
||||
"The gateway timed out waiting for the service. Try again later.",
|
||||
"refresh",
|
||||
["retry", "home"],
|
||||
],
|
||||
offline: [
|
||||
"Нет соединения",
|
||||
"Connection unavailable",
|
||||
"Не удалось связаться с сервером. Проверьте соединение и попробуйте ещё раз.",
|
||||
"Could not reach the server. Check your connection and try again.",
|
||||
"cloud",
|
||||
["retry", "home"],
|
||||
],
|
||||
banned: [
|
||||
"Аккаунт заблокирован",
|
||||
"Account suspended",
|
||||
"Доступ к сервисам ограничен. Информация об аккаунте и его настройки остаются доступны. Для уточнения обратитесь к администратору.",
|
||||
"Access to services is restricted. Account information and settings remain available. Contact an administrator for details.",
|
||||
"security",
|
||||
["account"],
|
||||
],
|
||||
};
|
||||
export const errorStatuses = Object.freeze(
|
||||
Object.keys(states).map((key) => (/^\d+$/.test(key) ? Number(key) : key)),
|
||||
);
|
||||
export function errorPageMarkup({
|
||||
status = 500,
|
||||
reason,
|
||||
requestId,
|
||||
t = (ru) => ru,
|
||||
id = "anidev-error",
|
||||
support = false,
|
||||
} = {}) {
|
||||
if (!/^[a-z][\w-]*$/i.test(id)) throw new TypeError("Invalid error page id");
|
||||
const resolved = Object.hasOwn(states, status) ? String(status) : "500";
|
||||
const key = /^\d{3}$/.test(resolved) ? Number(resolved) : resolved;
|
||||
const [ru, en, descriptionRu, descriptionEn, icon, actions] = states[key];
|
||||
const labels = {
|
||||
retry: t("Повторить", "Try again"),
|
||||
home: t("К доступным разделам", "Available sections"),
|
||||
account: t("Открыть аккаунт", "Open account"),
|
||||
support: t("Связаться с поддержкой", "Contact support"),
|
||||
};
|
||||
return `<section class="error-page" data-error-status="${key}" aria-labelledby="${id}-title"><div class="error-page-symbol">${iconSvg(icon, { size: 32 })}</div><p class="error-page-code">${typeof key === "number" ? key : key === "banned" ? t("ДОСТУП ОГРАНИЧЕН", "ACCESS RESTRICTED") : t("СОЕДИНЕНИЕ", "CONNECTION")}</p><h1 id="${id}-title">${t(ru, en)}</h1><p class="error-page-description">${t(descriptionRu, descriptionEn)}</p>${key === "banned" ? `<div class="error-page-reason"><h2>${t("Причина блокировки", "Suspension reason")}</h2><p>${escape(typeof reason === "string" && reason.trim() ? reason : t("Причина не указана. Уточните её у администратора.", "No reason was provided. Contact an administrator for details."))}</p></div>` : ""}<div class="error-page-actions">${[...actions, ...(support ? ["support"] : [])].map((action, i) => `<button type="button" class="${i === 0 ? "primary" : ""}" data-error-action="${action}">${labels[action]}</button>`).join("")}</div>${requestId ? `<p class="error-page-reference">${t("Код обращения", "Reference")}: <code>${escape(requestId)}</code></p>` : ""}</section>`;
|
||||
}
|
||||
export function mountErrorPage(
|
||||
root,
|
||||
{ onRetry, onHome, onAccount, onSupport } = {},
|
||||
) {
|
||||
const abort = new AbortController();
|
||||
const actions = {
|
||||
retry: onRetry,
|
||||
home: onHome,
|
||||
account: onAccount,
|
||||
support: onSupport,
|
||||
};
|
||||
root.querySelectorAll("[data-error-action]").forEach((button) => {
|
||||
const handler = actions[button.dataset.errorAction];
|
||||
button.disabled = typeof handler !== "function";
|
||||
if (handler)
|
||||
button.addEventListener("click", handler, { signal: abort.signal });
|
||||
});
|
||||
return () => abort.abort();
|
||||
}
|
||||
@@ -107,6 +107,7 @@ export async function exportSystem(
|
||||
"components/system.css",
|
||||
"components/toast.js",
|
||||
"components/copy-field.js",
|
||||
"components/error-page.js",
|
||||
"components/search-select.js",
|
||||
"components/workspaces.css",
|
||||
"components/ssh-console.js",
|
||||
|
||||
@@ -207,6 +207,13 @@ export function mountNavigation(
|
||||
return {
|
||||
setItems,
|
||||
setActive,
|
||||
clearActive() {
|
||||
if (disposed) return;
|
||||
const previous = active;
|
||||
active = null;
|
||||
render();
|
||||
if (previous !== null) onActiveChange(null);
|
||||
},
|
||||
get activeId() {
|
||||
return active;
|
||||
},
|
||||
|
||||
@@ -3117,3 +3117,109 @@ body[data-concept="dock"].dock-open
|
||||
body[data-concept="dock"] .copy-input .input-copy-action:active {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
/* Fixed identity controls stay outside the API-driven service menu. */
|
||||
[data-fixed-account] {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
[data-fixed-account] .account-identity {
|
||||
min-width: 0;
|
||||
}
|
||||
[data-fixed-account] .account-identity :is(b, small) {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
[data-fixed-account] .account-menu {
|
||||
max-width: calc(100vw - 32px);
|
||||
max-height: calc(100dvh - 100px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
[data-fixed-account] .dock-account[data-active="true"],
|
||||
[data-fixed-account] [aria-current="page"] {
|
||||
background: var(--color-row-active);
|
||||
color: var(--color-accent);
|
||||
}
|
||||
|
||||
.error-page {
|
||||
width: 100%;
|
||||
max-width: 680px;
|
||||
margin: clamp(24px, 8vh, 80px) auto;
|
||||
padding: 28px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 16px;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.error-page-symbol {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
margin-bottom: 24px;
|
||||
border-radius: 16px;
|
||||
color: var(--color-accent);
|
||||
background: var(--color-row-hover);
|
||||
}
|
||||
.error-page-code {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--color-muted);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.error-page h1 {
|
||||
font-size: clamp(24px, 3vw, 32px);
|
||||
line-height: 1.2;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.error-page-description {
|
||||
color: var(--color-muted);
|
||||
max-width: 60ch;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.error-page-reason {
|
||||
padding: 16px 18px;
|
||||
border-left: 3px solid var(--color-danger);
|
||||
border-radius: 0 10px 10px 0;
|
||||
background: color-mix(in srgb, var(--color-danger) 7%, var(--color-surface));
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.error-page-reason h2 {
|
||||
font-size: 14px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.error-page-reason p {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
margin: 0;
|
||||
}
|
||||
.error-page-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.error-preview-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
.error-page-reference {
|
||||
color: var(--color-muted);
|
||||
font-size: 12px;
|
||||
margin: 24px 0 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.error-page[data-error-status="banned"] .error-page-symbol {
|
||||
color: var(--color-danger);
|
||||
background: color-mix(in srgb, var(--color-danger) 10%, var(--color-surface));
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.error-page {
|
||||
margin-block: 20px;
|
||||
padding: 20px;
|
||||
}
|
||||
.error-page-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user