From c3257a0f4dc1ace7247e09a014c4702670c38783 Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Tue, 1 Dec 2026 16:21:17 +0300 Subject: [PATCH] Move appearance into compact account theme controls --- AGENTS.md | 2 ++ components/account-menu.js | 24 ++++++++++++++----- components/export-system.js | 1 + components/system.css | 36 ++++++++++++++++++++++++++++ components/theme-control.js | 30 +++++++++++++++++++++++ docs/BACKEND-INTEGRATION.md | 2 ++ docs/PUBLIC-API.md | 2 ++ examples/starter/app.js | 9 +++++++ playground/frame.js | 33 ++++++++++++++++++++----- references/QA.md | 2 ++ runtime/index.js | 4 ++++ scripts/build-package.mjs | 1 + skills/anidev-design-system/SKILL.md | 2 ++ 13 files changed, 136 insertions(+), 12 deletions(-) create mode 100644 components/theme-control.js diff --git a/AGENTS.md b/AGENTS.md index 464d408..92270f6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. + +Оформление не занимает отдельный пункт подменю: светлая/тёмная тема переключаются компактными кнопками солнце/луна внизу меню аккаунта, без навигации. По просьбе пользователя промежуточные правки выполняются без тестовых прогонов; полный набор проверок отложен на финальный этап. diff --git a/components/account-menu.js b/components/account-menu.js index d280272..f4ba4da 100644 --- a/components/account-menu.js +++ b/components/account-menu.js @@ -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 = ``; 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"); }, }; diff --git a/components/export-system.js b/components/export-system.js index c102267..8a28b72 100644 --- a/components/export-system.js +++ b/components/export-system.js @@ -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", diff --git a/components/system.css b/components/system.css index a7b7bc3..5c81079 100644 --- a/components/system.css +++ b/components/system.css @@ -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; diff --git a/components/theme-control.js b/components/theme-control.js new file mode 100644 index 0000000..22a711a --- /dev/null +++ b/components/theme-control.js @@ -0,0 +1,30 @@ +import { iconSvg } from "../icons/icons.js"; +export function themeControlMarkup({ theme = "light", t = (ru) => ru } = {}) { + return `
${t("Тема", "Theme")}
`; +} +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() }; +} diff --git a/docs/BACKEND-INTEGRATION.md b/docs/BACKEND-INTEGRATION.md index aee2876..4bba276 100644 --- a/docs/BACKEND-INTEGRATION.md +++ b/docs/BACKEND-INTEGRATION.md @@ -144,6 +144,8 @@ title/description/label/value — строки; rows — массив. Это п ## 5. Настройки и действия +Оформление теперь переключается компактным блоком солнце/луна внизу меню аккаунта, без отдельного пункта личного подменю и без смены страницы. Для темы отдельный API-запрос не нужен; старый маршрут настроек остаётся совместимым, но не является основным способом выбора оформления. + В starter настройки аккаунта переключают тему только в текущей вкладке. PATCH/POST настроек пока не выполняются и не заявлены как сохранённые на сервере. Когда API будет готов, отдельно согласуйте endpoint предпочтений, валидацию и поля, после успешного сохранения показывайте success-тост; при отказе сохраняйте введённые данные и показывайте ошибку. Не используйте GET для изменений. Для живого подключения потребуются: адрес API, схема авторизации/SSO, идентификаторы модулей, типы данных каждого экрана и endpoints команд. Это граница интеграции продукта; документация не требует заранее реализовывать SSR или BFF. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index 65356c4..9d9e375 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -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). diff --git a/examples/starter/app.js b/examples/starter/app.js index 7a68a53..54824d5 100644 --- a/examples/starter/app.js +++ b/examples/starter/app.js @@ -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) => { diff --git a/playground/frame.js b/playground/frame.js index ad6847a..22c013f 100644 --- a/playground/frame.js +++ b/playground/frame.js @@ -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)) ? `` : ""} - + ${themeControlMarkup({ theme, t })} `; } 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(); diff --git a/references/QA.md b/references/QA.md index 5775781..00c7837 100644 --- a/references/QA.md +++ b/references/QA.md @@ -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 всё равно проверяет права. diff --git a/runtime/index.js b/runtime/index.js index b465f4a..5cad0d8 100644 --- a/runtime/index.js +++ b/runtime/index.js @@ -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, diff --git a/scripts/build-package.mjs b/scripts/build-package.mjs index e8647b2..a2a1be2 100644 --- a/scripts/build-package.mjs +++ b/scripts/build-package.mjs @@ -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", diff --git a/skills/anidev-design-system/SKILL.md b/skills/anidev-design-system/SKILL.md index 17e183b..e682069 100644 --- a/skills/anidev-design-system/SKILL.md +++ b/skills/anidev-design-system/SKILL.md @@ -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.