SHA256
402 lines
15 KiB
JavaScript
402 lines
15 KiB
JavaScript
import { t } from '../i18n/index.js';
|
||
import { formatDate, formatTime, formatDateTime, formatRelative } from '../i18n/format.js';
|
||
import { iconHtml } from '../components/ui-icon.js';
|
||
const TOAST_HOST_ID = 'shine-toast-host';
|
||
|
||
|
||
function toNumber(value) {
|
||
const n = Number(value);
|
||
return Number.isFinite(n) ? n : 0;
|
||
}
|
||
|
||
function pickUnit(seconds) {
|
||
const abs = Math.abs(seconds);
|
||
if (abs < 60) return ['second', Math.round(seconds)];
|
||
const minutes = seconds / 60;
|
||
if (Math.abs(minutes) < 60) return ['minute', Math.round(minutes)];
|
||
const hours = minutes / 60;
|
||
if (Math.abs(hours) < 24) return ['hour', Math.round(hours)];
|
||
const days = hours / 24;
|
||
if (Math.abs(days) < 30) return ['day', Math.round(days)];
|
||
const months = days / 30;
|
||
if (Math.abs(months) < 12) return ['month', Math.round(months)];
|
||
const years = months / 12;
|
||
return ['year', Math.round(years)];
|
||
}
|
||
|
||
// Время поста внутри дня: «14:32». День показывается отдельной плашкой.
|
||
export function formatClockTime(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '';
|
||
return formatTime(new Date(ts));
|
||
}
|
||
|
||
const shortDay = (date) => formatDate(date, { day: 'numeric', month: 'short' });
|
||
|
||
// Дата записи в ряду действий: сегодня «10:24», раньше «25 сен, 10:24», в прошлом году «25 сен 2025».
|
||
export function formatPostStamp(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '';
|
||
const dt = new Date(ts);
|
||
const now = new Date();
|
||
const clock = formatClockTime(ts);
|
||
if (dt.toDateString() === now.toDateString()) return clock;
|
||
const day = shortDay(dt);
|
||
if (dt.getFullYear() !== now.getFullYear()) return `${day} ${dt.getFullYear()}`;
|
||
return `${day}, ${clock}`;
|
||
}
|
||
|
||
// Плашка дня в ленте: «Сегодня», «Вчера», «24 сентября», «24 сентября 2025».
|
||
export function formatDayLabel(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '';
|
||
const dt = new Date(ts);
|
||
const today = new Date();
|
||
const startOf = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||
const diffDays = Math.round((startOf(today) - startOf(dt)) / 86400000);
|
||
if (diffDays === 0) return formatRelative(0, 'day');
|
||
if (diffDays === 1) return formatRelative(-1, 'day');
|
||
const sameYear = dt.getFullYear() === today.getFullYear();
|
||
return formatDate(dt, { day: 'numeric', month: 'long', ...(sameYear ? {} : { year: 'numeric' }) });
|
||
}
|
||
|
||
export function dayKey(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '';
|
||
const dt = new Date(ts);
|
||
return `${dt.getFullYear()}-${dt.getMonth()}-${dt.getDate()}`;
|
||
}
|
||
|
||
// Время в строках списков (чаты, каналы) — коротко, как в мессенджерах:
|
||
// сегодня «21:41», вчера «вчера», на этой неделе «пт», в этом году «24.09», раньше «24.09.25».
|
||
export function formatListTime(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '';
|
||
const dt = new Date(ts);
|
||
const now = new Date();
|
||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
||
if (ts >= startOfToday) {
|
||
return formatTime(dt);
|
||
}
|
||
const dayMs = 86400000;
|
||
if (ts >= startOfToday - dayMs) return formatRelative(-1, 'day');
|
||
if (ts >= startOfToday - 6 * dayMs) {
|
||
return formatDate(dt, { weekday: 'short' });
|
||
}
|
||
if (dt.getFullYear() === now.getFullYear()) {
|
||
return formatDate(dt, { day: '2-digit', month: '2-digit' });
|
||
}
|
||
return formatDate(dt, { day: '2-digit', month: '2-digit', year: '2-digit' });
|
||
}
|
||
|
||
// Возраст записи в шапке поста и ответа: «сейчас», «5 мин», «2 ч», «3 д», потом «12 окт», в прошлом году «12 окт 2025».
|
||
export function formatShortAge(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '';
|
||
const ageMinutes = Math.max(0, Math.floor((Date.now() - ts) / 60000));
|
||
if (ageMinutes < 1) return formatRelative(0, 'second');
|
||
if (ageMinutes < 60) return formatRelative(-ageMinutes, 'minute', { numeric: 'always', style: 'narrow' });
|
||
const ageHours = Math.floor(ageMinutes / 60);
|
||
if (ageHours < 24) return formatRelative(-ageHours, 'hour', { numeric: 'always', style: 'narrow' });
|
||
const ageDays = Math.floor(ageHours / 24);
|
||
if (ageDays < 7) return formatRelative(-ageDays, 'day', { numeric: 'always', style: 'narrow' });
|
||
const dt = new Date(ts);
|
||
const day = shortDay(dt);
|
||
return dt.getFullYear() === new Date().getFullYear() ? day : `${day} ${dt.getFullYear()}`;
|
||
}
|
||
|
||
export function formatRelativeTime(timestampMs) {
|
||
const ts = toNumber(timestampMs);
|
||
if (!ts) return '–';
|
||
|
||
const now = Date.now();
|
||
const dt = new Date(ts);
|
||
const nowDt = new Date(now);
|
||
const diffSeconds = (ts - now) / 1000;
|
||
const ageSeconds = Math.max(0, (now - ts) / 1000);
|
||
const ageDays = ageSeconds / 86400;
|
||
|
||
if (ageSeconds < 60) return formatRelative(0, 'second');
|
||
|
||
if (ageDays < 7) {
|
||
const [unit, value] = pickUnit(diffSeconds);
|
||
return formatRelative(value, unit, { numeric: 'always' });
|
||
}
|
||
|
||
if (dt.getFullYear() === nowDt.getFullYear()) {
|
||
return formatDateTime(dt, {
|
||
day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit',
|
||
});
|
||
}
|
||
|
||
return formatDate(dt, {
|
||
day: '2-digit', month: '2-digit', year: 'numeric',
|
||
});
|
||
}
|
||
|
||
function ensureToastHost() {
|
||
let host = document.getElementById(TOAST_HOST_ID);
|
||
if (host) return host;
|
||
|
||
host = document.createElement('div');
|
||
host.id = TOAST_HOST_ID;
|
||
host.className = 'toast-host';
|
||
document.body.append(host);
|
||
return host;
|
||
}
|
||
|
||
// Тост встаёт над нижним меню и панелью ввода (что из них выше), а не поверх них.
|
||
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--${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');
|
||
});
|
||
|
||
// Время на чтение: ошибки и длинный текст висят дольше.
|
||
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) {
|
||
try {
|
||
if (navigator?.vibrate) navigator.vibrate(Math.max(5, Math.min(30, Number(duration) || 15)));
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
export function animatePress(el) {
|
||
if (!el) return;
|
||
el.classList.remove('is-springing');
|
||
// force reflow
|
||
// eslint-disable-next-line no-unused-expressions
|
||
el.offsetWidth;
|
||
el.classList.add('is-springing');
|
||
}
|
||
|
||
const CHANNEL_NOTIF_KEY = 'shine-channels-notify-v1';
|
||
|
||
export function readChannelNotificationsState() {
|
||
try {
|
||
const raw = localStorage.getItem(CHANNEL_NOTIF_KEY);
|
||
if (!raw) return {};
|
||
const parsed = JSON.parse(raw);
|
||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
|
||
} catch {
|
||
// ignore
|
||
}
|
||
return {};
|
||
}
|
||
|
||
export function writeChannelNotificationsState(nextState) {
|
||
try {
|
||
localStorage.setItem(CHANNEL_NOTIF_KEY, JSON.stringify(nextState || {}));
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
export function makeAuthorLabel(login, localNumber) {
|
||
const cleanLogin = String(login || t('remaining.channels.author'));
|
||
const n = Number(localNumber);
|
||
if (!Number.isFinite(n) || n < 1) return cleanLogin;
|
||
return `${cleanLogin} · #${n}`;
|
||
}
|
||
|
||
export function createSkeletonCard(className = '') {
|
||
const card = document.createElement('div');
|
||
card.className = `card skeleton-card ${className}`.trim();
|
||
card.innerHTML = `
|
||
<div class="skeleton-line w-40"></div>
|
||
<div class="skeleton-line w-90"></div>
|
||
<div class="skeleton-line w-70"></div>
|
||
`;
|
||
return card;
|
||
}
|
||
|
||
// Заглушка в форме настоящих экранов: 'list' – строки списка (круглый аватар, название, подпись),
|
||
// 'post' – записи как в ленте и обсуждении (аватар слева, имя, две строки текста).
|
||
export function createSkeletonRows(kind = 'list', count = 4) {
|
||
const wrap = document.createElement('div');
|
||
wrap.className = `skeleton-rows skeleton-rows--${kind}`;
|
||
wrap.setAttribute('aria-busy', 'true');
|
||
wrap.setAttribute('aria-label', t('remaining.channels.loading'));
|
||
for (let i = 0; i < count; i += 1) {
|
||
const row = document.createElement('div');
|
||
row.className = 'skeleton-row';
|
||
row.innerHTML = kind === 'post'
|
||
? '<span class="skeleton-avatar"></span><span class="skeleton-body"><span class="skeleton-line w-40"></span><span class="skeleton-line w-90"></span><span class="skeleton-line w-70"></span></span>'
|
||
: '<span class="skeleton-avatar"></span><span class="skeleton-body"><span class="skeleton-line w-40"></span><span class="skeleton-line w-70"></span></span>';
|
||
wrap.append(row);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
// Показать заглушку, только если загрузка заметно затянулась: быстрый ответ не должен мигать заглушкой.
|
||
export const SKELETON_DELAY_MS = 500;
|
||
|
||
export function normalizeChannelDescription(value) {
|
||
const text = String(value == null ? '' : value).trim().replace(/\s+/g, ' ');
|
||
if (!text) return '';
|
||
const chars = Array.from(text);
|
||
if (chars.length <= 200) return text;
|
||
return chars.slice(0, 200).join('');
|
||
}
|
||
|
||
function fallbackCopyText(text) {
|
||
const ta = document.createElement('textarea');
|
||
ta.value = String(text || '');
|
||
ta.setAttribute('readonly', 'readonly');
|
||
ta.style.position = 'fixed';
|
||
ta.style.opacity = '0';
|
||
ta.style.pointerEvents = 'none';
|
||
document.body.append(ta);
|
||
ta.focus();
|
||
ta.select();
|
||
const ok = document.execCommand('copy');
|
||
ta.remove();
|
||
return !!ok;
|
||
}
|
||
|
||
export async function shareOrCopyLink({ title = '', text = '', url = '' }) {
|
||
const link = String(url || '').trim();
|
||
if (!link) {
|
||
throw new Error('Ссылка для передачи не подготовлена.');
|
||
}
|
||
|
||
const payload = { title: String(title || '').trim(), text: String(text || '').trim(), url: link };
|
||
|
||
if (navigator?.share) {
|
||
try {
|
||
await navigator.share(payload);
|
||
return 'shared';
|
||
} catch (error) {
|
||
if (error?.name === 'AbortError') return 'cancelled';
|
||
// fallback to copy path
|
||
}
|
||
}
|
||
|
||
if (navigator?.clipboard?.writeText) {
|
||
await navigator.clipboard.writeText(link);
|
||
return 'copied';
|
||
}
|
||
|
||
if (fallbackCopyText(link)) {
|
||
return 'copied';
|
||
}
|
||
|
||
throw new Error('Не удалось передать ссылку.');
|
||
}
|
||
|
||
export async function longPressFeel(el, delayMs = 130) {
|
||
const node = el instanceof Element ? el : null;
|
||
if (node) node.classList.add('is-long-press');
|
||
await new Promise((resolve) => setTimeout(resolve, Math.max(60, Number(delayMs) || 130)));
|
||
if (node) node.classList.remove('is-long-press');
|
||
}
|
||
|
||
// Репост в блокчейне ещё дорабатывается (обещан скоро) – кнопка уже на месте, как четвёртая в ряду действий.
|
||
// Когда появится, здесь вызывать настоящий обработчик.
|
||
export const REPOSTS_ENABLED = false;
|
||
export function notifyRepostSoon() {
|
||
showToast(t('remaining.channels.reposts_are_coming_soon'), { kind: 'info' });
|
||
}
|
||
|
||
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
|
||
export function createLoadErrorCard({ title, message, onRetry, secondary = null }) {
|
||
const card = document.createElement('div');
|
||
card.className = 'card stack channels-status';
|
||
const heading = document.createElement('strong');
|
||
heading.textContent = title;
|
||
const details = document.createElement('p');
|
||
details.className = 'meta-muted';
|
||
// Под текстом и так кнопка «Повторить» – совет «повторите попытку» в тексте лишний.
|
||
details.textContent = String(message || '').replace(/\s*Повторите попытку[^.]*\.?\s*$/u, '').trim();
|
||
const retry = document.createElement('button');
|
||
retry.type = 'button';
|
||
retry.className = 'primary-btn';
|
||
retry.textContent = t('remaining.channels.retry');
|
||
retry.addEventListener('click', onRetry);
|
||
card.append(heading, details, retry);
|
||
if (secondary) {
|
||
const extra = document.createElement('button');
|
||
extra.type = 'button';
|
||
extra.className = 'secondary-btn';
|
||
extra.textContent = secondary.label;
|
||
extra.addEventListener('click', secondary.onClick);
|
||
card.append(extra);
|
||
}
|
||
return card;
|
||
}
|