Всплывающие сообщения: одна аккуратная система

- тост встаёт над нижним меню и полем ввода, а не поверх них;
- значок по смыслу (галочка, восклицание, «i») вместо красного текста ошибки;
- ошибки и длинные сообщения висят дольше (время на чтение), касание закрывает;
- одинаковое сообщение подряд не дублируется, можно добавить кнопку («Повторить»);
- ошибки, которые показывались как «успех», помечены ошибками; справочные – «i»;
  исправлено «Сообщение скопированно».

Стили тостов перенесены из modal.css в feedback.css (общие состояния и сообщения).
This commit is contained in:
q
2026-10-13 00:48:55 +03:00
parent 3fdff2a92b
commit e7cf98889b
11 changed files with 177 additions and 33 deletions
+1 -1
View File
@@ -1,2 +1,2 @@
client.version=1.19.3
client.version=1.19.4
server.version=1.15.0
+1 -1
View File
@@ -39,7 +39,7 @@
}());
</script>
<script>
window.__SHINE_BUILD_HASH__ = '20261013020000';
window.__SHINE_BUILD_HASH__ = '20261013030000';
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
</script>
<script>
+3 -2
View File
@@ -17,6 +17,7 @@ import { initPwaInstallPromptHandling } from './services/pwa-install-service.js'
import { initPwaPush } from './services/pwa-push-service.js';
import { initCallUiOverlay } from './services/call-ui-service.js';
import { showToast } from './services/channels-ux.js';
import { toUserMessage } from './services/ui-error-texts.js';
import { KeyRotationClient } from './services/key-rotation-service.js';
import {
handleCallPushAction,
@@ -936,7 +937,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
const currentLogin = String(state.session.login || '').trim();
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
if (!savedProfileExists(targetLogin)) {
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`);
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`, { kind: 'info' });
return false;
}
@@ -956,7 +957,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
}
return false;
} catch (error) {
showToast(`Не удалось переключить профиль: ${error?.message || 'unknown'}`);
showToast(toUserMessage(error, 'Не удалось переключить профиль.'), { kind: 'error' });
return false;
}
}
+2 -2
View File
@@ -1019,7 +1019,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
danger: true,
})) return;
try { await handlers.onEdit(target, '', { isChannelPost, isDelete: true }); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.')); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.'), { kind: 'error' }); }
} });
}
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: versions }) });
@@ -1214,7 +1214,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
menuItems.push({ divider: true }, { label: 'Удалить', danger: true, iconHtml: iconHtml('trash'), action: async () => {
if (!await confirmDialog({ title: 'Удалить комментарий?', text: 'Он скроется из обсуждения. Прежние версии останутся в блокчейне.', confirmLabel: 'Удалить', danger: true })) return;
try { await handlers.onEdit(target, '', { isChannelPost: false, isDelete: true }); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить комментарий.')); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить комментарий.'), { kind: 'error' }); }
} });
}
const menu = createDropdownMenu({ anchorEl: more, items: menuItems });
+6 -6
View File
@@ -1847,7 +1847,7 @@ function openMessageLikePopup({ anchor, post, navigate, onToggleLike }) {
close();
} catch (error) {
button.disabled = false;
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
}
});
}
@@ -2072,7 +2072,7 @@ function renderPostCard(post, {
try {
await onToggleLike(post.messageRef, isLiked ? 'unlike' : 'like');
} catch (error) {
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
} finally {
if (likeButton.isConnected) likeButton.disabled = false;
}
@@ -2274,7 +2274,7 @@ function renderPostCard(post, {
danger: true,
})) return;
try { await onEdit(post.messageRef, '', { isDelete: true }); }
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.')); }
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.'), { kind: 'error' }); }
} });
}
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
@@ -2638,7 +2638,7 @@ export function render({ navigate, route, chrome }) {
iconHtml: iconHtml('list'),
action: () => {
if (activeOpenEntrypointHistory) activeOpenEntrypointHistory();
else showToast('В этом канале пока нет оглавления');
else showToast('В этом канале пока нет оглавления', { kind: 'info' });
},
});
if (!apiData?.isOwnChannel) {
@@ -3023,7 +3023,7 @@ export function render({ navigate, route, chrome }) {
posts: apiData?.posts,
onSelect: (post) => {
if (!flashAndScrollToMessage(post?.messageRef)) {
showToast('Не удалось найти запись оглавления в ленте');
showToast('Не удалось найти запись оглавления в ленте', { kind: 'error' });
}
},
});
@@ -3068,7 +3068,7 @@ export function render({ navigate, route, chrome }) {
channelEntrypointButton.onclick = () => {
const latestEntrypoint = entrypointPosts[0];
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
showToast('Не удалось найти актуальное оглавление');
showToast('Не удалось найти актуальное оглавление', { kind: 'error' });
}
};
}
+2 -2
View File
@@ -703,7 +703,7 @@ function openMessageActionsMenu({
if (navigator?.clipboard?.writeText) {
await navigator.clipboard.writeText(String(messageText || ''));
}
showToast('Сообщение скопированно', { timeoutMs: 1000 });
showToast('Сообщение скопировано', { timeoutMs: 1000 });
} catch {
showToast('Не удалось скопировать сообщение', { kind: 'error', timeoutMs: 1200 });
} finally {
@@ -2594,7 +2594,7 @@ export function render({ navigate, route, chrome }) {
try {
for (let index = 0; index < allFiles.length; index += 1) {
const file = allFiles[index];
showToast(`Файл ${index + 1}/${allFiles.length}: «${String(file.name || 'file')}»`, { timeoutMs: 1200 });
showToast(`Файл ${index + 1}/${allFiles.length}: «${String(file.name || 'file')}»`, { kind: 'info', timeoutMs: 1200 });
const attachment = await encryptAndUploadDmFile({
file,
login: state.session.login,
+1 -1
View File
@@ -618,7 +618,7 @@ export function render({navigate, chrome}) {
await reloadRequests({ silent: true });
cleanupEvent = authService.onEvent('IncomingTrustedDeviceLoginRequest', () => {
if (disposed) return;
showToast('Пришла новая заявка на вход через доверенное устройство');
showToast('Пришла новая заявка на вход через доверенное устройство', { kind: 'info' });
void reloadRequests({ silent: true });
});
} catch (error) {
+1 -1
View File
@@ -605,7 +605,7 @@ export function render({ navigate, route, chrome } = {}) {
if (!friends.length) {
friendsOfFriends = false;
syncChips();
showToast(isSelfCenter() ? 'Пока нет друзей – раскрывать нечего' : 'У этого человека пока нет друзей на карте', { timeoutMs: 2200 });
showToast(isSelfCenter() ? 'Пока нет друзей – раскрывать нечего' : 'У этого человека пока нет друзей на карте', { kind: 'info', timeoutMs: 2200 });
return;
}
setBusy(true);
+72 -11
View File
@@ -1,4 +1,5 @@
const TOAST_HOST_ID = 'shine-toast-host';
import { iconHtml } from '../components/ui-icon.js';
const TOAST_HOST_ID = 'shine-toast-host';
const rtf = (() => {
try {
@@ -153,27 +154,87 @@ function ensureToastHost() {
return host;
}
export function showToast(message, { kind = 'success', timeoutMs = 2500 } = {}) {
// Тост встаёт над нижним меню и панелью ввода (что из них выше), а не поверх них.
function placeToastHost(host) {
const tops = ['toolbar-slot', 'composer-slot']
.map((id) => document.getElementById(id))
.filter((el) => el && !el.hidden && el.offsetHeight > 0)
.map((el) => el.getBoundingClientRect().top);
const viewportBottom = window.visualViewport ? window.visualViewport.height + window.visualViewport.offsetTop : window.innerHeight;
const edge = tops.length ? Math.min(...tops, viewportBottom) : viewportBottom;
host.style.bottom = `${Math.max(12, Math.round(window.innerHeight - edge + 12))}px`;
}
const TOAST_ICONS = { success: 'check', error: 'alert', info: 'info' };
/**
* Короткое сообщение внизу экрана. kind: 'success' (галочка), 'error' (восклицание, дольше
* висит), 'info' (i). action – { label, onClick } – кнопка справа («Повторить», «Отменить»).
* Одинаковое сообщение подряд не дублируется – показанное просто продлевается.
*/
export function showToast(message, { kind = 'success', timeoutMs = 2500, action = null } = {}) {
const text = String(message || '').trim();
if (!text) return;
const safeKind = TOAST_ICONS[kind] ? kind : 'success';
const host = ensureToastHost();
placeToastHost(host);
const same = [...host.children].find((el) => el.dataset.text === text && !el.classList.contains('is-hiding'));
if (same?.restartToast) {
same.restartToast();
return;
}
while (host.children.length >= 3) host.firstElementChild.remove();
const toast = document.createElement('div');
toast.className = `toast toast--${kind}`;
toast.textContent = text;
host.append(toast);
requestAnimationFrame(() => {
toast.classList.add('is-visible');
});
toast.className = `toast toast--${safeKind}`;
toast.dataset.text = text;
toast.setAttribute('role', safeKind === 'error' ? 'alert' : 'status');
const icon = document.createElement('span');
icon.className = 'toast__icon';
icon.setAttribute('aria-hidden', 'true');
icon.innerHTML = iconHtml(TOAST_ICONS[safeKind]);
const body = document.createElement('span');
body.className = 'toast__text';
body.textContent = text;
toast.append(icon, body);
let timer = 0;
const hide = () => {
window.clearTimeout(timer);
if (toast.classList.contains('is-hiding')) return;
toast.classList.remove('is-visible');
toast.classList.add('is-hiding');
setTimeout(() => toast.remove(), 220);
};
if (action?.label && typeof action.onClick === 'function') {
const button = document.createElement('button');
button.type = 'button';
button.className = 'toast__action';
button.textContent = action.label;
button.addEventListener('click', (event) => {
event.stopPropagation();
hide();
action.onClick();
});
toast.append(button);
}
// Касание закрывает сообщение раньше времени.
toast.addEventListener('click', hide);
host.append(toast);
requestAnimationFrame(() => {
toast.classList.add('is-visible');
});
setTimeout(hide, Math.max(1200, Number(timeoutMs) || 2500));
// Время на чтение: ошибки и длинный текст висят дольше.
const base = Math.max(1200, Number(timeoutMs) || 2500);
const forReading = 1500 + text.length * 45;
const duration = Math.min(8000, Math.max(base, safeKind === 'error' ? Math.max(4000, forReading) : Math.min(forReading, base * 1.6)));
toast.restartToast = () => {
window.clearTimeout(timer);
timer = window.setTimeout(hide, duration);
};
toast.restartToast();
}
export function softHaptic(duration = 15) {
@@ -318,7 +379,7 @@ export async function longPressFeel(el, delayMs = 130) {
// Когда появится, здесь вызывать настоящий обработчик.
export const REPOSTS_ENABLED = false;
export function notifyRepostSoon() {
showToast('Репосты скоро появятся');
showToast('Репосты скоро появятся', { kind: 'info' });
}
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
+87
View File
@@ -84,7 +84,94 @@
min-width: 160px;
}
/* Короткие сообщения внизу (showToast в services/channels-ux.js): над нижним меню и полем
* ввода (bottom задаёт JS), значок по смыслу, касание закрывает. */
.toast-host {
position: fixed;
left: 0;
right: 0;
bottom: calc(90px + env(safe-area-inset-bottom));
z-index: 140;
display: grid;
justify-items: center;
gap: 8px;
padding: 0 var(--page-gutter);
pointer-events: none;
}
.toast {
display: flex;
align-items: center;
gap: 10px;
max-width: min(100%, 440px);
min-height: 44px;
padding: 10px 14px;
border: 1px solid var(--border-subtle);
border-radius: 14px;
background: var(--surface-raised);
box-shadow: var(--shadow);
color: var(--text-primary);
font-size: var(--text-sm);
line-height: 1.35;
pointer-events: auto;
cursor: default;
opacity: 0;
transform: translateY(8px) scale(0.98);
transition: opacity 180ms ease, transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.toast.is-visible {
opacity: 1;
transform: none;
}
.toast.is-hiding {
opacity: 0;
transform: translateY(4px);
}
.toast__icon {
flex: 0 0 auto;
display: grid;
place-items: center;
width: 22px;
height: 22px;
color: var(--success);
}
.toast__icon svg {
width: 20px;
height: 20px;
}
.toast--error .toast__icon { color: var(--danger); }
.toast--info .toast__icon { color: var(--accent); }
.toast__text {
flex: 1 1 auto;
min-width: 0;
overflow-wrap: anywhere;
}
.toast__action {
flex: 0 0 auto;
margin: -6px -6px -6px 2px;
padding: 8px 8px;
border: 0;
border-radius: 10px;
background: none;
color: var(--accent);
font: inherit;
font-weight: var(--weight-bold);
cursor: pointer;
}
.toast__action:hover {
background: var(--surface-selected);
}
@media (prefers-reduced-motion: reduce) {
.spinner { animation-duration: 1.6s; }
.loading-state { animation: none; opacity: 1; }
.toast { transition: none; transform: none; }
}
+1 -6
View File
@@ -6,11 +6,6 @@
.modal-dialog { position: absolute; left: 16px; right: 16px; bottom: 24px; display: grid; gap: 12px; box-shadow: var(--shadow); }
.modal { position: fixed; inset: 0; background: var(--scrim); display: grid; place-items: center; padding: 16px; z-index: 60; }
.modal-card { width: min(100%, 560px); max-height: calc(100dvh - 32px); overflow-y: auto; color: var(--text-primary); background: var(--surface); border: 1px solid var(--border-subtle); border-radius: 20px; padding: 20px; box-shadow: var(--shadow); }
.toast-host { position: fixed; left: 0; right: 0; bottom: calc(18px + env(safe-area-inset-bottom)); display: grid; justify-items: center; gap: 8px; z-index: 140; pointer-events: none; }
.toast { max-width: min(92vw,420px); padding: 12px 16px; border-radius: 12px; color: var(--text-primary); background: var(--surface); box-shadow: var(--shadow); border: 1px solid var(--border-subtle); opacity: 0; transition: opacity 160ms; }
.toast.is-visible { opacity: 1; }
.toast.is-hiding { opacity: 0; }
.toast.toast--error { color: var(--danger); }
.skeleton-card { display: grid; gap: 12px; }
.skeleton-line { height: 12px; border-radius: 6px; background: var(--surface-selected); animation: skeleton-pulse 1.2s ease-in-out infinite alternate; }
.skeleton-line.w-40 { width: 40%; }
@@ -24,7 +19,7 @@
.skeleton-body { display: grid; gap: 10px; }
.skeleton-body .skeleton-line { display: block; }
@keyframes skeleton-pulse { to { opacity: .4; } }
@media (prefers-reduced-motion: reduce) { .skeleton-line, .toast { animation: none; transition: none; } }
@media (prefers-reduced-motion: reduce) { .skeleton-line { animation: none; transition: none; } }
@media (max-width: 599px) {
.modal { place-items: end stretch; padding: 0; }