From c41a5e4276bd8c043818e6bdeb77abdc3e28ef15 Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Sat, 28 Nov 2026 04:00:57 +0300 Subject: [PATCH] Expand Dock gallery with account workspace and identity states --- AGENTS.md | 2 + DESIGN.md | 4 + README.md | 8 + components/CONTRACT.md | 2 + components/account-pages.js | 626 ++++++++++++++++++ components/system.css | 588 ++++++++++++++++ package.json | 3 +- patterns/IDENTITY.md | 37 ++ patterns/UX.md | 4 +- patterns/demo-identity.js | 301 +++++++++ playground/frame.js | 191 ++++-- playground/gallery.js | 61 +- playground/index.html | 6 + references/QA.md | 8 + .../dock-revision/dark-desktop-account.png | Bin 83477 -> 83298 bytes .../dock-revision/dark-desktop-collapsed.png | Bin 78155 -> 77938 bytes .../dock-revision/dark-desktop-expanded.png | Bin 67977 -> 65449 bytes .../dock-revision/dark-mobile-account.png | Bin 46084 -> 45766 bytes .../dock-revision/dark-mobile-collapsed.png | Bin 43917 -> 43596 bytes .../dock-revision/dark-mobile-expanded.png | Bin 32453 -> 30154 bytes .../dock-revision/dark-tablet-account.png | Bin 68913 -> 68798 bytes .../dock-revision/dark-tablet-collapsed.png | Bin 66868 -> 66346 bytes .../dock-revision/dark-tablet-expanded.png | Bin 54484 -> 52158 bytes .../dock-revision/light-desktop-account.png | Bin 87537 -> 87386 bytes .../dock-revision/light-desktop-collapsed.png | Bin 77279 -> 76940 bytes .../dock-revision/light-desktop-expanded.png | Bin 70369 -> 67863 bytes .../dock-revision/light-mobile-account.png | Bin 48868 -> 48834 bytes .../dock-revision/light-mobile-collapsed.png | Bin 43758 -> 43392 bytes .../dock-revision/light-mobile-expanded.png | Bin 33653 -> 31479 bytes .../dock-revision/light-tablet-account.png | Bin 72690 -> 72643 bytes .../dock-revision/light-tablet-collapsed.png | Bin 66316 -> 65671 bytes .../dock-revision/light-tablet-expanded.png | Bin 56601 -> 54515 bytes references/dock-revision/preview.png | Bin 87612 -> 86961 bytes references/gallery.png | Bin 140703 -> 118838 bytes references/identity/README.md | 21 + .../identity/appearance-dark-desktop.png | Bin 0 -> 37008 bytes .../identity/appearance-dark-mobile.png | Bin 0 -> 30436 bytes .../identity/appearance-light-desktop.png | Bin 0 -> 36383 bytes .../identity/appearance-light-mobile.png | Bin 0 -> 29903 bytes .../identity/applications-dark-desktop.png | Bin 0 -> 48326 bytes .../identity/applications-dark-mobile.png | Bin 0 -> 40725 bytes .../identity/applications-light-desktop.png | Bin 0 -> 47727 bytes .../identity/applications-light-mobile.png | Bin 0 -> 39926 bytes references/identity/identity-dark-desktop.png | Bin 0 -> 42235 bytes references/identity/identity-dark-mobile.png | Bin 0 -> 35402 bytes .../identity/identity-light-desktop.png | Bin 0 -> 42115 bytes references/identity/identity-light-mobile.png | Bin 0 -> 35085 bytes references/identity/preview.png | Bin 0 -> 126962 bytes references/identity/profile-dark-desktop.png | Bin 0 -> 56732 bytes references/identity/profile-dark-mobile.png | Bin 0 -> 49310 bytes references/identity/profile-light-desktop.png | Bin 0 -> 56242 bytes references/identity/profile-light-mobile.png | Bin 0 -> 48379 bytes references/identity/qa.json | 7 + references/identity/security-dark-desktop.png | Bin 0 -> 57251 bytes references/identity/security-dark-mobile.png | Bin 0 -> 49318 bytes .../identity/security-light-desktop.png | Bin 0 -> 56483 bytes references/identity/security-light-mobile.png | Bin 0 -> 48159 bytes references/identity/sessions-dark-desktop.png | Bin 0 -> 50939 bytes references/identity/sessions-dark-mobile.png | Bin 0 -> 42690 bytes .../identity/sessions-light-desktop.png | Bin 0 -> 50304 bytes references/identity/sessions-light-mobile.png | Bin 0 -> 42035 bytes .../identity/totp-error-dark-desktop.png | Bin 0 -> 47850 bytes .../identity/totp-error-dark-mobile.png | Bin 0 -> 37027 bytes .../identity/totp-error-light-desktop.png | Bin 0 -> 47978 bytes .../identity/totp-error-light-mobile.png | Bin 0 -> 37190 bytes .../identity/user-access-light-desktop.png | Bin 0 -> 71495 bytes references/qa-summary.json | 16 +- tests/browser.mjs | 2 +- tests/dock.mjs | 22 +- tests/identity.mjs | 379 +++++++++++ tests/totp-layout.mjs | 33 + 71 files changed, 2254 insertions(+), 67 deletions(-) create mode 100644 components/account-pages.js create mode 100644 patterns/IDENTITY.md create mode 100644 patterns/demo-identity.js create mode 100644 references/identity/README.md create mode 100644 references/identity/appearance-dark-desktop.png create mode 100644 references/identity/appearance-dark-mobile.png create mode 100644 references/identity/appearance-light-desktop.png create mode 100644 references/identity/appearance-light-mobile.png create mode 100644 references/identity/applications-dark-desktop.png create mode 100644 references/identity/applications-dark-mobile.png create mode 100644 references/identity/applications-light-desktop.png create mode 100644 references/identity/applications-light-mobile.png create mode 100644 references/identity/identity-dark-desktop.png create mode 100644 references/identity/identity-dark-mobile.png create mode 100644 references/identity/identity-light-desktop.png create mode 100644 references/identity/identity-light-mobile.png create mode 100644 references/identity/preview.png create mode 100644 references/identity/profile-dark-desktop.png create mode 100644 references/identity/profile-dark-mobile.png create mode 100644 references/identity/profile-light-desktop.png create mode 100644 references/identity/profile-light-mobile.png create mode 100644 references/identity/qa.json create mode 100644 references/identity/security-dark-desktop.png create mode 100644 references/identity/security-dark-mobile.png create mode 100644 references/identity/security-light-desktop.png create mode 100644 references/identity/security-light-mobile.png create mode 100644 references/identity/sessions-dark-desktop.png create mode 100644 references/identity/sessions-dark-mobile.png create mode 100644 references/identity/sessions-light-desktop.png create mode 100644 references/identity/sessions-light-mobile.png create mode 100644 references/identity/totp-error-dark-desktop.png create mode 100644 references/identity/totp-error-dark-mobile.png create mode 100644 references/identity/totp-error-light-desktop.png create mode 100644 references/identity/totp-error-light-mobile.png create mode 100644 references/identity/user-access-light-desktop.png create mode 100644 tests/identity.mjs create mode 100644 tests/totp-layout.mjs diff --git a/AGENTS.md b/AGENTS.md index 2f29999..0194e80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,3 +9,5 @@ Проверка: npm run check; npm test при работающем npm run dev. Browser suite использует Edge или PLAYWRIGHT_EXECUTABLE_PATH. Проверяйте desktop/tablet/mobile, обе темы, RU/EN, диалоги, фокус, экспорт. Фиксируйте реальные ограничения в references/QA.md. Не называйте автоматический тест полным аудитом доступности. Не коммитьте .research, node_modules, .tools, приватные ключи, credentials и тестовые выгрузки. Для push используйте настроенную SSH-аутентификацию без сохранения содержимого ключей. + +Личный кабинет и состояния Identity в этой галерее являются демонстрационными. Промпт SSO — продуктовый контекст; не меняйте соседний репозиторий SSO Service и не подключайте реальную авторизацию без отдельного задания пользователя. diff --git a/DESIGN.md b/DESIGN.md index 6cdbc95..ec2561a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -36,3 +36,7 @@ Production-адаптеры React/Vue/Svelte впоследствии должн ## Перед фиксацией Пользователь выбирает концепцию либо конкретную комбинацию её свойств. Затем фиксируем типографику, лицензии локальных шрифтов, уровни токенов, компоненты и примеры новых/существующих проектов; формируем настоящий устанавливаемый Skill. До выбора `SKILL.md` — описание следующего этапа, не глобальная инструкция. + +## Промежуточный Dock / revision 04 + +Развитие только галереи: личный кабинет с собственной навигацией, профиль/безопасность/устройства/приложения/оформление, лаборатория состояний Identity, роли и права в редакторе пользователя. Отдельная иконка раскрытия удалена; hover панели и доступная бренд-кнопка сохраняют управление. Промпт SSO используется как продуктовый контекст; его приложение и backend не меняются. Экспорт включает новые представления, демо-адаптер и документы. Палитры обеих тем экспортируются раздельно, явный пользовательский акцент сохраняется как override. diff --git a/README.md b/README.md index fcba843..5b64927 100644 --- a/README.md +++ b/README.md @@ -50,3 +50,11 @@ Suite использует установленный Edge на Windows. Для Для просмотра правок откройте `/playground/?concept=dock`: компактная панель с иконками, раскрытие поверх контента с затемнением, меню аккаунта по пользовательскому референсу, новые петрольно-бирюзовые темы и анимации. Это не финальная версия. [Описание и скриншоты](references/dock-revision/README.md). Целевой browser suite: `npm run test:dock`. Проектный контекст будущей SSO-интеграции получен из чата «Переработать настройки SSO»: [промпт SSO](prompts/SSO.md), [происхождение](prompts/README.md). Это справочный контекст, не подключённый backend. + +## Dock / личный кабинет — revision 04 + +Новые демонстрационные экраны: Аккаунт, Безопасность, Устройства и сеансы, Приложения, Оформление, Состояния входа. Прямой просмотр: `/playground/?concept=dock&page=profile`. Отдельная иконка раскрытия убрана: панель открывается по наведению, а `a/` управляет ей с клавиатуры и touch. + +Личный кабинет отделён от администрирования; в редакторе пользователя — роли SSO и права на приложения. Работают тестовые формы, фото, Passkey-примеры, подтверждения по почте без отправки, отзыв сеансов и сценарии недоступности/отказа. Это развитие галереи, настоящий SSO Service не изменён. [Описание контракта](patterns/IDENTITY.md) · [скриншоты и QA](references/identity/README.md). + +Проверки: `npm test`, `npm run test:dock`, `npm run test:identity` при работающем сервере. Финальные токены и устанавливаемый Skill ждут утверждения дизайна. diff --git a/components/CONTRACT.md b/components/CONTRACT.md index 02b81c3..a171a0c 100644 --- a/components/CONTRACT.md +++ b/components/CONTRACT.md @@ -28,3 +28,5 @@ Hover и active — временные указательные состояни Это спецификация кандидатов и рабочие образцы, ещё не опубликованный пакет production-компонентов. Перед production нужны адаптер выбранного стека, ручная проверка screen reader, backend-контракт и обработка реальных ошибок сети. Dock revision 02: постоянная панель иконок, переключатель aria-expanded/aria-controls; раскрытая навигация имеет role=dialog/aria-modal, основной контент inert. Tab остаётся в меню, Escape возвращает фокус переключателю, подложка закрывает меню. Меню аккаунта использует native popover с autofocus, light dismiss и Escape; первый Escape закрывает popover, второй — панель. + +Revision 04: отдельной иконки раскрытия Dock нет. Hover всей панели открывает меню; бренд-кнопка `a/` сохраняет aria-expanded/aria-controls, Enter/Space и touch. Личный кабинет и статусы Identity описаны в `patterns/IDENTITY.md`. Фото использует одинаковое object-fit: cover во всех представлениях. Смена состояния аккаунта закрывает открытый приватный диалог и скрывает прежний контент. diff --git a/components/account-pages.js b/components/account-pages.js new file mode 100644 index 0000000..dfad8cb --- /dev/null +++ b/components/account-pages.js @@ -0,0 +1,626 @@ +import { + identityStates, + applicationCatalog, + systemRoles, +} from "../patterns/demo-identity.js"; +export const accountPageIds = [ + "profile", + "security", + "sessions", + "applications", + "appearance", + "identity", +]; +export function createAccountUI({ + adapter, + t, + escape: e, + heading, + icon, + openDialog, + toast, + render, + navigate, + setTheme, +}) { + const $ = (s) => document.querySelector(s), + snap = () => adapter.snapshot(); + let pendingEnrollment = false; + let avatarDraft = null, + avatarPreview = null, + selectedGrants = new Set(), + editingUser = null; + const title = { + profile: t("Аккаунт", "Account"), + security: t("Безопасность", "Security"), + sessions: t("Устройства и сеансы", "Devices and sessions"), + applications: t("Приложения", "Applications"), + appearance: t("Оформление", "Appearance"), + identity: t("Состояния входа", "Sign-in states"), + }; + const demo = `

${t("Демонстрация Anidev Identity · действия не обращаются к SSO", "Anidev Identity demo · actions do not contact SSO")}

`; + const names = (a) => `${a.firstName} ${a.lastName}`; + const avatar = (a, cls = "") => + a.avatar + ? `${e(names(a))}` + : ``; + const action = (id, ru, en, cls = "") => + ``; + const stateLabels = { + authenticated: t("Вход выполнен", "Signed in"), + loading: t("Проверяем сеанс", "Checking session"), + signed_out: t("Вы вышли из аккаунта", "You are signed out"), + access_denied: t("Нет доступа к приложению", "Application access denied"), + factor_required: t("Подтвердите вход", "Verify your sign-in"), + factor_enrollment_required: t( + "Подключите способ подтверждения", + "Set up a verification method", + ), + rebind_required: t("Восстановите подключение", "Reconnect your session"), + unavailable: t("Сервис входа недоступен", "Identity service unavailable"), + account_changed: t("Аккаунт изменился", "Account changed"), + signing_out: t("Завершаем сеанс", "Signing out"), + }; + const stateDescriptions = { + loading: t( + "Пока личность не проверена, данные аккаунта скрыты.", + "Account data stays hidden until identity is verified.", + ), + signed_out: t( + "Войдите, чтобы продолжить работу. Другие устройства сохраняют свои сеансы.", + "Sign in to continue. Other devices retain their sessions.", + ), + access_denied: t( + "Текущему аккаунту не выдан доступ. Обратитесь к администратору или смените аккаунт.", + "This account has not been granted access. Contact an administrator or switch account.", + ), + factor_required: t( + "Приложению требуется свежий код TOTP. Пароль повторно не запрашивается.", + "This application requires a fresh TOTP code. Your password is not requested again.", + ), + factor_enrollment_required: t( + "Для продолжения нужно зарегистрировать способ подтверждения в SSO.", + "Register a verification method in SSO to continue.", + ), + rebind_required: t( + "Повторно подключите приложение через SSO, используя действующий вход.", + "Reconnect the application through SSO using your existing sign-in.", + ), + unavailable: t( + "Защищённые данные скрыты. Проверьте соединение и повторите попытку.", + "Protected data is hidden. Check your connection and try again.", + ), + account_changed: t( + "Прежнее содержимое очищено. Подтвердите загрузку текущего аккаунта.", + "Previous content has been cleared. Continue to load the current account.", + ), + signing_out: t( + "Данные скрыты, повторное действие недоступно.", + "Data is hidden and repeat actions are disabled.", + ), + }; + function gate(status = snap().status) { + return `

${stateLabels[status] || stateLabels.signed_out}

${stateDescriptions[status] || ""}

${["loading", "signing_out"].includes(status) ? `
` : `
${status === "factor_required" ? action("verify-factor", "Подтвердить TOTP", "Verify TOTP", "primary") : status === "factor_enrollment_required" ? action("enroll-factor", "Подключить в SSO", "Set up in SSO", "primary") : status === "signed_out" ? action("begin-signin", "Войти", "Sign in", "primary") : status === "access_denied" ? action("switch", "Сменить аккаунт", "Switch account", "primary") : action("resolve", "Повторить проверку", "Check again", "primary")}${status !== "signed_out" ? action("logout", "Выйти из SSO", "Sign out of SSO") : ""}
`}${demo}
`; + } + function renderPage(page) { + if (page === "identity") return stateLab(); + if (snap().status !== "authenticated") return gate(); + const a = snap().account; + return { + profile: profile, + security: security, + sessions: sessions, + applications: applications, + appearance: appearance, + }[page](a); + } + function profile(a) { + return `${heading(title.profile, t("Личные данные и ваш профиль в экосистеме Anidev.", "Your profile across the Anidev ecosystem."))}
${avatar(a, "large")}

${e(names(a))}

@${e(a.username)}

${a.roles.map((r) => `${e(r)}`).join("")}

${t("Личные данные", "Personal information")}

${t("Имя и username можно изменить. Идентификатор аккаунта остаётся прежним.", "Your name and username may change. Your account ID stays the same.")}

Email${a.email ? e(a.email) : t("Не добавлен", "Not added")}${a.emailVerified ? `${t("Подтверждён", "Verified")}` : action("add-email", "Добавить и подтвердить", "Add and verify")}
${t("Для изменения подтверждённой почты обратитесь к администратору.", "Contact your administrator to change a verified email address.")}
${avatar(a)}
PNG, JPEG, WebP · ${t("до 2 МБ", "up to 2 MB")}${action("clear-avatar", "Убрать фото", "Remove photo")}
Account ID${e(a.sub)}
${demo}
`; + } + function security(a) { + return `${heading(title.security, t("Способы входа и подтверждение важных действий.", "Sign-in methods and verification for important changes."))}

${t("Способы входа", "Sign-in methods")}

${t("Пароль", "Password")}

${t("Последнее изменение: ", "Last changed: ")}${a.passwordChanged ? new Intl.DateTimeFormat(t("ru-RU", "en-US"), { dateStyle: "long" }).format(new Date(a.passwordChanged + "T12:00:00Z")) : t("нет данных", "no data")}

${action("password-link", "Сменить", "Change")}

TOTP

${a.totp ? t("Подключён", "Enabled") : t("Не подключён", "Not enabled")}

${t("Сброс подтверждается ссылкой из письма.", "Reset is verified using an email link.")}
${action(a.totp ? "totp-link" : "enroll-factor", a.totp ? "Сменить" : "Подключить", a.totp ? "Change" : "Set up")}

Passkey

${t("Встроенный способ входа: Windows Hello или Touch ID.", "Platform sign-in with Windows Hello or Touch ID.")}

${action("add-passkey", "Добавить", "Add")}
${a.passkeys.length ? a.passkeys.map((k) => `

${e(k.name)}

${t("Добавлен", "Added")} ${k.created}

`).join("") : `

${t("Passkey ещё не добавлен", "No passkey added yet")}

${t("Добавьте ключ, чтобы входить с помощью устройства.", "Add a key to sign in with your device.")}

`}

${t("Как работают проверки", "How verification works")}

${t("Приложение запрашивает только недостающий фактор. Возможность заменить TOTP свежим Passkey задаёт администратор приложения. Для администрирования SSO требуется отдельный TOTP.", "Applications request only the missing factor. An application administrator decides whether a fresh passkey can replace TOTP. SSO administration requires a separate TOTP verification.")}

${demo}
`; + } + function sessions() { + const rows = snap().sessions; + return `${heading(title.sessions, t("Устройства, на которых выполнен вход в ваш аккаунт.", "Devices currently signed in to your account."), action("revoke-others", "Завершить другие сеансы", "End other sessions"))}
${t("Устройство", "Device")}${t("Последняя активность", "Last activity")}
${rows.map((s) => `
${icon("sessions")}

${s.device}

${s.place}${s.current ? " · " + t("Текущий сеанс", "Current session") : ""}

`).join("")}

${t("Выход из SSO завершает текущий браузерный сеанс. Остальные устройства сохраняют вход, пока вы не завершите их отдельно.", "Signing out of SSO ends this browser session. Other devices stay signed in until you end those sessions separately.")}

${demo}
`; + } + function applications(a) { + const grants = adapter.getGrants(a.sub === "demo-anna" ? 1 : 2); + return `${heading(title.applications, t("Сервисы, доступные вашему аккаунту.", "Services available to your account."))}
${grants + .map((g) => { + const app = applicationCatalog.find((v) => v.id === g.application); + return `

${app.name}

${app.description[t("ru", "en") === "ru" ? 0 : 1]}

${g.status === "active" ? t("Доступ выдан", "Access granted") + " · " + g.added : t("Доступ приостановлен", "Access suspended") + (g.showReason ? " · " + e(g.reason) : "")}
`; + }) + .join( + "", + )}

${t("Нужен другой сервис? Запросите доступ у администратора организации.", "Need another service? Request access from your organization administrator.")}

${demo}
`; + } + function appearance() { + return `${heading(title.appearance, t("Выберите режим для повседневной работы.", "Choose a mode for everyday work."))}
${["light", "dark"].map((mode) => ``).join("")}

${t("Палитру организации настраивает администратор. Пользователь выбирает только светлый или тёмный режим.", "An administrator configures your organization palette. Users choose only light or dark mode.")}

${demo}
`; + } + function stateLab() { + const status = snap().status; + return `${heading(title.identity, t("Просмотрите реакцию интерфейса на состояние SSO.", "Inspect how the interface responds to SSO state."), action("reset", "Сбросить демо", "Reset demo"))}
${status}
${status === "authenticated" ? `

${stateLabels.authenticated}

${t("Личность проверена. Доступны профиль, сеансы и разрешённые приложения.", "Identity verified. Profile, sessions and permitted applications are available.")}

` : gate(status)}

${t("Все состояния здесь управляются вручную для сравнения дизайна. При реальной интеграции они приходят от backend приложения. События браузера сами по себе не подтверждают вход.", "All states here are controlled manually for design comparison. A real integration obtains them from the application backend. Browser events alone never establish authentication.")}

`; + } + function emailLink(kind) { + if (!snap().account.emailVerified) { + addEmail(); + return; + } + openDialog( + t("Подтверждение по почте", "Email verification"), + `

${kind === "password" ? t("Смена пароля подтверждается одноразовой ссылкой из письма.", "Password changes are verified with a single-use email link.") : t("Сброс TOTP подтверждается одноразовой ссылкой из письма.", "TOTP reset is verified with a single-use email link.")}

${e(snap().account.email)}

${t("Ссылка действует 1 час. В этом демо письмо не отправляется.", "The link is valid for 1 hour. This demo does not send an email.")}`, + ); + } + function addEmail() { + openDialog( + t("Добавить почту", "Add email"), + `

${t("Сначала подтвердите почту. В реальном SSO привязка требует недавнего подтверждения личности.", "Verify your email first. A real SSO link requires recent identity verification.")}

${t("Демо: письма не отправляются. Нажатие имитирует завершённое подтверждение.", "Demo: no email is sent. This button simulates completed verification.")}
`, + ); + $("#identity-email").onsubmit = (ev) => { + ev.preventDefault(); + adapter.verifyEmail(new FormData(ev.target).get("email")); + $("#dialog").close(); + render(); + toast(t("Почта подтверждена в демо", "Email verified in demo")); + }; + } + function confirm(titleText, description, confirmId, data = "") { + openDialog( + titleText, + `

${description}

`, + ); + } + function switchAccount() { + openDialog( + t("Сменить аккаунт", "Switch account"), + `

${t("Текущий браузерный вход будет завершён. Затем откроется новая форма входа SSO. Другие устройства сохранят свои сеансы.", "This browser session will end, followed by a new SSO sign-in form. Other devices will retain their sessions.")}

${t("Демо: письма, токены и запросы к провайдеру не используются.", "Demo: no email, tokens or provider requests are used.")}`, + ); + } + async function handleClick(event) { + const b = event.target.closest("[data-identity]"); + if (!b) return false; + event.preventDefault(); + const id = b.dataset.identity; + document + .querySelectorAll("[popover]:popover-open") + .forEach((p) => p.hidePopover()); + try { + if (id === "add-email") { + addEmail(); + return true; + } + if (id === "switch") { + switchAccount(); + return true; + } + if (id === "confirm-switch") { + $("#dialog").close(); + adapter.setScenario("signing_out"); + const revision = snap().revision; + render(); + await new Promise((resolve) => setTimeout(resolve, 250)); + if (snap().revision !== revision) return true; + adapter.signOut(); + navigate("auth"); + return true; + } + if (id === "logout") { + confirm( + t("Выйти из SSO?", "Sign out of SSO?"), + t( + "Завершится текущий браузерный сеанс. Другие устройства останутся в системе.", + "This browser session will end. Other devices will remain signed in.", + ), + "confirm-logout", + ); + return true; + } + if (id === "confirm-logout") { + $("#dialog").close(); + adapter.setScenario("signing_out"); + const revision = snap().revision; + render(); + await new Promise((resolve) => setTimeout(resolve, 250)); + if (snap().revision !== revision) return true; + adapter.signOut(); + navigate("auth"); + return true; + } + if (id === "begin-signin") { + navigate("auth"); + return true; + } + if (["resolve", "enroll-factor"].includes(id)) { + if (id === "enroll-factor") { + pendingEnrollment = true; + openDialog( + t("Подключение фактора", "Set up verification"), + `

${t("В настоящем потоке настройка выполняется в SSO после подтверждения личности.", "In a real flow this is configured in SSO after identity verification.")}

${demo}`, + ); + return true; + } + $("#dialog").close(); + adapter.setScenario("authenticated"); + if (pendingEnrollment) { + adapter.setTotp(true); + pendingEnrollment = false; + } + render(); + return true; + } + if (id === "verify-factor") { + openDialog( + t("Подтвердите TOTP", "Verify TOTP"), + `

${t("Введите 6 цифр. В демо подходит 123456.", "Enter 6 digits. Use 123456 in the demo.")}

`, + ); + const form = $("#identity-factor"); + const submit = () => { + if (form.elements.code.value !== "123456") { + $("#factor-error").textContent = t( + "Неверный код. Используйте 123456 для демонстрации.", + "Incorrect code. Use 123456 for this demo.", + ); + form.elements.code.setAttribute("aria-invalid", "true"); + return; + } + $("#dialog").close(); + adapter.setScenario("authenticated"); + render(); + }; + form.onsubmit = (e) => { + e.preventDefault(); + submit(); + }; + form.elements.code.oninput = (e) => { + if (e.target.value.length === 6) submit(); + }; + return true; + } + if (id === "password-link" || id === "totp-link") { + emailLink(id === "password-link" ? "password" : "totp"); + return true; + } + if (id === "email-sent") { + $("#dialog").close(); + toast( + t( + "Демо: запрос принят. Письмо не отправлено.", + "Demo request accepted. No email was sent.", + ), + ); + return true; + } + if (id === "add-passkey") { + openDialog( + t("Добавить Passkey", "Add passkey"), + `

${t("Демонстрационный ключ. Windows Hello или Touch ID здесь не запускается.", "Demo key. Windows Hello or Touch ID is not invoked here.")}

`, + ); + $("#identity-passkey").onsubmit = (ev) => { + ev.preventDefault(); + adapter.addPasskey(new FormData(ev.target).get("name")); + $("#dialog").close(); + render(); + toast(t("Демо-Passkey добавлен", "Demo passkey added")); + }; + return true; + } + if (id === "remove-passkey") { + confirm( + t("Удалить Passkey?", "Remove passkey?"), + t( + "Другие способы входа сохранятся.", + "Other sign-in methods will remain available.", + ), + "confirm-remove-key", + `data-key="${e(b.dataset.key)}"`, + ); + return true; + } + if (id === "confirm-remove-key") { + adapter.removePasskey(b.dataset.key); + $("#dialog").close(); + render(); + toast(t("Passkey удалён в демо", "Passkey removed in demo")); + return true; + } + if (id === "revoke-session") { + const current = b.dataset.session === "current"; + if (current) { + confirm( + t("Завершить текущий сеанс?", "End current session?"), + t( + "Вы выйдете из SSO в этом браузере.", + "You will be signed out of SSO in this browser.", + ), + "confirm-logout", + ); + return true; + } + confirm( + t("Завершить сеанс?", "End session?"), + t( + "Устройство потребуется авторизовать повторно.", + "The device will need to sign in again.", + ), + "confirm-revoke", + `data-session="${e(b.dataset.session)}"`, + ); + return true; + } + if (id === "confirm-revoke") { + adapter.revokeSession(b.dataset.session); + $("#dialog").close(); + render(); + toast(t("Сеанс завершён в демо", "Demo session ended")); + return true; + } + if (id === "revoke-others") { + confirm( + t("Завершить другие сеансы?", "End other sessions?"), + t( + "Текущий сеанс останется активным.", + "Your current session will stay active.", + ), + "confirm-revoke-others", + ); + return true; + } + if (id === "confirm-revoke-others") { + adapter.revokeOtherSessions(); + $("#dialog").close(); + render(); + toast(t("Другие сеансы завершены в демо", "Other demo sessions ended")); + return true; + } + if (id === "clear-avatar") { + avatarDraft = ""; + $("#avatar-preview").innerHTML = avatar({ + ...snap().account, + avatar: "", + }); + return true; + } + if (id === "theme") { + setTheme(b.dataset.theme); + return true; + } + if (id === "open-app") { + const app = applicationCatalog.find((a) => a.id === b.dataset.app); + openDialog( + app.name, + `

${t("Демонстрация перехода в приложение. Реальный адрес не подключён.", "Demo application handoff. No live destination is connected.")}

`, + ); + return true; + } + if (id === "reset") { + adapter.reset(); + render(); + toast(t("SSO-демо сброшено", "SSO demo reset")); + return true; + } + if (id.startsWith("grant-") || id === "add-role") { + return handleGrant(id, b); + } + } catch (error) { + toast( + t( + "Действие недоступно. Повторите вход в демо.", + "Action unavailable. Sign in to the demo again.", + ), + ); + } + return true; + } + function bind(page) { + if ($("#identity-state")) + $("#identity-state").onchange = (ev) => { + adapter.setScenario(ev.target.value); + render(); + $("#identity-state").focus(); + }; + const form = $("#identity-profile"); + if (form) { + avatarDraft = null; + form.onreset = (ev) => { + ev.preventDefault(); + render(); + }; + form.onsubmit = (ev) => { + ev.preventDefault(); + const values = Object.fromEntries(new FormData(form)); + if (!values.firstName.trim() || !values.lastName.trim()) { + $("#profile-error").textContent = t( + "Имя и фамилия не должны состоять из пробелов.", + "First and last name cannot be blank.", + ); + return; + } + if (avatarDraft !== null) values.avatar = avatarDraft; + adapter.updateProfile(values); + render(); + toast(t("Профиль сохранён в демо", "Demo profile saved")); + }; + $("#identity-avatar-file").onchange = async (ev) => { + const uploadRevision = snap().revision; + const file = ev.target.files[0]; + if (!file) return; + if ( + !["image/png", "image/jpeg", "image/webp"].includes(file.type) || + file.size > 2 * 1024 * 1024 + ) { + $("#profile-error").textContent = t( + "Выберите PNG, JPEG или WebP размером до 2 МБ.", + "Choose PNG, JPEG or WebP up to 2 MB.", + ); + return; + } + try { + const data = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = reject; + reader.readAsDataURL(file); + }); + const image = new Image(); + image.src = data; + await image.decode(); + if ( + !$("#avatar-preview") || + snap().revision !== uploadRevision || + !snap().account + ) + return; + avatarDraft = data; + $("#avatar-preview").innerHTML = avatar({ + ...snap().account, + avatar: data, + }); + $("#profile-error").textContent = ""; + } catch { + $("#profile-error").textContent = t( + "Изображение не удалось прочитать.", + "Could not read the image.", + ); + } + }; + } + } + function grantsMarkup(userId) { + const rows = adapter.getGrants(userId); + return `

${t("Доступ к приложениям", "Application access")}

${t("Выбрано", "Selected")}: ${selectedGrants.size}
${rows.map((g) => ``).join("")}
${t("Приложение", "Application")}${t("Выдано", "Granted")}${t("Кем", "By")}${t("Действия", "Actions")}
a.id === g.application).name}" ${selectedGrants.has(g.application) ? "checked" : ""}>${applicationCatalog.find((a) => a.id === g.application).name}${g.status === "active" ? t("Активен", "Active") : t("Приостановлен", "Suspended")}${g.added}${e(g.by)}
···
`; + } + function roleMarkup(userId) { + const roles = adapter.getUserRoles(userId); + return `
${t("Роли SSO", "SSO roles")}${[...systemRoles, ...snap().customRoles].map((r) => ``).join("")}
`; + } + function bindGrants(userId, reopen) { + editingUser = { id: userId, reopen }; + selectedGrants = new Set(); + bindGrantChecks(); + } + function bindGrantChecks() { + document.querySelectorAll("[data-grant]").forEach( + (c) => + (c.onchange = () => { + c.checked + ? selectedGrants.add(c.dataset.grant) + : selectedGrants.delete(c.dataset.grant); + updateGrantSelection(); + }), + ); + if ($("#grant-all")) + $("#grant-all").onchange = (ev) => { + document.querySelectorAll("[data-grant]").forEach((c) => { + c.checked = ev.target.checked; + c.checked + ? selectedGrants.add(c.dataset.grant) + : selectedGrants.delete(c.dataset.grant); + }); + updateGrantSelection(); + }; + } + function updateGrantSelection() { + if (!$("#grant-count")) return; + $("#grant-count").textContent = + t("Выбрано", "Selected") + ": " + selectedGrants.size; + $(".grant-bulk button").disabled = !selectedGrants.size; + const checks = [...document.querySelectorAll("[data-grant]")]; + $("#grant-all").checked = + checks.length > 0 && checks.every((c) => c.checked); + $("#grant-all").indeterminate = + checks.some((c) => c.checked) && !checks.every((c) => c.checked); + } + function handleGrant(id, b) { + const userId = editingUser.id, + reopen = editingUser.reopen; + if (id === "grant-add") { + const available = applicationCatalog.filter( + (a) => !adapter.getGrants(userId).some((g) => g.application === a.id), + ); + openDialog( + t("Добавить приложение", "Add application"), + available.length + ? `
` + : `

${t("Все приложения уже добавлены.", "All applications have already been added.")}

`, + ); + if ($("#grant-add-form")) + $("#grant-add-form").onsubmit = (ev) => { + ev.preventDefault(); + adapter.addGrant(userId, new FormData(ev.target).get("application")); + reopen(); + }; + return true; + } + if (id === "grant-suspend") { + const ids = b.dataset.app ? [b.dataset.app] : [...selectedGrants]; + openDialog( + t("Приостановить доступ", "Suspend access"), + `

${t("Приложений выбрано", "Applications selected")}: ${ids.length}

`, + ); + $("#grant-suspend-form").onsubmit = (ev) => { + ev.preventDefault(); + const f = new FormData(ev.target), + reason = f.get("reason").trim(); + if (!reason) { + ev.target.elements.reason.setCustomValidity( + t("Укажите причину", "Enter a reason"), + ); + ev.target.elements.reason.reportValidity(); + return; + } + adapter.updateGrants(userId, ids, { + status: "suspended", + reason, + showReason: f.has("showReason"), + }); + reopen(); + toast(t("Доступ приостановлен в демо", "Demo access suspended")); + }; + $("#grant-suspend-form textarea").oninput = (ev) => + ev.target.setCustomValidity(""); + return true; + } + if (id === "grant-resume") { + adapter.updateGrants(userId, [b.dataset.app], { + status: "active", + reason: "", + showReason: false, + }); + reopen(); + return true; + } + if (id === "add-role") { + const value = $("#custom-role").value.trim(); + if (value) { + adapter.addRole(value); + const field = $(".identity-role-fields"); + const label = document.createElement("label"); + const check = document.createElement("input"); + check.type = "checkbox"; + check.name = "ssoRole"; + check.value = value; + check.checked = true; + label.append(check, document.createTextNode(" " + value)); + if ( + ![...field.querySelectorAll("input")].some((c) => c.value === value) + ) + field.append(label); + $("#custom-role").value = ""; + } + return true; + } + return false; + } + return { + titles: title, + renderPage, + gate, + handleClick, + bind, + switchAccount, + grantsMarkup, + roleMarkup, + bindGrants, + }; +} diff --git a/components/system.css b/components/system.css index 9420b79..eb848de 100644 --- a/components/system.css +++ b/components/system.css @@ -2097,3 +2097,591 @@ body[data-concept="dock"].dock-open .account-more { body[data-concept="dock"] .header-actions > .avatar { display: none; } +/* Account workspace: flat sections, shared native controls and compact rows. */ +.identity-body { + max-width: 1100px; +} +.identity-demo { + margin: 26px 0 0; + padding-top: 14px; + border-top: 1px solid var(--color-border); + font-size: 12px; + color: var(--color-muted); +} +.identity-profile-summary { + display: flex; + align-items: center; + gap: 20px; + padding: 4px 0 25px; + border-bottom: 1px solid var(--color-border); + margin-bottom: 28px; +} +.identity-profile-summary h2 { + font: 600 25px/1.3 var(--font-heading); + margin: 0 0 3px; +} +.identity-profile-summary p { + margin: 0 0 8px; + color: var(--color-muted); + font-size: 14px; +} +.identity-avatar { + display: inline-flex; + width: 52px; + height: 52px; + object-fit: cover; + object-position: center; + align-items: center; + justify-content: center; + border-radius: 14px; + background: color-mix(in srgb, var(--color-accent) 12%, var(--color-surface)); + color: var(--color-accent); + font: 600 18px var(--font-body); + flex-shrink: 0; +} +.identity-avatar.large { + width: 76px; + height: 76px; + font-size: 25px; + border-radius: 19px; +} +.identity-roles { + display: flex; + gap: 8px; + flex-wrap: wrap; +} +.identity-roles span { + font-size: 12px; + color: var(--color-muted); + padding-right: 9px; + border-right: 1px solid var(--color-border); +} +.identity-roles span:last-child { + border: 0; +} +.identity-split { + display: grid; + grid-template-columns: minmax(180px, 0.8fr) minmax(0, 1.45fr); + gap: 55px; +} +.identity-split > section p { + font-size: 14px; + max-width: 30ch; +} +.identity-fields { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 14px; +} +.identity-readonly { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin: 8px 0; + font-size: 14px; +} +.identity-readonly > span:first-child { + color: var(--color-muted); +} +.identity-avatar-editor { + display: flex; + gap: 18px; + align-items: center; + padding-top: 25px; + margin-top: 25px; + border-top: 1px solid var(--color-border); +} +.identity-avatar-editor > div:last-child { + display: flex; + gap: 9px; + align-items: center; + flex-wrap: wrap; +} +.file-button { + display: inline-block; + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + padding: 9px 13px; + cursor: pointer; + font-size: 14px; + background: var(--color-surface); +} +.file-button:focus-within { + outline: 3px solid var(--color-accent); + outline-offset: 3px; +} +.file-button input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + padding: 0; + min-height: 0 !important; +} +.identity-footnote { + display: flex; + gap: 15px; + font-size: 12px; + color: var(--color-muted); + padding-top: 24px; +} +.identity-footnote code { + color: var(--color-text); +} +.identity-section { + padding: 8px 0 24px; + margin-bottom: 22px; + border-bottom: 1px solid var(--color-border); +} +.identity-section:last-of-type { + margin-bottom: 0; +} +.identity-setting-row { + display: flex; + justify-content: space-between; + gap: 20px; + align-items: center; + padding: 18px 0; + border-top: 1px solid var(--color-border); +} +.identity-setting-row h3, +.identity-session h3 { + font-size: 15px; + margin: 0 0 5px; +} +.identity-setting-row p, +.identity-session p { + font-size: 13px; + color: var(--color-muted); + margin: 0; +} +.identity-setting-row p.status { + color: var(--color-success); +} +.identity-setting-row p.status.warn { + color: var(--color-danger); +} +.identity-section .section-title { + align-items: center; +} +.identity-section .section-title h2 { + margin-bottom: 5px; +} +.identity-section .section-title p { + font-size: 14px; + margin: 0; +} +.identity-security-note p, +.identity-explanation { + max-width: 75ch; + font-size: 14px; + color: var(--color-muted); + line-height: 1.7; +} +.identity-list-heading { + display: flex; + justify-content: space-between; + color: var(--color-muted); + font-size: 12px; + padding-bottom: 12px; +} +.identity-session { + display: grid; + grid-template-columns: 35px minmax(0, 1fr) auto auto; + align-items: center; + gap: 18px; + padding: 20px 0; + border-top: 1px solid var(--color-border); +} +.identity-session time { + font: + 12px Consolas, + monospace; + color: var(--color-muted); + min-width: 105px; +} +.identity-device-icon .nav-icon { + width: 26px; + height: 26px; +} +.identity-apps { + display: flex; + flex-direction: column; +} +.identity-app { + display: flex; + align-items: center; + gap: 18px; + padding: 23px 0; + border-bottom: 1px solid var(--color-border); +} +.identity-app h2 { + font-size: 17px; + margin: 0 0 5px; +} +.identity-app p { + font-size: 14px; + color: var(--color-muted); + margin: 0 0 5px; +} +.identity-app > div { + flex: 1; + min-width: 0; +} +.identity-app > button { + flex-shrink: 0; +} +.app-monogram { + width: 48px; + height: 48px; + display: grid; + place-items: center; + font: + bold 16px Consolas, + monospace; + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: 12px; + color: var(--color-accent); + flex-shrink: 0; +} +.theme-choice-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 20px; + max-width: 760px; +} +.theme-choice { + text-align: left; + padding: 14px; + display: flex; + flex-direction: column; + gap: 10px; +} +.theme-choice[aria-pressed="true"] { + border-color: var(--color-accent); + box-shadow: 0 0 0 1px var(--color-accent); +} +.theme-choice > strong { + font-size: 16px; +} +.theme-choice small { + font-size: 12px; + line-height: 1.5; +} +.theme-thumbnail { + display: grid; + grid-template-columns: 22px 1fr; + grid-template-rows: 16px 1fr; + gap: 7px; + width: 100%; + height: 120px; + padding: 10px; + border-radius: 5px; + background: #edf3f3; + border: 1px solid #c6d7da; +} +.theme-thumbnail i { + display: block; + background: #fbfdfd; + border: 1px solid #c6d7da; + border-radius: 3px; +} +.theme-thumbnail i:first-child { + grid-row: 1/3; + background: #d5e4e5; +} +.theme-thumbnail.dark { + background: #111f26; + border-color: #3b535c; +} +.theme-thumbnail.dark i { + background: #192c34; + border-color: #3b535c; +} +.theme-thumbnail.dark i:first-child { + background: #2e4b53; +} +.identity-gate { + max-width: 540px; + margin: 50px auto; + padding: 28px; + text-align: center; +} +.identity-gate h1 { + font-size: 27px; + letter-spacing: -0.5px; +} +.identity-gate > p { + color: var(--color-muted); + font-size: 14px; + line-height: 1.7; +} +.identity-gate .component-row { + justify-content: center; + margin-top: 24px; +} +.identity-gate > .skeleton { + margin: 25px auto; + max-width: 250px; +} +.identity-gate-symbol { + display: inline-flex; + align-items: center; + justify-content: center; + width: 48px; + height: 48px; + color: var(--color-accent); + margin-bottom: 18px; +} +.identity-gate-symbol .nav-icon { + width: 36px; + height: 36px; +} +.identity-state-controls { + display: flex; + align-items: center; + gap: 20px; + flex-wrap: wrap; +} +.identity-state-controls .field { + margin: 0; + min-width: 240px; +} +.identity-state-controls code { + font-size: 12px; + color: var(--color-muted); +} +.identity-state-preview { + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + margin-top: 25px; + min-height: 340px; + background: var(--color-surface); +} +.identity-state-preview .identity-gate { + margin: 16px auto; +} +.identity-editor-dialog { + width: min(850px, calc(100% - 32px)); +} +.identity-role-fields { + padding: 16px 0; + border: 0; + border-top: 1px solid var(--color-border); + margin: 20px 0 0; + display: flex; + gap: 14px; + flex-wrap: wrap; +} +.identity-role-fields legend { + font-size: 14px; + padding: 8px 0; +} +.identity-role-fields label { + display: flex; + align-items: center; + gap: 6px; +} +.identity-grants { + margin-top: 25px; +} +.identity-grants h3 { + margin: 0; +} +.grant-bulk { + display: flex; + align-items: center; + gap: 14px; + font-size: 13px; + margin: 15px 0; +} +.identity-grants table { + min-width: 600px; + font-size: 13px; +} +.identity-grants td, +.identity-grants th { + padding: 12px 10px; +} +.identity-grants small { + display: block; + margin-top: 4px; +} +.grant-actions summary { + padding: 4px 12px; + list-style: none; + font-size: 18px; + line-height: 1.2; +} +.grant-actions .dropdown { + position: static; + box-shadow: none; + min-width: 140px; +} +.grant-actions .dropdown button { + font-size: 12px; +} +.dock-account .avatar img { + display: block; + width: 32px; + height: 32px; + object-fit: cover; + border-radius: 10px; +} +body[data-concept="dock"] .identity-body { + animation: dock-reveal 260ms ease-out both; +} +@media (max-width: 900px) { + .identity-split { + grid-template-columns: 1fr; + gap: 15px; + } + .identity-split > section p { + max-width: 65ch; + } + .identity-session { + grid-template-columns: 30px minmax(0, 1fr) auto; + gap: 12px; + } + .identity-session time { + grid-column: 2; + grid-row: 2; + } + .identity-session button { + grid-column: 3; + grid-row: 1/3; + font-size: 13px; + } + .identity-state-controls .field { + min-width: 200px; + } +} +@media (max-width: 600px) { + .identity-profile-summary { + gap: 14px; + padding-bottom: 20px; + } + .identity-profile-summary h2 { + font-size: 22px; + } + .identity-avatar.large { + width: 60px; + height: 60px; + border-radius: 15px; + font-size: 21px; + } + .identity-fields { + grid-template-columns: 1fr; + gap: 0; + } + .identity-avatar-editor { + gap: 12px; + align-items: flex-start; + } + .identity-avatar-editor > div:last-child { + gap: 8px; + } + .identity-avatar-editor small { + width: 100%; + } + .identity-readonly { + display: block; + } + .identity-readonly > * { + display: block; + margin-bottom: 4px; + } + .identity-setting-row { + gap: 10px; + } + .identity-section .section-title { + align-items: flex-start; + flex-direction: column; + } + .identity-list-heading > span:last-child { + display: none; + } + .identity-session { + grid-template-columns: 26px minmax(0, 1fr); + gap: 10px; + } + .identity-session time { + min-width: 0; + } + .identity-session button { + grid-column: 2; + grid-row: 3; + justify-self: start; + } + .identity-app { + gap: 12px; + flex-wrap: wrap; + padding: 20px 0; + } + .identity-app > div { + flex-basis: calc(100% - 60px); + } + .identity-app > button { + margin-left: 60px; + } + .theme-choice-grid { + grid-template-columns: 1fr; + gap: 14px; + } + .theme-thumbnail { + height: 100px; + } + .identity-gate { + margin: 20px auto; + padding: 15px 6px; + } + .identity-gate h1 { + font-size: 23px; + } + .identity-state-controls .field { + width: 100%; + min-width: 0; + } + .identity-state-preview { + min-height: 320px; + padding: 12px; + } + .identity-state-preview .identity-gate { + margin: 10px auto; + } + .identity-grants .section-title { + align-items: flex-start; + flex-direction: column; + } + .grant-bulk { + align-items: flex-start; + flex-direction: column; + } + .identity-footnote { + flex-wrap: wrap; + gap: 5px 12px; + } + .identity-editor-dialog { + padding: 20px; + } + .identity-role-fields { + gap: 12px; + } +} +@media (prefers-reduced-motion: reduce) { + body[data-concept="dock"] .identity-body { + animation: none !important; + } +} +#factor-error { + min-height: 42px; + line-height: 1.5; + margin: 12px 0; +} +@media (max-width: 600px) { + #factor-error { + min-height: 60px; + } +} diff --git a/package.json b/package.json index ef29fbf..cbe28aa 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "start": "node scripts/serve.mjs", "test": "node tests/browser.mjs", "check": "node scripts/check.mjs", - "test:dock": "node tests/dock.mjs" + "test:dock": "node tests/dock.mjs", + "test:identity": "node tests/identity.mjs && node tests/totp-layout.mjs" }, "devDependencies": { "playwright": "^1.58.0" diff --git a/patterns/IDENTITY.md b/patterns/IDENTITY.md new file mode 100644 index 0000000..beb232c --- /dev/null +++ b/patterns/IDENTITY.md @@ -0,0 +1,37 @@ +# Личный кабинет и состояния Identity — демонстрационный контракт + +Эти примеры живут только в галерее дизайн-системы. Репозиторий и backend SSO Service не изменяются. Источник продуктовых требований: [проектный промпт SSO](../prompts/SSO.md). Реальную интеграцию выполнять отдельно после утверждения дизайна. + +## Состав + +- `components/account-pages.js` — представления профиля, безопасности, сеансов, приложений, оформления и состояний входа; сценарии диалогов. +- `patterns/demo-identity.js` — тестовые аккаунты, приложения, права и управляемые состояния. В нём нет HTTP-запросов, OAuth, WebAuthn, отправки писем или секретов. +- `playground/frame.js` — оболочка и переключение контекстов личного кабинета/администрирования. В редакторе пользователя показаны роли SSO и доступы к приложениям. + +Визуальные компоненты читают снимок состояния через адаптер. При подключении backend нужно заменить транспорт и обработчики команд, включая их асинхронное выполнение, а не переписывать разметку и CSS. Текущий адаптер синхронный и демонстрационный; это не SDK для production. + +## Данные и состояния + +`snapshot()` возвращает `mode`, `status`, `revision`, `account`, `sessions`, `customRoles`. Личность определяется стабильным `sub`. При состоянии, отличном от `authenticated`, `account` равен `null`, список сеансов пустой, защищённые представления заменяются экраном состояния. + +Показаны `authenticated`, `loading`, `signed_out`, `access_denied`, `factor_required`, `factor_enrollment_required`, `rebind_required`, `unavailable`, `account_changed`, `signing_out`. Для сравнения ими управляет отдельный экран «Состояния входа». В настоящем приложении источником статуса должен стать проверенный ответ собственного backend. + +Обработчики профиля и демо-входа проверяют ревизию перед завершением отложенной операции. Ответ, начатый для прежнего состояния, не применяется к новому аккаунту. Демо-сеансы разделены по `sub`. `sessionStorage` содержит только тестовые профили, настройки и состояние примера в текущей вкладке; пароли, токены, session handle и watch credential туда не записываются. События storage синхронизируют демонстрации в iframe одной вкладки и не подтверждают реальную авторизацию. + +## Потоки + +- **Профиль:** редактирование имени/username, стабильный ID, отмена, фото PNG/JPEG/WebP до 2 МБ, одинаковый `object-fit: cover` в предпросмотре и после сохранения. Подтверждённая почта изменяется через администратора. +- **Безопасность:** пароль и сброс TOTP — через подтверждение письмом. Без почты сначала показывается её добавление и демо-подтверждение. В демо письмо не отправляется. Passkey — именованный пример, без запуска Windows Hello или Touch ID. +- **Сеансы:** подтверждение отзыва выбранного или других сеансов. Текущий сеанс сохраняется при завершении остальных. Выход завершает только текущий браузерный вход. +- **Приложения:** список выданных доступов, активное/приостановленное состояние, причина только при разрешённой видимости. «Открыть» показывает демо-переход без навигации на production. +- **Смена аккаунта:** подтверждение → завершение текущего демо-входа → новая форма → профиль выбранной тестовой личности. Списка сохранённых аккаунтов и подстановки пользователя без входа нет. +- **Оформление:** пользователь выбирает только светлый/тёмный режим. Выбор синхронизируется с оболочкой галереи. Default-палитры обеих тем сохраняются отдельно; пользовательский акцент — явное переопределение. +- **Редактор пользователя:** отдельная роль рабочего пространства и несколько SSO-ролей. Есть `Master Admin`, `SSO Admin`, `User` и пользовательские роли. Доступ к приложениям: дата/автор выдачи, добавление, массовый выбор, приостановка с обязательной причиной и опцией её показа, возобновление. Выдача/приостановка выполняются отдельными демо-командами сразу; форма ролей сохраняется кнопкой «Сохранить». + +## Как проверить + +Вход в демо: `anna.volkova` или `mikhail.orlov`, пароль от 8 символов. `wrong-password` демонстрирует ошибку: имя сохраняется, пароль очищается. Код TOTP для примера — `123456`; это не реальный секрет. Anna имеет административный контекст, Mikhail — только личный кабинет и отдельный список устройств. У Mikhail изначально нет почты для демонстрации её добавления. + +`npm run test:identity` проверяет обе темы, EN/RU, desktop/tablet/mobile, формы, права, скрытие прежних данных, ошибки и экспорт. Для возврата исходных фикстур — «Сбросить демо» на экране состояний входа. + +Тесты дизайна не являются проверкой безопасности настоящего SSO. Серверная авторизация, CSRF, OIDC, проверка факторов, отзыв сессий и очистка реальных данных остаются обязанностью отдельной backend-интеграции. diff --git a/patterns/UX.md b/patterns/UX.md index de8474d..eda1e2a 100644 --- a/patterns/UX.md +++ b/patterns/UX.md @@ -4,7 +4,7 @@ **Настройки.** Основные данные, безопасность и уведомления разделены вкладками. Enter отправляет форму, Cancel восстанавливает её сохранённые значения. Сохранение подтверждается toast. Поля не меняют production: всё в браузере. -**Авторизация.** Email → пароль → ожидание → dashboard. Ошибки форм обрабатываются native валидацией. SSO и восстановление имеют отдельные демо-формы с явным сообщением об отсутствии внешней отправки. В production этот слой заменяется безопасной интеграцией с identity provider; demo JS не служит защитой доступа. +**Авторизация.** Username/email → пароль → ожидание → личный кабинет. Ошибки форм обрабатываются native валидацией; демо-ошибка пароля сохраняет username и очищает пароль. SSO и восстановление имеют отдельные демо-формы с явным сообщением об отсутствии внешней отправки. В production этот слой заменяется безопасной интеграцией с identity provider; demo JS не служит защитой доступа. **Диалоги.** Инициирующая кнопка → осмысленный заголовок → форма → cancel/submit. Esc закрывает; фокус возвращается к инициатору. Опасное действие не выполняется открытием окна. @@ -13,3 +13,5 @@ **Новый проект.** После утверждения: подключить выбранные токены и CSS, выбрать layout, переносить semantic HTML и поведение в свой стек. Проверить keyboard/mobile/EN/RU и состояния ошибок до интеграции backend. **Существующий проект.** Инвентаризировать токены и компоненты; составить таблицу соответствия; сначала перевести цвета/типографику/ритм, затем контролы и layout. Сохранить бизнес-поведение, URL и контент. Не переписывать приложение ради смены стиля. + +**Identity.** Профиль, безопасность, устройства, приложения и оформление имеют отдельный личный контекст. Сценарии и граница демонстрационного адаптера: [IDENTITY.md](IDENTITY.md). Никакие экраны галереи не изменяют настоящий SSO Service. diff --git a/patterns/demo-identity.js b/patterns/demo-identity.js new file mode 100644 index 0000000..d6c4ea8 --- /dev/null +++ b/patterns/demo-identity.js @@ -0,0 +1,301 @@ +// Browser-only fixtures. A real adapter must obtain safe UI state from its own backend. +export const identityStates = [ + "authenticated", + "loading", + "signed_out", + "access_denied", + "factor_required", + "factor_enrollment_required", + "rebind_required", + "unavailable", + "account_changed", + "signing_out", +]; +export const applicationCatalog = [ + { + id: "identity", + name: "Anidev Identity", + code: "ID", + description: ["Аккаунт и способы входа", "Account and sign-in methods"], + }, + { + id: "license", + name: "License Console", + code: "LC", + description: ["Лицензии и активации", "Licenses and activations"], + }, + { + id: "monitor", + name: "Network Monitor", + code: "NM", + description: ["Сервисы и состояние сети", "Services and network health"], + }, + { + id: "files", + name: "File Browser", + code: "FB", + description: ["Файлы и общие ресурсы", "Files and shared resources"], + }, +]; +export const systemRoles = ["Master Admin", "SSO Admin", "User"]; +const fixture = () => ({ + status: "authenticated", + subject: "demo-anna", + revision: 1, + accounts: { + "demo-anna": { + sub: "demo-anna", + username: "anna.volkova", + firstName: "Anna", + lastName: "Volkova", + email: "anna@anidev.ru", + emailVerified: true, + roles: ["Master Admin", "User"], + avatar: "", + totp: true, + passwordChanged: "2026-11-14", + passkeys: [{ id: "pk-1", name: "Windows Hello", created: "2026-11-12" }], + }, + "demo-mikhail": { + sub: "demo-mikhail", + username: "mikhail.orlov", + firstName: "Mikhail", + lastName: "Orlov", + email: "", + emailVerified: false, + roles: ["User", "Developer"], + avatar: "", + totp: false, + passwordChanged: "2026-10-20", + passkeys: [], + }, + }, + sessions: { + "demo-mikhail": [ + { + id: "current", + device: "Linux · Firefox", + place: "Frankfurt", + seen: "09:38 UTC", + current: true, + }, + ], + "demo-anna": [ + { + id: "current", + device: "Windows · Edge", + place: "Moscow", + seen: "09:42 UTC", + current: true, + }, + { + id: "s-2", + device: "macOS · Safari", + place: "Frankfurt", + seen: "08:56 UTC", + current: false, + }, + { + id: "s-3", + device: "iOS · Safari", + place: "Moscow", + seen: "26.11 · 19:08 UTC", + current: false, + }, + ], + }, + grants: {}, + customRoles: ["Developer", "Auditor"], + lastApp: null, +}); +export function createDemoIdentityAdapter(storage = globalThis.sessionStorage) { + const key = "anidev.identity.demo.v2"; + let data = fixture(); + const listeners = new Set(); + try { + const saved = JSON.parse(storage?.getItem(key) || "null"); + if (saved?.accounts && identityStates.includes(saved.status)) data = saved; + } catch {} + const emit = () => { + data.revision++; + try { + storage?.setItem(key, JSON.stringify(data)); + } catch {} + listeners.forEach((fn) => fn(snapshot())); + }; + const snapshot = () => ({ + mode: "demo", + status: data.status, + revision: data.revision, + account: + data.status === "authenticated" + ? structuredClone(data.accounts[data.subject]) + : null, + sessions: + data.status === "authenticated" + ? structuredClone(data.sessions[data.subject]) + : [], + customRoles: [...data.customRoles], + }); + const requireAccount = () => { + if (data.status !== "authenticated") throw Error("not_authenticated"); + return data.accounts[data.subject]; + }; + const grantRows = (userId) => { + if (!data.grants[userId]) + data.grants[userId] = applicationCatalog.slice(0, 3).map((app) => ({ + application: app.id, + status: "active", + added: "2026-11-12", + by: "Anna Volkova", + reason: "", + showReason: false, + })); + return structuredClone(data.grants[userId]); + }; + const adapter = { + snapshot, + subscribe(fn) { + listeners.add(fn); + return () => listeners.delete(fn); + }, + setScenario(status) { + if (!identityStates.includes(status)) throw Error("invalid_state"); + data.status = status; + emit(); + }, + updateProfile(values) { + const a = requireAccount(); + for (const k of ["firstName", "lastName", "username"]) + if (typeof values[k] === "string") a[k] = values[k].trim(); + if (values.avatar !== undefined) a.avatar = values.avatar; + emit(); + }, + verifyEmail(email) { + const a = requireAccount(); + a.email = email.trim(); + a.emailVerified = true; + emit(); + }, + signOut() { + data.status = "signed_out"; + data.lastApp = null; + emit(); + }, + signIn(email) { + data.subject = email.toLowerCase().startsWith("mikhail") + ? "demo-mikhail" + : "demo-anna"; + data.status = "authenticated"; + data.lastApp = null; + emit(); + }, + revokeSession(id) { + requireAccount(); + if (id === "current") return adapter.signOut(); + data.sessions[data.subject] = data.sessions[data.subject].filter( + (s) => s.id !== id, + ); + emit(); + }, + revokeOtherSessions() { + requireAccount(); + data.sessions[data.subject] = data.sessions[data.subject].filter( + (s) => s.current, + ); + emit(); + }, + addPasskey(name) { + const a = requireAccount(); + a.passkeys.push({ + id: crypto.randomUUID(), + name: name.trim(), + created: "2026-11-28", + }); + emit(); + }, + removePasskey(id) { + const a = requireAccount(); + a.passkeys = a.passkeys.filter((k) => k.id !== id); + emit(); + }, + setTotp(value) { + requireAccount().totp = value; + emit(); + }, + getGrants: grantRows, + addGrant(userId, application) { + requireAccount(); + if (!applicationCatalog.some((a) => a.id === application)) + throw Error("unknown_application"); + const rows = grantRows(userId); + if (rows.some((g) => g.application === application)) + throw Error("duplicate_grant"); + rows.push({ + application, + status: "active", + added: "2026-11-28", + by: "Anna Volkova", + reason: "", + showReason: false, + }); + data.grants[userId] = rows; + emit(); + }, + updateGrants(userId, ids, change) { + requireAccount(); + data.grants[userId] = grantRows(userId).map((g) => + ids.includes(g.application) ? { ...g, ...change } : g, + ); + emit(); + }, + setUserRoles(userId, roles) { + requireAccount(); + data.grants["roles:" + userId] = [...new Set(roles)]; + const subject = + Number(userId) === 1 + ? "demo-anna" + : Number(userId) === 2 + ? "demo-mikhail" + : null; + if (subject) data.accounts[subject].roles = [...new Set(roles)]; + emit(); + }, + getUserRoles(userId) { + return ( + data.grants["roles:" + userId] || + (Number(userId) === 1 + ? [...data.accounts["demo-anna"].roles] + : Number(userId) === 2 + ? [...data.accounts["demo-mikhail"].roles] + : ["User"]) + ); + }, + addRole(role) { + requireAccount(); + if ( + role.trim() && + !systemRoles.includes(role) && + !data.customRoles.includes(role) + ) + data.customRoles.push(role.trim()); + emit(); + }, + reset() { + data = fixture(); + emit(); + }, + }; + const onStorage = (e) => { + if (e.key === key && e.newValue) { + try { + data = JSON.parse(e.newValue); + listeners.forEach((fn) => fn(snapshot())); + } catch {} + } + }; + globalThis.addEventListener?.("storage", onStorage); + adapter.dispose = () => + globalThis.removeEventListener?.("storage", onStorage); + return adapter; +} diff --git a/playground/frame.js b/playground/frame.js index c3440bf..83b47ee 100644 --- a/playground/frame.js +++ b/playground/frame.js @@ -1,7 +1,16 @@ import { concepts, tokensFor, cssVars } from "../concepts/registry.js"; +import { + createDemoIdentityAdapter, + identityStates, +} from "../patterns/demo-identity.js"; +import { + createAccountUI, + accountPageIds, +} from "../components/account-pages.js"; +const identityAdapter = createDemoIdentityAdapter(); const params = new URLSearchParams(location.search), concept = concepts.find((c) => c.id === params.get("concept")) || concepts[0]; -const theme = params.get("theme") === "dark" ? "dark" : "light", +let theme = params.get("theme") === "dark" ? "dark" : "light", density = params.get("density") || "normal", locale = params.get("locale") === "en" ? "en" : "ru"; const rawAccent = params.get("accent"), @@ -10,7 +19,7 @@ const rawAccent = params.get("accent"), : theme === "dark" ? concept.darkAccent || concept.accent : concept.accent; -const tokens = tokensFor(concept.id, theme, accent, density); +let tokens = tokensFor(concept.id, theme, accent, density); document.documentElement.style.cssText = cssVars(tokens); document.documentElement.lang = locale; document.body.dataset.concept = concept.id; @@ -135,6 +144,7 @@ let page = [ "auth", "components", "tokens", + ...accountPageIds, ].includes(params.get("page")) ? params.get("page") : "dashboard"; @@ -153,8 +163,25 @@ const pageNames = { auth: t("Авторизация", "Sign in"), components: t("Компоненты", "Components"), tokens: t("Токены", "Tokens"), + profile: t("Аккаунт", "Account"), + security: t("Безопасность", "Security"), + sessions: t("Устройства и сеансы", "Devices and sessions"), + applications: t("Приложения", "Applications"), + appearance: t("Оформление", "Appearance"), + identity: t("Состояния входа", "Sign-in states"), }; const icons = { + profile: + '', + security: + '', + sessions: + '', + applications: + '', + appearance: '', + identity: + '', dashboard: '', users: @@ -183,21 +210,48 @@ function toast(message) { clearTimeout(toastTimer); toastTimer = setTimeout(() => ($("#toast").style.display = "none"), 3500); } +function currentIdentity() { + return identityAdapter.snapshot().account; +} +function accountName() { + const a = currentIdentity(); + return a + ? `${a.firstName} ${a.lastName}` + : t("Нет активного входа", "No active sign-in"); +} +function accountInitials() { + const a = currentIdentity(); + return a ? (a.firstName[0] || "") + (a.lastName[0] || "") : "a/"; +} +function navigationPages() { + return accountPageIds.includes(page) + ? ["profile", "security", "sessions", "applications", "appearance"] + : ["dashboard", "users", "settings", "components", "tokens"]; +} function dockAccount() { return ``; +${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)) ? `` : ""} + + + `; } function nav() { - return ``; + const dockBrand = ``; + return ``; } function header() { - return `
`; + return `
`; } const heading = (title, desc, actions = "") => `
ANIDEV://PRODUCTION/${page.toUpperCase()}

${title}

${desc}

${actions}
`; @@ -206,7 +260,7 @@ let dockCloseTimer; function bindDockHover() { if (concept.id !== "dock" || !$(".dock-toggle")) return; const nav = $(".navigation"); - $(".dock-toggle").addEventListener("pointerenter", (e) => { + nav.addEventListener("pointerenter", (e) => { if ( e.pointerType !== "mouse" || !matchMedia("(hover: hover) and (pointer: fine)").matches @@ -263,13 +317,31 @@ function render() { clearTimeout(dockCloseTimer); document.body.classList.remove("dock-open"); document.title = `Anidev / ${concept.name} / ${pageNames[page]}`; + const content = accountPageIds.includes(page) + ? accountUI.renderPage(page) + : identityAdapter.snapshot().status !== "authenticated" && + !["components", "tokens", "auth"].includes(page) + ? accountUI.gate() + : ["dashboard", "users", "settings"].includes(page) && + !currentIdentity()?.roles.some((r) => + ["Master Admin", "SSO Admin"].includes(r), + ) + ? accountUI.gate("access_denied") + : { + dashboard, + users: userScreen, + settings: settingsScreen, + components: componentScreen, + tokens: tokenScreen, + }[page]?.() || ""; $("#app").innerHTML = page === "auth" ? auth() - : `
${nav()}${concept.id === "dock" ? `` : ""}
${header()}
${{ dashboard, users: userScreen, settings: settingsScreen, components: componentScreen, tokens: tokenScreen }[page]()}
`; + : `
${nav()}${concept.id === "dock" ? `` : ""}
${header()}
${content}
`; bindForms(); + accountUI.bind(page); bindDockHover(); - if (page === "users") bindUsers(); + if (page === "users" && $("#user-search")) bindUsers(); } function chart() { const values = @@ -422,7 +494,7 @@ function settingsScreen() { return `${heading(t("Настройки пространства", "Workspace settings"), t("Идентификация, безопасность и уведомления.", "Identity, security and notifications."))}
${["general", "security", "notifications"].map((v, i) => ``).join("")}

${tab === "general" ? t("Ваше пространство", "Your workspace") : tab === "security" ? t("Контроль доступа", "Access control") : t("Оповещения", "Notifications")}

${tab === "general" ? t("Эти данные видны участникам организации.", "These details are visible to organization members.") : t("Изменения применяются к этому демо.", "Changes apply to this demo.")}

${tab === "general" ? `` : tab === "security" ? `
` : `
`}
`; } function auth() { - return `
${wordmark}
${t("Ваша инфраструктура.
Под вашим контролем.", "Your infrastructure.
Under your control.")}
ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}

${t("Вход в Anidev", "Sign in to Anidev")}

${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}

${t("или корпоративный аккаунт", "or your company account")}
© Anidev 2026
`; + return `
${wordmark}
${t("Ваша инфраструктура.
Под вашим контролем.", "Your infrastructure.
Under your control.")}
ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}

${t("Вход в Anidev", "Sign in to Anidev")}

${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}

${t("или корпоративный аккаунт", "or your company account")}
© Anidev 2026
`; } function componentScreen() { return `${heading(t("Библиотека компонентов", "Component library"), t("Единые состояния. Шесть способов выражения.", "Shared states. Six ways of expressing them."), ``)}
@@ -493,13 +565,16 @@ function editUser(id) { if (!user) return; openDialog( escape(user.name), - `

${escape(user.email)}

`, + `

${escape(user.email)}

${accountUI.roleMarkup(id)}${accountUI.grantsMarkup(id)}
`, ); + $("#dialog").classList.add("identity-editor-dialog"); + accountUI.bindGrants(id, () => editUser(id)); $("#edit-user").onsubmit = (e) => { e.preventDefault(); const data = new FormData(e.target); user.role = data.get("role"); user.status = data.get("status"); + identityAdapter.setUserRoles(id, data.getAll("ssoRole")); persist(); $("#dialog").close(); refreshUsers(); @@ -576,12 +651,27 @@ function bindForms() { if ($("#auth-form")) $("#auth-form").onsubmit = async (e) => { e.preventDefault(); + const identityRevision = identityAdapter.snapshot().revision; const b = e.target.querySelector("[type=submit]"); b.disabled = true; b.setAttribute("aria-busy", "true"); b.textContent = t("Вход…", "Signing in…"); await new Promise((r) => setTimeout(r, 450)); - page = "dashboard"; + if (identityAdapter.snapshot().revision !== identityRevision) return; + if (new FormData(e.target).get("password") === "wrong-password") { + e.target.elements.password.value = ""; + $("#auth-error").textContent = t( + "Неверный пароль. Попробуйте другой пароль для демо.", + "Incorrect password. Try another password for this demo.", + ); + e.target.elements.password.setAttribute("aria-invalid", "true"); + b.disabled = false; + b.removeAttribute("aria-busy"); + b.textContent = t("Войти", "Sign in"); + return; + } + identityAdapter.signIn(new FormData(e.target).get("email")); + page = "profile"; render(); toast(t("Демонстрационный вход выполнен", "Demo sign-in complete")); }; @@ -617,6 +707,7 @@ function contextMenu(x, y) { menu.querySelector("button").focus(); } document.addEventListener("click", async (e) => { + if (await accountUI.handleClick(e)) return; const pageButton = e.target.closest("[data-page]"); if (pageButton) { page = pageButton.dataset.page; @@ -658,33 +749,7 @@ document.addEventListener("click", async (e) => { `

${t("Общих ресурсов пока нет.", "No shared resources yet.")}

`, "drawer", ), - "switch-account": () => { - setDockOpen(false, false); - openDialog( - t("Сменить аккаунт", "Switch account"), - `

${t("Демонстрация SSO-переключения. Реальный провайдер не подключён.", "Demo SSO account switching. No live provider is connected.")}

`, - ); - }, - "select-account": () => { - const name = button.dataset.account; - $("#dialog").close(); - document.querySelectorAll(".dock-account .avatar").forEach( - (el) => - (el.textContent = name - .split(" ") - .map((v) => v[0]) - .join("")), - ); - $(".account-identity b").textContent = name; - $(".account-identity small").textContent = name.startsWith("Anna") - ? "anna@anidev.ru" - : "mikhail@anidev.ru"; - $(".dock-account").setAttribute( - "aria-label", - t("Меню аккаунта ", "Account menu ") + name, - ); - toast(t("Демо-аккаунт выбран: ", "Demo account selected: ") + name); - }, + "switch-account": () => accountUI.switchAccount(), "dock-toggle": () => { if (dockHoverOpened) { dockHoverOpened = false; @@ -706,11 +771,7 @@ document.addEventListener("click", async (e) => { invite, command, activity: () => $("#activity").scrollIntoView({ behavior: "smooth" }), - profile: () => - openDialog( - "Anna Volkova", - `

anna@anidev.ru

${roleName("admin")} · Anidev Production

`, - ), + profile: () => navigate("profile"), prev: () => { userPage--; refreshUsers(); @@ -991,4 +1052,38 @@ addEventListener("storage", (e) => { } catch {} } }); +function navigate(next) { + page = next; + $("#dialog").close(); + render(); + $("#content")?.focus(); +} +const accountUI = createAccountUI({ + adapter: identityAdapter, + t, + escape, + heading, + icon, + openDialog, + toast, + render, + navigate, + setTheme: (mode) => { + theme = mode; + tokens = tokensFor(concept.id, theme, rawAccent || undefined, density); + document.documentElement.style.cssText = cssVars(tokens); + document.body.dataset.theme = theme; + render(); + if (parent !== window) + parent.postMessage({ type: "anidev-theme", theme }, location.origin); + }, +}); +if (identityStates.includes(params.get("identityState"))) + identityAdapter.setScenario(params.get("identityState")); +addEventListener("storage", (e) => { + if (e.key === "anidev.identity.demo.v2") { + $("#dialog").close(); + render(); + } +}); render(); diff --git a/playground/gallery.js b/playground/gallery.js index 730082f..342ac42 100644 --- a/playground/gallery.js +++ b/playground/gallery.js @@ -43,6 +43,12 @@ if (requested.get("concept") === "dock") { state.density = "compact"; delete state.accents.dock; } +if ( + [...document.querySelector("#page").options].some( + (o) => o.value === requested.get("page"), + ) +) + state.page = requested.get("page"); function render() { const en = state.locale === "en"; document.documentElement.lang = state.locale; @@ -103,6 +109,12 @@ function render() { "Authentication", "Components", "Tokens", + "Account", + "Security", + "Devices and sessions", + "Applications", + "Appearance", + "Sign-in states", ] : [ "Dashboard", @@ -111,6 +123,12 @@ function render() { "Авторизация", "Компоненты", "Токены", + "Аккаунт", + "Безопасность", + "Устройства и сеансы", + "Приложения", + "Оформление", + "Состояния входа", ]; [...$("#page").options].forEach((o, i) => (o.text = labels[i])); [...$("#theme").options].forEach( @@ -133,10 +151,8 @@ function render() { theme: state.theme, density: state.density, locale: state.locale, - accent: - state.accents[concept] || - tokensFor(concept, state.theme)["color.accent"], }); + if (state.accents[concept]) params.set("accent", state.accents[concept]); const src = "frame.html?" + params; if ($("#preview-" + side).getAttribute("src") !== src) $("#preview-" + side).src = src; @@ -265,12 +281,17 @@ $("#export").onclick = async () => { const files = {}; const paths = [ "components/system.css", + "components/account-pages.js", + "patterns/demo-identity.js", "concepts/registry.js", "playground/frame.html", "playground/frame.js", "tokens/schema.json", "components/CONTRACT.md", "patterns/UX.md", + "patterns/IDENTITY.md", + "prompts/SSO.md", + "prompts/README.md", "layouts/README.md", "DESIGN.md", "ANTI-SLOP.md", @@ -284,7 +305,12 @@ $("#export").onclick = async () => { ); for (const [p, t] of fetched) files[p] = t; for (const theme of ["light", "dark"]) { - const tokens = tokensFor(c.id, theme, accent, state.density); + const tokens = tokensFor( + c.id, + theme, + state.accents[c.id] || undefined, + state.density, + ); files[`tokens/${theme}.json`] = JSON.stringify(tokens, null, 2); files[`tokens/${theme}.css`] = `:root {\n${cssVars(tokens)}\n}\n`; } @@ -293,7 +319,9 @@ $("#export").onclick = async () => { version: "0.1.0", status: "candidate-export", concept: c.id, + page: state.page, accent, + customAccent: state.accents[c.id] || null, density: state.density, theme: state.theme, locale: state.locale, @@ -301,8 +329,16 @@ $("#export").onclick = async () => { null, 2, ); + const exportParams = new URLSearchParams({ + concept: c.id, + page: state.page, + density: state.density, + theme: state.theme, + locale: state.locale, + }); + if (state.accents[c.id]) exportParams.set("accent", state.accents[c.id]); files["index.html"] = - `Anidev ${c.name}