SHA256
Если в профиле автора указан пол, глагол в уведомлениях о связях и подписках согласуется с ним («Добавила вас в друзья», «Подписался на ваш канал»); пока профиль не пришёл или пол не указан – прежнее нейтральное «Добавил(а)». То же в подсказке на чужом профиле («добавила вас в контакты»).
559 lines
27 KiB
JavaScript
559 lines
27 KiB
JavaScript
import { createTopBar } from '../components/topbar.js';
|
||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||
import { authService, state } from '../state.js';
|
||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||
import { formatListTime, showToast } from '../services/channels-ux.js';
|
||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||
import { iconHtml } from '../components/ui-icon.js';
|
||
|
||
const CONNECTION_CLOSE_FRIEND = 10;
|
||
const CONNECTION_UNCLOSE_FRIEND = 11;
|
||
const CONNECTION_FRIEND = 14;
|
||
const CONNECTION_UNFRIEND = 15;
|
||
const CONNECTION_FOLLOW = 30;
|
||
const CONNECTION_UNFOLLOW = 31;
|
||
const CONNECTION_SHINE_CONFIRMED = 70;
|
||
const CONNECTION_SHINE_UNCONFIRMED = 71;
|
||
const CONNECTION_OFFICIAL_CONFIRMED = 80;
|
||
const CONNECTION_OFFICIAL_UNCONFIRMED = 81;
|
||
const profileSnapshotCache = new Map();
|
||
const profileSnapshotPending = new Map();
|
||
|
||
// Глагол по полу из профиля автора («Добавила вас в друзья»); пока профиль не пришёл или пол
|
||
// не указан – нейтральное «Добавил(а)».
|
||
function byGender(gender, male, female, neutral) {
|
||
if (gender === 'male') return male;
|
||
if (gender === 'female') return female;
|
||
return neutral;
|
||
}
|
||
|
||
function connectionActionLabel(typeCode, gender = '') {
|
||
const verb = (male, female) => byGender(gender, male, female, `${male}(а)`);
|
||
switch (Number(typeCode)) {
|
||
case CONNECTION_CLOSE_FRIEND: return `${verb('Добавил', 'Добавила')} вас в близкие друзья`;
|
||
case CONNECTION_UNCLOSE_FRIEND: return `${verb('Убрал', 'Убрала')} вас из близких друзей`;
|
||
case CONNECTION_FRIEND: return `${verb('Добавил', 'Добавила')} вас в друзья`;
|
||
case CONNECTION_UNFRIEND: return `${verb('Убрал', 'Убрала')} вас из друзей`;
|
||
case CONNECTION_SHINE_CONFIRMED: return `${verb('Подтвердил', 'Подтвердила')}, что вы сияющий`;
|
||
case CONNECTION_SHINE_UNCONFIRMED: return `${verb('Снял', 'Сняла')} подтверждение «сияющий»`;
|
||
case CONNECTION_OFFICIAL_CONFIRMED: return `${verb('Подтвердил', 'Подтвердила')} официальный статус аккаунта`;
|
||
case CONNECTION_OFFICIAL_UNCONFIRMED: return `${verb('Снял', 'Сняла')} подтверждение официального статуса`;
|
||
default: return `${verb('Изменил', 'Изменила')} связь с вами`;
|
||
}
|
||
}
|
||
|
||
function eventActionLabel(typeCode, gender = '') {
|
||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return `${byGender(gender, 'Отписался', 'Отписалась', 'Отписался(-ась)')} от вашего канала`;
|
||
return `${byGender(gender, 'Подписался', 'Подписалась', 'Подписался(-ась)')} на ваш канал`;
|
||
}
|
||
|
||
function actionLabel(item, activeTab) {
|
||
const gender = String(item.profile?.gender || '');
|
||
return activeTab === 'connections'
|
||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType, gender)
|
||
: eventActionLabel(item.sourceMsgSubType, gender);
|
||
}
|
||
|
||
export const pageMeta = { id: 'notifications-view', title: 'Уведомления' };
|
||
|
||
function normalizeItem(item) {
|
||
return {
|
||
kind: String(item?.kind || ''),
|
||
createdAtMs: Number(item?.createdAtMs || 0),
|
||
sourceLogin: String(item?.sourceLogin || ''),
|
||
sourceBlockchainName: String(item?.sourceBlockchainName || ''),
|
||
sourceBlockNumber: Number(item?.sourceBlockNumber || 0),
|
||
sourceBlockHash: String(item?.sourceBlockHash || ''),
|
||
sourceMsgSubType: item?.sourceMsgSubType == null ? null : Number(item.sourceMsgSubType),
|
||
sourceText: String(item?.sourceText || ''),
|
||
connectionTypeCode: item?.connectionTypeCode == null ? null : Number(item.connectionTypeCode),
|
||
targetLogin: String(item?.targetLogin || ''),
|
||
targetBlockchainName: String(item?.targetBlockchainName || ''),
|
||
targetBlockNumber: item?.targetBlockNumber == null ? null : Number(item.targetBlockNumber),
|
||
targetBlockHash: String(item?.targetBlockHash || ''),
|
||
profile: null,
|
||
engagement: null,
|
||
};
|
||
}
|
||
|
||
function profileField(snapshot, key) {
|
||
const row = (Array.isArray(snapshot?.fields) ? snapshot.fields : [])
|
||
.find((field) => String(field?.key || '') === key);
|
||
return String(row?.value || '').trim();
|
||
}
|
||
|
||
async function loadCachedProfileSnapshot(login) {
|
||
const cleanLogin = String(login || '').trim();
|
||
if (!cleanLogin) return null;
|
||
const key = cleanLogin.toLowerCase();
|
||
if (profileSnapshotCache.has(key)) return profileSnapshotCache.get(key);
|
||
if (profileSnapshotPending.has(key)) return profileSnapshotPending.get(key);
|
||
|
||
const pending = loadProfileSnapshot(cleanLogin)
|
||
.then((snapshot) => {
|
||
profileSnapshotCache.set(key, snapshot || null);
|
||
profileSnapshotPending.delete(key);
|
||
return snapshot || null;
|
||
})
|
||
.catch(() => {
|
||
profileSnapshotCache.set(key, null);
|
||
profileSnapshotPending.delete(key);
|
||
return null;
|
||
});
|
||
|
||
profileSnapshotPending.set(key, pending);
|
||
return pending;
|
||
}
|
||
|
||
function normalizeEngagement(source) {
|
||
if (!source || typeof source !== 'object') return null;
|
||
const likesCount = Math.max(0, Number(source.likesCount || 0));
|
||
const repliesCount = Math.max(0, Number(source.repliesCount || 0));
|
||
const ratingsCount = Math.max(0, Number(source.ratingsCount || 0));
|
||
const repostsCount = Math.max(0, Number(source.repostsCount ?? source.repostCount ?? 0));
|
||
const sharesCount = Math.max(0, Number(source.sharesCount ?? source.shareCount ?? 0));
|
||
|
||
const result = {
|
||
likesCount: Number.isFinite(likesCount) ? likesCount : 0,
|
||
repliesCount: Number.isFinite(repliesCount) ? repliesCount : 0,
|
||
ratingsCount: Number.isFinite(ratingsCount) ? ratingsCount : 0,
|
||
repostsCount: Number.isFinite(repostsCount) ? repostsCount : 0,
|
||
sharesCount: Number.isFinite(sharesCount) ? sharesCount : 0,
|
||
};
|
||
|
||
return Object.values(result).some((count) => count > 0) ? result : null;
|
||
}
|
||
|
||
async function loadSourceEngagement(item) {
|
||
const blockchainName = String(item?.sourceBlockchainName || '').trim();
|
||
const blockNumber = Number(item?.sourceBlockNumber);
|
||
const blockHash = String(item?.sourceBlockHash || '').trim();
|
||
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0 || !blockHash) return null;
|
||
|
||
try {
|
||
const payload = await authService.getMessageThread(
|
||
{ blockchainName, blockNumber, blockHash },
|
||
0,
|
||
0,
|
||
1,
|
||
String(state.session.login || '').trim(),
|
||
);
|
||
return normalizeEngagement(payload?.focus);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function enrichItem(item, activeTab) {
|
||
const [profile, engagement] = await Promise.all([
|
||
loadCachedProfileSnapshot(item.sourceLogin),
|
||
activeTab === 'replies' ? loadSourceEngagement(item) : Promise.resolve(null),
|
||
]);
|
||
return { ...item, profile, engagement };
|
||
}
|
||
|
||
function renderEmpty(activeTab) {
|
||
return createStateMessage({
|
||
icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
|
||
title: activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет новостей о связях' : 'Пока нет ответов',
|
||
text: activeTab === 'events'
|
||
? 'Подписки и отписки от ваших каналов появятся здесь.'
|
||
: activeTab === 'connections'
|
||
? 'Когда вас добавят в друзья или подтвердят статус, это появится здесь.'
|
||
: 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.',
|
||
});
|
||
}
|
||
|
||
function renderAvatar(item) {
|
||
const profile = item.profile;
|
||
const avatar = (profile?.avatar?.txId || profile?.avatar?.sha256Hex)
|
||
? {
|
||
ar: String(profile.avatar.txId || profile.avatar.ar || '').trim(),
|
||
sha256Hex: String(profile.avatar.sha256Hex || '').trim().toLowerCase(),
|
||
}
|
||
: null;
|
||
return renderUserAvatar({
|
||
login: item.sourceLogin || 'unknown',
|
||
firstName: profileField(profile, 'first_name'),
|
||
lastName: profileField(profile, 'last_name'),
|
||
avatar,
|
||
size: 'md',
|
||
className: 'notification-avatar',
|
||
});
|
||
}
|
||
|
||
// Строка как в списке чатов: имя и время, ниже – что произошло и текст ответа.
|
||
function renderHead(item) {
|
||
const profile = item.profile;
|
||
const fullName = [profileField(profile, 'first_name'), profileField(profile, 'last_name')].filter(Boolean).join(' ')
|
||
|| item.sourceLogin || 'Пользователь';
|
||
const head = document.createElement('div');
|
||
head.className = 'notification-card__head';
|
||
const name = document.createElement('strong');
|
||
name.className = 'notification-card__name';
|
||
name.textContent = fullName;
|
||
head.append(name);
|
||
const time = document.createElement('span');
|
||
time.className = 'notification-card__time';
|
||
time.textContent = formatListTime(item.createdAtMs);
|
||
head.append(time);
|
||
return head;
|
||
}
|
||
|
||
function renderEngagement(engagement) {
|
||
if (!engagement) return null;
|
||
|
||
const stats = [
|
||
{ key: 'likesCount', icon: 'heart', label: 'Лайки' },
|
||
{ key: 'repliesCount', icon: 'message', label: 'Ответы' },
|
||
{ key: 'repostsCount', icon: 'refresh', label: 'Репосты' },
|
||
{ key: 'sharesCount', icon: 'forward', label: 'Отправки' },
|
||
].filter(({ key }) => Number(engagement[key] || 0) > 0);
|
||
|
||
if (!stats.length) return null;
|
||
|
||
const row = document.createElement('div');
|
||
row.className = 'notification-engagement';
|
||
stats.forEach(({ key, icon, label }) => {
|
||
const stat = document.createElement('span');
|
||
stat.className = 'notification-engagement-item';
|
||
stat.title = label;
|
||
|
||
const iconEl = document.createElement('span');
|
||
iconEl.className = 'notification-engagement-icon';
|
||
iconEl.setAttribute('aria-hidden', 'true');
|
||
iconEl.innerHTML = iconHtml(icon);
|
||
|
||
const countEl = document.createElement('span');
|
||
countEl.className = 'notification-engagement-count';
|
||
countEl.textContent = String(engagement[key]);
|
||
stat.append(iconEl, countEl);
|
||
row.append(stat);
|
||
});
|
||
|
||
return row;
|
||
}
|
||
|
||
function notificationRoute(item, activeTab) {
|
||
if (activeTab === 'events' || activeTab === 'connections') {
|
||
const login = String(item?.sourceLogin || '').trim();
|
||
return login ? makeProfileRoute(login) : '';
|
||
}
|
||
|
||
const blockchainName = String(item?.sourceBlockchainName || '').trim();
|
||
const blockNumber = Number(item?.sourceBlockNumber);
|
||
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0) return '';
|
||
|
||
return makeShineMessageRoute({
|
||
messageBlockchainName: blockchainName,
|
||
messageBlockNumber: blockNumber,
|
||
});
|
||
}
|
||
|
||
function bindNotificationNavigation(row, routePath, navigate) {
|
||
if (!routePath || typeof navigate !== 'function') return;
|
||
|
||
row.classList.add('notification-card--clickable');
|
||
row.tabIndex = 0;
|
||
row.setAttribute('role', 'link');
|
||
|
||
const open = () => navigate(routePath);
|
||
row.addEventListener('click', open);
|
||
row.addEventListener('keydown', (event) => {
|
||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||
event.preventDefault();
|
||
open();
|
||
});
|
||
}
|
||
|
||
function renderItem(item, activeTab, navigate) {
|
||
const row = document.createElement('article');
|
||
row.className = 'notification-card';
|
||
bindNotificationNavigation(row, notificationRoute(item, activeTab), navigate);
|
||
|
||
const body = document.createElement('div');
|
||
body.className = 'notification-card__body';
|
||
body.append(renderHead(item));
|
||
|
||
if (activeTab === 'replies') {
|
||
// Во вкладке «Ответы» всё – ответы: подпись «ответил(а)» не нужна, сразу текст.
|
||
const text = document.createElement('p');
|
||
text.className = 'notification-card__text';
|
||
text.textContent = item.sourceText || 'Ответ без текста';
|
||
body.append(text);
|
||
const engagement = renderEngagement(item.engagement);
|
||
if (engagement) body.append(engagement);
|
||
} else {
|
||
const action = document.createElement('p');
|
||
action.className = 'notification-card__action';
|
||
action.textContent = actionLabel(item, activeTab);
|
||
body.append(action);
|
||
}
|
||
|
||
row.append(renderAvatar(item), body);
|
||
return row;
|
||
}
|
||
|
||
// Профиль и счётчики пришли позже – обновляем строку на месте (наблюдение «прочитано» не теряется).
|
||
function refreshItemRow(row, item, activeTab) {
|
||
if (!row?.isConnected) return;
|
||
row.querySelector('.notification-avatar')?.replaceWith(renderAvatar(item));
|
||
const name = row.querySelector('.notification-card__name');
|
||
if (name) name.textContent = renderHead(item).querySelector('.notification-card__name').textContent;
|
||
const action = row.querySelector('.notification-card__action');
|
||
if (action && activeTab !== 'replies') action.textContent = actionLabel(item, activeTab);
|
||
if (activeTab === 'replies' && item.engagement && !row.querySelector('.notification-engagement')) {
|
||
const engagement = renderEngagement(item.engagement);
|
||
if (engagement) row.querySelector('.notification-card__body')?.append(engagement);
|
||
}
|
||
}
|
||
|
||
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
|
||
let lastNotifications = null;
|
||
|
||
export function render({ navigate, chrome } = {}) {
|
||
const screen = document.createElement('section');
|
||
screen.className = 'stack notifications-screen';
|
||
|
||
const tabs = document.createElement('div');
|
||
tabs.className = 'tabs tabs--three notification-feed-tabs';
|
||
tabs.setAttribute('role', 'radiogroup');
|
||
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||
const topbar = createTopBar({
|
||
title: 'Уведомления',
|
||
className: 'topbar--root notifications-topbar',
|
||
actions: [{
|
||
icon: 'check-double',
|
||
title: 'Прочитать все',
|
||
ariaLabel: 'Отметить все уведомления прочитанными',
|
||
className: 'notifications-read-all',
|
||
onClick: () => { void markAllRead(); },
|
||
}],
|
||
});
|
||
chrome?.setTopbar(topbar);
|
||
const readAllBtn = topbar.querySelector('.notifications-read-all');
|
||
if (readAllBtn) readAllBtn.disabled = true;
|
||
screen.append(tabs);
|
||
|
||
const list = document.createElement('div');
|
||
list.className = 'notifications-list';
|
||
let payloadCache = null;
|
||
let requestSeq = 0;
|
||
let observer = null;
|
||
const pendingSeenTimers = { replies: null, connections: null, events: null };
|
||
const localSeen = { replies: 0, connections: 0, events: 0 };
|
||
|
||
function countsFromPayload(payload) {
|
||
return {
|
||
replies: Number(payload?.repliesUnseenCount || 0),
|
||
connections: Number(payload?.connectionsUnseenCount || 0),
|
||
events: Number(payload?.eventsUnseenCount || 0),
|
||
};
|
||
}
|
||
|
||
function updateToolbarBadge(payload) {
|
||
const c = countsFromPayload(payload);
|
||
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
||
if (readAllBtn) readAllBtn.disabled = state.notificationUnreadTotal <= 0;
|
||
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
||
if (!btn) return;
|
||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||
if (state.notificationUnreadTotal <= 0) { badge?.remove(); return; }
|
||
if (!badge) { badge = document.createElement('span'); badge.className = 'toolbar-unread-badge notification-toolbar-badge'; (btn.querySelector('.toolbar-icon') || btn).append(badge); }
|
||
badge.textContent = state.notificationUnreadTotal > 99 ? '99+' : String(state.notificationUnreadTotal);
|
||
}
|
||
|
||
function renderTabs(payload) {
|
||
const counts = countsFromPayload(payload);
|
||
tabs.replaceChildren(...tabDefs.map(([key,label]) => {
|
||
const b=document.createElement('button'); b.type='button'; b.className='tab-btn notification-tab-btn'; b.dataset.tab=key; b.setAttribute('role','radio'); b.setAttribute('aria-checked',state.notificationsTab===key?'true':'false');
|
||
b.textContent = label;
|
||
if (counts[key] > 0) {
|
||
const count = document.createElement('span');
|
||
count.className = 'tab-count';
|
||
count.textContent = counts[key] > 99 ? '99+' : String(counts[key]);
|
||
count.setAttribute('aria-label', `новых: ${counts[key]}`);
|
||
b.append(count);
|
||
}
|
||
b.addEventListener('click',()=>{ if(state.notificationsTab===key)return; state.notificationsTab=key; renderCurrent(); });
|
||
return b;
|
||
}));
|
||
}
|
||
|
||
function categoryData(payload, tab) {
|
||
if (tab === 'connections') return { items: payload?.connections || [], seenAt: Number(payload?.connectionsSeenAtMs || 0) };
|
||
if (tab === 'events') return { items: payload?.events || [], seenAt: Number(payload?.eventsSeenAtMs || 0) };
|
||
return { items: payload?.replies || [], seenAt: Number(payload?.repliesSeenAtMs || 0) };
|
||
}
|
||
|
||
function scheduleSeen(category, seenAtMs) {
|
||
if (seenAtMs <= Number(localSeen[category] || 0)) return;
|
||
localSeen[category] = seenAtMs;
|
||
clearTimeout(pendingSeenTimers[category]);
|
||
pendingSeenTimers[category] = setTimeout(async () => {
|
||
const target = Number(localSeen[category] || 0);
|
||
try {
|
||
await authService.setNotificationSeen({ login: state.session.login, category, seenAtMs: target, storagePwd: state.session.storagePwdInMemory });
|
||
if (!payloadCache) return;
|
||
const key = category === 'connections' ? 'connectionsSeenAtMs' : category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||
const countKey = category === 'connections' ? 'connectionsUnseenCount' : category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||
payloadCache[key] = Math.max(Number(payloadCache[key] || 0), target);
|
||
payloadCache[countKey] = (payloadCache[category] || []).filter(x => Number(x?.createdAtMs || 0) > payloadCache[key]).length;
|
||
renderTabs(payloadCache); updateToolbarBadge(payloadCache);
|
||
} catch (e) { console.warn('Не удалось подписать watermark уведомлений', e); }
|
||
}, 350);
|
||
}
|
||
|
||
let renderSeq = 0;
|
||
async function renderCurrent() {
|
||
const seq = ++renderSeq;
|
||
observer?.disconnect(); observer=null; renderTabs(payloadCache || {});
|
||
const tab=state.notificationsTab; const {items:raw,seenAt}=categoryData(payloadCache || {},tab); localSeen[tab]=Math.max(localSeen[tab]||0,seenAt);
|
||
const base=raw.map(normalizeItem); if(!base.length){list.replaceChildren(renderEmpty(tab));return;}
|
||
// Список рисуется сразу – с профилями из кэша; остальное догружается в фоне и
|
||
// обновляет строки на месте (раньше экран ждал загрузки профиля каждого автора).
|
||
const items=base.map((x)=>({ ...x, profile: profileSnapshotCache.get(String(x.sourceLogin || '').toLowerCase()) || null }));
|
||
const rowByItem = new Map();
|
||
const unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
|
||
const nodes=[];
|
||
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;};
|
||
if(unread.length) nodes.push(groupTitle(`Новые · ${unread.length}`));
|
||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);rowByItem.set(x,n);nodes.push(n);});
|
||
if(unread.length && old.length) nodes.push(groupTitle('Ранее'));
|
||
old.forEach(x=>{const n=renderItem(x,tab,navigate);rowByItem.set(x,n);nodes.push(n);}); list.replaceChildren(...nodes);
|
||
void enrichInBackground(items, tab, rowByItem, seq);
|
||
if (tab === 'connections') void offerFriendBack(items, rowByItem, seq);
|
||
if(unread.length && 'IntersectionObserver' in window){
|
||
observer=new IntersectionObserver(entries=>{ entries.forEach(e=>{ if(e.isIntersecting && e.intersectionRatio>=0.5){ const ts=Number(e.target.dataset.createdAtMs||0); if(ts>0){e.target.classList.remove('notification-card--new');scheduleSeen(tab,ts);} } }); },{threshold:[0.5]});
|
||
list.querySelectorAll('.notification-card--new').forEach(n=>observer.observe(n));
|
||
}
|
||
}
|
||
|
||
// «Добавил(а) вас в друзья», а вы ещё нет – кнопка «Дружить в ответ» прямо в уведомлении.
|
||
// Кто у вас уже в друзьях – из одного запроса своего графа связей.
|
||
async function offerFriendBack(items, rowByItem, seq) {
|
||
const self = String(state.session.login || '').trim();
|
||
const candidates = items.filter((x) => [CONNECTION_FRIEND, CONNECTION_CLOSE_FRIEND].includes(Number(x.connectionTypeCode ?? x.sourceMsgSubType)));
|
||
if (!self || !candidates.length) return;
|
||
let graph;
|
||
try { graph = await authService.getUserConnectionsGraph(self); } catch { return; }
|
||
if (seq !== renderSeq) return;
|
||
const mine = new Set([...(graph?.outFriends || []), ...(graph?.outCloseFriends || [])].map((login) => String(login).toLowerCase()));
|
||
const offered = new Set();
|
||
for (const item of candidates) {
|
||
const login = String(item.sourceLogin || '').trim();
|
||
const key = login.toLowerCase();
|
||
// Одна кнопка на человека – у самого свежего уведомления.
|
||
if (!login || mine.has(key) || offered.has(key)) continue;
|
||
offered.add(key);
|
||
const row = rowByItem.get(item);
|
||
const body = row?.querySelector('.notification-card__body');
|
||
if (!body) continue;
|
||
const button = document.createElement('button');
|
||
button.type = 'button';
|
||
button.className = 'secondary-btn notification-card__answer';
|
||
button.textContent = 'Дружить в ответ';
|
||
button.addEventListener('click', async (event) => {
|
||
event.stopPropagation();
|
||
button.disabled = true;
|
||
button.textContent = 'Сохраняю…';
|
||
try {
|
||
await authService.setUserRelation({ login: self, toLogin: login, kind: 'friend', enabled: true, storagePwd: state.session.storagePwdInMemory });
|
||
const done = document.createElement('span');
|
||
done.className = 'notification-card__answered';
|
||
done.innerHTML = `${iconHtml('check')}<span>Вы друзья</span>`;
|
||
button.replaceWith(done);
|
||
showToast('Теперь вы друзья');
|
||
} catch (error) {
|
||
button.disabled = false;
|
||
button.textContent = 'Дружить в ответ';
|
||
showToast(toUserMessage(error, 'Не удалось добавить в друзья.'), { kind: 'error' });
|
||
}
|
||
});
|
||
body.append(button);
|
||
}
|
||
}
|
||
|
||
async function enrichInBackground(items, tab, rowByItem, seq) {
|
||
let cursor = 0;
|
||
const worker = async () => {
|
||
while (cursor < items.length) {
|
||
const item = items[cursor++];
|
||
const needProfile = !item.profile;
|
||
if (!needProfile && tab !== 'replies') continue;
|
||
const enriched = await enrichItem(item, tab);
|
||
if (seq !== renderSeq) return;
|
||
refreshItemRow(rowByItem.get(item), enriched, tab);
|
||
}
|
||
};
|
||
await Promise.all(Array.from({ length: 6 }, worker));
|
||
}
|
||
|
||
async function markAllRead() {
|
||
if (!payloadCache) return;
|
||
const jobs = ['replies', 'connections', 'events'].map((category) => {
|
||
const { items, seenAt } = categoryData(payloadCache, category);
|
||
const maxTs = items.reduce((max, x) => Math.max(max, Number(x?.createdAtMs || 0)), 0);
|
||
return { category, maxTs, seenAt };
|
||
}).filter((job) => job.maxTs > job.seenAt);
|
||
if (!jobs.length) return;
|
||
if (readAllBtn) readAllBtn.disabled = true;
|
||
try {
|
||
for (const job of jobs) {
|
||
await authService.setNotificationSeen({ login: state.session.login, category: job.category, seenAtMs: job.maxTs, storagePwd: state.session.storagePwdInMemory });
|
||
const seenKey = job.category === 'connections' ? 'connectionsSeenAtMs' : job.category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||
const countKey = job.category === 'connections' ? 'connectionsUnseenCount' : job.category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||
payloadCache[seenKey] = job.maxTs;
|
||
payloadCache[countKey] = 0;
|
||
localSeen[job.category] = Math.max(localSeen[job.category] || 0, job.maxTs);
|
||
}
|
||
if (lastNotifications?.payload) lastNotifications = { ...lastNotifications, payload: structuredClone(payloadCache), signature: '' };
|
||
updateToolbarBadge(payloadCache);
|
||
await renderCurrent();
|
||
showToast('Все уведомления прочитаны');
|
||
} catch (error) {
|
||
updateToolbarBadge(payloadCache);
|
||
showToast(toUserMessage(error, 'Не удалось отметить уведомления прочитанными.'), { kind: 'error' });
|
||
}
|
||
}
|
||
|
||
async function load() {
|
||
const seq=++requestSeq;
|
||
const login = state.session.login;
|
||
const cached = lastNotifications?.login === login ? lastNotifications : null;
|
||
if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); }
|
||
else { renderTabs({}); if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю уведомления' })); }
|
||
try {
|
||
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
|
||
const signature = JSON.stringify(fresh);
|
||
lastNotifications = { login, payload: structuredClone(fresh), signature };
|
||
updateToolbarBadge(fresh);
|
||
if (cached?.signature === signature) return;
|
||
payloadCache=fresh; await renderCurrent();
|
||
}
|
||
catch(error){
|
||
if(seq!==requestSeq)return;
|
||
if (payloadCache) { showToast(toUserMessage(error, 'Не удалось обновить уведомления.'), { kind: 'error' }); return; }
|
||
list.replaceChildren(createErrorState({
|
||
title: 'Не удалось загрузить уведомления',
|
||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||
onRetry: () => { list.replaceChildren(); void load(); },
|
||
}));
|
||
}
|
||
}
|
||
|
||
if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
|
||
screen.cleanup = () => {
|
||
renderSeq += 1; // фоновая догрузка профилей больше не трогает экран
|
||
requestSeq += 1;
|
||
observer?.disconnect();
|
||
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
||
};
|
||
screen.append(list);
|
||
void load();
|
||
return screen;
|
||
}
|