SHA256
Всплывающие сообщения: одна аккуратная система
- тост встаёт над нижним меню и полем ввода, а не поверх них; - значок по смыслу (галочка, восклицание, «i») вместо красного текста ошибки; - ошибки и длинные сообщения висят дольше (время на чтение), касание закрывает; - одинаковое сообщение подряд не дублируется, можно добавить кнопку («Повторить»); - ошибки, которые показывались как «успех», помечены ошибками; справочные – «i»; исправлено «Сообщение скопированно». Стили тостов перенесены из modal.css в feedback.css (общие состояния и сообщения).
This commit is contained in:
@@ -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' });
|
||||
}
|
||||
|
||||
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
|
||||
|
||||
Reference in New Issue
Block a user