Separate guest and panel navigation and add account flyout

This commit is contained in:
SantaSpeen committed 2026-12-01 16:04:40 +03:00
1 parent 60b584b7c1
commit 5852bf1897
42 files changed
+1024 -55

No files matched your search

+2
View File
@@ -17,3 +17,5 @@ Dock утверждён пользователем 30.11.2026 и являетс
По уточнению пользователя Dock — сам сайт: root index.html сразу показывает приложение, внешняя оболочка и iframe удалены. Не возвращайте их. Hover/focus/active обязательны именно для пунктов бокового меню (Обзор, Пользователи и остальные).
Аккаунт и настройки аккаунта всегда остаются в нижней части единой панели, независимо от сервисных вкладок API и блокировки сервисов. account/account-settings — системные маршруты. API пока не существует: JSON в starter — fixtures, будущий контракт описан в docs/BACKEND-INTEGRATION.md. Ошибки используют общий error-page, бан — отдельное состояние banned с причиной текстом.
Уточнение: постоянный аккаунт существует только после входа. Без подтверждённой сессии нет Dock/шапки/подложки — только вход или состояние. Пользовательская и административная панели имеют разные Dock; личное управление убрано из основного nav. В строке «Аккаунт» — боковое подменю Управление/Безопасность/Устройства и сеансы/Настройки; обычный клик по строке открывает Управление. Учитывайте hover, клавиатуру и touch.
+1
View File
@@ -6,6 +6,7 @@
- Одна панель получает доступные разделы из API и обновляет пункты/группы без перезагрузки. Предусмотрены смена активного раздела, удаление доступа, пустой ответ, ошибки и отмена устаревших запросов.
- Самостоятельный frontend-пример с тестовыми API-ответами и контрактом для подключения реального backend.
- Постоянные аккаунт и настройки вне динамического меню. Страницы HTTP-ошибок, сетевого сбоя и блокировки с причиной; руководство подключения будущего API.
- Вход и состояния без Dock; разные пользовательский/административный контексты. Личные разделы перенесены в боковое подменю аккаунта, прямой клик открывает управление.
- Устанавливаемый Anidev Skill с локальными ресурсами, проектный установщик без перезаписи существующей версии и manifest с SHA-256.
- Единая команда проверки перед релизом и тест подключения из изолированной копии пакета.
+1 -1
View File
@@ -12,7 +12,7 @@ Dock утверждён пользователем 30.11.2026. Это единс
Фиксированная панель 68px на desktop и 60px на mobile. Сверху a/ — доступная кнопка для клавиатуры и touch; отдельной иконки раскрытия нет. Hover панели открывает её до 252px поверх контента, с затемнением и inert для основной области. Клик закрепляет меню, Escape и подложка закрывают. Геометрия контента не меняется.
Личный кабинет и администрирование имеют отдельную навигацию. Внизу — аккаунт. Основной текст 16px, таблицы и подписи 14px, метаданные 12–13px. Плотность меняет контролы и интервалы, мобильные цели остаются удобными для касания.
Пользовательская и административная панели имеют разные Dock. Личные разделы собраны в нижней строке «Аккаунт» с боковым подменю; основной клик открывает управление. Без подтверждённого входа Dock, шапка и подложка отсутствуют — показывается только вход или состояние. Основной текст 16px, таблицы и подписи 14px, метаданные 12–13px. Плотность меняет контролы и интервалы, мобильные цели остаются удобными для касания.
## Обратная связь и прокрутка
+3 -1
View File
@@ -26,7 +26,9 @@ node scripts/serve.mjs
## Аккаунт и страницы ошибок
В отдельной панели аккаунт и настройки всегда доступны внизу Dock, даже при пустом меню сервисов. [Аккаунт](http://127.0.0.1:4173/dist/starter/?page=account) · [Настройки аккаунта](http://127.0.0.1:4173/dist/starter/?page=account-settings).
Без входа и во время его проверки Dock не показывается — остаётся только вход или состояние. Пользовательская и административная панели имеют разные меню. Все личные разделы собраны в строке «Аккаунт»: её боковое подменю содержит управление, безопасность, устройства и настройки; обычный клик открывает управление. В галерее административный аккаунт может вернуться к администрированию через «Панель управления» в меню аккаунта.
После входа аккаунт и настройки доступны внизу 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).
+3 -1
View File
@@ -2,7 +2,9 @@
Уточнения Dock: переключатель 44×24px с бегунком 18px и равными отступами; перемещение и смена цвета — 160ms. Выпадающие и контекстные меню имеют скругление control и появление 180ms; reduced motion отключает анимацию. График показывает ближайшее время и p95 при наведении/касании; стрелки, Home/End и Escape доступны с клавиатуры. Числовая таблица сохранена. Тост использует manual popover в верхнем слое браузера и виден поверх модального затемнения.
Меню аккаунта содержит только Аккаунт, доступную по роли Панель управления, Сменить аккаунт и Выйти из SSO. Настройки и приложения доступны через навигацию личного кабинета.
Меню аккаунта содержит Аккаунт, доступную по роли Панель управления, Сменить аккаунт и Выйти из SSO. Строка «Аккаунт» открывает управление при обычном клике; рядом появляется боковое подменю Управление/Безопасность/Устройства и сеансы/Приложения/Настройки. В переиспользуемом starter приложения не добавлены, пока нет отдельного модуля. Личные пункты больше не дублируются в основном Dock. Hover/ArrowRight/кнопка раскрытия открывают боковой список, Left/Escape возвращают к строке. На мобильном остаются две помещающиеся в viewport колонки.
Dock существует только при подтверждённом входе. Loading/guest/ошибка определения сессии — самостоятельный экран без панели, шапки и подложки. Пользовательский и административный контексты имеют разные основные меню; блокировка сервисов у вошедшего аккаунта сохраняет личные разделы. 401 закрывает overlays, отменяет запросы, очищает private content и скрывает shell.
Навигация Dock: выбранный пункт сохраняет цвет при наведении. «Администрирование» — disclosure-группа с SSH-консолью и логами. aria-expanded и aria-controls описывают её состояние; закрытые дети inert и aria-hidden. В узком Dock видна только иконка раздела. Переход на дочернюю страницу сохраняет раскрытие Dock и группы, повторный клик не пересоздаёт рабочую область. Enter/Space переключают группу, Right открывает и фокусирует первый пункт, Left закрывает, Up/Down перемещают фокус внутри группы. Escape сначала закрывает подменю, затем Dock; модифицированные стрелки сохраняют браузерное поведение. Переход по меню сохраняет раскрытую панель и режим открытия (hover или закрепление); Escape, подложка и уход мыши из hover-меню закрывают её.
+34 -7
View File
@@ -1,9 +1,13 @@
import { iconSvg } from "../icons/icons.js";
import {
accountSubmenuMarkup,
mountAccountSubmenu,
} from "./account-submenu.js";
let sequence = 0;
/** Fixed account controls live outside the API-driven service navigation. */
export function mountAccountMenu(
root,
{ onNavigate, t = (ru) => ru, name = "", email = "" } = {},
{ onNavigate, t = (ru) => ru, name = "", email = "", items } = {},
) {
if (typeof onNavigate !== "function")
throw new TypeError("Account menu needs onNavigate");
@@ -12,9 +16,28 @@ export function mountAccountMenu(
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>`;
items ||= [
{ id: "account", label: t("Управление", "Management"), icon: "profile" },
{
id: "account-security",
label: t("Безопасность", "Security"),
icon: "security",
},
{
id: "account-sessions",
label: t("Устройства и сеансы", "Devices and sessions"),
icon: "sessions",
},
{
id: "account-settings",
label: t("Настройки", "Settings"),
icon: "settings",
},
];
root.innerHTML = `<div id="${id}" class="account-menu" popover="auto" role="menu" aria-label="${t("Меню аккаунта", "Account menu")}">${accountSubmenuMarkup({ id: id + "-sections", items, t })}</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");
const sections = mountAccountSubmenu(popup);
function update(identity = {}) {
root.querySelector(".account-identity b").textContent =
identity.name || t("Аккаунт", "Account");
@@ -23,6 +46,7 @@ export function mountAccountMenu(
}
update({ name, email });
const close = (restore = false) => {
sections.close();
if (popup.matches(":popover-open")) popup.hidePopover();
if (restore) trigger.focus({ preventScroll: true });
};
@@ -57,7 +81,9 @@ export function mountAccountMenu(
}
if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
event.preventDefault();
const items = [...popup.querySelectorAll("button")],
const items = [...popup.querySelectorAll("button")].filter(
(button) => !button.closest(".account-submenu"),
),
current = items.indexOf(document.activeElement);
const index =
event.key === "Home"
@@ -79,7 +105,9 @@ export function mountAccountMenu(
if (["ArrowDown", "ArrowUp"].includes(event.key)) {
event.preventDefault();
popup.showPopover();
const buttons = popup.querySelectorAll("button");
const buttons = [...popup.querySelectorAll("button")].filter(
(button) => !button.closest(".account-submenu"),
);
buttons[event.key === "ArrowDown" ? 0 : buttons.length - 1].focus();
}
},
@@ -102,13 +130,12 @@ export function mountAccountMenu(
button.setAttribute("aria-current", "page");
else button.removeAttribute("aria-current");
});
trigger.dataset.active = String(
["account", "account-settings"].includes(id),
);
trigger.dataset.active = String(items.some((item) => item.id === id));
},
dispose() {
close();
abort.abort();
sections.dispose();
trigger.removeAttribute("popovertarget");
},
};
+233
View File
@@ -0,0 +1,233 @@
import { iconSvg, iconNames } from "../icons/icons.js";
const escape = (value) =>
String(value).replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
export function accountSubmenuMarkup({
id,
items,
t = (ru) => ru,
pageAttribute = "data-account-page",
}) {
if (
!/^[a-z][\w-]*$/i.test(id) ||
!["data-account-page", "data-page"].includes(pageAttribute) ||
!Array.isArray(items) ||
!items.length
)
throw new TypeError("Invalid account submenu");
for (const item of items)
if (!/^[a-z][\w-]*$/i.test(item.id) || !iconNames.includes(item.icon))
throw new TypeError("Invalid account section");
return `<div class="account-parent" data-account-parent><button type="button" class="account-parent-link" autofocus ${pageAttribute}="${items[0].id}" aria-haspopup="menu" aria-expanded="false" aria-controls="${id}">${iconSvg("profile", { size: 20 })}<span>${t("Аккаунт", "Account")}</span></button><button type="button" class="account-submenu-toggle" aria-label="${t("Разделы аккаунта", "Account sections")}" aria-expanded="false" aria-controls="${id}">${iconSvg("chevron-right", { size: 16 })}</button><div id="${id}" class="account-submenu" popover="auto" role="menu" aria-label="${t("Разделы аккаунта", "Account sections")}">${items.map((item) => `<button type="button" role="menuitem" ${pageAttribute}="${item.id}">${iconSvg(item.icon, { size: 20 })}<span>${escape(item.label)}</span></button>`).join("")}</div></div>`;
}
export function mountAccountSubmenu(parent) {
const wrapper = parent.querySelector("[data-account-parent]"),
row = wrapper.querySelector(".account-parent-link"),
toggle = wrapper.querySelector(".account-submenu-toggle"),
submenu = wrapper.querySelector(".account-submenu");
const abort = new AbortController(),
{ signal } = abort;
const original = { width: parent.style.width, left: parent.style.left };
let timer,
frame,
disposed = false;
const open = () => submenu.matches(":popover-open");
function fitParent() {
const vw =
window.visualViewport?.width || document.documentElement.clientWidth,
ox = window.visualViewport?.offsetLeft || 0;
if (parent.matches(":popover-open") && vw < 508) {
parent.style.width = Math.max(100, Math.floor((vw - 36) / 2)) + "px";
parent.style.left = ox + 12 + "px";
} else {
parent.style.width = original.width;
parent.style.left = original.left;
}
}
function position() {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
if (disposed || !open()) return;
const viewport = window.visualViewport,
vw = viewport?.width || document.documentElement.clientWidth,
vh = viewport?.height || innerHeight,
ox = viewport?.offsetLeft || 0,
oy = viewport?.offsetTop || 0;
let rect = parent.getBoundingClientRect(),
width = Math.min(236, vw - 24);
if (Math.max(ox + vw - rect.right, rect.left - ox) < width + 12) {
width = Math.max(100, Math.floor((vw - 36) / 2));
parent.style.width = width + "px";
parent.style.left = ox + 12 + "px";
rect = parent.getBoundingClientRect();
}
submenu.style.width = width + "px";
submenu.style.maxHeight = Math.max(80, vh - 24) + "px";
const left =
ox + vw - rect.right >= width + 12
? rect.right + 6
: rect.left - width - 6;
submenu.style.left =
Math.max(ox + 12, Math.min(left, ox + vw - width - 12)) + "px";
const h = submenu.getBoundingClientRect().height;
submenu.style.top =
Math.max(
oy + 12,
Math.min(row.getBoundingClientRect().top, oy + vh - h - 12),
) + "px";
});
}
function close(restore = false) {
clearTimeout(timer);
cancelAnimationFrame(frame);
if (open()) submenu.hidePopover();
fitParent();
row.setAttribute("aria-expanded", "false");
toggle.setAttribute("aria-expanded", "false");
if (restore) row.focus({ preventScroll: true });
}
function show(focus = false) {
if (disposed || !parent.matches(":popover-open")) return;
clearTimeout(timer);
if (!open()) submenu.showPopover();
row.setAttribute("aria-expanded", "true");
toggle.setAttribute("aria-expanded", "true");
position();
if (focus) submenu.querySelector("button").focus({ preventScroll: true });
}
function scheduleClose() {
clearTimeout(timer);
timer = setTimeout(() => {
if (
!submenu.contains(document.activeElement) &&
!wrapper.matches(":hover")
)
close();
}, 180);
}
wrapper.addEventListener(
"pointerenter",
(event) => {
if (event.pointerType === "mouse" && matchMedia("(hover:hover)").matches)
show();
},
{ signal },
);
wrapper.addEventListener(
"pointerleave",
(event) => {
if (
!wrapper.contains(event.relatedTarget) &&
!submenu.contains(document.activeElement)
)
scheduleClose();
},
{ signal },
);
wrapper.addEventListener(
"focusout",
(event) => {
if (!wrapper.contains(event.relatedTarget)) close();
},
{ signal },
);
toggle.addEventListener(
"click",
(event) => {
event.stopPropagation();
open() ? close() : show(true);
},
{ signal },
);
wrapper.addEventListener(
"keydown",
(event) => {
const inSubmenu = submenu.contains(event.target);
if (event.key === "ArrowRight" && !inSubmenu) {
event.preventDefault();
event.stopPropagation();
show(true);
}
if (
(inSubmenu || open()) &&
["ArrowLeft", "Escape"].includes(event.key)
) {
event.preventDefault();
event.stopPropagation();
close(true);
}
if (
inSubmenu &&
["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)
) {
event.preventDefault();
event.stopPropagation();
const items = [...submenu.querySelectorAll("button")],
index = items.indexOf(document.activeElement);
items[
event.key === "Home"
? 0
: event.key === "End"
? items.length - 1
: (index + (event.key === "ArrowDown" ? 1 : -1) + items.length) %
items.length
].focus();
}
if (inSubmenu && event.key === "Tab") close(true);
},
{ signal },
);
parent.addEventListener(
"toggle",
() => {
fitParent();
if (!parent.matches(":popover-open")) close();
},
{ signal },
);
submenu.addEventListener(
"toggle",
() => {
if (!open()) close();
},
{ signal },
);
parent.addEventListener(
"pointerleave",
(event) => {
if (
!wrapper.contains(event.relatedTarget) &&
!submenu.contains(document.activeElement)
)
scheduleClose();
},
{ signal },
);
window.addEventListener(
"resize",
() => {
fitParent();
position();
},
{ signal },
);
window.addEventListener("scroll", position, { signal, capture: true });
window.visualViewport?.addEventListener("resize", position, { signal });
window.visualViewport?.addEventListener("scroll", position, { signal });
return {
close,
show,
dispose() {
close();
parent.style.width = original.width;
parent.style.left = original.left;
disposed = true;
abort.abort();
},
};
}
+1
View File
@@ -108,6 +108,7 @@ export async function exportSystem(
"components/toast.js",
"components/copy-field.js",
"components/error-page.js",
"components/account-submenu.js",
"components/search-select.js",
"components/workspaces.css",
"components/ssh-console.js",
+104
View File
@@ -3118,6 +3118,110 @@ body[data-concept="dock"] .copy-input .input-copy-action:active {
transform: none;
}
.account-menu .account-parent {
display: grid;
grid-template-columns: minmax(0, 1fr) 32px;
align-items: stretch;
}
.account-menu .account-parent > .account-submenu-toggle {
padding: 8px;
justify-content: center;
min-width: 0;
}
.account-menu .account-parent-link {
min-width: 0;
width: 100%;
}
.account-menu .account-parent-link > span {
min-width: 0;
white-space: normal;
overflow-wrap: anywhere;
}
.account-submenu {
position: fixed;
inset: auto;
margin: 0;
padding: 6px;
background: var(--color-surface);
color: var(--color-text);
border: 1px solid var(--color-border);
border-radius: 12px;
box-shadow: 0 12px 32px #07181f35;
overflow-y: auto;
}
.account-submenu:popover-open {
display: flex;
flex-direction: column;
animation: account-flyout-enter 140ms ease-out;
}
.account-submenu button {
border: 0;
background: transparent;
display: flex;
align-items: center;
gap: 10px;
text-align: left;
min-height: 44px;
padding: 10px;
white-space: normal;
}
.account-submenu button > svg {
flex-shrink: 0;
}
.account-submenu button > span {
overflow-wrap: anywhere;
min-width: 0;
}
.account-submenu button:is(:hover, :focus-visible) {
background: var(--color-row-hover);
}
.account-submenu [aria-current="page"] {
background: var(--color-row-active);
color: var(--color-accent);
}
@keyframes account-flyout-enter {
from {
opacity: 0;
translate: -4px 0;
}
to {
opacity: 1;
translate: 0 0;
}
}
.guest-page {
min-height: 100dvh;
display: grid;
place-content: center;
padding: 24px;
width: 100%;
}
.guest-page > .identity-gate {
max-width: 560px;
margin: 0 auto;
}
body[data-session="loading"] .shell,
body[data-session="guest"] .shell,
body[data-session="unavailable"] .shell {
display: none;
}
body[data-session="authenticated"] #session-screen {
display: none;
}
#session-screen {
min-height: 100dvh;
padding: 24px;
display: grid;
place-content: center;
}
#session-screen .error-page {
margin: 0 auto;
}
@media (prefers-reduced-motion: reduce) {
.account-submenu:popover-open {
animation: none;
}
}
/* Fixed identity controls stay outside the API-driven service menu. */
[data-fixed-account] {
flex-shrink: 0;
+36 -1
View File
@@ -11,6 +11,10 @@
## 1. Данные текущего аккаунта
Обновлённое правило сессии: пока ответ аккаунта загружается, Dock скрыт. Для отсутствующего входа верните 401 или `{"status":"guest"}` с кодом 200. Фронт покажет только экран входа; сервисное меню в этом состоянии не запрашивается. Ошибка проверки аккаунта показывает отдельное состояние без Dock. Сам факт отсутствия меню не означает отсутствие входа: authenticated с items=[] сохраняет панель и личные разделы. В starter кнопка входа пока показывает пояснение о демонстрации; реальный redirect SSO подключается отдельно.
В ответ вошедшего аккаунта добавьте `panel: "user"` либо `panel: "admin"` — контекст, разрешённый сервером. Это не параметр, по которому backend должен доверять правам клиента. Состав Dock различается по этому контексту; личные страницы не входят в основное сервисное меню. При отсутствии panel старые ответы считаются пользовательским контекстом.
`GET {apiBase}/account.json`, ответ 200, Content-Type: application/json:
```json
@@ -19,6 +23,7 @@
"name": "Анна Волкова",
"email": "anna@example.test",
"status": "active",
"panel": "user",
"banReason": null
}
```
@@ -33,6 +38,7 @@ id/name/email — строки; status — active или banned; banReason —
"name": "Анна Волкова",
"email": "anna@example.test",
"status": "banned",
"panel": "user",
"banReason": "Нарушение правил использования сервиса.\nОбратитесь к администратору для уточнения."
}
```
@@ -43,6 +49,33 @@ GET данных самого аккаунта и разрешённые лич
## 2. Доступные сервисные вкладки
Для раздельных панелей рекомендуемый ответ содержит `panels`, например:
```json
{
"panels": {
"user": {
"defaultPage": "overview",
"items": [{ "id": "overview", "label": "Обзор", "icon": "dashboard" }]
},
"admin": {
"defaultPage": "overview",
"items": [
{ "id": "overview", "label": "Обзор", "icon": "dashboard" },
{
"id": "administration",
"label": "Администрирование",
"icon": "server",
"children": [{ "id": "logs", "label": "Логи", "icon": "document" }]
}
]
}
}
}
```
Фронт выбирает ветку из разрешённого account.panel. Не отправляйте пользователю административную конфигурацию/данные, если они для него закрыты: сервер может прислать только доступную ветку panels.user. Приведённый ниже плоский формат продолжает поддерживаться как уже выбранная сервером конфигурация одной панели. В статических fixtures обе ветки нужны для разработки, а не для выдачи полномочий.
`GET {apiBase}/navigation.json`, ответ 200:
```json
@@ -61,7 +94,9 @@ GET данных самого аккаунта и разрешённые лич
}
```
API присылает только сервисные разделы. Аккаунт и настройки аккаунта находятся в постоянной нижней части Dock и не удаляются через items=[]. Идентификаторы account, account-settings, account-banned и префикс error- зарезервированы фронтом; в серверное меню их включать нельзя. Пустое items — корректный ответ: сервисов нет, личные страницы остаются.
API присылает только сервисные разделы. После входа аккаунт и настройки находятся в постоянной нижней части Dock и не удаляются через items=[]. Идентификаторы account, account-security, account-sessions, account-settings, account-banned и префикс error- зарезервированы фронтом; в серверное меню их включать нельзя. Пустое items — корректный ответ: сервисов нет, личные страницы остаются.
Строка «Аккаунт» открывает управление по обычному клику. Наведение, ArrowRight или отдельная кнопка раскрытия показывают боковое меню: Управление / Безопасность / Устройства и сеансы / Настройки. Для безопасности и сеансов starter читает account/security.json и account/sessions.json с той же схемой title/description/rows, что ниже. Эти endpoint должны быть доступны вошедшему аккаунту даже при блокировке сервисов. Личные пункты не дублируются в основном Dock.
До 100 элементов вместе с группами, уникальные id (буква, затем буквы/цифры/underscore/дефис, до 64 символов), label до 160 символов, icon из iconNames, необязательный disabled boolean. Один уровень children. Активная доступная вкладка сохраняется после обновления меню; при удалении текущей выбирается доступная, при пустом меню отображается пустое состояние. Прямая ссылка на неизвестный маршрут показывает 404; известный сервисный модуль без доступа — 403.
+1 -1
View File
@@ -2,7 +2,7 @@
Панель — статически размещаемое приложение. API сообщает доступные разделы и предоставляет данные; панель выбирает локальный модуль по id. Ответ сервера не содержит исполняемого JavaScript или HTML. Один Dock обновляется через setItems, без перезагрузки shell.
Пока API отсутствует, используйте [полное руководство для будущего сервера](BACKEND-INTEGRATION.md): bootstrap аккаунта, зарезервированные маршруты, 401/403/блокировка, форматы ответов и запуск. Аккаунт и настройки — постоянные системные страницы вне items; серверное меню не может их удалить или подменить.
Пока API отсутствует, используйте [полное руководство для будущего сервера](BACKEND-INTEGRATION.md): bootstrap аккаунта, зарезервированные маршруты, 401/403/блокировка, форматы ответов и запуск. После входа аккаунт и настройки — постоянные системные страницы вне items; серверное меню не может их удалить или подменить. Без входа shell скрыт, меню не загружается. account.panel выбирает пользовательскую или административную ветку panels в ответе конфигурации.
Starter использует локальные JSON-файлы как тестовые HTTP endpoints. Это предлагаемый контракт для интеграции, а не утверждение о существующих маршрутах сервера. `apiBase` и fetch-опции в app.js заменяются под реальный backend.
+8 -2
View File
@@ -16,12 +16,18 @@
`t` по умолчанию выбирает русский у Dock, notifier и copy field. Select требует явный t. Все mount-функции нужно очистить до удаления их DOM. notify.dispose и dock.dispose допускают повторный вызов. Для повторного mount сначала выполните предыдущий cleanup. Подписывайте navigation через aria-label, свяжите trigger aria-controls с её id; scrim не входит в Tab-порядок. Пример показывает эти связи.
## 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).
`mountAccountMenu(root,{onNavigate,t,name,email,items})` создаёт нижний блок личных разделов вошедшего аккаунта; возвращает update({name,email}), setActive(id), close(restoreFocus), dispose(). Он располагается отдельно от root.nav-links и не удаляется при setItems([]). Для системного экрана вызовите navigation.clearActive(), чтобы сервисный пункт не оставался текущим; метод очищает aria-current и сообщает onActiveChange(null).
Меню аккаунта теперь каскадное: обычный клик по строке «Аккаунт» вызывает onNavigate("account"), наведение/ArrowRight/кнопка раскрытия открывают боковой список account/account-security/account-sessions/account-settings. Необязательный items позволяет адаптировать ids/подписи/иконки к роутеру приложения. `accountSubmenuMarkup({id,items,t,pageAttribute})` и `mountAccountSubmenu(parentPopover)` доступны для существующей разметки; контроллер возвращает show(focus), close(restoreFocus), dispose(). На узком экране две колонки ужимаются, сохраняя боковое расположение; дочерний popover вложен в родительский.
Shell показывается только после подтверждения вошедшего аккаунта. Loading/guest/ошибка определения сессии используют отдельный main без видимого Dock и без активных скрытых контролов. После 401 скрывайте shell, закрывайте popover, отменяйте запросы и удаляйте прежние данные. Пользовательский и административный Dock получают разные items; личные разделы находятся в строке аккаунта, не в основном nav.
`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.
## CSS-контракты
Токены: `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).
+1
View File
@@ -3,5 +3,6 @@
"name": "Anna Volkova",
"email": "anna@example.test",
"status": "active",
"panel": "admin",
"banReason": null
}
@@ -0,0 +1,9 @@
{
"title": "Безопасность",
"description": "Способы входа в аккаунт. Тестовые данные; изменение факторов входа в примере не выполняется.",
"rows": [
{ "label": "Пароль", "value": "Установлен" },
{ "label": "TOTP", "value": "Подключён" },
{ "label": "Passkey", "value": "Windows Hello" }
]
}
@@ -0,0 +1,11 @@
{
"title": "Устройства и сеансы",
"description": "Пример активных сеансов аккаунта.",
"rows": [
{ "label": "Windows · Edge", "value": "Текущий сеанс" },
{
"label": "Android · Chrome",
"value": "Последняя активность: сегодня, 09:30"
}
]
}
+43 -10
View File
@@ -1,13 +1,46 @@
{
"defaultPage": "overview",
"items": [
{ "id": "overview", "label": "Обзор", "icon": "dashboard" },
{ "id": "projects", "label": "Проекты", "icon": "applications" },
{
"id": "administration",
"label": "Администрирование",
"icon": "server",
"children": [{ "id": "logs", "label": "Логи", "icon": "document" }]
"panels": {
"user": {
"defaultPage": "overview",
"items": [
{
"id": "overview",
"label": "Обзор",
"icon": "dashboard"
},
{
"id": "projects",
"label": "Проекты",
"icon": "applications"
}
]
},
"admin": {
"defaultPage": "overview",
"items": [
{
"id": "overview",
"label": "Обзор",
"icon": "dashboard"
},
{
"id": "projects",
"label": "Проекты",
"icon": "applications"
},
{
"id": "administration",
"label": "Администрирование",
"icon": "server",
"children": [
{
"id": "logs",
"label": "Логи",
"icon": "document"
}
]
}
]
}
]
}
}
+141 -9
View File
@@ -22,7 +22,12 @@ const cleanups = [];
const pageIds = new Set(["overview", "projects", "logs"]);
let allowedIds = new Set(),
serviceHome = null;
const fixedIds = new Set(["account", "account-settings"]);
const fixedIds = new Set([
"account",
"account-security",
"account-sessions",
"account-settings",
]);
let theme = "light",
disposed = false,
menuRequest,
@@ -82,6 +87,71 @@ function urlFor(id, push = false) {
else url.searchParams.delete("page");
history[push ? "pushState" : "replaceState"]({}, "", url);
}
let sessionCleanup = () => {};
function showSession(error = { status: 401 }) {
pageRequest?.abort();
pageRequest = undefined;
menuRequest?.abort();
menuRequest = undefined;
accountRequest?.abort();
accountRequest = undefined;
errorCleanup();
errorCleanup = () => {};
sessionCleanup();
sessionCleanup = () => {};
dock.close();
accountMenu.close();
notify.dismiss();
document.querySelectorAll("[popover]:popover-open").forEach((popup) => {
if (popup.matches(":popover-open")) popup.hidePopover();
});
document.querySelectorAll("dialog[open]").forEach((dialog) => dialog.close());
identity = null;
accountError = error;
changingMenu = true;
navigation.setItems([]);
changingMenu = false;
allowedIds.clear();
serviceHome = null;
accountMenu.update({});
$("#page-data").replaceChildren();
$(".integration-form").hidden = true;
document.body.dataset.session =
error.status === 401 ? "guest" : "unavailable";
$(".shell").inert = true;
$(".skip").href = "#session-screen";
const screen = $("#session-screen");
screen.innerHTML = errorPageMarkup({
status: error.status || (error instanceof TypeError ? "offline" : 500),
t,
});
sessionCleanup = mountErrorPage(screen, {
onAccount: () =>
notify("Это пример состояния входа. SSO пока не подключён.", {
type: "info",
title: "Вход в аккаунт",
}),
onRetry: async () => {
await loadAccount();
if (identity) refreshNavigation();
},
});
const login = screen.querySelector('[data-error-action="account"]');
if (login) login.textContent = "Войти";
}
function showShell() {
sessionCleanup();
sessionCleanup = () => {};
$("#session-screen").replaceChildren();
$(".shell").inert = false;
document.body.dataset.session = "authenticated";
$(".skip").href = "#content";
document.body.dataset.panel = identity.panel;
$(".breadcrumb").textContent =
identity.panel === "admin"
? "Anidev / Панель администратора"
: "Anidev / Панель пользователя";
}
function displayError(status, { reason, requestId, retry } = {}) {
errorCleanup();
errorCleanup = () => {};
@@ -157,6 +227,10 @@ function renderAccount(id) {
}
}
async function showPage(id) {
if (!identity) {
if (accountError) showSession(accountError);
return;
}
pageRequest?.abort();
errorCleanup();
errorCleanup = () => {};
@@ -167,10 +241,53 @@ async function showPage(id) {
$(".page-heading").hidden = false;
$(".integration-form").hidden = true;
accountMenu.setActive(id);
if (fixedIds.has(id)) {
if (["account", "account-settings"].includes(id)) {
renderAccount(id);
return;
}
if (["account-security", "account-sessions"].includes(id)) {
$("#page-title").textContent = "Загрузка…";
$("#page-description").textContent = "Получаем данные аккаунта.";
container.setAttribute("aria-busy", "true");
try {
const data = await get(
`account/${id === "account-security" ? "security" : "sessions"}.json`,
request.signal,
);
if (disposed || request !== pageRequest) return;
if (
typeof data.title !== "string" ||
typeof data.description !== "string" ||
!Array.isArray(data.rows)
)
throw Error("Invalid account section");
$("#page-title").textContent = data.title;
$("#page-description").textContent = data.description;
const list = document.createElement("dl");
list.className = "account-details";
for (const row of data.rows.slice(0, 100)) {
if (typeof row.label !== "string" || typeof row.value !== "string")
throw Error("Invalid account row");
const item = document.createElement("div"),
term = document.createElement("dt"),
value = document.createElement("dd");
term.textContent = row.label;
value.textContent = row.value;
item.append(term, value);
list.append(item);
}
container.append(list);
} catch (error) {
if (error.name !== "AbortError" && request === pageRequest && !disposed) {
if (error.status === 401) showSession(error);
else
displayError(error.status || 500, { retry: () => showPage(current) });
}
} finally {
if (request === pageRequest) container.setAttribute("aria-busy", "false");
}
return;
}
if (identity?.status === "banned") {
displayError("banned", { reason: identity.banReason });
return;
@@ -234,6 +351,10 @@ async function showPage(id) {
} catch (error) {
if (error.name === "AbortError" || disposed || request !== pageRequest)
return;
if (error.status === 401) {
showSession(error);
return;
}
if (error.status === 403 && error.code === "ACCOUNT_BANNED") {
accountError = null;
identity = {
@@ -302,18 +423,24 @@ async function loadAccount() {
try {
const data = await get("account.json", request.signal);
if (disposed || request !== accountRequest) return;
if (data?.status === "guest") {
showSession({ status: 401 });
return;
}
if (
!data ||
typeof data.id !== "string" ||
typeof data.name !== "string" ||
typeof data.email !== "string" ||
!["active", "banned"].includes(data.status) ||
(data.panel !== undefined && !["user", "admin"].includes(data.panel)) ||
(data.banReason != null && typeof data.banReason !== "string")
)
throw Error("Invalid account response");
identity = data;
identity = { ...data, panel: data.panel || "user" };
accountError = null;
accountMenu.update(data);
showShell();
} catch (error) {
if (
error.name !== "AbortError" &&
@@ -325,20 +452,25 @@ async function loadAccount() {
identity = {
...identity,
status: "banned",
panel: "user",
banReason: typeof error.reason === "string" ? error.reason : null,
};
accountError = null;
}
showShell();
} else showSession(error);
}
}
}
async function refreshNavigation() {
if (!identity) return;
menuRequest?.abort();
const request = (menuRequest = new AbortController());
$("#connection-status").textContent = "Обновляем доступные разделы…";
try {
const data = await get("navigation.json", request.signal);
const response = await get("navigation.json", request.signal);
if (disposed || request !== menuRequest) return;
const data = response.panels ? response.panels[identity.panel] : response;
if (!data) throw Error("Panel navigation not configured");
const reserved = (items) =>
Array.isArray(items) &&
items.some(
@@ -391,9 +523,8 @@ async function refreshNavigation() {
pageRequest?.abort();
accountError = null;
if (error.status === 401) {
identity = null;
accountError = error;
accountMenu.update({});
showSession(error);
return;
} else
identity = {
...identity,
@@ -464,7 +595,7 @@ $("#check-settings").addEventListener(
{ signal },
);
await loadAccount();
refreshNavigation();
if (identity) refreshNavigation();
function dispose() {
if (disposed) return;
disposed = true;
@@ -472,6 +603,7 @@ function dispose() {
pageRequest?.abort();
accountRequest?.abort();
errorCleanup();
sessionCleanup();
abort.abort();
cleanups.forEach((cleanup) => cleanup());
navigation.dispose();
+8 -2
View File
@@ -8,8 +8,14 @@
<link rel="stylesheet" href="./anidev/components/system.css" />
<link rel="stylesheet" href="./app.css" />
</head>
<body data-concept="dock" data-theme="light">
<a class="skip" href="#content">Перейти к содержимому</a>
<body data-concept="dock" data-theme="light" data-session="loading">
<main id="session-screen" tabindex="-1" aria-live="polite">
<section class="identity-gate">
<h1>Проверяем вход…</h1>
<p>Получаем состояние аккаунта.</p>
</section>
</main>
<a class="skip" href="#session-screen">Перейти к содержимому</a>
<div class="shell">
<aside
class="navigation"
+1
View File
@@ -8,6 +8,7 @@
"package:archives": "python scripts/package-release.py",
"test:package": "node tests/package.mjs",
"test:system-pages": "node tests/system-pages.mjs",
"test:panel-navigation": "node tests/panel-navigation.mjs",
"test:release": "node scripts/test-release.mjs",
"test:select": "node tests/search-select.mjs",
"terminal:vendor": "node scripts/vendor-terminal.mjs",
+109 -12
View File
@@ -5,6 +5,10 @@ import {
} from "../components/search-select.js";
import { createNotifier } from "../components/toast.js";
import { mountCopyField } from "../components/copy-field.js";
import {
accountSubmenuMarkup,
mountAccountSubmenu,
} from "../components/account-submenu.js";
import {
errorPageMarkup,
errorStatuses,
@@ -182,6 +186,10 @@ let page = [
].includes(params.get("page"))
? params.get("page")
: "dashboard";
let panel =
params.get("panel") === "user" || accountPageIds.includes(page)
? "user"
: "admin";
let query = "",
role = "all",
userPage = 1,
@@ -243,8 +251,8 @@ function accountInitials() {
return a ? (a.firstName[0] || "") + (a.lastName[0] || "") : "a/";
}
function navigationPages() {
return accountPageIds.includes(page)
? ["profile", "security", "sessions", "applications", "appearance"]
return panel === "user"
? ["dashboard"]
: [
"dashboard",
"users",
@@ -256,8 +264,35 @@ function navigationPages() {
}
function dockAccount() {
return `<div class="dock-account-area"><div id="account-menu" class="account-menu" popover="auto" aria-label="${t("Меню аккаунта", "Account menu")}">
<button autofocus data-page="profile">${icon("profile")}<span>${t("Аккаунт", "Account")}</span></button>
${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)) ? `<button data-page="dashboard">${icon("dashboard")}<span>${t("Панель управления", "Control panel")}</span></button>` : ""}
${accountSubmenuMarkup({
id: "account-sections",
t,
pageAttribute: "data-page",
items: [
{ id: "profile", label: t("Управление", "Management"), icon: "profile" },
{
id: "security",
label: t("Безопасность", "Security"),
icon: "security",
},
{
id: "sessions",
label: t("Устройства и сеансы", "Devices and sessions"),
icon: "sessions",
},
{
id: "applications",
label: t("Приложения", "Applications"),
icon: "applications",
},
{
id: "appearance",
label: t("Настройки", "Settings"),
icon: "appearance",
},
],
})}
${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)) ? `<button data-page="dashboard" data-panel="admin">${icon("dashboard")}<span>${t("Панель управления", "Control panel")}</span></button>` : ""}
<button class="account-separator" data-identity="switch">${icon("switch-account")}<span>${t("Сменить аккаунт", "Switch account")}</span></button>
<button class="account-separator" data-identity="logout">${icon("logout")}<span>${t("Выйти из SSO", "Sign out of SSO")}</span></button></div>
<button class="dock-account" popovertarget="account-menu" aria-label="${escape(t("Меню аккаунта ", "Account menu ") + accountName())}"><span class="avatar">${currentIdentity()?.avatar ? `<img src="${escape(currentIdentity().avatar)}" alt="">` : escape(accountInitials())}</span><span class="account-identity"><b>${escape(accountName())}</b><small>${escape(currentIdentity()?.username || "Anidev Identity")}</small></span><span class="account-more" aria-hidden="true">···</span></button></div>`;
@@ -389,13 +424,25 @@ function render({ preserveDock = false } = {}) {
selectCleanups = [];
workspaceCleanup = () => {};
const workspaceVersion = ++workspaceRender;
const signedIn = identityAdapter.snapshot().status === "authenticated";
if (
accountPageIds.includes(page) ||
!currentIdentity()?.roles.some((role) =>
["Master Admin", "SSO Admin"].includes(role),
)
)
panel = "user";
document.body.dataset.panel = panel;
document.body.dataset.session = signedIn ? "authenticated" : "guest";
const dockWasOpen =
preserveDock &&
document.body.classList.contains("dock-open") &&
page !== "auth";
page !== "auth" &&
signedIn;
const route = new URL(location.href);
route.searchParams.delete("concept");
route.searchParams.set("page", page);
route.searchParams.set("panel", panel);
route.searchParams.set("theme", theme);
route.searchParams.set("locale", locale);
if (route.href !== location.href) {
@@ -420,7 +467,7 @@ function render({ preserveDock = false } = {}) {
: identityAdapter.snapshot().status !== "authenticated" &&
!["components", "tokens", "auth", "errors"].includes(page)
? accountUI.gate()
: ["dashboard", "users", "settings", "ssh", "logs"].includes(page) &&
: ["users", "settings", "ssh", "logs"].includes(page) &&
!currentIdentity()?.roles.some((r) =>
["Master Admin", "SSO Admin"].includes(r),
)
@@ -428,7 +475,7 @@ function render({ preserveDock = false } = {}) {
: {
ssh: () => sshScreen({ t, heading }),
logs: () => logsScreen({ t, heading }),
dashboard,
dashboard: panel === "admin" ? dashboard : userOverview,
users: userScreen,
settings: settingsScreen,
components: componentScreen,
@@ -438,13 +485,25 @@ function render({ preserveDock = false } = {}) {
$("#app").innerHTML =
page === "auth"
? auth()
: `<div class="shell">${nav()}<button class="dock-scrim" data-action="dock-close" tabindex="-1" aria-label="${t("Закрыть меню", "Close navigation")}" aria-hidden="true"></button><div class="main-column">${header()}<main id="content" tabindex="-1">${content}</main></div></div>`;
: !signedIn
? `<main id="content" class="guest-page" tabindex="-1">${page === "identity" ? accountUI.renderPage("identity") : accountUI.gate()}</main>`
: `<div class="shell">${nav()}<button class="dock-scrim" data-action="dock-close" tabindex="-1" aria-label="${t("Закрыть меню", "Close navigation")}" aria-hidden="true"></button><div class="main-column">${header()}<main id="content" tabindex="-1">${content}</main></div></div>`;
bindForms();
accountUI.bind(page);
bindDockHover();
if (dockWasOpen) setDockOpen(true, false);
bindCharts();
if (page === "errors") {
if ($("#account-menu")) {
const submenu = mountAccountSubmenu($("#account-menu"));
selectCleanups.push(() => submenu.dispose());
$("#account-menu").addEventListener("keydown", (event) => {
if (event.key === "Tab") {
$("#account-menu").hidePopover();
$(".dock-account").focus();
}
});
}
if (page === "errors" && $("[data-error-status]")) {
selectCleanups.push(
mountErrorPage($("[data-error-status]"), {
onRetry: () =>
@@ -717,6 +776,18 @@ 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 userOverview() {
return (
heading(
t("Обзор", "Overview"),
t(
"Личная панель Anidev. Управление аккаунтом доступно в нижней строке Dock.",
"Your Anidev workspace. Account management is available at the bottom of the Dock.",
),
) +
`<section class="panel"><h2>${t("Сеанс активен", "Session active")}</h2><p>${escape(accountName())}</p><p class="muted">${t("Это демонстрация пользовательской панели. Административные разделы находятся в отдельном Dock.", "This is a user-panel preview. Administrative sections use a separate Dock.")}</p></section>`
);
}
function errorScreen() {
const requested = new URL(location.href).searchParams.get("status") || "404";
const status =
@@ -970,8 +1041,17 @@ document.addEventListener("click", async (e) => {
if (await accountUI.handleClick(e)) return;
const pageButton = e.target.closest("[data-page]");
if (pageButton) {
const panelChanged =
pageButton.dataset.panel && panel !== pageButton.dataset.panel;
if (pageButton.dataset.panel) panel = pageButton.dataset.panel;
const fromDock = Boolean(pageButton.closest(".navigation"));
if (fromDock && page === pageButton.dataset.page) return;
if (fromDock && page === pageButton.dataset.page && !panelChanged) {
if (pageButton.closest(".account-menu")) {
$("#account-menu").hidePopover();
$(".dock-account").focus({ preventScroll: true });
}
return;
}
page = pageButton.dataset.page;
if (["ssh", "logs"].includes(page)) administrationOpen = true;
$("#dialog").close();
@@ -1235,10 +1315,26 @@ document.addEventListener("click", async (e) => {
});
});
document.addEventListener("keydown", (e) => {
if (
identityAdapter.snapshot().status !== "authenticated" &&
(e.ctrlKey || e.metaKey) &&
e.key.toLowerCase() === "k"
) {
e.preventDefault();
return;
}
if (e.key === "Escape" && $("[popover=auto]:popover-open")) {
e.preventDefault();
$("[popover=auto]:popover-open").hidePopover();
$(".dock-account")?.focus();
const popup = [
...document.querySelectorAll("[popover=auto]:popover-open"),
].at(-1);
popup.hidePopover();
if (popup.classList.contains("account-submenu"))
popup
.closest("[data-account-parent]")
.querySelector(".account-parent-link")
.focus();
else $(".dock-account")?.focus();
return;
}
const groupTarget = e.target.closest?.("[data-nav-group=administration]");
@@ -1428,6 +1524,7 @@ addEventListener("storage", (e) => {
});
addEventListener("popstate", () => {
const route = new URL(location.href);
panel = route.searchParams.get("panel") === "admin" ? "admin" : "user";
page = Object.keys(pageNames).includes(route.searchParams.get("page"))
? route.searchParams.get("page")
: "dashboard";
+10
View File
@@ -165,3 +165,13 @@ Log reader: фильтры уровня/сервиса/текста, подсв
Общий 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 не подключались.
## Сессия, разные Dock и боковое меню аккаунта / 01.12.2026
Без подтверждённого входа галерея рендерит только вход/состояние, без Dock, шапки и подложки. В starter shell скрыт и inert до ответа account.json; guest/401 и ошибка bootstrap не загружают меню. Потеря сессии закрывает popover/dialog, отменяет и инвалидирует запросы, очищает private content. Вошедший аккаунт с пустым сервисным меню сохраняет личные страницы; бан сервисов остаётся отдельным состоянием вошедшего аккаунта.
Пользовательский Dock не дублирует профиль/безопасность/сеансы/настройки. Они собраны в строке «Аккаунт»: обычный клик открывает управление, hover/Right/кнопка раскрытия — боковое меню, Left/Escape возвращают к строке. Проверены перенос указателя через зазор, два Escape, касание после паузы и две колонки в пределах мобильного viewport. Исправлен конфликт двух таймеров pointerleave, который преждевременно закрывал список после касания. Проверено переключение личного и административного обзора на одном page=dashboard. В starter account.panel выбирает user/admin-ветку конфигурации; backend всё равно проверяет права.
Набор проверок: Browser 50, Dock 10, Approved 24, Site 35, Identity 94, TOTP 4, Icons 91, Workspaces 83, Navigation/feedback 79, Search-select 6, Package 31, System pages 183, Panel navigation 14 — суммарно 704 успешных сценария, без ошибок JavaScript. Финальные изменения аккаунта повторно проверены Package 31 / Panel navigation 14 / Browser 50; check и штатный Skill validator проходят. Скриншоты references/panel-navigation просмотрены в light/dark на 1440/768/390; signed-out просмотрен отдельно. Архивы пересобраны, ZIP CRC проверен.
Во время общего запуска был единичный Windows-сбой записи PNG и зависимый от нагрузки результат терминального теста после фиксированной паузы 80 мс. Identity и Workspaces отдельно повторены успешно (94/94 и 83/83). Это наблюдение о воспроизводимости QA, не полный аудит доступности. Настоящие API/SSO не подключались; контракт и fixtures обновлены под новую схему.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

+5
View File
@@ -0,0 +1,5 @@
{
"passed": 14,
"errors": [],
"checks": "Separate user/admin Dock; account side flyout in both themes/three widths; pointer travel, direct management click, keys, touch, no Dock for guest/loading/error/factor states"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+4
View File
@@ -7,6 +7,10 @@ export {
export { mountCopyField } from "../components/copy-field.js";
export { mountDock } from "../components/dock.js";
export { mountAccountMenu } from "../components/account-menu.js";
export {
accountSubmenuMarkup,
mountAccountSubmenu,
} from "../components/account-submenu.js";
export {
errorStatuses,
errorPageMarkup,
+1
View File
@@ -48,6 +48,7 @@ for (const file of [
"components/dock.js",
"components/navigation.js",
"components/account-menu.js",
"components/account-submenu.js",
"components/error-page.js",
"components/ssh-console.js",
"components/log-reader.js",
+1
View File
@@ -59,6 +59,7 @@ try {
"search-select",
"package",
"system-pages",
"panel-navigation",
]) {
console.log(`\nChecking ${name}`);
await run(`tests/${name}.mjs`, env);
+2
View File
@@ -27,6 +27,8 @@ The host can be an independent frontend that calls an API. Treat available secti
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.
The fixed account block applies only after sign-in. While checking the session, signed out, or unable to establish a session, show only the standalone sign-in/state screen with no visible Dock/header/scrim or active hidden controls. A 401 closes overlays, cancels and invalidates pending requests, clears private content and hides the shell. User and admin contexts have different service items; do not mirror personal sections into the main user Dock. The Account row opens Management on direct click, with a side flyout for Management/Security/Devices and sessions/Settings on hover, ArrowRight or an explicit touch control. Keep both columns within the viewport and preserve the route on disclosure-only actions.
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
+3 -1
View File
@@ -137,7 +137,9 @@ try {
await page.goto(frame("profile", "light"));
await page.locator("#identity-profile").waitFor();
const long = await page.locator(".main-column").boundingBox();
await page.locator(".nav-links [data-page=applications]").click();
await page.locator(".dock-account").click();
await page.locator(".account-parent-link").hover();
await page.locator(".account-submenu [data-page=applications]").click();
await page.locator(".identity-app").first().waitFor();
const short = await page.locator(".main-column").boundingBox();
assert.equal(long.width, short.width);
+7 -4
View File
@@ -112,11 +112,14 @@ try {
);
// Keyboard modality, rather than programmatic focus after a mouse click.
await p.keyboard.press("Tab");
await p.locator(".nav-links [aria-current=page]").focus();
const focusTarget = (await p
.locator(".nav-links [aria-current=page]")
.count())
? p.locator(".nav-links [aria-current=page]")
: p.locator(".dock-account");
await focusTarget.focus();
assert.equal(
await p
.locator(".nav-links [aria-current=page]")
.evaluate((e) => getComputedStyle(e).outlineOffset),
await focusTarget.evaluate((e) => getComputedStyle(e).outlineOffset),
"-2px",
);
if (locale === "ru") await p.waitForTimeout(300);
+62 -3
View File
@@ -94,7 +94,7 @@ const consumer = await mkdtemp(path.resolve("test-results/consumer-"));
await cp("dist/starter", consumer, { recursive: true });
const original = JSON.parse(
await readFile(path.join(consumer, "api/navigation.json"), "utf8"),
);
).panels.admin;
let config = structuredClone(original),
configDelay = 0,
failMenu = false,
@@ -397,7 +397,9 @@ try {
.waitFor();
await page.locator(".dock-brand").click();
await page.locator(".dock-account").click();
await page.locator('[data-account-page="account"]').click();
await page
.locator('.account-parent-link[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);
@@ -490,11 +492,19 @@ try {
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(".search-select-trigger").click();
await page.evaluate(() =>
document.querySelector("#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);
assert.equal(await page.locator(".navigation").isVisible(), false);
assert.equal(await page.locator("[popover]:popover-open").count(), 0);
passed++;
menuFailure = null;
await page.reload();
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
menuFailure = {
status: 403,
body: { error: { code: "ACCOUNT_BANNED", reason: "Изменение доступа" } },
@@ -506,6 +516,55 @@ try {
passed++;
menuFailure = null;
// Core modules also work independently of the starter's host logic.
const savedAccount = { ...account };
account = { status: "guest" };
config = structuredClone(original);
const beforeMenuRequests = requests.filter((url) =>
url.includes("/api/navigation.json"),
).length;
await page.goto(origin + "/");
await page.locator('#session-screen [data-error-status="401"]').waitFor();
assert.equal(await page.locator(".navigation").isVisible(), false);
assert.equal(
requests.filter((url) => url.includes("/api/navigation.json")).length,
beforeMenuRequests,
);
assert.equal(await page.locator(".shell").evaluate((e) => e.inert), true);
passed++;
account = { ...savedAccount, panel: "user" };
config = {
panels: {
user: { defaultPage: "overview", items: original.items.slice(0, 2) },
admin: original,
},
};
await page.goto(origin + "/?page=overview");
await page.locator("#page-title").filter({ hasText: "Обзор" }).waitFor();
assert.equal(await page.locator("body").getAttribute("data-panel"), "user");
assert.equal(
await page.locator('[data-nav-toggle="administration"]').count(),
0,
);
await page.locator(".dock-account").click();
await page.locator(".account-parent-link").focus();
await page.keyboard.press("ArrowRight");
await page
.locator('.account-submenu [data-account-page="account-security"]')
.click();
await page
.locator("#page-title")
.filter({ hasText: "Безопасность" })
.waitFor();
await page.locator(".dock-account").click();
await page.locator(".account-submenu-toggle").click();
await page
.locator('.account-submenu [data-account-page="account-sessions"]')
.click();
await page
.locator("#page-title")
.filter({ hasText: "Устройства и сеансы" })
.waitFor();
passed++;
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");
+179
View File
@@ -0,0 +1,179 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
import { mkdir, writeFile } from "node:fs/promises";
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));
let passed = 0;
await mkdir("references/panel-navigation", { recursive: true });
async function seed(status = "authenticated", subject = "demo-anna") {
await page.goto(base + "/?page=dashboard");
await page.evaluate(
async ({ status, subject }) => {
const { createDemoIdentityAdapter } =
await import("/patterns/demo-identity.js");
const adapter = createDemoIdentityAdapter();
adapter.setScenario(status);
const key = "anidev.identity.demo.v2",
data = JSON.parse(sessionStorage.getItem(key));
data.subject = subject;
sessionStorage.setItem(key, JSON.stringify(data));
},
{ status, subject },
);
}
try {
for (const theme of ["light", "dark"])
for (const width of [1440, 768, 390]) {
await page.setViewportSize({ width, height: 900 });
await seed();
await page.goto(`${base}/?page=profile&theme=${theme}&locale=ru`);
assert.equal(
await page.locator("body").getAttribute("data-panel"),
"user",
);
assert.equal(
await page.locator('.nav-links [data-page="security"]').count(),
0,
);
await page.locator(".dock-brand").click();
await page.locator(".dock-account").click();
await page.locator(".account-parent-link").hover();
await page.locator(".account-submenu:popover-open").waitFor();
await page.waitForTimeout(200);
const parent = await page.locator("#account-menu").boundingBox(),
sub = await page.locator(".account-submenu").boundingBox();
assert.ok(
sub.x >= 0 &&
sub.x + sub.width <= width &&
sub.y >= 0 &&
sub.y + sub.height <= 901,
);
assert.ok(
sub.x >= parent.x + parent.width + 4 ||
sub.x + sub.width <= parent.x - 4,
);
await page.screenshot({
path: `references/panel-navigation/flyout-${theme}-${width}.png`,
});
await page.locator('.account-submenu [data-page="security"]').hover();
await page.waitForTimeout(220);
assert.equal(await page.locator("#account-menu").isVisible(), true);
await page.locator('.account-submenu [data-page="security"]').click();
assert.equal(new URL(page.url()).searchParams.get("page"), "security");
assert.equal(
await page.locator(".dock-brand").getAttribute("aria-expanded"),
"true",
);
await page.keyboard.press("Escape");
await page.locator(".dock-account").click();
await page.locator(".account-parent-link").click();
assert.equal(new URL(page.url()).searchParams.get("page"), "profile");
passed++;
}
await seed();
await page.goto(base + "/?page=profile&theme=dark&locale=ru");
await page.locator(".dock-account").click();
await page.locator(".account-parent-link").focus();
await page.keyboard.press("ArrowRight");
assert.equal(
await page
.locator('.account-submenu [data-page="profile"]')
.evaluate((e) => e === document.activeElement),
true,
);
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowLeft");
assert.equal(
await page
.locator(".account-parent-link")
.evaluate((e) => e === document.activeElement),
true,
);
assert.equal(await page.locator(".account-submenu").isVisible(), false);
await page.keyboard.press("ArrowRight");
await page.keyboard.press("Escape");
assert.equal(await page.locator("#account-menu").isVisible(), true);
await page.keyboard.press("Escape");
assert.equal(await page.locator("#account-menu").isVisible(), false);
passed++;
await page.locator(".dock-account").click();
await page.locator('[data-panel="admin"]').click();
assert.equal(await page.locator("body").getAttribute("data-panel"), "admin");
assert.equal(await page.locator('.nav-links [data-page="users"]').count(), 1);
await page.goto(base + "/?page=dashboard&panel=user");
await page.locator(".dock-account").click();
await page.locator('#account-menu [data-panel="admin"]').click();
assert.equal(await page.locator("body").getAttribute("data-panel"), "admin");
assert.equal(await page.locator('.nav-links [data-page="users"]').count(), 1);
passed++;
await seed("authenticated", "demo-mikhail");
await page.goto(base + "/?page=dashboard&panel=admin");
assert.equal(await page.locator("body").getAttribute("data-panel"), "user");
assert.equal(await page.locator('.nav-links [data-page="users"]').count(), 0);
assert.equal(
await page.locator('#account-menu [data-panel="admin"]').count(),
0,
);
passed++;
for (const status of [
"signed_out",
"loading",
"unavailable",
"factor_required",
]) {
await seed(status);
await page.goto(base + "/?page=profile&theme=dark");
await page.locator(".identity-gate").waitFor();
assert.equal(
await page.locator(".navigation,.dock-scrim,.app-header").count(),
0,
);
await page.keyboard.press("Control+k");
assert.equal(await page.locator("dialog[open]").count(), 0);
if (status === "signed_out")
await page.screenshot({
path: "references/panel-navigation/signed-out.png",
});
passed++;
}
const touch = await browser.newContext({
viewport: { width: 390, height: 844 },
hasTouch: true,
isMobile: true,
});
const tp = await touch.newPage();
await tp.goto(base + "/?page=profile&theme=dark&locale=ru");
await tp.locator(".dock-account").tap();
await tp.locator(".account-submenu-toggle").tap();
await tp.locator(".account-submenu:popover-open").waitFor();
await tp.waitForTimeout(300);
await tp.locator('.account-submenu [data-page="sessions"]').tap();
assert.equal(new URL(tp.url()).searchParams.get("page"), "sessions");
await touch.close();
passed++;
assert.deepEqual(errors, []);
await writeFile(
"references/panel-navigation/qa.json",
JSON.stringify(
{
passed,
errors,
checks:
"Separate user/admin Dock; account side flyout in both themes/three widths; pointer travel, direct management click, keys, touch, no Dock for guest/loading/error/factor states",
},
null,
2,
) + "\n",
);
console.log(`Panel navigation: ${passed} checks passed, no runtime errors`);
} finally {
await browser.close();
}