testirovanie-robot/src/views.ts
Peppa 9212c12810
All checks were successful
peppa/lint lint: success за 0с
peppa/typecheck typecheck: success за 0с
peppa/test test: success за 4с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 10s
deploy / deploy (pull_request) Successful in 4s
TR-19: страница входа объясняет ответы на пустое поле и неверную пару (ru/kk/en), тесты, памятка, снимок, архив изменения, память проекта
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 12:12:50 +05:00

172 lines
7.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { LOCK_MS, MAX_FAILS } from "./auth.ts";
import { LANGS, type Lang, type PluralKey, type TextKey, t, tPlural } from "./i18n.ts";
const ESCAPES: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
};
export const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (ch) => ESCAPES[ch] ?? ch);
export const STYLESHEET = `
:root { color-scheme: light dark; --bg: #f4f5f7; --card: #fff; --text: #1c1e21; --muted: #5f6672;
--line: #d5d9e0; --accent: #2457d6; --accent-text: #fff; --error-bg: #fdecec; --error-text: #a11a1a; }
@media (prefers-color-scheme: dark) {
:root { --bg: #15171a; --card: #1f2226; --text: #eceef1; --muted: #a3aab5; --line: #3a3f47;
--accent: #6f95f5; --accent-text: #10131a; --error-bg: #3b1c1c; --error-text: #ffb4b4; }
}
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; align-items: center;
justify-content: center; gap: 16px; padding: 24px 16px; background: var(--bg); color: var(--text);
font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
main { width: 100%; max-width: 400px; padding: 32px 28px; background: var(--card);
border: 1px solid var(--line); border-radius: 14px; }
h1 { margin: 0 0 8px; font-size: 26px; line-height: 1.2; overflow-wrap: anywhere; }
p { margin: 0 0 16px; }
.lead { color: var(--muted); }
.lead:last-child { margin-bottom: 0; }
.error { padding: 10px 12px; border-radius: 8px; font-size: 15px; }
.error { background: var(--error-bg); color: var(--error-text); }
.field-error { margin: 0 0 16px; font-size: 14px; color: var(--error-text); }
label { display: block; margin: 0 0 6px; font-weight: 600; font-size: 15px; }
input { width: 100%; margin: 0 0 16px; padding: 11px 12px; font: inherit; color: inherit;
background: transparent; border: 1px solid var(--line); border-radius: 8px; }
input[aria-invalid] { margin-bottom: 6px; border-color: var(--error-text); }
input:focus-visible, button:focus-visible, a:focus-visible { outline: 2px solid var(--accent);
outline-offset: 2px; }
button, .button { display: block; width: 100%; padding: 12px; font: inherit; font-weight: 600;
text-align: center; text-decoration: none; color: var(--accent-text); background: var(--accent);
border: 0; border-radius: 8px; cursor: pointer; }
form { margin: 0; }
.info { margin-top: 24px; padding-top: 16px; border-top: 1px solid var(--line); font-size: 14px;
color: var(--muted); }
.info h2 { margin: 0 0 8px; font-size: 15px; color: var(--text); }
.info ul { margin: 0; padding-left: 20px; }
.info li { margin-bottom: 6px; }
nav { display: flex; gap: 14px; font-size: 14px; color: var(--muted); }
nav a { color: var(--accent); }
nav [aria-current] { color: var(--text); font-weight: 600; text-decoration: none; }
`;
interface PageOptions {
lang: Lang;
path: string;
title: string;
body: string;
}
function page({ lang, path, title, body }: PageOptions): string {
const switcher = LANGS.map(({ code, name }) =>
code === lang
? `<a href="${path}?lang=${code}" lang="${code}" aria-current="true">${name}</a>`
: `<a href="${path}?lang=${code}" lang="${code}">${name}</a>`,
).join("");
return `<!doctype html>
<html lang="${lang}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<main>
${body}
</main>
<nav aria-label="${escapeHtml(t(lang, "lang.label"))}">${switcher}</nav>
</body>
</html>
`;
}
export interface LoginPageOptions {
lang: Lang;
login?: string;
/** Сообщение над формой; `plural` — текст с числом, форма слова зависит от `count`. */
error?:
| { key: TextKey; params?: Record<string, string | number> }
| { plural: PluralKey; param: string; count: number };
/** Незаполненные поля: сообщение показывается под каждым из них, а не над формой. */
emptyFields?: { login: boolean; password: boolean };
}
/**
* Пояснение под формой: чем страница ответит на пустое поле и неверную пару, после скольких
* попыток вход закроется, когда блокировка снимется и что увидит пользователь.
*/
function lockInfo(lang: Lang): string {
const minutes = LOCK_MS / 60000;
const message = tPlural(lang, "login.errorLocked", "minutes", minutes);
const text = (value: string) => escapeHtml(value);
return `<section class="info" aria-labelledby="lock-info-title">
<h2 id="lock-info-title">${text(t(lang, "login.lockInfo.title"))}</h2>
<ul>
<li>${text(t(lang, "login.lockInfo.empty"))}</li>
<li>${text(t(lang, "login.lockInfo.invalid"))}</li>
<li>${text(tPlural(lang, "login.lockInfo.attempts", "attempts", MAX_FAILS))}</li>
<li>${text(tPlural(lang, "login.lockInfo.minutes", "minutes", minutes))}</li>
<li>${text(t(lang, "login.lockInfo.message", { message }))}</li>
<li>${text(t(lang, "login.lockInfo.check"))}</li>
</ul>
</section>`;
}
export function loginPage({ lang, login = "", error, emptyFields }: LoginPageOptions): string {
const e = (key: TextKey, params?: Record<string, string | number>) =>
escapeHtml(t(lang, key, params));
const errorText =
error &&
escapeHtml(
"plural" in error
? tPlural(lang, error.plural, error.param, error.count)
: t(lang, error.key, error.params),
);
// Поле с сообщением под ним: рамка выделена, сообщение привязано к полю для чтения с экрана.
const invalid = (id: string) => ` aria-invalid="true" aria-describedby="${id}-error"`;
const fieldError = (id: string, key: TextKey) =>
`\n<p class="field-error" id="${id}-error">${e(key)}</p>`;
const loginEmpty = emptyFields?.login ?? false;
const passwordEmpty = emptyFields?.password ?? false;
const body = `<h1>${e("login.title")}</h1>
<p class="lead">${e("login.lead")}</p>
${errorText ? `<p class="error" role="alert">${errorText}</p>` : ""}
<form method="post" action="/login" novalidate>
<label for="login">${e("login.loginLabel")}</label>
<input id="login" name="login" type="text" value="${escapeHtml(login)}" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="200"${loginEmpty ? invalid("login") : ""}${login ? "" : " autofocus"}>${loginEmpty ? fieldError("login", "login.errorLoginEmpty") : ""}
<label for="password">${e("login.passwordLabel")}</label>
<input id="password" name="password" type="password" autocomplete="current-password" maxlength="1000"${passwordEmpty ? invalid("password") : ""}${login ? " autofocus" : ""}>${passwordEmpty ? fieldError("password", "login.errorPasswordEmpty") : ""}
<button type="submit">${e("login.submit")}</button>
</form>
${lockInfo(lang)}`;
return page({ lang, path: "/login", title: t(lang, "login.title"), body });
}
export function homePage({ lang, login }: { lang: Lang; login: string }): string {
const e = (key: TextKey, params?: Record<string, string | number>) =>
escapeHtml(t(lang, key, params));
const body = `<h1>${e("home.signedInAs", { login })}</h1>
<p class="lead">${e("home.lead")}</p>
<form method="post" action="/logout">
<button type="submit">${e("home.logout")}</button>
</form>`;
return page({ lang, path: "/", title: t(lang, "home.title"), body });
}
/** Страница с одним сообщением: «страницы нет» или «что-то пошло не так». */
export function messagePage(options: {
lang: Lang;
path: string;
title: TextKey;
text: TextKey;
link?: TextKey;
}): string {
const { lang } = options;
const body = `<h1>${escapeHtml(t(lang, options.title))}</h1>
<p class="lead">${escapeHtml(t(lang, options.text))}</p>
${options.link ? `<a class="button" href="/">${escapeHtml(t(lang, options.link))}</a>` : ""}`;
return page({ lang, path: options.path, title: t(lang, options.title), body });
}