feat(ui): срезы Фаза2 (a11y/мобайл) + Фаза3 (чаты: поиск/переименование/удаление)
Фаза2 a11y WCAG2.2: sr-status live-регион (на уровне body), role=log aria-live=off (без спама стримом), skip-link, landmark-роли, aria-label иконкам/полям, role=alert на ошибках, клавиатурная доступность списка чатов, мобайл (тач-таргет 44px, шапка не переполняется). Фаза3: таблица session_titles + эндпоинты DELETE/POST title; поиск-фильтр, инлайн-переименование, удаление с confirm. Fable-фиксы (9): единый канал озвучки ошибок; sr-status вне скрытого контейнера; озвучка логина; srAnnounce clearTimeout; удаление чистит файлы на диске; удаление прерывает стрим (чат не воскресает); перерисовка не убивает переименование; rename 400 на кривой JSON; reset/clear стирают title.
This commit is contained in:
+129
-21
@@ -30,6 +30,10 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
|
||||
/* Видимый фокус для клавиатуры — Ководство: состояния обязательны */
|
||||
:focus-visible { outline: none; box-shadow: var(--focus-ring); border-radius: var(--radius-sm); }
|
||||
button { font-family: inherit; }
|
||||
/* Только для скринридеров (срез 2.1): визуально скрыто, доступно ассистивным технологиям */
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
|
||||
.skip-link { position: absolute; left: -999px; top: 0; z-index: 200; background: var(--accent); color: #fff; padding: .5rem .9rem; border-radius: 0 0 var(--radius) 0; }
|
||||
.skip-link:focus { left: 0; }
|
||||
::selection { background: rgba(192,69,58,.18); }
|
||||
|
||||
/* Тихий скроллбар */
|
||||
@@ -163,6 +167,13 @@ button { font-family: inherit; }
|
||||
.chat-item.active { background: var(--accent-light); }
|
||||
.chat-item.active::before { content: ""; position: absolute; left: 0; top: 6px; bottom: 6px; width: 3px; border-radius: 3px; background: var(--accent); }
|
||||
.chat-item.active .ci-title { color: var(--accent); font-weight: 600; }
|
||||
#chat-search { width: 100%; margin-top: .5rem; padding: .4rem .6rem; border: 1.5px solid var(--border); border-radius: var(--radius-sm); font-size: .85rem; background: var(--bg-sunken); color: var(--text); outline: none; }
|
||||
#chat-search:focus { border-color: var(--accent); }
|
||||
.ci-actions { position: absolute; right: .35rem; top: .35rem; display: none; gap: .1rem; }
|
||||
.chat-item:hover .ci-actions, .chat-item:focus-within .ci-actions { display: flex; }
|
||||
.ci-act { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: pointer; font-size: .8rem; line-height: 1; padding: .18rem .3rem; color: var(--text-muted); }
|
||||
.ci-act:hover { color: var(--accent); border-color: var(--accent); }
|
||||
.ci-rename { width: 100%; padding: .2rem .35rem; border: 1.5px solid var(--accent); border-radius: var(--radius-sm); font-size: .85rem; font-family: inherit; background: var(--bg-card); color: var(--text); outline: none; }
|
||||
.ci-title { font-size: .82rem; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.ci-date { font-size: .66rem; color: var(--text-muted); margin-top: .12rem; }
|
||||
.main-col { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||
@@ -171,8 +182,15 @@ button { font-family: inherit; }
|
||||
@media (max-width: 720px) {
|
||||
.sidebar { position: fixed; left: 0; top: 0; bottom: 0; z-index: 60; transform: translateX(-100%); transition: transform .2s; box-shadow: var(--shadow-md); }
|
||||
.sidebar.open { transform: translateX(0); }
|
||||
#sidebar-toggle { display: inline-block; }
|
||||
#sidebar-toggle { display: inline-block; padding: .5rem .7rem; min-width: 44px; min-height: 44px; } /* тач-таргет ≥44px */
|
||||
.sidebar-backdrop.show { display: block; position: fixed; inset: 0; background: rgba(0,0,0,.3); z-index: 55; }
|
||||
/* Срез 2.2: шапка не переполняется на узком экране — заголовок компактнее, кнопки прокручиваются */
|
||||
#header h1 { font-size: 1.05rem; }
|
||||
.header-actions { flex-wrap: nowrap; overflow-x: auto; -webkit-overflow-scrolling: touch; gap: .3rem; padding: 3px 2px; scroll-padding-inline: 3px; }
|
||||
.header-actions button { white-space: nowrap; flex: 0 0 auto; }
|
||||
#messages { padding-left: .7rem; padding-right: .7rem; }
|
||||
.msg { max-width: 92%; }
|
||||
.onboarding { margin: 1.2rem auto; padding: 1rem; }
|
||||
}
|
||||
|
||||
/* ===== Тёмная тема (Ководство: тёплый «не-чёрный» фон, «не-белый» текст, */
|
||||
@@ -225,14 +243,18 @@ html { color-scheme: light; }
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Живёт на уровне body (не в скрытом #chat-screen), иначе часть скринридеров не
|
||||
регистрирует live-регион и озвучка недоступна до логина (Fable Ф2). -->
|
||||
<div id="sr-status" class="sr-only" aria-live="polite" aria-atomic="true"></div>
|
||||
|
||||
<!-- Login Screen -->
|
||||
<div id="login-screen" style="display:none">
|
||||
<form id="login-form" onsubmit="return doLogin(event)">
|
||||
<h2>Сметный ИИ</h2>
|
||||
<span class="subtitle">Профессиональный ассистент</span>
|
||||
<div id="login-error">Неверный логин или пароль</div>
|
||||
<input type="text" id="login-user" placeholder="Email или логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" autocomplete="current-password" required>
|
||||
<div id="login-error" role="alert"></div>
|
||||
<input type="text" id="login-user" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" aria-label="Пароль" autocomplete="current-password" required>
|
||||
<button type="submit">Войти</button>
|
||||
<p style="text-align:center;margin-top:.8rem;font-size:.85rem;color:var(--text-muted)">Нет аккаунта? Попросите приглашение у администратора</p>
|
||||
</form>
|
||||
@@ -240,18 +262,20 @@ html { color-scheme: light; }
|
||||
|
||||
<!-- Chat Screen -->
|
||||
<div id="chat-screen" style="display:none">
|
||||
<a href="#msg-input" class="skip-link">Перейти к вводу сообщения</a>
|
||||
<div class="sidebar-backdrop" id="sidebar-backdrop" onclick="closeSidebar()"></div>
|
||||
<div class="app-layout">
|
||||
<aside class="sidebar" id="sidebar">
|
||||
<aside class="sidebar" id="sidebar" aria-label="Список диалогов">
|
||||
<div class="sidebar-head">
|
||||
<button class="new-chat-btn" onclick="newChat()">+ Новый чат</button>
|
||||
<input id="chat-search" type="search" placeholder="Поиск по чатам" aria-label="Поиск по чатам" oninput="renderSessions()">
|
||||
</div>
|
||||
<div class="chat-list" id="chat-list"></div>
|
||||
<nav class="chat-list" id="chat-list" aria-label="Ваши диалоги"></nav>
|
||||
</aside>
|
||||
<div class="main-col">
|
||||
<div id="header">
|
||||
<div id="header" role="banner">
|
||||
<div style="display:flex;align-items:center">
|
||||
<button id="sidebar-toggle" onclick="toggleSidebar()" title="Чаты">☰</button>
|
||||
<button id="sidebar-toggle" onclick="toggleSidebar()" title="Чаты" aria-label="Открыть список диалогов" aria-expanded="false" aria-controls="sidebar">☰</button>
|
||||
<h1>Сметный ИИ-ассистент</h1>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
@@ -273,14 +297,16 @@ html { color-scheme: light; }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="messages"></div>
|
||||
<!-- role=log имеет неявный aria-live=polite; глушим его (aria-live=off), иначе стрим-перерисовка
|
||||
innerHTML на каждый чанк зачитывала бы весь растущий ответ. Объявления — через #sr-status. -->
|
||||
<div id="messages" role="log" aria-live="off" aria-label="История сообщений"></div>
|
||||
|
||||
<div id="input-area">
|
||||
<div id="input-area" role="region" aria-label="Ввод сообщения">
|
||||
<div id="drop-zone">
|
||||
<div id="file-list"></div>
|
||||
<div id="input-row">
|
||||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл">📎</button>
|
||||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" onkeydown="handleKey(event)"></textarea>
|
||||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл" aria-label="Прикрепить файл">📎</button>
|
||||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" aria-label="Сообщение" onkeydown="handleKey(event)"></textarea>
|
||||
<button id="send-btn" onclick="onSendClick()">Отправить</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -605,6 +631,15 @@ function onSendClick() {
|
||||
if (streaming) { if (abortCtrl && (performance.now() - streamStartedAt) > 400) abortCtrl.abort(); }
|
||||
else sendMessage();
|
||||
}
|
||||
// Озвучка событий скринридеру (срез 2.1): #messages как role=log не делаем live,
|
||||
// иначе стрим-перерисовка спамит SR всем растущим текстом. Вместо — точечный live-регион.
|
||||
function srAnnounce(t) {
|
||||
const el = document.getElementById('sr-status');
|
||||
if (!el) return;
|
||||
clearTimeout(el._t); // не терять объявление при быстрой серии вызовов
|
||||
el.textContent = '';
|
||||
el._t = setTimeout(() => { el.textContent = t; }, 30); // clear→set форсит повторное объявление
|
||||
}
|
||||
// crypto.randomUUID работает только в secure context (HTTPS / localhost),
|
||||
// под голым HTTP по IP его нет — используем fallback
|
||||
function genUUID() {
|
||||
@@ -674,7 +709,10 @@ async function doLogin(e) {
|
||||
checkAdmin();
|
||||
showChat(); // loadHistory сам покажет онбординг на пустом чате
|
||||
} catch {
|
||||
document.getElementById('login-error').style.display = 'block';
|
||||
const le = document.getElementById('login-error');
|
||||
le.textContent = ''; // очистка+переустановка гарантирует объявление role=alert
|
||||
le.style.display = 'block';
|
||||
setTimeout(() => { le.textContent = 'Неверный логин или пароль'; }, 30);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -764,6 +802,7 @@ function addMsg(type, text, ts) {
|
||||
const ob = document.getElementById('onboarding'); if (ob) ob.remove(); // любое сообщение убирает приветствие
|
||||
const div = document.createElement('div');
|
||||
div.className = 'msg msg-' + type;
|
||||
if (type === 'error') div.setAttribute('role', 'alert'); // единый канал озвучки ошибок (assertive)
|
||||
// Timestamp
|
||||
const time = document.createElement('span');
|
||||
time.className = 'msg-time';
|
||||
@@ -981,8 +1020,7 @@ function httpErrText(status) {
|
||||
|
||||
// Ошибка с кнопкой «Повторить» — текст пользователя не теряется, повтор не дублирует пузырь.
|
||||
function addErrorRetry(msg, retryText) {
|
||||
const div = addMsg('error', msg);
|
||||
div.setAttribute('role', 'alert');
|
||||
const div = addMsg('error', msg); // addMsg сам ставит role=alert (assertive-озвучка) для type=error
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = 'Повторить';
|
||||
btn.className = 'retry-btn';
|
||||
@@ -1141,12 +1179,13 @@ async function runChat(text) {
|
||||
}
|
||||
}
|
||||
if (!aiDiv && !aiText) addMsg('ai', '(пустой ответ)');
|
||||
srAnnounce('Ответ получен');
|
||||
|
||||
} catch (err) {
|
||||
removeTyping();
|
||||
if (err && err.name === 'AbortError') {
|
||||
// при переключении/новом чате abort «тихий» — не сорим системным сообщением
|
||||
if (!myCtrl._silent) addMsg('system', '⏹ Остановлено. Ответ мог сгенерироваться не полностью.');
|
||||
if (!myCtrl._silent) { addMsg('system', '⏹ Остановлено. Ответ мог сгенерироваться не полностью.'); srAnnounce('Ответ остановлен'); }
|
||||
} else {
|
||||
addErrorRetry('Нет связи с сервисом. ' + (err.message || ''), text);
|
||||
}
|
||||
@@ -1178,10 +1217,14 @@ function toggleSidebar() {
|
||||
const sb = document.getElementById('sidebar');
|
||||
const open = sb.classList.toggle('open');
|
||||
document.getElementById('sidebar-backdrop').classList.toggle('show', open);
|
||||
const t = document.getElementById('sidebar-toggle');
|
||||
if (t) t.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||
}
|
||||
function closeSidebar() {
|
||||
document.getElementById('sidebar').classList.remove('open');
|
||||
document.getElementById('sidebar-backdrop').classList.remove('show');
|
||||
const t = document.getElementById('sidebar-toggle');
|
||||
if (t) t.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
|
||||
function downloadWorkFile(name) {
|
||||
@@ -1256,21 +1299,34 @@ async function loadSessions() {
|
||||
function renderSessions() {
|
||||
const list = document.getElementById('chat-list');
|
||||
if (!list) return;
|
||||
// Идёт инлайн-переименование — не перерисовывать (innerHTML='' снёс бы фокусированный
|
||||
// input без blur → набранный текст пропал бы молча). Fable Ф3.
|
||||
if (list.querySelector('.ci-rename')) return;
|
||||
const q = (document.getElementById('chat-search')?.value || '').trim().toLowerCase();
|
||||
const match = s => !q || (((s.title || '') + ' ' + (s.last_question || '')).toLowerCase().includes(q));
|
||||
list.innerHTML = '';
|
||||
// Текущий ещё не сохранённый диалог (без сообщений) — показываем сверху активным
|
||||
if (!allSessions.some(s => s.tab_id === tabId)) {
|
||||
// Текущий ещё не сохранённый диалог (без сообщений) — показываем сверху активным (не при поиске)
|
||||
if (!q && !allSessions.some(s => s.tab_id === tabId)) {
|
||||
list.appendChild(makeChatItem({tab_id: tabId, last_question: 'Новый чат', last_ts: null}, true));
|
||||
}
|
||||
for (const s of allSessions) list.appendChild(makeChatItem(s, s.tab_id === tabId));
|
||||
if (!list.children.length) list.innerHTML = '<div class="chat-list-empty">Пока нет чатов</div>';
|
||||
for (const s of allSessions) if (match(s)) list.appendChild(makeChatItem(s, s.tab_id === tabId));
|
||||
if (!list.children.length) list.innerHTML = '<div class="chat-list-empty">' + (q ? 'Ничего не найдено' : 'Пока нет чатов') + '</div>';
|
||||
}
|
||||
function makeChatItem(s, active) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'chat-item' + (active ? ' active' : '');
|
||||
const label = (s.title || s.last_question || 'Без названия').slice(0, 90) || 'Новый чат';
|
||||
div.onclick = () => switchChat(s.tab_id);
|
||||
// Клавиатурная доступность (Fable Ф2): строка списка операбельна с клавиатуры.
|
||||
// role не button (внутри вложенные кнопки ✎/✕) — фокусируемый элемент с именем.
|
||||
div.tabIndex = 0;
|
||||
div.setAttribute('aria-label', 'Открыть диалог: ' + label);
|
||||
div.onkeydown = e => {
|
||||
if ((e.key === 'Enter' || e.key === ' ') && e.target === div) { e.preventDefault(); switchChat(s.tab_id); }
|
||||
};
|
||||
const t = document.createElement('div');
|
||||
t.className = 'ci-title';
|
||||
t.textContent = (s.last_question || 'Без названия').slice(0, 90) || 'Новый чат';
|
||||
t.textContent = label;
|
||||
div.appendChild(t);
|
||||
if (s.last_ts) {
|
||||
const d = document.createElement('div');
|
||||
@@ -1278,9 +1334,61 @@ function makeChatItem(s, active) {
|
||||
d.textContent = new Date(s.last_ts * 1000).toLocaleString('ru-RU',
|
||||
{day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'});
|
||||
div.appendChild(d);
|
||||
// Действия (переименовать/удалить) — только для сохранённых диалогов
|
||||
const acts = document.createElement('div');
|
||||
acts.className = 'ci-actions';
|
||||
const ren = document.createElement('button');
|
||||
ren.className = 'ci-act'; ren.title = 'Переименовать'; ren.setAttribute('aria-label', 'Переименовать диалог'); ren.textContent = '✎';
|
||||
ren.onclick = e => { e.stopPropagation(); startRename(div, t, s); };
|
||||
const del = document.createElement('button');
|
||||
del.className = 'ci-act'; del.title = 'Удалить'; del.setAttribute('aria-label', 'Удалить диалог'); del.textContent = '✕';
|
||||
del.onclick = e => { e.stopPropagation(); deleteChat(s); };
|
||||
acts.appendChild(ren); acts.appendChild(del);
|
||||
div.appendChild(acts);
|
||||
}
|
||||
return div;
|
||||
}
|
||||
// Инлайн-переименование: заголовок → поле ввода, Enter/blur сохраняют, Esc отменяет.
|
||||
function startRename(div, titleEl, s) {
|
||||
if (div.querySelector('.ci-rename')) return;
|
||||
const input = document.createElement('input');
|
||||
input.className = 'ci-rename'; input.type = 'text';
|
||||
input.value = s.title || s.last_question || '';
|
||||
input.onclick = e => e.stopPropagation();
|
||||
let done = false;
|
||||
const finish = async (save) => {
|
||||
if (done) return; done = true;
|
||||
const val = input.value.trim();
|
||||
if (input.isConnected) input.replaceWith(titleEl);
|
||||
if (save && val && val !== (s.title || '')) {
|
||||
try {
|
||||
const r = await authFetch('/api/sessions/' + encodeURIComponent(s.tab_id) + '/title', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({title: val})});
|
||||
if (r.ok) { s.title = val; titleEl.textContent = val.slice(0, 90); }
|
||||
} catch (e) {}
|
||||
}
|
||||
};
|
||||
input.onkeydown = e => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') { e.preventDefault(); finish(true); }
|
||||
else if (e.key === 'Escape') { e.preventDefault(); finish(false); }
|
||||
};
|
||||
input.onblur = () => finish(true);
|
||||
titleEl.replaceWith(input);
|
||||
input.focus(); input.select();
|
||||
}
|
||||
async function deleteChat(s) {
|
||||
if (!confirm('Удалить диалог целиком? Это действие необратимо.')) return;
|
||||
// Прерываем стрим ДО удаления: иначе финальный ответ агента допишется в БД и
|
||||
// «удалённый навсегда» чат воскреснет (Fable Ф3).
|
||||
if (s.tab_id === tabId && abortCtrl) { abortCtrl._silent = true; abortCtrl.abort(); }
|
||||
try {
|
||||
const r = await authFetch('/api/sessions/' + encodeURIComponent(s.tab_id), {method: 'DELETE'});
|
||||
if (!r.ok) return;
|
||||
if (s.tab_id === tabId) newChat(); // удалили текущий — открыть новый
|
||||
await loadSessions();
|
||||
} catch (e) {}
|
||||
}
|
||||
async function switchChat(id) {
|
||||
closeSidebar();
|
||||
if (id === tabId) return;
|
||||
|
||||
Reference in New Issue
Block a user