Move appearance into compact account theme controls
This commit is contained in:
1 parent
5852bf1897
commit
c3257a0f4d
13 files changed
+136
-12
No files matched your search
@@ -19,3 +19,5 @@ Dock утверждён пользователем 30.11.2026 и являетс
|
||||
Аккаунт и настройки аккаунта всегда остаются в нижней части единой панели, независимо от сервисных вкладок API и блокировки сервисов. account/account-settings — системные маршруты. API пока не существует: JSON в starter — fixtures, будущий контракт описан в docs/BACKEND-INTEGRATION.md. Ошибки используют общий error-page, бан — отдельное состояние banned с причиной текстом.
|
||||
|
||||
Уточнение: постоянный аккаунт существует только после входа. Без подтверждённой сессии нет Dock/шапки/подложки — только вход или состояние. Пользовательская и административная панели имеют разные Dock; личное управление убрано из основного nav. В строке «Аккаунт» — боковое подменю Управление/Безопасность/Устройства и сеансы/Настройки; обычный клик по строке открывает Управление. Учитывайте hover, клавиатуру и touch.
|
||||
|
||||
Оформление не занимает отдельный пункт подменю: светлая/тёмная тема переключаются компактными кнопками солнце/луна внизу меню аккаунта, без навигации. По просьбе пользователя промежуточные правки выполняются без тестовых прогонов; полный набор проверок отложен на финальный этап.
|
||||
@@ -1,4 +1,5 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
import { themeControlMarkup, mountThemeControl } from "./theme-control.js";
|
||||
import {
|
||||
accountSubmenuMarkup,
|
||||
mountAccountSubmenu,
|
||||
@@ -7,7 +8,15 @@ let sequence = 0;
|
||||
/** Fixed account controls live outside the API-driven service navigation. */
|
||||
export function mountAccountMenu(
|
||||
root,
|
||||
{ onNavigate, t = (ru) => ru, name = "", email = "", items } = {},
|
||||
{
|
||||
onNavigate,
|
||||
t = (ru) => ru,
|
||||
name = "",
|
||||
email = "",
|
||||
items,
|
||||
theme = "light",
|
||||
onThemeChange,
|
||||
} = {},
|
||||
) {
|
||||
if (typeof onNavigate !== "function")
|
||||
throw new TypeError("Account menu needs onNavigate");
|
||||
@@ -28,16 +37,17 @@ export function mountAccountMenu(
|
||||
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);
|
||||
if (onThemeChange)
|
||||
popup.insertAdjacentHTML("beforeend", themeControlMarkup({ theme, t }));
|
||||
const themeControl = mountThemeControl(popup, {
|
||||
theme,
|
||||
onChange: onThemeChange,
|
||||
});
|
||||
function update(identity = {}) {
|
||||
root.querySelector(".account-identity b").textContent =
|
||||
identity.name || t("Аккаунт", "Account");
|
||||
@@ -123,6 +133,7 @@ export function mountAccountMenu(
|
||||
);
|
||||
return {
|
||||
update,
|
||||
setTheme: themeControl.update,
|
||||
close,
|
||||
setActive(id) {
|
||||
popup.querySelectorAll("[data-account-page]").forEach((button) => {
|
||||
@@ -136,6 +147,7 @@ export function mountAccountMenu(
|
||||
close();
|
||||
abort.abort();
|
||||
sections.dispose();
|
||||
themeControl.dispose();
|
||||
trigger.removeAttribute("popovertarget");
|
||||
},
|
||||
};
|
||||
|
||||
@@ -109,6 +109,7 @@ export async function exportSystem(
|
||||
"components/copy-field.js",
|
||||
"components/error-page.js",
|
||||
"components/account-submenu.js",
|
||||
"components/theme-control.js",
|
||||
"components/search-select.js",
|
||||
"components/workspaces.css",
|
||||
"components/ssh-console.js",
|
||||
|
||||
@@ -3118,6 +3118,42 @@ body[data-concept="dock"] .copy-input .input-copy-action:active {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.account-theme-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 10px 6px 3px;
|
||||
margin-top: 6px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
font-size: 12px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.account-theme-options {
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
padding: 3px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-bg);
|
||||
}
|
||||
.account-menu .account-theme-options button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
min-height: 32px;
|
||||
padding: 8px;
|
||||
border-radius: 50%;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.account-menu .account-theme-options button[aria-pressed="true"] {
|
||||
background: var(--color-row-active);
|
||||
color: var(--color-accent);
|
||||
}
|
||||
.account-menu .account-theme-options button:focus-visible {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.account-menu .account-parent {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 32px;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
export function themeControlMarkup({ theme = "light", t = (ru) => ru } = {}) {
|
||||
return `<div class="account-theme-row"><span>${t("Тема", "Theme")}</span><div class="account-theme-options" role="group" aria-label="${t("Цветовая тема", "Color theme")}">${["light", "dark"].map((mode) => `<button type="button" data-account-theme="${mode}" aria-pressed="${mode === theme}" aria-label="${mode === "light" ? t("Светлая тема", "Light theme") : t("Тёмная тема", "Dark theme")}" title="${mode === "light" ? t("Светлая тема", "Light theme") : t("Тёмная тема", "Dark theme")}">${iconSvg(mode === "light" ? "sun" : "moon", { size: 16 })}</button>`).join("")}</div></div>`;
|
||||
}
|
||||
export function mountThemeControl(root, { theme = "light", onChange } = {}) {
|
||||
const abort = new AbortController();
|
||||
function update(mode) {
|
||||
root
|
||||
.querySelectorAll("[data-account-theme]")
|
||||
.forEach((button) =>
|
||||
button.setAttribute(
|
||||
"aria-pressed",
|
||||
String(button.dataset.accountTheme === mode),
|
||||
),
|
||||
);
|
||||
}
|
||||
root.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const button = event.target.closest("[data-account-theme]");
|
||||
if (!button) return;
|
||||
event.stopPropagation();
|
||||
update(button.dataset.accountTheme);
|
||||
onChange?.(button.dataset.accountTheme);
|
||||
},
|
||||
{ signal: abort.signal },
|
||||
);
|
||||
update(theme);
|
||||
return { update, dispose: () => abort.abort() };
|
||||
}
|
||||
@@ -144,6 +144,8 @@ title/description/label/value — строки; rows — массив. Это п
|
||||
|
||||
## 5. Настройки и действия
|
||||
|
||||
Оформление теперь переключается компактным блоком солнце/луна внизу меню аккаунта, без отдельного пункта личного подменю и без смены страницы. Для темы отдельный API-запрос не нужен; старый маршрут настроек остаётся совместимым, но не является основным способом выбора оформления.
|
||||
|
||||
В starter настройки аккаунта переключают тему только в текущей вкладке. PATCH/POST настроек пока не выполняются и не заявлены как сохранённые на сервере. Когда API будет готов, отдельно согласуйте endpoint предпочтений, валидацию и поля, после успешного сохранения показывайте success-тост; при отказе сохраняйте введённые данные и показывайте ошибку. Не используйте GET для изменений.
|
||||
|
||||
Для живого подключения потребуются: адрес API, схема авторизации/SSO, идентификаторы модулей, типы данных каждого экрана и endpoints команд. Это граница интеграции продукта; документация не требует заранее реализовывать SSR или BFF.
|
||||
|
||||
@@ -28,6 +28,8 @@ Shell показывается только после подтверждени
|
||||
|
||||
## CSS-контракты
|
||||
|
||||
Оформление вынесено из списка личных страниц в компактный theme-control в меню аккаунта. `mountAccountMenu` принимает theme/onThemeChange и возвращает setTheme(mode) для синхронизации с другими переключателями. `themeControlMarkup` и `mountThemeControl` позволяют подключить тот же блок к существующей разметке; смена темы не закрывает меню и не меняет маршрут. Старые прямые маршруты оформления оставлены для совместимости.
|
||||
|
||||
Токены: `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).
|
||||
|
||||
@@ -19,6 +19,7 @@ const abort = new AbortController(),
|
||||
{ signal } = abort;
|
||||
const notify = createNotifier($("#project-toast"), { t });
|
||||
const cleanups = [];
|
||||
let syncAccountTheme = () => {};
|
||||
const pageIds = new Set(["overview", "projects", "logs"]);
|
||||
let allowedIds = new Set(),
|
||||
serviceHome = null;
|
||||
@@ -45,6 +46,7 @@ const preview = (id) =>
|
||||
: /^error-(\d{3}|offline|banned)$/.exec(id || "")?.[1];
|
||||
const fixed = (id) => fixedIds.has(id) || Boolean(preview(id));
|
||||
function renderTheme() {
|
||||
syncAccountTheme();
|
||||
applyTheme({ theme });
|
||||
$("#theme-toggle").innerHTML = iconSvg(theme === "light" ? "moon" : "sun", {
|
||||
size: 20,
|
||||
@@ -388,7 +390,14 @@ const dock = mountDock({
|
||||
const accountMenu = mountAccountMenu($("#persistent-account"), {
|
||||
t,
|
||||
onNavigate: go,
|
||||
theme,
|
||||
onThemeChange: (mode) => {
|
||||
theme = mode;
|
||||
renderTheme();
|
||||
if (current === "account-settings") showPage(current);
|
||||
},
|
||||
});
|
||||
syncAccountTheme = () => accountMenu.setTheme(theme);
|
||||
const navigation = mountNavigation($(".nav-links"), {
|
||||
t,
|
||||
onActiveChange: (id) => {
|
||||
|
||||
+27
-6
@@ -5,6 +5,10 @@ import {
|
||||
} from "../components/search-select.js";
|
||||
import { createNotifier } from "../components/toast.js";
|
||||
import { mountCopyField } from "../components/copy-field.js";
|
||||
import {
|
||||
themeControlMarkup,
|
||||
mountThemeControl,
|
||||
} from "../components/theme-control.js";
|
||||
import {
|
||||
accountSubmenuMarkup,
|
||||
mountAccountSubmenu,
|
||||
@@ -285,16 +289,11 @@ function dockAccount() {
|
||||
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="account-separator" data-identity="logout">${icon("logout")}<span>${t("Выйти из SSO", "Sign out of SSO")}</span></button>${themeControlMarkup({ theme, t })}</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>`;
|
||||
}
|
||||
let administrationOpen = ["ssh", "logs"].includes(page);
|
||||
@@ -496,6 +495,28 @@ function render({ preserveDock = false } = {}) {
|
||||
if ($("#account-menu")) {
|
||||
const submenu = mountAccountSubmenu($("#account-menu"));
|
||||
selectCleanups.push(() => submenu.dispose());
|
||||
const themeControl = mountThemeControl($("#account-menu"), {
|
||||
theme,
|
||||
onChange: (mode) => {
|
||||
theme = mode;
|
||||
tokens = tokensFor(concept.id, theme, rawAccent || undefined, density);
|
||||
document.documentElement.style.cssText = cssVars(tokens);
|
||||
document.body.dataset.theme = theme;
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set("theme", theme);
|
||||
history.replaceState({}, "", url);
|
||||
savePreferences();
|
||||
document
|
||||
.querySelectorAll('[data-identity="theme"]')
|
||||
.forEach((button) =>
|
||||
button.setAttribute(
|
||||
"aria-pressed",
|
||||
String(button.dataset.theme === theme),
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
selectCleanups.push(() => themeControl.dispose());
|
||||
$("#account-menu").addEventListener("keydown", (event) => {
|
||||
if (event.key === "Tab") {
|
||||
$("#account-menu").hidePopover();
|
||||
|
||||
@@ -168,6 +168,8 @@ Log reader: фильтры уровня/сервиса/текста, подсв
|
||||
|
||||
## Сессия, разные Dock и боковое меню аккаунта / 01.12.2026
|
||||
|
||||
Последующая промежуточная правка: оформление перенесено в компактный переключатель темы меню аккаунта. По просьбе пользователя тестовые прогоны и обновление QA-скриншотов для этой правки отложены на финальный этап; результаты ниже относятся к предыдущей редакции.
|
||||
|
||||
Без подтверждённого входа галерея рендерит только вход/состояние, без 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 всё равно проверяет права.
|
||||
|
||||
@@ -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 {
|
||||
themeControlMarkup,
|
||||
mountThemeControl,
|
||||
} from "../components/theme-control.js";
|
||||
export {
|
||||
accountSubmenuMarkup,
|
||||
mountAccountSubmenu,
|
||||
|
||||
@@ -48,6 +48,7 @@ for (const file of [
|
||||
"components/dock.js",
|
||||
"components/navigation.js",
|
||||
"components/account-menu.js",
|
||||
"components/theme-control.js",
|
||||
"components/account-submenu.js",
|
||||
"components/error-page.js",
|
||||
"components/ssh-console.js",
|
||||
|
||||
@@ -33,4 +33,6 @@ Use semantic tokens for surfaces, text and states; preserve native form controls
|
||||
|
||||
## Verification
|
||||
|
||||
Appearance is a compact light/dark icon control at the bottom of the account menu, not a separate flyout item. Switching it preserves the route and keeps the menu open. When working in this source project, follow the user's current instruction to defer intermediate test runs to the final validation stage.
|
||||
|
||||
Verify the changed flows in both themes and desktop/mobile, with keyboard, long Russian labels, empty/error data and any affected modal or popover. Confirm that dynamic menu changes preserve an available active section and provide a sensible fallback when it disappears. Dispose controllers, listeners and requests on unmount. Review the rendered result; automated checks alone are not an accessibility audit. Report the actual checks and remaining integration limits.
|
||||
Reference in new issue
Block a user