SHA256
Шапки: ниже и с нужными действиями; уведомления и профиль без ожидания
- шапка 52 px вместо 56, заголовок корневых разделов 22 px вместо 24; - одинаковое «•••» меню во всех шапках (в «Каналах» и ленте канала было «⋮»); - «Чаты»: лупа – мгновенный поиск по своим чатам и контактам (была – переход на поиск человека), «Новый чат» – отдельной кнопкой; - «Уведомления»: «Прочитать все» в шапке; список рисуется сразу, профили авторов и счётчики догружаются в фоне (раньше экран ждал профиль каждого автора); пустые вкладки и ошибка – общим видом, ошибка с «Повторить»; - «Профиль»: «Поделиться профилем» (ссылка), загрузка – спиннер с задержкой вместо «Загрузка профиля...», ошибка с «Повторить»; - лента канала: при наведении (на телефоне – после касания) аватар записи прыгал на текст – общий :hover кнопок с filter делал плитку автора контейнером для аватара; - атрибут hidden снова скрывает переключатели и ряды чипов.
This commit is contained in:
+3
-3
@@ -71,7 +71,7 @@ import * as loginOtherDeviceView from './pages/login-other-device-view.js?v=2026
|
||||
import * as loginPasswordView from './pages/login-password-view.js?v=202606201650';
|
||||
import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
||||
|
||||
import * as profileView from './pages/profile-view.js?v=202609260900';
|
||||
import * as profileView from './pages/profile-view.js?v=202610130400';
|
||||
import * as profileEditView from './pages/profile-edit-view.js';
|
||||
import * as profilesView from './pages/profiles-view.js';
|
||||
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
||||
@@ -101,7 +101,7 @@ import * as appLogView from './pages/app-log-view.js';
|
||||
import * as pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
|
||||
import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
||||
import * as solanaRpcCheckView from './pages/solana-rpc-check-view.js';
|
||||
import * as messagesList from './pages/messages-list.js?v=202610130330';
|
||||
import * as messagesList from './pages/messages-list.js?v=202610130400';
|
||||
import * as contactSearchView from './pages/contact-search-view.js';
|
||||
import * as chatView from './pages/chat-view.js?v=202610130200';
|
||||
import * as chatMediaView from './pages/chat-media-view.js';
|
||||
@@ -118,7 +118,7 @@ import * as channelThreadView from './pages/channel-thread-view.js';
|
||||
import * as addChannelView from './pages/add-channel-view.js';
|
||||
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-view.js';
|
||||
import * as networkView from './pages/network-view.js?v=202610130200';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202609260900';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||
|
||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||
|
||||
@@ -42,7 +42,7 @@ export function openShareSheet({ title = 'Поделиться', kicker = '', te
|
||||
} catch {
|
||||
field.focus();
|
||||
field.select();
|
||||
showToast('Выделил ссылку – скопируйте её вручную', { kind: 'error' });
|
||||
showToast('Ссылка выделена – скопируйте её вручную', { kind: 'info' });
|
||||
}
|
||||
});
|
||||
wrap.append(preview, label, copy);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { getPreviousTrackedPath, navigateUp, parseRouteFromPath, toPrettyPath } from '../router.js';
|
||||
import { prefetchThreadPage, threadTotalReplies } from './channel-thread-view.js';
|
||||
@@ -2612,7 +2613,7 @@ export function render({ navigate, route, chrome }) {
|
||||
className: 'channel-view-topbar topbar--identity',
|
||||
actions: [
|
||||
{
|
||||
icon: 'moreVertical',
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Действия канала',
|
||||
ariaLabel: 'Открыть меню канала',
|
||||
className: 'channel-header-more-btn',
|
||||
|
||||
@@ -1077,7 +1077,7 @@ export function render({ navigate, route, chrome }) {
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'moreVertical',
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню каналов',
|
||||
ariaLabel: 'Открыть меню каналов',
|
||||
className: 'channels-menu-btn',
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createSearchTopBar, createTopBar } from '../components/topbar.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import {
|
||||
@@ -23,7 +23,8 @@ import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
|
||||
const PREVIEW_MAX_LEN = 200;
|
||||
@@ -258,20 +259,60 @@ export function render({ navigate, chrome }) {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
// Шапка: поиск по своим чатам и контактам (мгновенно, на устройстве) и «Новый чат».
|
||||
let chatQuery = '';
|
||||
let chatSearch = null;
|
||||
const head = createTopBar({
|
||||
title: 'Чаты',
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'search',
|
||||
title: 'Найти человека',
|
||||
ariaLabel: 'Найти человека',
|
||||
title: 'Поиск по чатам',
|
||||
ariaLabel: 'Поиск по чатам',
|
||||
className: 'messages-search-btn',
|
||||
onClick: () => openChatsSearch(),
|
||||
},
|
||||
{
|
||||
icon: 'compose',
|
||||
title: 'Новый чат',
|
||||
ariaLabel: 'Новый чат',
|
||||
className: 'messages-compose-btn',
|
||||
onClick: () => navigate('contact-search-view'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function openChatsSearch() {
|
||||
if (chatSearch) return;
|
||||
const bar = createSearchTopBar({
|
||||
placeholder: 'Имя или логин',
|
||||
onInput: (value) => {
|
||||
chatQuery = String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
renderList();
|
||||
},
|
||||
onSubmit: () => list.querySelector('.dm-dialog-card')?.click(),
|
||||
onClose: () => closeChatsSearch(),
|
||||
});
|
||||
chatSearch = { bar, layer: openHistoryLayer(() => closeChatsSearch({ fromHistory: true })) };
|
||||
chrome?.setTopbar(bar);
|
||||
bar.searchInput?.focus();
|
||||
filterRow.hidden = true;
|
||||
}
|
||||
|
||||
function closeChatsSearch({ fromHistory = false } = {}) {
|
||||
if (!chatSearch) return;
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
chatQuery = '';
|
||||
if (!fromHistory) layer?.close();
|
||||
filterRow.hidden = false;
|
||||
if (!disposed) {
|
||||
chrome?.setTopbar(head);
|
||||
renderList();
|
||||
}
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack dm-list';
|
||||
|
||||
@@ -439,10 +480,18 @@ function renderRow(item) {
|
||||
return Boolean(item.hasDialog || item.lastMessageTimeMs > 0 || item.unreadCount > 0 || item.pinned);
|
||||
}
|
||||
|
||||
function matchesChatQuery(item) {
|
||||
const hay = `${item.firstName || ''} ${item.lastName || ''} ${item.peerLogin || ''}`.toLowerCase().replaceAll('ё', 'е');
|
||||
return hay.includes(chatQuery);
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
if (!lastItems) return;
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
const filtered = lastItems.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter);
|
||||
// В поиске – по всем чатам и контактам сразу, без фильтра по типу связи.
|
||||
const filtered = chatQuery
|
||||
? lastItems.filter(matchesChatQuery)
|
||||
: lastItems.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter);
|
||||
// Переписки – по свежести, закреплённые выше всех (последний закреплённый – первым).
|
||||
const chats = filtered.filter(hasConversation).sort((a, b) => {
|
||||
const pinA = a.pinned ? pinnedOrder.indexOf(normalizeDmChatId(a.peerLogin)) : -1;
|
||||
@@ -460,16 +509,34 @@ function renderRow(item) {
|
||||
|| String(a.firstName || a.peerLogin).localeCompare(String(b.firstName || b.peerLogin), 'ru');
|
||||
const silent = filtered
|
||||
.filter((item) => !hasConversation(item) && normalizeRelationFlag(item.relationFlag) !== 'none')
|
||||
.filter((item) => currentChatFilter !== 'all' || ['close_friend', 'friend'].includes(normalizeRelationFlag(item.relationFlag)))
|
||||
.filter((item) => chatQuery || currentChatFilter !== 'all' || ['close_friend', 'friend'].includes(normalizeRelationFlag(item.relationFlag)))
|
||||
.sort(byName);
|
||||
|
||||
list.replaceChildren();
|
||||
if (!chats.length && !silent.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = currentChatFilter === 'all'
|
||||
? 'Пока нет переписок. Найдите человека через поиск вверху.'
|
||||
: 'Здесь пока никого.';
|
||||
if (chatQuery) {
|
||||
empty.textContent = 'Среди ваших чатов и контактов никого не нашлось.';
|
||||
const wide = document.createElement('button');
|
||||
wide.type = 'button';
|
||||
wide.className = 'secondary-btn dm-search-wide';
|
||||
wide.textContent = 'Искать во всей сети';
|
||||
wide.addEventListener('click', () => navigate('contact-search-view'));
|
||||
list.append(empty, wide);
|
||||
return;
|
||||
}
|
||||
if (currentChatFilter === 'all') {
|
||||
list.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: 'Пока нет переписок',
|
||||
text: 'Напишите кому-нибудь из друзей или найдите человека по имени.',
|
||||
actionLabel: 'Новый чат',
|
||||
onAction: () => navigate('contact-search-view'),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
empty.textContent = 'Здесь пока никого.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
@@ -480,7 +547,7 @@ function renderRow(item) {
|
||||
divider.className = 'dm-divider';
|
||||
divider.textContent = chats.length ? `Начать переписку · ${silent.length}` : `Без переписки · ${silent.length}`;
|
||||
frag.append(divider);
|
||||
const collapsed = !startExpanded && silent.length > START_PREVIEW + 1 && chats.length > 0;
|
||||
const collapsed = !chatQuery && !startExpanded && silent.length > START_PREVIEW + 1 && chats.length > 0;
|
||||
(collapsed ? silent.slice(0, START_PREVIEW) : silent).forEach((item) => frag.append(renderRow(item)));
|
||||
if (collapsed) {
|
||||
const more = document.createElement('button');
|
||||
@@ -637,6 +704,11 @@ function renderRow(item) {
|
||||
avatarObserver?.disconnect();
|
||||
visibleWaiters.clear();
|
||||
rowMenu.destroy();
|
||||
if (chatSearch) {
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
layer?.close();
|
||||
}
|
||||
};
|
||||
|
||||
return screen;
|
||||
|
||||
@@ -3,7 +3,9 @@ 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 } from '../services/channels-ux.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;
|
||||
@@ -137,15 +139,15 @@ async function enrichItem(item, activeTab) {
|
||||
}
|
||||
|
||||
function renderEmpty(activeTab) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'stack notification-empty-state';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.';
|
||||
card.append(title, text);
|
||||
return card;
|
||||
return createStateMessage({
|
||||
icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
|
||||
title: activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет новостей о связях' : 'Пока нет ответов',
|
||||
text: activeTab === 'events'
|
||||
? 'Подписки и отписки от ваших каналов появятся здесь.'
|
||||
: activeTab === 'connections'
|
||||
? 'Когда вас добавят в друзья или подтвердят статус, это появится здесь.'
|
||||
: 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.',
|
||||
});
|
||||
}
|
||||
|
||||
function renderAvatar(item) {
|
||||
@@ -280,6 +282,18 @@ function renderItem(item, activeTab, navigate) {
|
||||
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;
|
||||
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;
|
||||
|
||||
@@ -292,10 +306,20 @@ export function render({ navigate, chrome } = {}) {
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
||||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||||
chrome?.setTopbar(createTopBar({
|
||||
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');
|
||||
@@ -317,6 +341,7 @@ export function render({ navigate, chrome } = {}) {
|
||||
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');
|
||||
@@ -366,30 +391,79 @@ export function render({ navigate, chrome } = {}) {
|
||||
}, 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=await Promise.all(base.map(x=>enrichItem(x,tab)));
|
||||
// Список рисуется сразу – с профилями из кэша; остальное догружается в фоне и
|
||||
// обновляет строки на месте (раньше экран ждал загрузки профиля каждого автора).
|
||||
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);nodes.push(n);});
|
||||
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=>nodes.push(renderItem(x,tab,navigate))); list.replaceChildren(...nodes);
|
||||
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(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 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({});
|
||||
else { renderTabs({}); if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю уведомления' })); }
|
||||
try {
|
||||
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
|
||||
const signature = JSON.stringify(fresh);
|
||||
@@ -398,11 +472,21 @@ export function render({ navigate, chrome } = {}) {
|
||||
if (cached?.signature === signature) return;
|
||||
payloadCache=fresh; await renderCurrent();
|
||||
}
|
||||
catch(error){ if(seq!==requestSeq)return; const card=document.createElement('article');card.className='card stack';card.innerHTML='<strong>Не удалось загрузить уведомления</strong>';const t=document.createElement('p');t.className='meta-muted';t.textContent=error?.message||'Ошибка запроса к серверу';card.append(t);list.replaceChildren(card);}
|
||||
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));
|
||||
};
|
||||
|
||||
@@ -4,30 +4,42 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { openShareSheet } from '../components/share-sheet.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'profile-view', title: 'Профиль' };
|
||||
|
||||
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
|
||||
const cardCache = new Map();
|
||||
const STATUS_DELAY_MS = 250;
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || profile.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack user-profile-screen';
|
||||
|
||||
// Ссылка на свой профиль – самое частое «поделиться» в соцсети.
|
||||
const shareProfile = () => {
|
||||
const url = new URL(window.location.href);
|
||||
url.pathname = `/${makeProfileRoute(login)}`;
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
const name = [card?.firstName, card?.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
openShareSheet({ title: 'Поделиться профилем', kicker: name ? `${name} · @${login}` : `@${login}`, text: 'Профиль в Сиянии', url: url.toString() });
|
||||
};
|
||||
const topbar = createTopBar({
|
||||
title: 'Профиль',
|
||||
className: 'topbar--root user-profile-header',
|
||||
actions: [{ icon: 'share', title: 'Поделиться профилем', ariaLabel: 'Поделиться профилем', className: 'profile-share-btn', onClick: shareProfile }],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line user-profile-status';
|
||||
status.className = 'user-profile-status';
|
||||
let card = cardCache.get(login.toLowerCase()) || null;
|
||||
if (!card) {
|
||||
window.setTimeout(() => { if (!card && status.isConnected && !status.textContent) status.textContent = 'Загрузка профиля...'; }, STATUS_DELAY_MS);
|
||||
}
|
||||
// Первый заход – спиннер, но только если профиль грузится заметно долго.
|
||||
if (!card) status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
@@ -59,7 +71,7 @@ export function render({ navigate, chrome }) {
|
||||
official: card.accountRole === 'primary',
|
||||
}));
|
||||
|
||||
status.textContent = '';
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
@@ -100,11 +112,18 @@ export function render({ navigate, chrome }) {
|
||||
|
||||
renderProfile();
|
||||
|
||||
refresh().catch((error) => {
|
||||
const showLoadError = (error) => {
|
||||
if (card) return;
|
||||
status.className = 'status-line user-profile-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
||||
});
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить профиль',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user