Keep account controls permanent and add system error pages
No files matched your search
@@ -15,3 +15,5 @@ Dock утверждён пользователем 30.11.2026 и являетс
|
||||
Панель задумана отдельным фронтендом, который делает API-запросы. Один Dock получает доступные разделы/группы как данные; не создавайте отдельную панель для каждого сервера. Контроллеры в components/dock.js и components/navigation.js не владеют запросами и маршрутизатором. Контракт примера — docs/PANEL-API.md. При обновлении меню сохраняйте доступную активную страницу, убирайте недоступные данные и отменяйте устаревшие запросы.
|
||||
|
||||
По уточнению пользователя Dock — сам сайт: root index.html сразу показывает приложение, внешняя оболочка и iframe удалены. Не возвращайте их. Hover/focus/active обязательны именно для пунктов бокового меню (Обзор, Пользователи и остальные).
|
||||
|
||||
Аккаунт и настройки аккаунта всегда остаются в нижней части единой панели, независимо от сервисных вкладок API и блокировки сервисов. account/account-settings — системные маршруты. API пока не существует: JSON в starter — fixtures, будущий контракт описан в docs/BACKEND-INTEGRATION.md. Ошибки используют общий error-page, бан — отдельное состояние banned с причиной текстом.
|
||||
@@ -5,6 +5,7 @@
|
||||
- Отдельный приватный пакет HTML/CSS/ESM: публичная точка входа, темы и три плотности, иконки, тосты, select с поиском, поле копирования, Dock и динамическое меню.
|
||||
- Одна панель получает доступные разделы из API и обновляет пункты/группы без перезагрузки. Предусмотрены смена активного раздела, удаление доступа, пустой ответ, ошибки и отмена устаревших запросов.
|
||||
- Самостоятельный frontend-пример с тестовыми API-ответами и контрактом для подключения реального backend.
|
||||
- Постоянные аккаунт и настройки вне динамического меню. Страницы HTTP-ошибок, сетевого сбоя и блокировки с причиной; руководство подключения будущего API.
|
||||
- Устанавливаемый Anidev Skill с локальными ресурсами, проектный установщик без перезаписи существующей версии и manifest с SHA-256.
|
||||
- Единая команда проверки перед релизом и тест подключения из изолированной копии пакета.
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@ node scripts/serve.mjs
|
||||
|
||||
Архивы после сборки: `npm pack ./dist/package --pack-destination dist` создаёт npm tarball, `npm run package:archives` — ZIP панели и Skill (нужен Python 3). Артефакты остаются в dist; исходники и сборщик хранятся в Git.
|
||||
|
||||
## Аккаунт и страницы ошибок
|
||||
|
||||
В отдельной панели аккаунт и настройки всегда доступны внизу Dock, даже при пустом меню сервисов. [Аккаунт](http://127.0.0.1:4173/dist/starter/?page=account) · [Настройки аккаунта](http://127.0.0.1:4173/dist/starter/?page=account-settings).
|
||||
|
||||
[Страницы ошибок](http://127.0.0.1:4173/?page=errors&status=404) включают 404/500/502 и другие HTTP-состояния, сетевой сбой и [блокировку с причиной](http://127.0.0.1:4173/?page=errors&status=banned). API пока нет: как фронт запрашивает меню, аккаунт и данные, описано в [руководстве подключения backend](docs/BACKEND-INTEGRATION.md).
|
||||
|
||||
## Иконки
|
||||
|
||||
[Каталог Dock Icons](http://127.0.0.1:4173/icons/) · [SVG-пак](icons/anidev-dock-icons.zip) · [Использование](icons/README.md).
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
# Как подключить будущий сервер к панели
|
||||
|
||||
Сервера API пока нет. Ниже — предлагаемый контракт, под который уже работает frontend-пример. JSON-файлы в examples/starter/api заменяют сервер только для просмотра и тестов. Реальной авторизации, отправки настроек и SSH в этом примере нет.
|
||||
|
||||
## Запуск фронта и замена API
|
||||
|
||||
1. Выполните `npm ci`, затем `npm run build:package`. Раздавайте содержимое dist/starter по HTTP. У него нет зависимости от приложения галереи и не требуется Node.js на сервере для отрисовки.
|
||||
2. Сейчас app.js задаёт `apiBase = new URL('./api/', import.meta.url)`. Для реального API измените эту базу и при необходимости функцию get(). Суффикс .json выбран для статических fixtures; будущий сервер может поддержать эти пути или адаптер get() может перевести их в его endpoints.
|
||||
3. Сначала фронт делает GET account.json, затем GET navigation.json. После выбора сервисной вкладки — GET pages/{id}.json. Аккаунт и настройки — локальные системные маршруты, не зависящие от ответа с меню.
|
||||
4. Фронт и API можно раздавать раздельно. Самый простой вариант подключения — обратный прокси /api под origin панели. При разных origin настройте CORS на конкретный origin и согласуйте cookies/токены со своей SSO-схемой. Пример использует credentials: same-origin. Секретные ключи в браузер не передаются.
|
||||
|
||||
## 1. Данные текущего аккаунта
|
||||
|
||||
`GET {apiBase}/account.json`, ответ 200, Content-Type: application/json:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "account-123",
|
||||
"name": "Анна Волкова",
|
||||
"email": "anna@example.test",
|
||||
"status": "active",
|
||||
"banReason": null
|
||||
}
|
||||
```
|
||||
|
||||
id/name/email — строки; status — active или banned; banReason — строка или null. Поля используются только для отображения. Настоящие права проверяет сервер в каждом endpoint.
|
||||
|
||||
Для заблокированного аккаунта верните 200 с status=banned и пользовательской причиной:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "account-123",
|
||||
"name": "Анна Волкова",
|
||||
"email": "anna@example.test",
|
||||
"status": "banned",
|
||||
"banReason": "Нарушение правил использования сервиса.\nОбратитесь к администратору для уточнения."
|
||||
}
|
||||
```
|
||||
|
||||
GET данных самого аккаунта и разрешённые личные настройки должны оставаться доступны после блокировки сервисов. Фронт показывает причину, скрывает сервисные разделы, сохраняет постоянный доступ к аккаунту/настройкам. Отсутствие причины отображается явно, не заменяется выдуманной причиной. Причина — обычный текст, не HTML; переносы строк сохраняются. Не отправляйте в ней внутренние служебные сведения, которые не предназначены владельцу аккаунта.
|
||||
|
||||
Если вход отсутствует/истёк — 401. Экран «Нужно войти в аккаунт» уже есть; реальный redirect/SSO login/logout ещё нужно связать с вашим провайдером. Кнопка аккаунта сама по себе не выполняет вход.
|
||||
|
||||
## 2. Доступные сервисные вкладки
|
||||
|
||||
`GET {apiBase}/navigation.json`, ответ 200:
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultPage": "overview",
|
||||
"items": [
|
||||
{ "id": "overview", "label": "Обзор", "icon": "dashboard" },
|
||||
{ "id": "projects", "label": "Проекты", "icon": "applications" },
|
||||
{
|
||||
"id": "administration",
|
||||
"label": "Администрирование",
|
||||
"icon": "server",
|
||||
"children": [{ "id": "logs", "label": "Логи", "icon": "document" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
API присылает только сервисные разделы. Аккаунт и настройки аккаунта находятся в постоянной нижней части Dock и не удаляются через items=[]. Идентификаторы account, account-settings, account-banned и префикс error- зарезервированы фронтом; в серверное меню их включать нельзя. Пустое items — корректный ответ: сервисов нет, личные страницы остаются.
|
||||
|
||||
До 100 элементов вместе с группами, уникальные id (буква, затем буквы/цифры/underscore/дефис, до 64 символов), label до 160 символов, icon из iconNames, необязательный disabled boolean. Один уровень children. Активная доступная вкладка сохраняется после обновления меню; при удалении текущей выбирается доступная, при пустом меню отображается пустое состояние. Прямая ссылка на неизвестный маршрут показывает 404; известный сервисный модуль без доступа — 403.
|
||||
|
||||
Статус доступа не передаётся произвольным исполняемым шаблоном. Добавление нового id на сервере не создаёт реализацию страницы: frontend должен иметь соответствующий модуль. В starter есть overview/projects/logs; новые экраны добавляются в локальный реестр pageIds и renderer, а не загружаются как код из API.
|
||||
|
||||
## 3. Содержимое выбранной вкладки
|
||||
|
||||
Пример `GET {apiBase}/pages/overview.json`, 200:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Обзор",
|
||||
"description": "Состояние сервисов проекта",
|
||||
"rows": [{ "label": "Identity", "value": "Работает · 18 мс" }]
|
||||
}
|
||||
```
|
||||
|
||||
title/description/label/value — строки; rows — массив. Это простая схема именно starter: фронт выводит до 100 строк. Реальные SSH, логи, таблицы и формы могут иметь собственные endpoints и схемы; общую панель при этом переписывать не нужно. Данные выводятся текстом. Loading/empty/error очищают прежнее содержимое; при смене страницы запрос отменяется, запоздалый ответ не заменяет актуальную страницу.
|
||||
|
||||
## 4. Ошибки и отзыв доступа
|
||||
|
||||
Сервисный endpoint возвращает настоящий HTTP-статус. Пример тела ошибки:
|
||||
|
||||
```json
|
||||
{ "error": { "code": "SERVICE_UNAVAILABLE", "requestId": "req-7f2c" } }
|
||||
```
|
||||
|
||||
Фронт различает 401/403/404/429/500/502/503/504 и другие описанные состояния; сетевой сбой отображается отдельно. Не возвращайте 200 с HTML-страницей ошибки. requestId — необязательный публичный идентификатор обращения, не stack trace. 400/422 при отправке форм обычно обрабатываются около конкретных полей; полноэкранный вариант предусмотрен как fallback. Повтор на готовых страницах повторяет чтение данных, не должен автоматически повторять необратимые команды.
|
||||
|
||||
Блокировка во время работы: сервисный запрос или обновление меню возвращает 403 и специальный code:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "ACCOUNT_BANNED",
|
||||
"reason": "Нарушение правил сервиса.",
|
||||
"requestId": "req-7f2c"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Обычный 403 показывает «Нет доступа» только к разделу; ACCOUNT_BANNED показывает отдельную страницу с причиной, убирает доступные сервисы и прежние данные. 401 при обновлении меню также очищает прежние сервисные данные. После снятия блокировки данные аккаунта нужно запросить заново; в starter это происходит при перезагрузке. В реальном приложении тот же refresh можно вызвать после события SSE/WebSocket или смены сессии.
|
||||
|
||||
Ошибка 5xx/сети при обновлении меню сохраняет предыдущую успешную конфигурацию и сообщает о сбое, не выдаёт её за отзыв прав. Реальную блокировку/отзыв сервер всё равно проверяет в каждом запросе.
|
||||
|
||||
## 5. Настройки и действия
|
||||
|
||||
В starter настройки аккаунта переключают тему только в текущей вкладке. PATCH/POST настроек пока не выполняются и не заявлены как сохранённые на сервере. Когда API будет готов, отдельно согласуйте endpoint предпочтений, валидацию и поля, после успешного сохранения показывайте success-тост; при отказе сохраняйте введённые данные и показывайте ошибку. Не используйте GET для изменений.
|
||||
|
||||
Для живого подключения потребуются: адрес API, схема авторизации/SSO, идентификаторы модулей, типы данных каждого экрана и endpoints команд. Это граница интеграции продукта; документация не требует заранее реализовывать SSR или BFF.
|
||||
|
||||
## Проверка до подключения
|
||||
|
||||
`npm run test:package` после сборки проверяет изолированную копию фронта на тестовом HTTP-сервере. `npm run test:system-pages` при работающей галерее проверяет страницы ошибок в обеих темах и RU/EN. Для просмотра: dist/starter/?page=account, ?page=account-settings, ?page=error-404, ?page=error-500, ?page=error-502, ?page=account-banned. Последняя ссылка — только демонстрация; реальное состояние задаётся ответом сервера.
|
||||
@@ -13,6 +13,8 @@ npm run build:package
|
||||
|
||||
## Подключение к приложению
|
||||
|
||||
Пока API нет, используйте тестовые JSON. Порядок запросов и форматы для будущего backend описаны в [контракте интеграции](BACKEND-INTEGRATION.md). Аккаунт и его настройки закреплены в панели и не входят в динамическое серверное меню.
|
||||
|
||||
Скопируйте содержимое `dist/package` в `anidev/` своего проекта. Подключите базовые стили и начальную тему до отрисовки страницы:
|
||||
|
||||
```html
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Панель — статически размещаемое приложение. API сообщает доступные разделы и предоставляет данные; панель выбирает локальный модуль по id. Ответ сервера не содержит исполняемого JavaScript или HTML. Один Dock обновляется через setItems, без перезагрузки shell.
|
||||
|
||||
Пока API отсутствует, используйте [полное руководство для будущего сервера](BACKEND-INTEGRATION.md): bootstrap аккаунта, зарезервированные маршруты, 401/403/блокировка, форматы ответов и запуск. Аккаунт и настройки — постоянные системные страницы вне items; серверное меню не может их удалить или подменить.
|
||||
|
||||
Starter использует локальные JSON-файлы как тестовые HTTP endpoints. Это предлагаемый контракт для интеграции, а не утверждение о существующих маршрутах сервера. `apiBase` и fetch-опции в app.js заменяются под реальный backend.
|
||||
|
||||
## Меню
|
||||
|
||||
@@ -18,6 +18,10 @@
|
||||
|
||||
## CSS-контракты
|
||||
|
||||
Дополнения к API: `mountAccountMenu(root,{onNavigate,t,name,email})` создаёт постоянный нижний блок с пунктами account и account-settings; возвращает update({name,email}), setActive(id), close(restoreFocus), dispose(). Он располагается отдельно от root.nav-links и не удаляется при setItems([]). Для системного экрана вызовите navigation.clearActive(), чтобы сервисный пункт не оставался текущим; метод очищает aria-current и сообщает onActiveChange(null).
|
||||
|
||||
`errorStatuses` содержит поддерживаемые состояния. `errorPageMarkup({status,reason,requestId,t,id,support})` возвращает страницу ошибки; неизвестный status отображается как 500. reason выводится только для banned, как текст с сохранением переносов; без причины есть явное пояснение. `mountErrorPage(root,{onRetry,onHome,onAccount,onSupport})` подключает действия и возвращает cleanup; кнопки без обработчика отключены. support включайте только при наличии реального обработчика обращения. Готовые состояния: 400/401/403/404/408/409/410/422/429/500/502/503/504, offline и banned.
|
||||
|
||||
Токены: `tokens/dock/{light,dark}.{css,json}`. Генератор и три плотности остаются источником значений. Основные поверхности: --color-bg/surface/text/muted/border/accent; состояния: success/warning/danger/row-hover/row-active. Не переопределяйте тему десятками локальных цветов.
|
||||
|
||||
Разметка: `.shell`, `.navigation`, `.dock-brand.wordmark`, `.nav-links`, `.main-column`, `main#content` задают Dock. Поля используют `.field`, копирование — `.copy-input` и `.input-copy-action`. Выбор: native input внутри `.choice-pill` или fieldset/legend с общей `.choice-group` и `.choice-group-option`; `--vertical` задаёт столбец. Buttons: `.primary`, `.danger`, native disabled и aria-busy. Диалоги — native dialog.showModal(). Подробности и остальные образцы — [контракт компонентов](../components/CONTRACT.md).
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
- Один утверждённый Dock, обе темы, три плотности, общие иконки и состояния компонентов.
|
||||
- Отдельный пакет без маршрутов и Identity-данных галереи; публичный API и контракты cleanup.
|
||||
- Самостоятельная API-панель: динамические пункты/группы, обработка недоступного активного раздела, отмена устаревших запросов.
|
||||
- Постоянные аккаунт/настройки, общие страницы ошибок и блокировка с причиной. Контракт будущего backend описан до появления API; пример продолжает использовать fixtures.
|
||||
- Skill с автономными ресурсами; установка в проект и фиксация версии.
|
||||
- Пример потребителя, построенный из копии пакета; проверки manifest, импортов, взаимодействий и ссылок Skill.
|
||||
- Changelog, правила обновления, сохранённые MIT notices терминала и одна команда `npm run test:release`.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"build:package": "node scripts/check.mjs && node scripts/build-package.mjs",
|
||||
"package:archives": "python scripts/package-release.py",
|
||||
"test:package": "node tests/package.mjs",
|
||||
"test:system-pages": "node tests/system-pages.mjs",
|
||||
"test:release": "node scripts/test-release.mjs",
|
||||
"test:select": "node tests/search-select.mjs",
|
||||
"terminal:vendor": "node scripts/vendor-terminal.mjs",
|
||||
|
||||
@@ -5,6 +5,11 @@ import {
|
||||
} from "../components/search-select.js";
|
||||
import { createNotifier } from "../components/toast.js";
|
||||
import { mountCopyField } from "../components/copy-field.js";
|
||||
import {
|
||||
errorPageMarkup,
|
||||
errorStatuses,
|
||||
mountErrorPage,
|
||||
} from "../components/error-page.js";
|
||||
import { sshScreen, mountSsh } from "../components/ssh-console.js";
|
||||
import { logsScreen, mountLogs } from "../components/log-reader.js";
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
@@ -172,6 +177,7 @@ let page = [
|
||||
"tokens",
|
||||
"ssh",
|
||||
"logs",
|
||||
"errors",
|
||||
...accountPageIds,
|
||||
].includes(params.get("page"))
|
||||
? params.get("page")
|
||||
@@ -185,6 +191,7 @@ let query = "",
|
||||
tab = "general",
|
||||
chartRange = "24h";
|
||||
const pageNames = {
|
||||
errors: t("Страницы ошибок", "Error pages"),
|
||||
ssh: t("SSH-консоль", "SSH console"),
|
||||
logs: t("Журнал событий", "Log reader"),
|
||||
dashboard: t("Обзор", "Overview"),
|
||||
@@ -202,7 +209,12 @@ const pageNames = {
|
||||
};
|
||||
const icon = (id) =>
|
||||
iconSvg(
|
||||
{ ssh: "terminal", logs: "document", administration: "server" }[id] || id,
|
||||
{
|
||||
ssh: "terminal",
|
||||
logs: "document",
|
||||
administration: "server",
|
||||
errors: "warning",
|
||||
}[id] || id,
|
||||
{
|
||||
className: "nav-icon",
|
||||
},
|
||||
@@ -406,7 +418,7 @@ function render({ preserveDock = false } = {}) {
|
||||
const content = accountPageIds.includes(page)
|
||||
? accountUI.renderPage(page)
|
||||
: identityAdapter.snapshot().status !== "authenticated" &&
|
||||
!["components", "tokens", "auth"].includes(page)
|
||||
!["components", "tokens", "auth", "errors"].includes(page)
|
||||
? accountUI.gate()
|
||||
: ["dashboard", "users", "settings", "ssh", "logs"].includes(page) &&
|
||||
!currentIdentity()?.roles.some((r) =>
|
||||
@@ -420,6 +432,7 @@ function render({ preserveDock = false } = {}) {
|
||||
users: userScreen,
|
||||
settings: settingsScreen,
|
||||
components: componentScreen,
|
||||
errors: errorScreen,
|
||||
tokens: tokenScreen,
|
||||
}[page]?.() || "";
|
||||
$("#app").innerHTML =
|
||||
@@ -431,6 +444,33 @@ function render({ preserveDock = false } = {}) {
|
||||
bindDockHover();
|
||||
if (dockWasOpen) setDockOpen(true, false);
|
||||
bindCharts();
|
||||
if (page === "errors") {
|
||||
selectCleanups.push(
|
||||
mountErrorPage($("[data-error-status]"), {
|
||||
onRetry: () =>
|
||||
toast(
|
||||
t(
|
||||
"Это пример страницы ошибки. Реальный запрос не выполняется.",
|
||||
"This is an error page preview. No request is sent.",
|
||||
),
|
||||
),
|
||||
onHome: () => {
|
||||
page = "components";
|
||||
render();
|
||||
},
|
||||
onAccount: () => {
|
||||
page = "profile";
|
||||
render();
|
||||
},
|
||||
}),
|
||||
);
|
||||
$("#error-preview-status").addEventListener("change", (event) => {
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set("status", event.target.value);
|
||||
history.replaceState({}, "", url);
|
||||
render();
|
||||
});
|
||||
}
|
||||
document
|
||||
.querySelectorAll(".copy-input")
|
||||
.forEach((root) =>
|
||||
@@ -677,8 +717,14 @@ function settingsScreen() {
|
||||
function auth() {
|
||||
return `<main id="content" class="auth-layout" style="max-width:none;padding:0"><section class="auth-brand">${wordmark}<div class="auth-statement">${t("Ваша инфраструктура.<br>Под вашим контролем.", "Your infrastructure.<br>Under your control.")}</div><small>ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}</small></section><section class="auth-main"><form id="auth-form" class="auth-form"><h1>${t("Вход в Anidev", "Sign in to Anidev")}</h1><p>${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}</p><label class="field">${t("Username или email", "Username or email")}<input name="email" type="text" autocomplete="username" placeholder="anna.volkova" required></label><label class="field">${t("Пароль", "Password")}<input name="password" type="password" autocomplete="current-password" minlength="8" required aria-describedby="password-hint"><small id="password-hint">${t("Демо: anna.volkova или mikhail.orlov; пароль от 8 символов.", "Demo: anna.volkova or mikhail.orlov; password of 8+ characters.")}</small></label><div class="form-row"><input id="remember" type="checkbox"><label for="remember">${t("Запомнить меня", "Remember me")}</label><button class="row-action" type="button" data-action="recover">${t("Забыли пароль?", "Forgot password?")}</button></div><p class="error-text" id="auth-error" role="alert"></p><button class="primary" type="submit">${t("Войти", "Sign in")}</button><div class="auth-divider">${t("или корпоративный аккаунт", "or your company account")}</div><button type="button" class="sso" data-action="sso">${t("Войти через SSO", "Continue with SSO")}</button><div class="auth-foot"><span>© Anidev 2026</span><button class="row-action" type="button" data-page="dashboard">${t("Вернуться к обзору", "Back to overview")}</button></div></form></section></main>`;
|
||||
}
|
||||
function errorScreen() {
|
||||
const requested = new URL(location.href).searchParams.get("status") || "404";
|
||||
const status =
|
||||
errorStatuses.find((value) => String(value) === requested) ?? 500;
|
||||
return `<div class="error-preview-controls"><label for="error-preview-status">${t("Состояние", "State")}</label><select id="error-preview-status">${errorStatuses.map((value) => `<option value="${value}" ${value === status ? "selected" : ""}>${value === "banned" ? t("Аккаунт заблокирован", "Account suspended") : value === "offline" ? t("Нет соединения", "Connection unavailable") : value}</option>`).join("")}</select><button data-page="components">${t("К компонентам", "Components")}</button></div>${errorPageMarkup({ status, t, reason: t("Повторное нарушение правил сервиса.\nЭто демонстрационный пример причины блокировки.", "Repeated violations of service rules.\nThis is a sample suspension reason."), requestId: "demo-7f2c" })}`;
|
||||
}
|
||||
function componentScreen() {
|
||||
return `${heading(t("Библиотека компонентов", "Component library"), t("Единые компоненты и состояния Dock.", "Shared Dock components and states."), `<button data-action="command">${t("Команды", "Commands")} ${commandShortcut}</button>`)}<div class="page-body"><div class="library">
|
||||
return `${heading(t("Библиотека компонентов", "Component library"), t("Единые компоненты и состояния Dock.", "Shared Dock components and states."), `<button data-page="errors">${t("Страницы ошибок", "Error pages")}</button><button data-action="command">${t("Команды", "Commands")} ${commandShortcut}</button>`)}<div class="page-body"><div class="library">
|
||||
<section class="specimen"><h2>Buttons</h2><div class="component-row"><button class="primary" data-action="demo-save">${t("Сохранить", "Save")}</button><button data-action="toast">${t("Вторичная", "Secondary")}</button><button class="danger" data-action="delete">${t("Удалить", "Delete")}</button><button disabled>Disabled</button><button aria-busy="true" disabled>${t("Загрузка…", "Loading…")}</button></div><small>Hover · active · focus · disabled · loading</small></section>
|
||||
<section class="specimen"><h2>Inputs & selects</h2><label class="field">${t("Имя проекта", "Project name")}<input placeholder="Anidev Production"></label><label class="field">Email<input aria-invalid="true" aria-describedby="sample-error" value="invalid-email"><small class="error-text" id="sample-error">${t("Введите корректный email", "Enter a valid email")}</small></label><div class="sample-control-row"><select aria-label="${t("Окружение", "Environment")}"><option>Production</option><option>Staging</option></select><input aria-label="${t("Только для чтения", "Read-only field")}" readonly value="Read only"></div><div class="search-select-example">${searchSelectMarkup({ id: "environment-search", name: "searchEnvironment", label: t("Окружение — с поиском", "Environment — searchable"), options: environmentOptions, value: "production", t })}</div><div class="field copy-field-example"><label for="copy-input-example">${t("Строка с копированием", "Field with copy action")}</label><div class="copy-input"><button type="button" class="input-copy-action" data-copy-input aria-label="${t("Скопировать значение", "Copy field value")}" title="${t("Скопировать значение", "Copy field value")}">${iconSvg("copy", { size: 16 })}</button><input id="copy-input-example" name="copyExample" value="anidev-production" autocomplete="off"></div></div></section>
|
||||
<section class="specimen selection-specimen"><h2>Selection controls</h2><div class="form-row"><label class="choice-pill" for="check-demo"><input id="check-demo" type="checkbox" checked><span>${t("Email-уведомления", "Email notifications")}</span></label></div><fieldset style="border:0;padding:0"><legend>${t("Период хранения", "Retention period")}</legend><div class="component-row"><label class="choice-pill"><input type="radio" name="retention" value="30" checked><span>30 ${t("дней", "days")}</span></label><label class="choice-pill"><input type="radio" name="retention" value="90"><span>90 ${t("дней", "days")}</span></label></div></fieldset><div class="form-row"><label for="switch-demo">${t("Автообновление", "Auto refresh")}</label><input id="switch-demo" class="switch" role="switch" type="checkbox" checked></div></section>
|
||||
|
||||
@@ -157,3 +157,11 @@ Log reader: фильтры уровня/сервиса/текста, подсв
|
||||
Единая команда scripts/test-release.mjs поднимает собственный сервер на свободном порту и завершает его после прохода. Результат в Edge: Browser 50, Dock 10, Approved 24, Site 35, Identity 94, TOTP 4, Icons 91, Workspaces 83, Navigation/feedback 79, Search-select 6, Package 19 — всего 495 проверок, без ошибок JavaScript. Скриншоты отдельного приложения просмотрены: references/integration. Последняя пересборка документации проверяется package-suite отдельно.
|
||||
|
||||
Это не выпуск 1.0 и не полный аудит доступности. Настоящие API/SSO ещё не подключены; API endpoints starter — тестовые JSON. Firefox/Safari и ручной скринридер не проверены, CI-runner на Git-сервере не настраивался. Критерии следующего этапа: docs/RELEASE-1.0.md.
|
||||
|
||||
## Постоянный аккаунт и системные страницы / 01.12.2026
|
||||
|
||||
Аккаунт и настройки вынесены в отдельный нижний блок вне сервисных items. Они переживают пустое меню, обновление конфигурации и блокировку сервисов. Проверены открытие и выбор меню, смена темы в настройках, перезагрузка личного маршрута, возвращение в сервисную страницу, clearActive и cleanup native popover.
|
||||
|
||||
Общий error-page покрывает 400/401/403/404/408/409/410/422/429/500/502/503/504, offline и banned. Для blocked/banned есть отдельная причина текстом, переносы, fallback без причины и публичный reference. В галерее есть переключаемые образцы, в starter HTTP-ошибки чтения показываются как страницы, неизвестный маршрут — 404, недоступный модуль — 403. ACCOUNT_BANNED отличается от обычного 403, очищает сервисы и прежние данные; 401 при обновлении меню также убирает защищённое содержимое.
|
||||
|
||||
Текущая проверка: Browser 50, System pages 183 (темы × RU/EN × 1440/768/390 и поведение), Package 29 — 262 сценарных проверки без ошибок JavaScript. scripts/check.mjs проходит. Причины/идентификаторы проверены на безопасный вывод текста, выбор ошибки и действия — в браузере; скриншоты references/system-pages просмотрены. API ещё не существует: запуск фронта, порядок запросов, схемы и будущие границы интеграции описаны в docs/BACKEND-INTEGRATION.md. Реальный backend и SSO не подключались.
|
||||
|
Before Width: | Height: | Size: 41 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 41 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"passed": 183,
|
||||
"errors": [],
|
||||
"checks": "All status pages in both themes/RU/EN/three widths; preview actions/fallback; escaped reason/reference, missing reason, cleanup, account access"
|
||||
}
|
||||
@@ -6,6 +6,12 @@ export {
|
||||
} from "../components/search-select.js";
|
||||
export { mountCopyField } from "../components/copy-field.js";
|
||||
export { mountDock } from "../components/dock.js";
|
||||
export { mountAccountMenu } from "../components/account-menu.js";
|
||||
export {
|
||||
errorStatuses,
|
||||
errorPageMarkup,
|
||||
mountErrorPage,
|
||||
} from "../components/error-page.js";
|
||||
export {
|
||||
mountNavigation,
|
||||
validateNavigation,
|
||||
|
||||
@@ -47,6 +47,8 @@ for (const file of [
|
||||
"components/copy-field.js",
|
||||
"components/dock.js",
|
||||
"components/navigation.js",
|
||||
"components/account-menu.js",
|
||||
"components/error-page.js",
|
||||
"components/ssh-console.js",
|
||||
"components/log-reader.js",
|
||||
"patterns/demo-pty.js",
|
||||
@@ -79,6 +81,7 @@ await writeFile(
|
||||
path.join(pkg, "README.md"),
|
||||
integration
|
||||
.replaceAll("(PUBLIC-API.md)", "(docs/PUBLIC-API.md)")
|
||||
.replaceAll("(BACKEND-INTEGRATION.md)", "(docs/BACKEND-INTEGRATION.md)")
|
||||
.replaceAll("(../NOTICE.md)", "(NOTICE.md)"),
|
||||
);
|
||||
const publicApi = await readFile(path.join(root, "docs/PUBLIC-API.md"), "utf8");
|
||||
@@ -89,6 +92,10 @@ await writeFile(
|
||||
.replaceAll("(../patterns/", "(patterns/"),
|
||||
);
|
||||
await copy("docs/PANEL-API.md", path.join(pkg, "docs/PANEL-API.md"));
|
||||
await copy(
|
||||
"docs/BACKEND-INTEGRATION.md",
|
||||
path.join(pkg, "docs/BACKEND-INTEGRATION.md"),
|
||||
);
|
||||
await copy("NOTICE.md", path.join(pkg, "NOTICE.md"));
|
||||
await writeFile(
|
||||
path.join(pkg, "package.json"),
|
||||
|
||||
@@ -58,6 +58,7 @@ try {
|
||||
"navigation-feedback",
|
||||
"search-select",
|
||||
"package",
|
||||
"system-pages",
|
||||
]) {
|
||||
console.log(`\nChecking ${name}`);
|
||||
await run(`tests/${name}.mjs`, env);
|
||||
|
||||
@@ -25,6 +25,8 @@ One document owns one Dock and a document-wide theme. The rail is compact, expan
|
||||
|
||||
The host can be an independent frontend that calls an API. Treat available sections as data: update items/groups through mountNavigation rather than hardcoding one panel per service. The host owns routes and active content; the server authorizes every operation regardless of menu visibility. Render API strings as text. Use loading/empty/error states and cancel stale requests during navigation. Do not introduce a backend proxy unless the product requires it.
|
||||
|
||||
Account and account settings always remain available in the fixed bottom block, outside the API-driven service items. An empty service list must not remove them. Use mountAccountMenu for the starter, clear the service aria-current on account routes, and keep personal pages reachable when service access is suspended. Use shared error pages for 404/5xx/network failures; account suspension is a separate banned state with a plain-text reason, not a generic 403. Read [backend integration](assets/anidev/docs/BACKEND-INTEGRATION.md) when wiring the future API; fixtures do not imply that a real backend already exists.
|
||||
|
||||
Use semantic tokens for surfaces, text and states; preserve native form controls, associated labels, keyboard behavior and focus return. Related checkboxes may share horizontal or vertical capsules. Status includes words and an icon when useful, rather than relying on color. Toasts report results without stealing focus. Terminal surfaces remain black in either theme.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -99,6 +99,11 @@ let config = structuredClone(original),
|
||||
configDelay = 0,
|
||||
failMenu = false,
|
||||
failPage = false;
|
||||
let account = JSON.parse(
|
||||
await readFile(path.join(consumer, "api/account.json"), "utf8"),
|
||||
),
|
||||
pageFailure = null,
|
||||
menuFailure = null;
|
||||
const pageDelays = {};
|
||||
const mime = {
|
||||
".html": "text/html",
|
||||
@@ -111,7 +116,24 @@ const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url, "http://localhost"),
|
||||
pathname = decodeURIComponent(url.pathname);
|
||||
if (pathname === "/api/account.json") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(account));
|
||||
return;
|
||||
}
|
||||
if (pageFailure && pathname.startsWith("/api/pages/")) {
|
||||
res.writeHead(pageFailure.status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(pageFailure.body));
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/navigation.json") {
|
||||
if (menuFailure) {
|
||||
res.writeHead(menuFailure.status, {
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
res.end(JSON.stringify(menuFailure.body));
|
||||
return;
|
||||
}
|
||||
const snapshot = JSON.stringify(config),
|
||||
delay = configDelay;
|
||||
if (failMenu) {
|
||||
@@ -252,6 +274,13 @@ try {
|
||||
path: "references/integration/dynamic-menu-dark.png",
|
||||
});
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(
|
||||
await page
|
||||
.locator(".dock-account")
|
||||
.evaluate((e) => e === document.activeElement),
|
||||
true,
|
||||
);
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(
|
||||
await page
|
||||
.locator(".dock-brand")
|
||||
@@ -259,6 +288,13 @@ try {
|
||||
true,
|
||||
);
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
assert.equal(
|
||||
await page
|
||||
.locator(".dock-account")
|
||||
.evaluate((e) => e === document.activeElement),
|
||||
true,
|
||||
);
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
assert.equal(
|
||||
await page.evaluate(() => document.activeElement?.dataset.navId),
|
||||
"logs",
|
||||
@@ -304,10 +340,7 @@ try {
|
||||
await page.locator("#refresh-navigation").click();
|
||||
await page.locator('[data-nav-id="injected"]').waitFor();
|
||||
assert.equal(await page.locator(".navigation img").count(), 0);
|
||||
await page
|
||||
.locator("#page-title")
|
||||
.filter({ hasText: "Раздел недоступен" })
|
||||
.waitFor();
|
||||
await page.locator('[data-error-status="404"]').waitFor();
|
||||
passed++;
|
||||
config = { items: [{ id: "bad", label: "Bad", icon: "unknown" }] };
|
||||
await page.locator("#refresh-navigation").click();
|
||||
@@ -334,10 +367,7 @@ try {
|
||||
await page.locator(".dock-brand").click();
|
||||
await page.locator('[data-nav-id="projects"]').click();
|
||||
await page.keyboard.press("Escape");
|
||||
await page
|
||||
.locator("#page-title")
|
||||
.filter({ hasText: "Раздел недоступен" })
|
||||
.waitFor();
|
||||
await page.locator('[data-error-status="503"]').waitFor();
|
||||
failPage = false;
|
||||
await page.getByRole("button", { name: "Повторить", exact: true }).click();
|
||||
await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor();
|
||||
@@ -358,9 +388,131 @@ try {
|
||||
assert.equal(await page.locator("#page-title").innerText(), "Логи");
|
||||
pageDelays["/api/pages/overview.json"] = 0;
|
||||
passed++;
|
||||
// Fixed account routes survive an empty service menu and reloads.
|
||||
config = { items: [] };
|
||||
await page.locator("#refresh-navigation").click();
|
||||
await page
|
||||
.locator("#page-title")
|
||||
.filter({ hasText: "Нет доступных разделов" })
|
||||
.waitFor();
|
||||
await page.locator(".dock-brand").click();
|
||||
await page.locator(".dock-account").click();
|
||||
await page.locator('[data-account-page="account"]').click();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator("#page-title").filter({ hasText: "Аккаунт" }).waitFor();
|
||||
assert.equal(await page.locator("[data-nav-id]").count(), 0);
|
||||
await page
|
||||
.getByRole("button", { name: "Настройки аккаунта", exact: true })
|
||||
.click();
|
||||
await page.locator('input[name="account-theme"][value="light"]').check();
|
||||
assert.equal(await page.locator("body").getAttribute("data-theme"), "light");
|
||||
await page.reload();
|
||||
await page
|
||||
.locator("#page-title")
|
||||
.filter({ hasText: "Настройки аккаунта" })
|
||||
.waitFor();
|
||||
passed++;
|
||||
// Normal service clicks still render after leaving a fixed account route.
|
||||
config = structuredClone(original);
|
||||
await page.locator("#refresh-navigation").click();
|
||||
await page.locator('[data-nav-id="projects"]').waitFor();
|
||||
assert.equal(
|
||||
new URL(page.url()).searchParams.get("page"),
|
||||
"account-settings",
|
||||
);
|
||||
await page.locator(".dock-brand").click();
|
||||
await page.locator('[data-nav-id="projects"]').click();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator("#page-title").filter({ hasText: "Проекты" }).waitFor();
|
||||
passed++;
|
||||
// Live ban: plain 403 is distinct from ACCOUNT_BANNED and never leaks HTML.
|
||||
pageFailure = { status: 403, body: { error: { code: "FORBIDDEN" } } };
|
||||
await page.locator(".dock-brand").click();
|
||||
await page.locator('[data-nav-id="overview"]').click();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator('[data-error-status="403"]').waitFor();
|
||||
assert.equal(await page.locator(".error-page-reason").count(), 0);
|
||||
passed++;
|
||||
pageFailure = {
|
||||
status: 403,
|
||||
body: {
|
||||
error: {
|
||||
code: "ACCOUNT_BANNED",
|
||||
reason: "<img src=x>\nПричина из API",
|
||||
requestId: "req-test",
|
||||
},
|
||||
},
|
||||
};
|
||||
await page.locator(".dock-brand").click();
|
||||
await page.locator('[data-nav-id="projects"]').click();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator('[data-error-status="banned"]').waitFor();
|
||||
assert.equal(await page.locator(".error-page-reason img").count(), 0);
|
||||
assert.equal(
|
||||
await page.locator(".error-page-reason p").innerText(),
|
||||
"<img src=x>\nПричина из API",
|
||||
);
|
||||
assert.equal(await page.locator("[data-nav-id]").count(), 0);
|
||||
assert.equal(await page.locator(".integration-form").isVisible(), false);
|
||||
await page.locator('[data-error-action="account"]').click();
|
||||
await page.locator("#page-title").filter({ hasText: "Аккаунт" }).waitFor();
|
||||
passed++;
|
||||
// Server reports a ban at bootstrap; account/settings remain reachable.
|
||||
pageFailure = null;
|
||||
account = {
|
||||
...account,
|
||||
status: "banned",
|
||||
banReason: "Блокировка на сервере",
|
||||
};
|
||||
await page.goto(origin + "/?page=logs");
|
||||
await page.locator('[data-error-status="banned"]').waitFor();
|
||||
assert.equal(await page.locator("[data-nav-id]").count(), 0);
|
||||
await page.locator('[data-error-action="account"]').click();
|
||||
await page
|
||||
.getByRole("button", { name: "Настройки аккаунта", exact: true })
|
||||
.click();
|
||||
await page
|
||||
.locator("#page-title")
|
||||
.filter({ hasText: "Настройки аккаунта" })
|
||||
.waitFor();
|
||||
passed++;
|
||||
account = { ...account, status: "active", banReason: null };
|
||||
await page.goto(origin + "/?page=missing-page");
|
||||
await page.locator('[data-error-status="404"]').waitFor();
|
||||
await page.locator('[data-error-action="home"]').click();
|
||||
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
|
||||
passed++;
|
||||
config = { items: [] };
|
||||
await page.goto(origin + "/?page=logs");
|
||||
await page.locator('[data-error-status="403"]').waitFor();
|
||||
passed++;
|
||||
config = structuredClone(original);
|
||||
await page.goto(origin + "/?page=overview");
|
||||
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
|
||||
menuFailure = { status: 401, body: { error: { code: "UNAUTHENTICATED" } } };
|
||||
await page.locator("#refresh-navigation").click();
|
||||
await page.locator('[data-error-status="401"]').waitFor();
|
||||
assert.equal(await page.locator("[data-nav-id]").count(), 0);
|
||||
assert.equal(await page.locator(".resource-row").count(), 0);
|
||||
passed++;
|
||||
menuFailure = {
|
||||
status: 403,
|
||||
body: { error: { code: "ACCOUNT_BANNED", reason: "Изменение доступа" } },
|
||||
};
|
||||
await page.locator("#refresh-navigation").click();
|
||||
await page.locator('[data-error-status="banned"]').waitFor();
|
||||
await page.locator('[data-error-action="account"]').click();
|
||||
await page.locator("#page-title").filter({ hasText: "Аккаунт" }).waitFor();
|
||||
passed++;
|
||||
menuFailure = null;
|
||||
// Core modules also work independently of the starter's host logic.
|
||||
await page.goto(origin + "/?page=error-502");
|
||||
await page.locator('[data-error-status="502"]').waitFor();
|
||||
assert.equal(await page.locator(".error-page-code").innerText(), "502");
|
||||
assert.equal(await page.locator(".integration-form").isVisible(), false);
|
||||
passed++;
|
||||
await page.evaluate(async () => {
|
||||
const { createNotifier, mountCopyField } =
|
||||
const { createNotifier, mountCopyField, mountAccountMenu } =
|
||||
await import("/anidev/runtime/index.js");
|
||||
const toast = document.createElement("div");
|
||||
document.body.append(toast);
|
||||
@@ -389,6 +541,18 @@ try {
|
||||
cleanup();
|
||||
root.remove();
|
||||
toast.remove();
|
||||
const accountRoot = document.createElement("div");
|
||||
document.body.append(accountRoot);
|
||||
const menu = mountAccountMenu(accountRoot, { onNavigate: () => {} }),
|
||||
trigger = accountRoot.querySelector(".dock-account");
|
||||
trigger.click();
|
||||
if (!accountRoot.querySelector(".account-menu").matches(":popover-open"))
|
||||
throw Error("Account menu did not open");
|
||||
menu.dispose();
|
||||
trigger.click();
|
||||
if (accountRoot.querySelector(".account-menu").matches(":popover-open"))
|
||||
throw Error("Account menu survived dispose");
|
||||
accountRoot.remove();
|
||||
});
|
||||
passed++;
|
||||
assert.ok(requests.every((url) => url.startsWith(origin + "/")));
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { chromium } from "playwright";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { errorStatuses } from "../components/error-page.js";
|
||||
const base = process.env.BASE_URL || "http://127.0.0.1:4173";
|
||||
const browser = await chromium.launch({
|
||||
executablePath:
|
||||
process.env.PLAYWRIGHT_EXECUTABLE_PATH ||
|
||||
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
|
||||
headless: true,
|
||||
});
|
||||
const page = await browser.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await mkdir("references/system-pages", { recursive: true });
|
||||
let passed = 0;
|
||||
try {
|
||||
for (const theme of ["light", "dark"])
|
||||
for (const locale of ["ru", "en"])
|
||||
for (const width of [1440, 768, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.goto(
|
||||
`${base}/?page=errors&status=404&theme=${theme}&locale=${locale}`,
|
||||
);
|
||||
for (const status of errorStatuses) {
|
||||
await page
|
||||
.locator("#error-preview-status")
|
||||
.selectOption(String(status));
|
||||
const card = page.locator(`[data-error-status="${status}"]`);
|
||||
await card.waitFor();
|
||||
assert.equal(await page.locator("#content h1").count(), 1);
|
||||
assert.ok(await card.locator("h1").innerText());
|
||||
if (typeof status === "number")
|
||||
assert.equal(
|
||||
await card.locator(".error-page-code").innerText(),
|
||||
String(status),
|
||||
);
|
||||
if (status === "banned")
|
||||
assert.ok(await card.locator(".error-page-reason p").innerText());
|
||||
assert.equal(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
),
|
||||
true,
|
||||
);
|
||||
const rect = await card.boundingBox();
|
||||
assert.ok(rect.x >= 0 && rect.x + rect.width <= width);
|
||||
if (
|
||||
locale === "ru" &&
|
||||
width !== 768 &&
|
||||
[404, 500, 502, "banned"].includes(status)
|
||||
)
|
||||
await card.screenshot({
|
||||
path: `references/system-pages/${status}-${theme}-${width}.png`,
|
||||
});
|
||||
passed++;
|
||||
}
|
||||
}
|
||||
await page.goto(`${base}/?page=errors&status=599&locale=ru`);
|
||||
await page.locator('[data-error-status="500"]').waitFor();
|
||||
await page.getByRole("button", { name: "Повторить", exact: true }).click();
|
||||
await page.locator("#toast:popover-open").waitFor();
|
||||
await page.locator("[data-toast-dismiss]").click();
|
||||
await page
|
||||
.getByRole("button", { name: "К доступным разделам", exact: true })
|
||||
.click();
|
||||
await page
|
||||
.getByRole("button", { name: "Страницы ошибок", exact: true })
|
||||
.click();
|
||||
await page.locator("#error-preview-status").waitFor();
|
||||
passed++;
|
||||
await page.evaluate(async () => {
|
||||
const { errorPageMarkup, mountErrorPage } =
|
||||
await import("/components/error-page.js");
|
||||
const root = document.createElement("div");
|
||||
const numeric = document.createElement("div");
|
||||
numeric.innerHTML = errorPageMarkup({ status: "502", id: "numeric-code" });
|
||||
if (numeric.querySelector(".error-page-code").textContent !== "502")
|
||||
throw Error("Numeric string status lost");
|
||||
root.innerHTML = errorPageMarkup({
|
||||
id: "safety-example",
|
||||
status: "banned",
|
||||
reason: "<img src=x onerror=alert(1)>\nПричина из API",
|
||||
requestId: "<script>bad</script>",
|
||||
});
|
||||
document.body.append(root);
|
||||
if (root.querySelector("img,script"))
|
||||
throw Error("Error page did not escape server strings");
|
||||
if (
|
||||
!root.querySelector(".error-page-reason p").textContent.includes("<img")
|
||||
)
|
||||
throw Error("Reason text lost");
|
||||
let clicked = 0;
|
||||
const cleanup = mountErrorPage(root, { onAccount: () => clicked++ });
|
||||
root.querySelector("button").click();
|
||||
cleanup();
|
||||
root.querySelector("button").click();
|
||||
if (clicked !== 1) throw Error("Error page handlers survived cleanup");
|
||||
root.remove();
|
||||
const missing = document.createElement("div");
|
||||
missing.innerHTML = errorPageMarkup({
|
||||
id: "missing-reason",
|
||||
status: "banned",
|
||||
});
|
||||
if (
|
||||
!missing
|
||||
.querySelector(".error-page-reason")
|
||||
.textContent.includes("Причина не указана")
|
||||
)
|
||||
throw Error("Missing reason fallback");
|
||||
});
|
||||
passed++;
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await page.goto(`${base}/?page=errors&status=banned&theme=dark&locale=ru`);
|
||||
await page.locator('[data-error-action="account"]').click();
|
||||
assert.equal(new URL(page.url()).searchParams.get("page"), "profile");
|
||||
passed++;
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile(
|
||||
"references/system-pages/qa.json",
|
||||
JSON.stringify(
|
||||
{
|
||||
passed,
|
||||
errors,
|
||||
checks:
|
||||
"All status pages in both themes/RU/EN/three widths; preview actions/fallback; escaped reason/reference, missing reason, cleanup, account access",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log(`System pages: ${passed} checks passed, no runtime errors`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||