Expand Dock gallery with account workspace and identity states

This commit is contained in:
SantaSpeen committed 2026-11-28 04:00:57 +03:00
1 parent d2002071e6
commit c41a5e4276
71 files changed
+2254 -67

No files matched your search

+2
View File
@@ -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 и не подключайте реальную авторизацию без отдельного задания пользователя.
+4
View File
@@ -36,3 +36,7 @@ Production-адаптеры React/Vue/Svelte впоследствии должн
## Перед фиксацией
Пользователь выбирает концепцию либо конкретную комбинацию её свойств. Затем фиксируем типографику, лицензии локальных шрифтов, уровни токенов, компоненты и примеры новых/существующих проектов; формируем настоящий устанавливаемый Skill. До выбора `SKILL.md` — описание следующего этапа, не глобальная инструкция.
## Промежуточный Dock / revision 04
Развитие только галереи: личный кабинет с собственной навигацией, профиль/безопасность/устройства/приложения/оформление, лаборатория состояний Identity, роли и права в редакторе пользователя. Отдельная иконка раскрытия удалена; hover панели и доступная бренд-кнопка сохраняют управление. Промпт SSO используется как продуктовый контекст; его приложение и backend не меняются. Экспорт включает новые представления, демо-адаптер и документы. Палитры обеих тем экспортируются раздельно, явный пользовательский акцент сохраняется как override.
+8
View File
@@ -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 ждут утверждения дизайна.
+2
View File
@@ -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 во всех представлениях. Смена состояния аккаунта закрывает открытый приватный диалог и скрывает прежний контент.
+626
View File
@@ -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 = `<p class="identity-demo">${t("Демонстрация Anidev Identity · действия не обращаются к SSO", "Anidev Identity demo · actions do not contact SSO")}</p>`;
const names = (a) => `${a.firstName} ${a.lastName}`;
const avatar = (a, cls = "") =>
a.avatar
? `<img class="identity-avatar ${cls}" src="${e(a.avatar)}" alt="${e(names(a))}">`
: `<span class="identity-avatar ${cls}" aria-hidden="true">${e(a.firstName[0] || "")}${e(a.lastName[0] || "")}</span>`;
const action = (id, ru, en, cls = "") =>
`<button class="${cls}" data-identity="${id}">${t(ru, en)}</button>`;
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 `<section class="identity-gate" aria-live="polite"><span class="identity-gate-symbol" aria-hidden="true">${icon(["factor_required", "factor_enrollment_required"].includes(status) ? "security" : "profile")}</span><h1>${stateLabels[status] || stateLabels.signed_out}</h1><p>${stateDescriptions[status] || ""}</p>${["loading", "signing_out"].includes(status) ? `<div class="skeleton" aria-busy="true" aria-label="${t("Ожидание", "Waiting")}"></div>` : `<div class="component-row">${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") : ""}</div>`}${demo}</section>`;
}
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."))}<div class="page-body identity-body"><div class="identity-profile-summary">${avatar(a, "large")}<div><h2>${e(names(a))}</h2><p>@${e(a.username)}</p><div class="identity-roles">${a.roles.map((r) => `<span>${e(r)}</span>`).join("")}</div></div></div><div class="identity-split"><section><h2>${t("Личные данные", "Personal information")}</h2><p class="muted">${t("Имя и username можно изменить. Идентификатор аккаунта остаётся прежним.", "Your name and username may change. Your account ID stays the same.")}</p></section><form id="identity-profile"><div class="identity-fields"><label class="field">${t("Имя", "First name")}<input name="firstName" required maxlength="50" autocomplete="given-name" value="${e(a.firstName)}"></label><label class="field">${t("Фамилия", "Last name")}<input name="lastName" required maxlength="50" autocomplete="family-name" value="${e(a.lastName)}"></label></div><label class="field">Username<input name="username" required pattern="[a-zA-Z0-9._-]+" maxlength="40" autocomplete="username" value="${e(a.username)}"></label><div class="identity-readonly"><span>Email</span><strong>${a.email ? e(a.email) : t("Не добавлен", "Not added")}</strong>${a.emailVerified ? `<span class="status">${t("Подтверждён", "Verified")}</span>` : action("add-email", "Добавить и подтвердить", "Add and verify")}</div><small>${t("Для изменения подтверждённой почты обратитесь к администратору.", "Contact your administrator to change a verified email address.")}</small><div class="identity-avatar-editor"><div id="avatar-preview">${avatar(a)}</div><div><label class="file-button">${t("Выбрать фотографию", "Choose photo")}<input id="identity-avatar-file" type="file" accept="image/png,image/jpeg,image/webp"></label><small>PNG, JPEG, WebP · ${t("до 2 МБ", "up to 2 MB")}</small>${action("clear-avatar", "Убрать фото", "Remove photo")}</div></div><p id="profile-error" class="error-text" role="alert"></p><div class="form-footer"><button type="reset">${t("Отмена", "Cancel")}</button><button class="primary" type="submit">${t("Сохранить профиль", "Save profile")}</button></div></form></div><div class="identity-footnote"><span>Account ID</span><code>${e(a.sub)}</code></div>${demo}</div>`;
}
function security(a) {
return `${heading(title.security, t("Способы входа и подтверждение важных действий.", "Sign-in methods and verification for important changes."))}<div class="page-body identity-body"><section class="identity-section"><h2>${t("Способы входа", "Sign-in methods")}</h2><div class="identity-setting-row"><div><h3>${t("Пароль", "Password")}</h3><p>${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")}</p></div>${action("password-link", "Сменить", "Change")}</div><div class="identity-setting-row"><div><h3>TOTP</h3><p class="status ${a.totp ? "" : "warn"}">${a.totp ? t("Подключён", "Enabled") : t("Не подключён", "Not enabled")}</p><small>${t("Сброс подтверждается ссылкой из письма.", "Reset is verified using an email link.")}</small></div>${action(a.totp ? "totp-link" : "enroll-factor", a.totp ? "Сменить" : "Подключить", a.totp ? "Change" : "Set up")}</div></section><section class="identity-section"><div class="section-title"><div><h2>Passkey</h2><p class="muted">${t("Встроенный способ входа: Windows Hello или Touch ID.", "Platform sign-in with Windows Hello or Touch ID.")}</p></div>${action("add-passkey", "Добавить", "Add")}</div>${a.passkeys.length ? a.passkeys.map((k) => `<div class="identity-setting-row"><div><h3>${e(k.name)}</h3><p>${t("Добавлен", "Added")} ${k.created}</p></div><button class="danger" data-identity="remove-passkey" data-key="${e(k.id)}">${t("Удалить", "Remove")}</button></div>`).join("") : `<div class="empty-state"><h3>${t("Passkey ещё не добавлен", "No passkey added yet")}</h3><p>${t("Добавьте ключ, чтобы входить с помощью устройства.", "Add a key to sign in with your device.")}</p></div>`}</section><section class="identity-section identity-security-note"><h2>${t("Как работают проверки", "How verification works")}</h2><p>${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.")}</p></section>${demo}</div>`;
}
function sessions() {
const rows = snap().sessions;
return `${heading(title.sessions, t("Устройства, на которых выполнен вход в ваш аккаунт.", "Devices currently signed in to your account."), action("revoke-others", "Завершить другие сеансы", "End other sessions"))}<div class="page-body identity-body"><section class="identity-section"><div class="identity-list-heading"><span>${t("Устройство", "Device")}</span><span>${t("Последняя активность", "Last activity")}</span></div>${rows.map((s) => `<div class="identity-session"><span class="identity-device-icon">${icon("sessions")}</span><div><h3>${s.device}</h3><p>${s.place}${s.current ? " · " + t("Текущий сеанс", "Current session") : ""}</p></div><time>${s.seen}</time><button class="${s.current ? "" : "danger"}" data-identity="revoke-session" data-session="${s.id}">${s.current ? t("Выйти", "Sign out") : t("Завершить", "End session")}</button></div>`).join("")}</section><p class="identity-explanation">${t("Выход из SSO завершает текущий браузерный сеанс. Остальные устройства сохраняют вход, пока вы не завершите их отдельно.", "Signing out of SSO ends this browser session. Other devices stay signed in until you end those sessions separately.")}</p>${demo}</div>`;
}
function applications(a) {
const grants = adapter.getGrants(a.sub === "demo-anna" ? 1 : 2);
return `${heading(title.applications, t("Сервисы, доступные вашему аккаунту.", "Services available to your account."))}<div class="page-body identity-body"><div class="identity-apps">${grants
.map((g) => {
const app = applicationCatalog.find((v) => v.id === g.application);
return `<article class="identity-app"><span class="app-monogram" aria-hidden="true">${app.code}</span><div><h2>${app.name}</h2><p>${app.description[t("ru", "en") === "ru" ? 0 : 1]}</p><small>${g.status === "active" ? t("Доступ выдан", "Access granted") + " · " + g.added : t("Доступ приостановлен", "Access suspended") + (g.showReason ? " · " + e(g.reason) : "")}</small></div><button data-identity="open-app" data-app="${app.id}" ${g.status !== "active" ? "disabled" : ""}>${t("Открыть", "Open")}</button></article>`;
})
.join(
"",
)}</div><p class="identity-explanation">${t("Нужен другой сервис? Запросите доступ у администратора организации.", "Need another service? Request access from your organization administrator.")}</p>${demo}</div>`;
}
function appearance() {
return `${heading(title.appearance, t("Выберите режим для повседневной работы.", "Choose a mode for everyday work."))}<div class="page-body identity-body"><div class="theme-choice-grid">${["light", "dark"].map((mode) => `<button class="theme-choice" data-identity="theme" data-theme="${mode}" aria-pressed="${document.body.dataset.theme === mode}"><span class="theme-thumbnail ${mode}" aria-hidden="true"><i></i><i></i><i></i></span><strong>${mode === "light" ? t("Светлая", "Light") : t("Тёмная", "Dark")}</strong><small>${mode === "light" ? t("Светлые поверхности и петрольный текст", "Light surfaces and petrol text") : t("Глубокий петроль и мягкий контраст", "Deep petrol and soft contrast")}</small></button>`).join("")}</div><p class="identity-explanation">${t("Палитру организации настраивает администратор. Пользователь выбирает только светлый или тёмный режим.", "An administrator configures your organization palette. Users choose only light or dark mode.")}</p>${demo}</div>`;
}
function stateLab() {
const status = snap().status;
return `${heading(title.identity, t("Просмотрите реакцию интерфейса на состояние SSO.", "Inspect how the interface responds to SSO state."), action("reset", "Сбросить демо", "Reset demo"))}<div class="page-body"><div class="identity-state-controls"><label class="field">${t("Состояние", "State")}<select id="identity-state">${identityStates.map((s) => `<option value="${s}" ${s === status ? "selected" : ""}>${stateLabels[s]}</option>`).join("")}</select></label><code>${status}</code></div><div class="identity-state-preview">${status === "authenticated" ? `<div class="identity-gate"><h2>${stateLabels.authenticated}</h2><p>${t("Личность проверена. Доступны профиль, сеансы и разрешённые приложения.", "Identity verified. Profile, sessions and permitted applications are available.")}</p><div class="component-row"><button data-page="profile">${title.profile}</button><button data-page="applications">${title.applications}</button></div></div>` : gate(status)}</div><p class="identity-explanation">${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.")}</p></div>`;
}
function emailLink(kind) {
if (!snap().account.emailVerified) {
addEmail();
return;
}
openDialog(
t("Подтверждение по почте", "Email verification"),
`<p>${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.")}</p><p>${e(snap().account.email)}</p><small>${t("Ссылка действует 1 час. В этом демо письмо не отправляется.", "The link is valid for 1 hour. This demo does not send an email.")}</small><div class="form-footer">${action("email-sent", "Показать результат", "Show result", "primary")}</div>`,
);
}
function addEmail() {
openDialog(
t("Добавить почту", "Add email"),
`<p>${t("Сначала подтвердите почту. В реальном SSO привязка требует недавнего подтверждения личности.", "Verify your email first. A real SSO link requires recent identity verification.")}</p><form id="identity-email"><label class="field">Email<input type="email" name="email" autocomplete="email" required></label><small>${t("Демо: письма не отправляются. Нажатие имитирует завершённое подтверждение.", "Demo: no email is sent. This button simulates completed verification.")}</small><div class="form-footer"><button class="primary" type="submit">${t("Подтвердить в демо", "Verify in demo")}</button></div></form>`,
);
$("#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,
`<p>${description}</p><div class="form-footer"><button data-action="close">${t("Отмена", "Cancel")}</button><button class="danger" data-identity="${confirmId}" ${data}>${t("Подтвердить", "Confirm")}</button></div>`,
);
}
function switchAccount() {
openDialog(
t("Сменить аккаунт", "Switch account"),
`<p>${t("Текущий браузерный вход будет завершён. Затем откроется новая форма входа SSO. Другие устройства сохранят свои сеансы.", "This browser session will end, followed by a new SSO sign-in form. Other devices will retain their sessions.")}</p><small>${t("Демо: письма, токены и запросы к провайдеру не используются.", "Demo: no email, tokens or provider requests are used.")}</small><div class="form-footer"><button data-action="close">${t("Отмена", "Cancel")}</button><button class="primary" data-identity="confirm-switch">${t("Продолжить", "Continue")}</button></div>`,
);
}
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"),
`<p>${t("В настоящем потоке настройка выполняется в SSO после подтверждения личности.", "In a real flow this is configured in SSO after identity verification.")}</p>${demo}<button class="primary" data-identity="resolve">${t("Завершить демо-проверку", "Complete demo verification")}</button>`,
);
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"),
`<p>${t("Введите 6 цифр. В демо подходит 123456.", "Enter 6 digits. Use 123456 in the demo.")}</p><form id="identity-factor"><label class="field">${t("Код подтверждения", "Verification code")}<input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" minlength="6" required aria-describedby="factor-error"></label><p id="factor-error" class="error-text" role="alert"></p><button class="primary" type="submit">${t("Подтвердить", "Verify")}</button></form>`,
);
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"),
`<p>${t("Демонстрационный ключ. Windows Hello или Touch ID здесь не запускается.", "Demo key. Windows Hello or Touch ID is not invoked here.")}</p><form id="identity-passkey"><label class="field">${t("Название устройства", "Device name")}<input name="name" required maxlength="60" value="Windows Hello"></label><button class="primary" type="submit">${t("Добавить в демо", "Add to demo")}</button></form>`,
);
$("#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,
`<p>${t("Демонстрация перехода в приложение. Реальный адрес не подключён.", "Demo application handoff. No live destination is connected.")}</p><button data-action="close">${t("Вернуться", "Go back")}</button>`,
);
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 `<section class="identity-grants"><div class="section-title"><h3>${t("Доступ к приложениям", "Application access")}</h3><button type="button" data-identity="grant-add">${t("Добавить приложение", "Add application")}</button></div><div class="grant-bulk"><span id="grant-count">${t("Выбрано", "Selected")}: ${selectedGrants.size}</span><button type="button" data-identity="grant-suspend" ${selectedGrants.size ? "" : "disabled"}>${t("Приостановить выбранные", "Suspend selected")}</button></div><div class="table-wrap"><table><thead><tr><th><input type="checkbox" id="grant-all" aria-label="${t("Выбрать все приложения", "Select all applications")}"></th><th>${t("Приложение", "Application")}</th><th>${t("Выдано", "Granted")}</th><th>${t("Кем", "By")}</th><th>${t("Действия", "Actions")}</th></tr></thead><tbody>${rows.map((g) => `<tr><td><input type="checkbox" data-grant="${g.application}" aria-label="${t("Выбрать", "Select")} ${applicationCatalog.find((a) => a.id === g.application).name}" ${selectedGrants.has(g.application) ? "checked" : ""}></td><td>${applicationCatalog.find((a) => a.id === g.application).name}<small class="${g.status === "active" ? "status" : "error-text"}">${g.status === "active" ? t("Активен", "Active") : t("Приостановлен", "Suspended")}</small></td><td>${g.added}</td><td>${e(g.by)}</td><td><details class="grant-actions"><summary aria-label="${t("Действия приложения", "Application actions")}">···</summary><div class="dropdown"><button type="button" data-identity="${g.status === "active" ? "grant-suspend" : "grant-resume"}" data-app="${g.application}">${g.status === "active" ? t("Приостановить", "Suspend") : t("Возобновить", "Resume")}</button></div></details></td></tr>`).join("")}</tbody></table></div></section>`;
}
function roleMarkup(userId) {
const roles = adapter.getUserRoles(userId);
return `<fieldset class="identity-role-fields"><legend>${t("Роли SSO", "SSO roles")}</legend>${[...systemRoles, ...snap().customRoles].map((r) => `<label><input type="checkbox" name="ssoRole" value="${e(r)}" ${roles.includes(r) ? "checked" : ""}> ${e(r)}</label>`).join("")}</fieldset><div class="component-row"><input id="custom-role" placeholder="${t("Новая роль", "New role")}" aria-label="${t("Название новой роли", "New role name")}" maxlength="40"><button type="button" data-identity="add-role">${t("Добавить роль", "Add role")}</button></div>`;
}
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
? `<form id="grant-add-form"><label class="field">${t("Приложение", "Application")}<select name="application">${available.map((a) => `<option value="${a.id}">${a.name}</option>`).join("")}</select></label><button class="primary" type="submit">${t("Выдать доступ", "Grant access")}</button></form>`
: `<p>${t("Все приложения уже добавлены.", "All applications have already been added.")}</p>`,
);
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"),
`<form id="grant-suspend-form"><p>${t("Приложений выбрано", "Applications selected")}: ${ids.length}</p><label class="field">${t("Причина", "Reason")}<textarea name="reason" required maxlength="300" rows="3"></textarea></label><div class="form-row"><input id="show-reason" type="checkbox" name="showReason"><label for="show-reason">${t("Показывать причину пользователю", "Show reason to user")}</label></div><button class="primary" type="submit">${t("Приостановить", "Suspend")}</button></form>`,
);
$("#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,
};
}
+588
View File
@@ -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;
}
}
+2 -1
View File
@@ -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"
+37
View File
@@ -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-интеграции.
+3 -1
View File
@@ -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.
+301
View File
@@ -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;
}
+143 -48
View File
@@ -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:
'<circle cx="12" cy="7" r="4"/><path d="M4 22v-3a8 8 0 0 1 16 0v3"/>',
security:
'<path d="m12 2 8 4v6c0 5-8 10-8 10S4 17 4 12V6Z"/><path d="m8 12 3 3 5-6"/>',
sessions:
'<rect x="2" y="3" width="16" height="12" rx="2"/><path d="M6 20h8M10 15v5"/><rect x="16" y="9" width="6" height="12" rx="1"/>',
applications:
'<rect x="3" y="3" width="7" height="7" rx="2"/><rect x="14" y="3" width="7" height="7" rx="2"/><rect x="3" y="14" width="7" height="7" rx="2"/><rect x="14" y="14" width="7" height="7" rx="2"/>',
appearance: '<circle cx="12" cy="12" r="9"/><path d="M12 3v18"/>',
identity:
'<rect x="3" y="4" width="18" height="16" rx="3"/><circle cx="8" cy="10" r="2"/><path d="M5 16a3 3 0 0 1 6 0M14 9h4M14 13h4"/>',
dashboard:
'<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>',
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 `<div class="dock-account-area"><div id="account-menu" class="account-menu" popover="auto" aria-label="${t("Меню аккаунта", "Account menu")}">
<button autofocus data-action="profile">${icon("users")}<span>${t("Аккаунт", "Account")}</span></button>
<button data-page="settings">${icon("settings")}<span>${t("Настройки", "Settings")}</span></button>
<button autofocus data-page="profile">${icon("users")}<span>${t("Аккаунт", "Account")}</span></button>
<button data-page="security">${icon("settings")}<span>${t("Настройки", "Settings")}</span></button>
<button data-page="applications">${icon("applications")}<span>${t("Приложения", "Applications")}</span></button>
<button data-action="shares">${icon("components")}<span>${t("Мои общие ресурсы", "My shares")}</span></button>
<button data-page="dashboard">${icon("dashboard")}<span>${t("Панель управления", "Control panel")}</span></button>
<button class="account-separator" data-action="switch-account">${icon("users")}<span>${t("Сменить аккаунт", "Switch account")}</span></button>
<button class="account-separator" data-page="auth"><svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M9 4H4v16h5M13 7l5 5-5 5M8 12h11"/></svg><span>${t("Выйти", "Logout")}</span></button></div>
<button class="dock-account" popovertarget="account-menu" aria-label="${t("Меню аккаунта Anna Volkova", "Anna Volkova account menu")}"><span class="avatar">AV</span><span class="account-identity"><b>Anna Volkova</b><small>anna@anidev.ru</small></span><span class="account-more" aria-hidden="true">···</span></button></div>`;
${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)) ? `<button data-page="dashboard">${icon("dashboard")}<span>${t("Панель управления", "Control panel")}</span></button>` : ""}
<button class="account-separator" data-identity="switch">${icon("users")}<span>${t("Сменить аккаунт", "Switch account")}</span></button>
<button class="account-separator" data-identity="logout"><svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M9 4H4v16h5M13 7l5 5-5 5M8 12h11"/></svg><span>${t("Выйти из SSO", "Sign out of SSO")}</span></button></div>
<button class="dock-account" popovertarget="account-menu" aria-label="${escape(t("Меню аккаунта ", "Account menu ") + accountName())}"><span class="avatar">${currentIdentity()?.avatar ? `<img src="${escape(currentIdentity().avatar)}" alt="">` : escape(accountInitials())}</span><span class="account-identity"><b>${escape(accountName())}</b><small>${escape(currentIdentity()?.username || "Anidev Identity")}</small></span><span class="account-more" aria-hidden="true">···</span></button></div>`;
}
function nav() {
return `<aside class="navigation" id="dock-navigation">${concept.id === "dock" ? wordmark : ""}${concept.id === "dock" ? `<button class="dock-toggle" data-action="dock-toggle" aria-expanded="false" aria-controls="dock-navigation" aria-label="${t("Развернуть меню", "Expand navigation")}" title="${t("Развернуть меню", "Expand navigation")}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M9 4v16M14 9l3 3-3 3"/></svg><span>${t("Свернуть меню", "Collapse navigation")}</span></button>` : ""}${concept.id !== "dock" ? wordmark : ""}<div class="workspace-label">ANIDEV / PRODUCTION</div><nav aria-label="${t("Основная навигация", "Main navigation")}" class="nav-links">${["dashboard", "users", "settings", "components", "tokens"].map((p) => `<button data-page="${p}" ${page === p ? 'aria-current="page"' : ""} title="${pageNames[p]}" aria-label="${pageNames[p]}">${icon(p)}<span>${pageNames[p]}</span></button>`).join("")}</nav><div class="nav-bottom">eu-central-1<br>Workspace / Pro<br><button data-page="auth" style="font-size:12px;margin-top:15px">${t("Выйти", "Sign out")}</button></div>${concept.id === "dock" ? dockAccount() : ""}</aside>`;
const dockBrand = `<button class="dock-toggle dock-brand wordmark" data-action="dock-toggle" aria-expanded="false" aria-controls="dock-navigation" aria-label="${t("Развернуть меню Anidev", "Expand Anidev navigation")}" title="${t("Навигация Anidev", "Anidev navigation")}"><b>a/</b><span>anidev</span></button>`;
return `<aside class="navigation" id="dock-navigation">${concept.id === "dock" ? dockBrand : wordmark}<div class="workspace-label">ANIDEV / PRODUCTION</div><nav aria-label="${t("Основная навигация", "Main navigation")}" class="nav-links">${navigationPages()
.map(
(p) =>
`<button data-page="${p}" ${page === p ? 'aria-current="page"' : ""} title="${pageNames[p]}" aria-label="${pageNames[p]}">${icon(p)}<span>${pageNames[p]}</span></button>`,
)
.join(
"",
)}</nav><div class="nav-bottom">eu-central-1<br>Workspace / Pro<br><button data-page="auth" style="font-size:12px;margin-top:15px">${t("Выйти", "Sign out")}</button></div>${concept.id === "dock" ? dockAccount() : ""}</aside>`;
}
function header() {
return `<header class="app-header"><button class="mobile-menu" data-action="mobile-menu" aria-label="${t("Открыть навигацию", "Open navigation")}" aria-expanded="false">☰</button><div class="breadcrumb">Anidev <span aria-hidden="true">/</span> Production <span aria-hidden="true">/</span> ${pageNames[page]}</div><div class="header-actions"><button class="command-trigger" data-action="command">${t("Найти команду", "Find a command")} <kbd>⌘ K</kbd></button><button class="avatar" data-action="profile" aria-label="${t("Профиль Anna Volkova", "Anna Volkova profile")}">AV</button></div></header>`;
return `<header class="app-header"><button class="mobile-menu" data-action="mobile-menu" aria-label="${t("Открыть навигацию", "Open navigation")}" aria-expanded="false">☰</button><div class="breadcrumb">Anidev <span aria-hidden="true">/</span> ${accountPageIds.includes(page) ? t("Личный кабинет", "My account") : "Production"} <span aria-hidden="true">/</span> ${pageNames[page]}</div><div class="header-actions"><button class="command-trigger" data-action="command">${t("Найти команду", "Find a command")} <kbd>⌘ K</kbd></button><button class="avatar" data-action="profile" aria-label="${escape(accountName())}">${escape(accountInitials())}</button></div></header>`;
}
const heading = (title, desc, actions = "") =>
`<div class="page-heading"><div><div class="overline">ANIDEV://PRODUCTION/${page.toUpperCase()}</div><h1>${title}</h1><p>${desc}</p></div><div class="heading-actions">${actions}</div></div>`;
@@ -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()
: `<div class="shell">${nav()}${concept.id === "dock" ? `<button class="dock-scrim" data-action="dock-close" tabindex="-1" aria-label="${t("Закрыть меню", "Close navigation")}" aria-hidden="true"></button>` : ""}<div class="main-column">${header()}<main id="content" tabindex="-1">${{ dashboard, users: userScreen, settings: settingsScreen, components: componentScreen, tokens: tokenScreen }[page]()}</main></div></div>`;
: `<div class="shell">${nav()}${concept.id === "dock" ? `<button class="dock-scrim" data-action="dock-close" tabindex="-1" aria-label="${t("Закрыть меню", "Close navigation")}" aria-hidden="true"></button>` : ""}<div class="main-column">${header()}<main id="content" tabindex="-1">${content}</main></div></div>`;
bindForms();
accountUI.bind(page);
bindDockHover();
if (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."))}<div class="page-body"><div class="tabs" role="tablist" aria-label="${t("Раздел настроек", "Settings section")}">${["general", "security", "notifications"].map((v, i) => `<button role="tab" id="tab-${v}" aria-controls="settings-panel" data-tab="${v}" aria-selected="${tab === v}" tabindex="${tab === v ? "0" : "-1"}">${[t("Основные", "General"), t("Безопасность", "Security"), t("Уведомления", "Notifications")][i]}</button>`).join("")}</div><section id="settings-panel" role="tabpanel" aria-labelledby="tab-${tab}" class="settings-layout"><div class="settings-copy"><h2>${tab === "general" ? t("Ваше пространство", "Your workspace") : tab === "security" ? t("Контроль доступа", "Access control") : t("Оповещения", "Notifications")}</h2><p>${tab === "general" ? t("Эти данные видны участникам организации.", "These details are visible to organization members.") : t("Изменения применяются к этому демо.", "Changes apply to this demo.")}</p></div><form id="settings-form">${tab === "general" ? `<label class="field">${t("Название", "Workspace name")}<input name="name" required maxlength="60" value="${escape(settings.name)}"></label><label class="field">${t("Идентификатор", "Workspace slug")}<input name="slug" required pattern="[a-z0-9-]+" value="${escape(settings.slug)}"><small>${t("Строчные латинские буквы, цифры и дефис.", "Lowercase letters, numbers and hyphens.")}</small></label><label class="field">${t("Регион данных", "Data region")}<select name="region"><option value="eu" ${settings.region === "eu" ? "selected" : ""}>Europe / Frankfurt</option><option value="us" ${settings.region === "us" ? "selected" : ""}>US / Virginia</option></select></label>` : tab === "security" ? `<div class="form-row"><label for="mfa"><b>${t("Двухфакторная авторизация", "Two-factor authentication")}</b><small style="display:block">${t("Обязательна для всех участников", "Required for all members")}</small></label><input class="switch" type="checkbox" role="switch" name="mfa" id="mfa" ${settings.mfa ? "checked" : ""}></div><div class="form-row"><label for="audit">${t("Журналировать действия", "Record audit events")}</label><input class="switch" type="checkbox" role="switch" name="audit" id="audit" ${settings.audit ? "checked" : ""}></div><button type="button" data-action="sessions">${t("Управление сессиями", "Manage sessions")}</button>` : `<label class="field">${t("Email для оповещений", "Alert email")}<input type="email" name="email" required value="${escape(settings.email)}"></label><div class="form-row"><input type="checkbox" id="incidents" checked><label for="incidents">${t("Инциденты и недоступность сервисов", "Incidents and service outages")}</label></div>`}<div class="form-footer"><button type="reset">${t("Отменить", "Cancel")}</button><button class="primary" type="submit">${t("Сохранить изменения", "Save changes")}</button></div></form></section></div>`;
}
function auth() {
return `<main id="content" class="auth-layout" style="max-width:none;padding:0"><section class="auth-brand">${wordmark}<div class="auth-statement">${t("Ваша инфраструктура.<br>Под вашим контролем.", "Your infrastructure.<br>Under your control.")}</div><small>ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}</small></section><section class="auth-main"><form id="auth-form" class="auth-form"><h1>${t("Вход в Anidev", "Sign in to Anidev")}</h1><p>${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}</p><label class="field">Email<input name="email" type="email" autocomplete="username" placeholder="you@company.com" required></label><label class="field">${t("Пароль", "Password")}<input name="password" type="password" autocomplete="current-password" minlength="8" required aria-describedby="password-hint"><small id="password-hint">${t("Демо: любой email и пароль от 8 символов.", "Demo: any email and a password of 8+ characters.")}</small></label><div class="form-row"><input id="remember" type="checkbox"><label for="remember">${t("Запомнить меня", "Remember me")}</label><button class="row-action" type="button" data-action="recover">${t("Забыли пароль?", "Forgot password?")}</button></div><p class="error-text" id="auth-error" role="alert"></p><button class="primary" type="submit">${t("Войти", "Sign in")}</button><div class="auth-divider">${t("или корпоративный аккаунт", "or your company account")}</div><button type="button" class="sso" data-action="sso">${t("Войти через SSO", "Continue with SSO")}</button><div class="auth-foot"><span>© Anidev 2026</span><button class="row-action" type="button" data-page="dashboard">${t("Вернуться к обзору", "Back to overview")}</button></div></form></section></main>`;
return `<main id="content" class="auth-layout" style="max-width:none;padding:0"><section class="auth-brand">${wordmark}<div class="auth-statement">${t("Ваша инфраструктура.<br>Под вашим контролем.", "Your infrastructure.<br>Under your control.")}</div><small>ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}</small></section><section class="auth-main"><form id="auth-form" class="auth-form"><h1>${t("Вход в Anidev", "Sign in to Anidev")}</h1><p>${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}</p><label class="field">${t("Username или email", "Username or email")}<input name="email" type="text" autocomplete="username" placeholder="anna.volkova" required></label><label class="field">${t("Пароль", "Password")}<input name="password" type="password" autocomplete="current-password" minlength="8" required aria-describedby="password-hint"><small id="password-hint">${t("Демо: anna.volkova или mikhail.orlov; пароль от 8 символов.", "Demo: anna.volkova or mikhail.orlov; password of 8+ characters.")}</small></label><div class="form-row"><input id="remember" type="checkbox"><label for="remember">${t("Запомнить меня", "Remember me")}</label><button class="row-action" type="button" data-action="recover">${t("Забыли пароль?", "Forgot password?")}</button></div><p class="error-text" id="auth-error" role="alert"></p><button class="primary" type="submit">${t("Войти", "Sign in")}</button><div class="auth-divider">${t("или корпоративный аккаунт", "or your company account")}</div><button type="button" class="sso" data-action="sso">${t("Войти через SSO", "Continue with SSO")}</button><div class="auth-foot"><span>© Anidev 2026</span><button class="row-action" type="button" data-page="dashboard">${t("Вернуться к обзору", "Back to overview")}</button></div></form></section></main>`;
}
function componentScreen() {
return `${heading(t("Библиотека компонентов", "Component library"), t("Единые состояния. Шесть способов выражения.", "Shared states. Six ways of expressing them."), `<button data-action="command">${t("Команды", "Commands")} ⌘K</button>`)}<div class="page-body"><div class="library">
@@ -493,13 +565,16 @@ function editUser(id) {
if (!user) return;
openDialog(
escape(user.name),
`<p>${escape(user.email)}</p><form id="edit-user"><label class="field">${t("Роль", "Role")}<select name="role">${["admin", "developer", "viewer"].map((r) => `<option value="${r}" ${user.role === r ? "selected" : ""}>${roleName(r)}</option>`).join("")}</select></label><label class="field">${t("Статус", "Status")}<select name="status">${["active", "invited", "suspended"].map((s) => `<option value="${s}" ${user.status === s ? "selected" : ""}>${statusName(s)}</option>`).join("")}</select></label><div class="form-footer"><button type="button" data-action="close">${t("Отмена", "Cancel")}</button><button type="submit" class="primary">${t("Сохранить", "Save")}</button></div></form>`,
`<p>${escape(user.email)}</p><form id="edit-user"><label class="field">${t("Роль в пространстве", "Workspace role")}<select name="role">${["admin", "developer", "viewer"].map((r) => `<option value="${r}" ${user.role === r ? "selected" : ""}>${roleName(r)}</option>`).join("")}</select></label><label class="field">${t("Статус", "Status")}<select name="status">${["active", "invited", "suspended"].map((s) => `<option value="${s}" ${user.status === s ? "selected" : ""}>${statusName(s)}</option>`).join("")}</select></label>${accountUI.roleMarkup(id)}${accountUI.grantsMarkup(id)}<div class="form-footer"><button type="button" data-action="close">${t("Отмена", "Cancel")}</button><button type="submit" class="primary">${t("Сохранить", "Save")}</button></div></form>`,
);
$("#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) => {
`<p>${t("Общих ресурсов пока нет.", "No shared resources yet.")}</p><button data-action="close">${t("Закрыть", "Close")}</button>`,
"drawer",
),
"switch-account": () => {
setDockOpen(false, false);
openDialog(
t("Сменить аккаунт", "Switch account"),
`<p>${t("Демонстрация SSO-переключения. Реальный провайдер не подключён.", "Demo SSO account switching. No live provider is connected.")}</p><div class="command-list"><button data-action="select-account" data-account="Anna Volkova">Anna Volkova <small>anna@anidev.ru</small></button><button data-action="select-account" data-account="Mikhail Orlov">Mikhail Orlov <small>mikhail@anidev.ru</small></button></div>`,
);
},
"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",
`<p>anna@anidev.ru</p><p>${roleName("admin")} · Anidev Production</p><button data-page="settings">${t("Настройки пространства", "Workspace settings")}</button><button data-page="auth">${t("Выйти", "Sign out")}</button>`,
),
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();
+56 -5
View File
@@ -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"] =
`<!doctype html><meta charset="utf-8"><title>Anidev ${c.name}</title><script>location.replace('playground/frame.html?${new URLSearchParams({ concept: c.id, accent, density: state.density, theme: state.theme, locale: state.locale })}')<\/script>`;
`<!doctype html><meta charset="utf-8"><title>Anidev ${c.name}</title><script>location.replace('playground/frame.html?${exportParams}')<\/script>`;
files["README.md"] =
`# Anidev / ${c.name}\nCandidate export, not final approval.\nServe this folder over HTTP (for example python -m http.server 8080).\nOpen index.html.\nUse tokens/light.css or tokens/dark.css and components/system.css in any framework.\nSemantic token JSON is the source of values.\nNo upstream implementation is bundled. Final Skill follows user concept selection.\n`;
const url = URL.createObjectURL(zip(files)),
@@ -323,3 +359,18 @@ $("#export").onclick = async () => {
}
};
render();
addEventListener("message", (event) => {
if (
event.origin === location.origin &&
[
document.querySelector("#preview-a").contentWindow,
document.querySelector("#preview-b").contentWindow,
].includes(event.source) &&
event.data?.type === "anidev-theme" &&
["light", "dark"].includes(event.data.theme)
) {
state.theme = event.data.theme;
render();
}
});
+6
View File
@@ -41,6 +41,12 @@
<option value="auth">Авторизация</option>
<option value="components">Компоненты</option>
<option value="tokens">Токены</option>
<option value="profile">Аккаунт</option>
<option value="security">Безопасность</option>
<option value="sessions">Устройства и сеансы</option>
<option value="applications">Приложения</option>
<option value="appearance">Оформление</option>
<option value="identity">Состояния входа</option>
</select></label
><label
><span data-i="theme">Тема</span
+8
View File
@@ -46,3 +46,11 @@
## Dock revision 03 / 28.11.2026
10 целевых browser-проверок прошли после переноса логотипа и добавления hover. Проверены logo-before-trigger, наведение/переход внутрь/уход курсора, touch fallback, обе темы и три ширины, меню аккаунта, Escape и reduced motion; ошибок JavaScript нет. Общая матрица после изменений также повторена: 230/230, ошибок JavaScript нет.
## Dock / личный кабинет, revision 04
28.11.2026: общая browser suite 230/230; Dock 10/10; Identity 94/94, ошибок JavaScript нет. Identity включает 72 сочетания шести новых экранов, двух тем, EN/RU и трёх разрешений; остальные проверки — профиль, фото, сохранение/отмена, email, Passkey, отзыв сеансов, роли и массовые права, девять закрытых состояний, TOTP, смена аккаунта, тема/экспорт и закрытие приватного диалога при изменении личности между iframe.
10 проверок Dock адаптированы к корректному потоку смены аккаунта через форму входа и отсутствию отдельной иконки. Это Edge/Playwright и визуальная проверка скриншотов; не полный WCAG-аудит и не проверка настоящего SSO. Актуальные снимки новых экранов: `identity/`.
Дополнительно: в обеих темах на desktop/mobile проверено, что неверный TOTP не меняет геометрию диалога (4/4, `tests/totp-layout.mjs`). Распакованный ZIP содержит 22 файла, CRC проверен, профиль работает отдельно от галереи, а акценты обеих тем совпадают с их default-токенами.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 KiB

After

Width:  |  Height:  |  Size: 116 KiB

+21
View File
@@ -0,0 +1,21 @@
# Dock — личный кабинет, revision 04
Это экраны галереи дизайн-системы, а не новая версия приложения SSO Service. Настоящие endpoints, почта, WebAuthn и OAuth не подключены. Финальное утверждение Dock и создание устанавливаемого Skill остаются следующим этапом.
Новые экраны: профиль, безопасность, устройства и сеансы, доступные приложения, оформление и лаборатория состояний входа. Они используют общую типографику, компактные строки, native формы и диалоги. Навигация личного кабинета отделена от административной.
Снимки сделаны в настоящем Edge: `{page}-{light|dark}-{desktop|mobile}.png`. Desktop — 1440×900; mobile — 390×844 с полной высотой страницы. В `qa.json` сохранён итог 94 успешных проверок без ошибок. Tablet 768×1024 также проверяется, но не дублируется в снимках.
- `profile` — сохранение данных и фотографии, стабильный ID.
- `security` — пароль, статус TOTP, именованные демо-Passkey.
- `sessions` — текущий и другие сеансы, подтверждение отзыва.
- `applications` — приложения с активным/приостановленным доступом.
- `appearance` — только светлый/тёмный режим для пользователя.
- `identity` — управляемые состояния авторизации; закрытые состояния скрывают данные аккаунта.
- `user-access-light-desktop.png` — роли и доступы к приложениям в редакторе пользователя.
Браузерные проверки также покрывают ошибочный TOTP, добавление почты, очистку пароля после ошибки, смену личности через новый вход, разделение сеансов разных аккаунтов, отсутствие доступа к администрированию у обычного пользователя, причины приостановки, экспорт обеих палитр и закрытие приватного диалога при изменении состояния в соседнем iframe.
Отдельная иконка раскрытия Dock удалена. Меню открывается по наведению на панель, а `a/` остаётся доступным переключателем для клавиатуры и touch. Ранее выбранные палитры и анимации сохранены.
`totp-error-*.png` показывают ошибочный код без смещения окна: четыре проверки геометрии (обе темы, desktop/mobile) прошли отдельно и включены в `npm run test:identity`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

+7
View File
@@ -0,0 +1,7 @@
{
"date": "2026-11-28T00:56:52.649Z",
"passed": 94,
"failed": 0,
"failures": [],
"errors": []
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

+10 -6
View File
@@ -1,12 +1,16 @@
{
"date": "2026-11-28T00:34:19.796Z",
"clientDate": "2026-11-28",
"browser": "158.0.4370.45",
"passed": 230,
"corePassed": 230,
"identityPassed": 94,
"dockPassed": 10,
"totpGeometryPassed": 4,
"failed": 0,
"errors": [],
"clientDate": "2026-11-28",
"dockTargetedPassed": 10,
"matrix": "6 concepts x 2 themes x 3 viewports x 6 screens",
"standaloneExport": "passed",
"exportFiles": 22,
"zipCRC": "passed",
"themeExportAccents": "passed",
"tokenConfigurations": 36,
"status": "intermediate Dock revision 03"
"status": "intermediate Dock revision 04, gallery only"
}
+1 -1
View File
@@ -164,7 +164,7 @@ try {
assert.equal(await page.locator("#auth-form").count(), 1);
await page.locator("input[name=password]").fill("long-password");
await page.locator("#auth-form button[type=submit]").click();
await page.locator(".health-line").waitFor();
await page.locator("#identity-profile").waitFor();
});
await check("Command palette keyboard and modal focus trap", async () => {
await page.keyboard.press("Control+k");
+17 -5
View File
@@ -21,6 +21,8 @@ try {
["mobile", 390, 844],
]) {
await p.setViewportSize({ width, height });
await p.goto(`${base}/playground/frame.html?concept=dock&page=identity`);
await p.locator("[data-identity=reset]").click();
await p.goto(
`${base}/playground/frame.html?concept=dock&density=compact&theme=${theme}`,
);
@@ -73,9 +75,13 @@ try {
await p.screenshot({
path: `references/dock-revision/${theme}-${device}-account.png`,
});
await p.locator("#account-menu [data-action=switch-account]").click();
await p.locator("#account-menu [data-identity=switch]").click();
await p.locator("#dialog").waitFor({ state: "visible" });
await p.locator('[data-account="Mikhail Orlov"]').click();
await p.locator("[data-identity=confirm-switch]").click();
await p.locator("#auth-form [name=email]").fill("mikhail.orlov");
await p.locator("#auth-form [name=password]").fill("demo-password");
await p.locator("#auth-form [type=submit]").click();
await p.locator("#identity-profile").waitFor();
assert.equal(
await p.locator(".account-identity b").innerText(),
"Mikhail Orlov",
@@ -118,11 +124,17 @@ try {
"false",
);
passed++;
await p.goto(`${base}/playground/frame.html?concept=dock&page=identity`);
await p.locator("[data-identity=reset]").click();
await p.goto(`${base}/playground/frame.html?concept=dock`);
await p.locator(".dock-toggle").waitFor();
const brand = await p.locator(".navigation .wordmark").boundingBox();
const trigger = await p.locator(".dock-toggle").boundingBox();
assert.ok(brand.y < trigger.y, "Brand is above menu trigger");
assert.equal(
await p
.locator(".navigation")
.evaluate((el) => el.firstElementChild.classList.contains("dock-brand")),
true,
);
assert.equal(await p.locator(".dock-brand svg").count(), 0);
await p.locator(".dock-toggle").hover();
await p.waitForTimeout(300);
assert.equal(
+379
View File
@@ -0,0 +1,379 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
import { mkdir, writeFile } from "node:fs/promises";
import { tokensFor } from "../concepts/registry.js";
import { identityStates } from "../patterns/demo-identity.js";
const base = process.env.BASE_URL || "http://127.0.0.1:4173";
const b = await chromium.launch({
executablePath:
process.env.PLAYWRIGHT_EXECUTABLE_PATH ||
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
headless: true,
});
const ctx = await b.newContext(),
p = await ctx.newPage();
p.setDefaultTimeout(7000);
const failures = [],
errors = [];
let passed = 0;
p.on("pageerror", (e) => errors.push(e.message));
const path = (page = "profile", theme = "light", locale = "ru", extra = "") =>
`${base}/playground/frame.html?concept=dock&page=${page}&theme=${theme}&locale=${locale}&density=compact${extra}`;
async function check(name, run) {
try {
await run();
passed++;
} catch (error) {
failures.push({ name, error: error.message });
console.log("FAIL", name, error.message);
}
}
const reset = async () => {
await p.goto(path("identity"));
await p.locator("[data-identity=reset]").click();
};
await mkdir("references/identity", { recursive: true });
try {
for (const theme of ["light", "dark"])
for (const locale of ["ru", "en"])
for (const [device, width, height] of [
["desktop", 1440, 900],
["tablet", 768, 1024],
["mobile", 390, 844],
])
for (const page of [
"profile",
"security",
"sessions",
"applications",
"appearance",
"identity",
]) {
await check(`${page}/${theme}/${locale}/${device}`, async () => {
await p.setViewportSize({ width, height });
await p.goto(path(page, theme, locale));
await p.locator("h1").waitFor();
assert.ok(
await p.evaluate(
() => document.documentElement.scrollWidth <= innerWidth + 1,
),
);
if (locale === "en")
assert.equal(
/[А-Яа-яЁё]/.test(await p.locator("body").innerText()),
false,
);
if (locale === "ru" && device !== "tablet") {
await p.waitForTimeout(320);
await p.screenshot({
path: `references/identity/${page}-${theme}-${device}.png`,
fullPage: true,
});
}
});
}
await p.setViewportSize({ width: 1440, height: 900 });
await check("Profile update, stable subject and cancel", async () => {
await p.goto(path());
await p.locator("[name=firstName]").fill("Anya");
await p.locator("#identity-profile [type=submit]").click();
assert.equal(
await p.locator(".identity-profile-summary h2").innerText(),
"Anya Volkova",
);
assert.match(
await p.locator(".identity-footnote").innerText(),
/demo-anna/,
);
await p.reload();
assert.equal(await p.locator("[name=firstName]").inputValue(), "Anya");
await p.locator("[name=firstName]").fill("Unsaved");
await p.locator("#identity-profile [type=reset]").click();
assert.equal(await p.locator("[name=firstName]").inputValue(), "Anya");
await reset();
});
await check("Profile markup is escaped", async () => {
await p.goto(path());
await p.locator("[name=firstName]").fill("<img src=x onerror=alert(1)>");
await p.locator("#identity-profile [type=submit]").click();
assert.equal(await p.locator(".identity-profile-summary img").count(), 0);
assert.match(
await p.locator(".identity-profile-summary").innerText(),
/<img/,
);
await reset();
});
await check("Avatar preview and persistence", async () => {
await p.goto(path());
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aT90AAAAASUVORK5CYII=",
"base64",
);
await p.locator("#identity-avatar-file").setInputFiles({
name: "avatar.png",
mimeType: "image/png",
buffer: png,
});
await p.locator("#avatar-preview img").waitFor();
await p.locator("#identity-profile [type=submit]").click();
await p.reload();
await p.locator(".identity-profile-summary img").waitFor();
assert.equal(
await p
.locator(".identity-profile-summary img")
.evaluate((e) => getComputedStyle(e).objectFit),
"cover",
);
await reset();
});
await check("Email change request stays a demo", async () => {
await p.goto(path("security"));
await p.locator("[data-identity=password-link]").click();
assert.match(await p.locator("#dialog").innerText(), /1 час/);
await p.locator("[data-identity=email-sent]").click();
assert.match(await p.locator("#toast").innerText(), /не отправлено/);
});
await check("Passkey creation and removal", async () => {
await p.locator("[data-identity=add-passkey]").click();
await p.locator("#identity-passkey input").fill("Laptop demo");
await p.locator("#identity-passkey [type=submit]").click();
assert.equal(await p.locator("[data-identity=remove-passkey]").count(), 2);
await p.locator("[data-identity=remove-passkey]").last().click();
await p.locator("[data-identity=confirm-remove-key]").click();
assert.equal(await p.locator("[data-identity=remove-passkey]").count(), 1);
});
await check("Session revocation preserves current session", async () => {
await p.goto(path("sessions"));
await p.locator("[data-identity=revoke-session][data-session=s-2]").click();
await p.locator("[data-identity=confirm-revoke]").click();
assert.equal(await p.locator(".identity-session").count(), 2);
await p.locator("[data-identity=revoke-others]").click();
await p.locator("[data-identity=confirm-revoke-others]").click();
assert.equal(await p.locator(".identity-session").count(), 1);
assert.match(
await p.locator(".identity-session").innerText(),
/Текущий сеанс/,
);
await reset();
});
await check(
"SSO roles, custom role, bulk suspension, add grant and resume",
async () => {
await p.goto(path("users"));
await p.locator("#user-search").fill("anna@anidev.ru");
await p.locator('[data-edit="1"]').click();
await p.locator("#custom-role").fill("Release Manager");
await p.locator("[data-identity=add-role]").click();
await p.locator("[name=ssoRole][value=Auditor]").check();
await p.locator("#edit-user [type=submit]").click();
await p.locator('[data-edit="1"]').click();
assert.equal(
await p.locator('[name=ssoRole][value="Release Manager"]').isChecked(),
true,
);
assert.equal(
await p.locator("[name=ssoRole][value=Auditor]").isChecked(),
true,
);
await p.locator("#grant-all").check();
await p.locator(".grant-bulk [data-identity=grant-suspend]").click();
await p.locator("[name=reason]").fill("Maintenance window");
await p.locator("#show-reason").check();
await p.locator("#grant-suspend-form [type=submit]").click();
assert.equal(await p.locator(".identity-grants .error-text").count(), 3);
await p.waitForTimeout(350);
await p.screenshot({
path: "references/identity/user-access-light-desktop.png",
});
await p.keyboard.press("Escape");
await p.goto(path("applications"));
assert.equal(
await p.locator("[data-identity=open-app]:disabled").count(),
3,
);
assert.match(
await p.locator(".identity-apps").innerText(),
/Maintenance window/,
);
await p.goto(path("users"));
await p.locator("#user-search").fill("anna@anidev.ru");
await p.locator('[data-edit="1"]').click();
await p.locator("[data-identity=grant-add]").click();
await p.locator("#grant-add-form [type=submit]").click();
assert.equal(await p.locator("[data-grant]").count(), 4);
await p.locator(".grant-actions summary").first().click();
await p.locator("[data-identity=grant-resume]").first().click();
assert.equal(await p.locator(".identity-grants .status").count(), 2);
await p.keyboard.press("Escape");
await reset();
},
);
for (const status of identityStates.filter((s) => s !== "authenticated"))
await check(`Gate ${status} hides private content`, async () => {
await p.goto(path("profile", "dark", "ru", "&identityState=" + status));
await p.locator(".identity-gate").waitFor();
const text = await p.locator("body").innerText();
assert.equal(/Anna Volkova|anna@anidev.ru|demo-anna/.test(text), false);
assert.equal(await p.locator("#identity-profile").count(), 0);
});
await check("TOTP errors remain in the same dialog", async () => {
await p.goto(
path("identity", "light", "ru", "&identityState=factor_required"),
);
await p.locator("[data-identity=verify-factor]").click();
await p.locator("#identity-factor input").fill("000000");
assert.match(await p.locator("#factor-error").innerText(), /Неверный код/);
await p.locator("#identity-factor input").fill("123456");
assert.equal(await p.locator("#dialog").evaluate((e) => e.open), false);
await p.locator("#identity-state").waitFor();
assert.equal(
await p.locator("#identity-state").inputValue(),
"authenticated",
);
});
await check(
"Account change signs out and hides previous account, then loads new scope",
async () => {
await reset();
await p.goto(path());
await p.locator(".dock-account").click();
await p.locator("[data-identity=switch]").click();
assert.equal(await p.locator("[data-account]").count(), 0);
await p.locator("[data-identity=confirm-switch]").click();
await p.locator("#auth-form").waitFor();
assert.equal(
/Anna Volkova|anna@anidev.ru/.test(await p.locator("#app").innerText()),
false,
);
await p.locator("[name=email]").fill("mikhail.orlov");
await p.locator("[name=password]").fill("wrong-password");
await p.locator("#auth-form [type=submit]").click();
await p
.locator("#auth-error")
.filter({ hasText: "Неверный пароль" })
.waitFor();
assert.equal(
await p.locator("[name=email]").inputValue(),
"mikhail.orlov",
);
assert.equal(await p.locator("[name=password]").inputValue(), "");
await p.locator("[name=password]").fill("demo-password");
await p.locator("#auth-form [type=submit]").click();
await p.locator("#identity-profile").waitFor();
assert.match(
await p.locator(".identity-profile-summary").innerText(),
/Mikhail Orlov/,
);
await p.goto(path("sessions"));
assert.equal(await p.locator(".identity-session").count(), 1);
assert.match(await p.locator(".identity-session").innerText(), /Linux/);
await p.goto(path("users"));
await p.locator(".identity-gate").waitFor();
assert.equal(await p.locator("#user-search").count(), 0);
},
);
await check(
"Missing email requires verification before password request",
async () => {
await p.goto(path("security"));
await p.locator("[data-identity=password-link]").click();
await p.locator("#identity-email").waitFor();
await p
.locator("#identity-email [name=email]")
.fill("mikhail@example.com");
await p.locator("#identity-email [type=submit]").click();
await p.locator("[data-identity=password-link]").click();
assert.match(
await p.locator("#dialog").innerText(),
/mikhail@example.com/,
);
await p.keyboard.press("Escape");
await reset();
},
);
await check("Appearance theme and gallery synchronization", async () => {
await p.goto(path("appearance"));
await p.locator("[data-identity=theme][data-theme=dark]").click();
assert.equal(await p.locator("body").getAttribute("data-theme"), "dark");
await p.goto(base + "/playground/?concept=dock");
await p.locator("#page").selectOption("appearance");
await p
.frameLocator("#preview-a")
.locator("[data-identity=theme][data-theme=dark]")
.click();
await p.waitForFunction(
() => document.querySelector("#theme").value === "dark",
);
await p
.frameLocator("#preview-a")
.locator("body[data-theme=dark]")
.waitFor();
assert.equal(
(
await p
.frameLocator("#preview-a")
.locator("html")
.evaluate((el) => el.style.getPropertyValue("--color-accent"))
).trim(),
tokensFor("dock", "dark")["color.accent"],
);
const download = p.waitForEvent("download");
await p.locator("#export").click();
await (await download).saveAs("test-results/identity-export.zip");
});
await check(
"Identity change in comparison clears an open private dialog",
async () => {
await p.goto(base + "/playground/?concept=dock&page=security");
await p.locator("#compare").check();
const first = p.frameLocator("#preview-a"),
second = p.frameLocator("#preview-b");
await second.locator("h1").waitFor();
await first.locator("[data-identity=password-link]").click();
await first
.locator("#dialog")
.filter({ hasText: "anna@anidev.ru" })
.waitFor({ state: "visible" });
await second.locator("body").evaluate(() => {
const key = "anidev.identity.demo.v2";
const data = JSON.parse(sessionStorage.getItem(key));
data.status = "account_changed";
data.revision++;
sessionStorage.setItem(key, JSON.stringify(data));
});
await first.locator(".identity-gate").waitFor();
assert.equal(
await first.locator("#dialog").evaluate((d) => d.open),
false,
);
assert.equal(
/Anna Volkova|anna@anidev.ru/.test(
await first.locator("body").innerText(),
),
false,
);
},
);
await check("No identity runtime errors", async () =>
assert.deepEqual(errors, []),
);
} finally {
await writeFile(
"references/identity/qa.json",
JSON.stringify(
{
date: new Date().toISOString(),
passed,
failed: failures.length,
failures,
errors,
},
null,
2,
),
);
await ctx.close();
await b.close();
}
console.log(`Identity QA: ${passed} passed, ${failures.length} failed`);
if (failures.length) process.exitCode = 1;
+33
View File
@@ -0,0 +1,33 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
const base = process.env.BASE_URL || "http://127.0.0.1:4173";
const b = await chromium.launch({
executablePath:
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
headless: true,
});
try {
const p = await b.newPage();
for (const theme of ["light", "dark"])
for (const [device, width, height] of [
["desktop", 1440, 900],
["mobile", 390, 844],
]) {
await p.setViewportSize({ width, height });
await p.goto(
`${base}/playground/frame.html?concept=dock&page=identity&theme=${theme}&identityState=factor_required`,
);
await p.locator("[data-identity=verify-factor]").click();
await p.waitForTimeout(300);
const before = await p.locator("#dialog").boundingBox();
await p.locator("#identity-factor input").fill("000000");
const after = await p.locator("#dialog").boundingBox();
assert.deepEqual(after, before);
await p.screenshot({
path: `references/identity/totp-error-${theme}-${device}.png`,
});
console.log(theme, device, "TOTP dialog geometry stable");
}
} finally {
await b.close();
}