Шапки: ниже и с нужными действиями; уведомления и профиль без ожидания

- шапка 52 px вместо 56, заголовок корневых разделов 22 px вместо 24;
- одинаковое «•••» меню во всех шапках (в «Каналах» и ленте канала было «⋮»);
- «Чаты»: лупа – мгновенный поиск по своим чатам и контактам (была – переход на поиск
  человека), «Новый чат» – отдельной кнопкой;
- «Уведомления»: «Прочитать все» в шапке; список рисуется сразу, профили авторов и
  счётчики догружаются в фоне (раньше экран ждал профиль каждого автора); пустые
  вкладки и ошибка – общим видом, ошибка с «Повторить»;
- «Профиль»: «Поделиться профилем» (ссылка), загрузка – спиннер с задержкой вместо
  «Загрузка профиля...», ошибка с «Повторить»;
- лента канала: при наведении (на телефоне – после касания) аватар записи прыгал на текст –
  общий :hover кнопок с filter делал плитку автора контейнером для аватара;
- атрибут hidden снова скрывает переключатели и ряды чипов.
This commit is contained in:
q
2026-10-13 03:43:04 +03:00
parent 8fee7e1a9b
commit 26db18e250
14 changed files with 231 additions and 49 deletions
+1 -1
View File
@@ -1,2 +1,2 @@
client.version=1.19.5 client.version=1.19.6
server.version=1.15.0 server.version=1.15.0
+1 -1
View File
@@ -39,7 +39,7 @@
}()); }());
</script> </script>
<script> <script>
window.__SHINE_BUILD_HASH__ = '20261013033000'; window.__SHINE_BUILD_HASH__ = '20261013040000';
window.__SHINE_CLIENT_VERSION__ = '1.2.10'; window.__SHINE_CLIENT_VERSION__ = '1.2.10';
</script> </script>
<script> <script>
+3 -3
View File
@@ -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 loginPasswordView from './pages/login-password-view.js?v=202606201650';
import * as publicSupportQueueView from './pages/public-support-queue-view.js'; 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 profileEditView from './pages/profile-edit-view.js';
import * as profilesView from './pages/profiles-view.js'; import * as profilesView from './pages/profiles-view.js';
import * as walletView from './pages/wallet-view.js?v=202609260900'; 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 pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
import * as solanaUsersInitView from './pages/solana-users-init-view.js'; import * as solanaUsersInitView from './pages/solana-users-init-view.js';
import * as solanaRpcCheckView from './pages/solana-rpc-check-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 contactSearchView from './pages/contact-search-view.js';
import * as chatView from './pages/chat-view.js?v=202610130200'; import * as chatView from './pages/chat-view.js?v=202610130200';
import * as chatMediaView from './pages/chat-media-view.js'; 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 addChannelView from './pages/add-channel-view.js';
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-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 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 CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается'; const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
+1 -1
View File
@@ -42,7 +42,7 @@ export function openShareSheet({ title = 'Поделиться', kicker = '', te
} catch { } catch {
field.focus(); field.focus();
field.select(); field.select();
showToast('Выделил ссылку – скопируйте её вручную', { kind: 'error' }); showToast('Ссылка выделена – скопируйте её вручную', { kind: 'info' });
} }
}); });
wrap.append(preview, label, copy); wrap.append(preview, label, copy);
+2 -1
View File
@@ -1,6 +1,7 @@
import { appendShineMessageLinks } from '../services/shine-message-links.js'; import { appendShineMessageLinks } from '../services/shine-message-links.js';
import { confirmDialog } from '../components/confirm-dialog.js'; import { confirmDialog } from '../components/confirm-dialog.js';
import { iconHtml } from '../components/ui-icon.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 { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
import { getPreviousTrackedPath, navigateUp, parseRouteFromPath, toPrettyPath } from '../router.js'; import { getPreviousTrackedPath, navigateUp, parseRouteFromPath, toPrettyPath } from '../router.js';
import { prefetchThreadPage, threadTotalReplies } from './channel-thread-view.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', className: 'channel-view-topbar topbar--identity',
actions: [ actions: [
{ {
icon: 'moreVertical', iconNode: createOverflowDots(),
title: 'Действия канала', title: 'Действия канала',
ariaLabel: 'Открыть меню канала', ariaLabel: 'Открыть меню канала',
className: 'channel-header-more-btn', className: 'channel-header-more-btn',
+1 -1
View File
@@ -1077,7 +1077,7 @@ export function render({ navigate, route, chrome }) {
className: 'topbar--root', className: 'topbar--root',
actions: [ actions: [
{ {
icon: 'moreVertical', iconNode: createOverflowDots(),
title: 'Меню каналов', title: 'Меню каналов',
ariaLabel: 'Открыть меню каналов', ariaLabel: 'Открыть меню каналов',
className: 'channels-menu-btn', className: 'channels-menu-btn',
+82 -10
View File
@@ -9,7 +9,7 @@ import {
terminateCurrentSession, terminateCurrentSession,
} from '../state.js'; } from '../state.js';
import { renderUserAvatar } from '../components/avatar-image.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 { createDropdownMenu } from '../components/dropdown-menu.js';
import { iconHtml } from '../components/ui-icon.js'; import { iconHtml } from '../components/ui-icon.js';
import { import {
@@ -23,7 +23,8 @@ import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js'; import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
import { formatListTime } from '../services/channels-ux.js'; import { formatListTime } from '../services/channels-ux.js';
import { toUserMessage } from '../services/ui-error-texts.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: 'Личные сообщения' }; export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
const PREVIEW_MAX_LEN = 200; const PREVIEW_MAX_LEN = 200;
@@ -258,20 +259,60 @@ export function render({ navigate, chrome }) {
event.preventDefault(); event.preventDefault();
}); });
// Шапка: поиск по своим чатам и контактам (мгновенно, на устройстве) и «Новый чат».
let chatQuery = '';
let chatSearch = null;
const head = createTopBar({ const head = createTopBar({
title: 'Чаты', title: 'Чаты',
className: 'topbar--root', className: 'topbar--root',
actions: [ actions: [
{ {
icon: 'search', icon: 'search',
title: 'Найти человека', title: 'Поиск по чатам',
ariaLabel: 'Найти человека', ariaLabel: 'Поиск по чатам',
className: 'messages-search-btn', className: 'messages-search-btn',
onClick: () => openChatsSearch(),
},
{
icon: 'compose',
title: 'Новый чат',
ariaLabel: 'Новый чат',
className: 'messages-compose-btn',
onClick: () => navigate('contact-search-view'), 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'); const list = document.createElement('div');
list.className = 'stack dm-list'; list.className = 'stack dm-list';
@@ -439,10 +480,18 @@ function renderRow(item) {
return Boolean(item.hasDialog || item.lastMessageTimeMs > 0 || item.unreadCount > 0 || item.pinned); 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() { function renderList() {
if (!lastItems) return; if (!lastItems) return;
const pinnedOrder = getPinnedDmChats(); 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 chats = filtered.filter(hasConversation).sort((a, b) => {
const pinA = a.pinned ? pinnedOrder.indexOf(normalizeDmChatId(a.peerLogin)) : -1; 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'); || String(a.firstName || a.peerLogin).localeCompare(String(b.firstName || b.peerLogin), 'ru');
const silent = filtered const silent = filtered
.filter((item) => !hasConversation(item) && normalizeRelationFlag(item.relationFlag) !== 'none') .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); .sort(byName);
list.replaceChildren(); list.replaceChildren();
if (!chats.length && !silent.length) { if (!chats.length && !silent.length) {
const empty = document.createElement('div'); const empty = document.createElement('div');
empty.className = 'empty-note'; 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); list.append(empty);
return; return;
} }
@@ -480,7 +547,7 @@ function renderRow(item) {
divider.className = 'dm-divider'; divider.className = 'dm-divider';
divider.textContent = chats.length ? `Начать переписку · ${silent.length}` : `Без переписки · ${silent.length}`; divider.textContent = chats.length ? `Начать переписку · ${silent.length}` : `Без переписки · ${silent.length}`;
frag.append(divider); 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))); (collapsed ? silent.slice(0, START_PREVIEW) : silent).forEach((item) => frag.append(renderRow(item)));
if (collapsed) { if (collapsed) {
const more = document.createElement('button'); const more = document.createElement('button');
@@ -637,6 +704,11 @@ function renderRow(item) {
avatarObserver?.disconnect(); avatarObserver?.disconnect();
visibleWaiters.clear(); visibleWaiters.clear();
rowMenu.destroy(); rowMenu.destroy();
if (chatSearch) {
const { layer } = chatSearch;
chatSearch = null;
layer?.close();
}
}; };
return screen; return screen;
+101 -17
View File
@@ -3,7 +3,9 @@ import { renderUserAvatar } from '../components/avatar-image.js';
import { authService, state } from '../state.js'; import { authService, state } from '../state.js';
import { loadProfileSnapshot } from '../services/user-profile-params.js'; import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.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'; import { iconHtml } from '../components/ui-icon.js';
const CONNECTION_CLOSE_FRIEND = 10; const CONNECTION_CLOSE_FRIEND = 10;
@@ -137,15 +139,15 @@ async function enrichItem(item, activeTab) {
} }
function renderEmpty(activeTab) { function renderEmpty(activeTab) {
const card = document.createElement('article'); return createStateMessage({
card.className = 'stack notification-empty-state'; icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
const title = document.createElement('strong'); title: activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет новостей о связях' : 'Пока нет ответов',
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов'; text: activeTab === 'events'
const text = document.createElement('p'); ? 'Подписки и отписки от ваших каналов появятся здесь.'
text.className = 'meta-muted'; : activeTab === 'connections'
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.'; ? 'Когда вас добавят в друзья или подтвердят статус, это появится здесь.'
card.append(title, text); : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.',
return card; });
} }
function renderAvatar(item) { function renderAvatar(item) {
@@ -280,6 +282,18 @@ function renderItem(item, activeTab, navigate) {
return row; 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; let lastNotifications = null;
@@ -292,10 +306,20 @@ export function render({ navigate, chrome } = {}) {
tabs.setAttribute('role', 'radiogroup'); tabs.setAttribute('role', 'radiogroup');
tabs.setAttribute('aria-label', 'Категория уведомлений'); tabs.setAttribute('aria-label', 'Категория уведомлений');
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']]; const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
chrome?.setTopbar(createTopBar({ const topbar = createTopBar({
title: 'Уведомления', title: 'Уведомления',
className: 'topbar--root notifications-topbar', 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); screen.append(tabs);
const list = document.createElement('div'); const list = document.createElement('div');
@@ -317,6 +341,7 @@ export function render({ navigate, chrome } = {}) {
function updateToolbarBadge(payload) { function updateToolbarBadge(payload) {
const c = countsFromPayload(payload); const c = countsFromPayload(payload);
state.notificationUnreadTotal = c.replies + c.connections + c.events; state.notificationUnreadTotal = c.replies + c.connections + c.events;
if (readAllBtn) readAllBtn.disabled = state.notificationUnreadTotal <= 0;
const btn = document.querySelector('[data-toolbar-page="notifications-view"]'); const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
if (!btn) return; if (!btn) return;
let badge = btn.querySelector('.notification-toolbar-badge'); let badge = btn.querySelector('.notification-toolbar-badge');
@@ -366,30 +391,79 @@ export function render({ navigate, chrome } = {}) {
}, 350); }, 350);
} }
let renderSeq = 0;
async function renderCurrent() { async function renderCurrent() {
const seq = ++renderSeq;
observer?.disconnect(); observer=null; renderTabs(payloadCache || {}); 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 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 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 unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
const nodes=[]; const nodes=[];
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;}; 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}`)); 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('Ранее')); 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){ 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]}); 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)); 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() { async function load() {
const seq=++requestSeq; const seq=++requestSeq;
const login = state.session.login; const login = state.session.login;
const cached = lastNotifications?.login === login ? lastNotifications : null; const cached = lastNotifications?.login === login ? lastNotifications : null;
if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); } if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); }
else renderTabs({}); else { renderTabs({}); if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю уведомления' })); }
try { try {
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return; const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
const signature = JSON.stringify(fresh); const signature = JSON.stringify(fresh);
@@ -398,11 +472,21 @@ export function render({ navigate, chrome } = {}) {
if (cached?.signature === signature) return; if (cached?.signature === signature) return;
payloadCache=fresh; await renderCurrent(); 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'; if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
screen.cleanup = () => { screen.cleanup = () => {
renderSeq += 1; // фоновая догрузка профилей больше не трогает экран
requestSeq += 1;
observer?.disconnect(); observer?.disconnect();
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer)); Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
}; };
+29 -10
View File
@@ -4,30 +4,42 @@ import { renderUserAvatar } from '../components/avatar-image.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { loadUserProfileCard } from '../services/user-connections.js'; import { loadUserProfileCard } from '../services/user-connections.js';
import { profileCardHtml, profileTileHtml } from '../components/profile-card.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: 'Профиль' }; export const pageMeta = { id: 'profile-view', title: 'Профиль' };
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем. // Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
const cardCache = new Map(); const cardCache = new Map();
const STATUS_DELAY_MS = 250;
export function render({ navigate, chrome }) { export function render({ navigate, chrome }) {
const login = String(state.session.login || profile.login || '').trim(); const login = String(state.session.login || profile.login || '').trim();
const screen = document.createElement('section'); const screen = document.createElement('section');
screen.className = 'stack user-profile-screen'; 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({ const topbar = createTopBar({
title: 'Профиль', title: 'Профиль',
className: 'topbar--root user-profile-header', className: 'topbar--root user-profile-header',
actions: [{ icon: 'share', title: 'Поделиться профилем', ariaLabel: 'Поделиться профилем', className: 'profile-share-btn', onClick: shareProfile }],
}); });
chrome?.setTopbar(topbar); chrome?.setTopbar(topbar);
const status = document.createElement('div'); const status = document.createElement('div');
status.className = 'status-line user-profile-status'; status.className = 'user-profile-status';
let card = cardCache.get(login.toLowerCase()) || null; 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'); const body = document.createElement('div');
body.className = 'user-profile-body'; body.className = 'user-profile-body';
@@ -59,7 +71,7 @@ export function render({ navigate, chrome }) {
official: card.accountRole === 'primary', official: card.accountRole === 'primary',
})); }));
status.textContent = ''; status.replaceChildren();
} }
body.addEventListener('click', (event) => { body.addEventListener('click', (event) => {
@@ -100,11 +112,18 @@ export function render({ navigate, chrome }) {
renderProfile(); renderProfile();
refresh().catch((error) => { const showLoadError = (error) => {
if (card) return; if (card) return;
status.className = 'status-line user-profile-status is-unavailable'; status.replaceChildren(createErrorState({
status.textContent = `Ошибка: ${error?.message || 'unknown'}`; title: 'Не удалось загрузить профиль',
}); text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
onRetry: () => {
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
refresh().catch(showLoadError);
},
}));
};
refresh().catch(showLoadError);
return screen; return screen;
} }
+1
View File
@@ -9,6 +9,7 @@
-webkit-overflow-scrolling: touch; -webkit-overflow-scrolling: touch;
} }
.chip-row::-webkit-scrollbar { display: none; } .chip-row::-webkit-scrollbar { display: none; }
.chip-row[hidden] { display: none; }
.chip, .chip,
.fg-filter-chip { .fg-filter-chip {
+1
View File
@@ -12,6 +12,7 @@
padding: 4px; padding: 4px;
background: var(--surface); background: var(--surface);
} }
.tabs[hidden] { display: none; }
.tabs--three { grid-template-columns: repeat(3, minmax(0, 1fr)); } .tabs--three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.tabs--auto { grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); } .tabs--auto { grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); }
/* Много коротких пунктов (4–5) в одну полосу: мельче шрифт и поля. */ /* Много коротких пунктов (4–5) в одну полосу: мельче шрифт и поля. */
+3 -3
View File
@@ -1,5 +1,5 @@
:root { --app-topbar-base-height: 56px; --app-topbar-title-size: 1.0625rem; --app-topbar-bg: var(--background); --app-topbar-fg: var(--text-primary); --app-topbar-gold: var(--text-primary); --app-topbar-blue-glow: transparent; --app-topbar-blue-glow-soft: transparent; } :root { --app-topbar-base-height: 52px; --app-topbar-title-size: 1.0625rem; --app-topbar-bg: var(--background); --app-topbar-fg: var(--text-primary); --app-topbar-gold: var(--text-primary); --app-topbar-blue-glow: transparent; --app-topbar-blue-glow-soft: transparent; }
.topbar { width: 100%; min-height: calc(56px + env(safe-area-inset-top)); padding: env(safe-area-inset-top) 0 0; display: grid; grid-template-columns: minmax(44px, 1fr) minmax(0, auto) minmax(44px, 1fr); align-items: center; gap: 4px; background: var(--surface); border-bottom: 1px solid var(--border-subtle); } .topbar { width: 100%; min-height: calc(var(--app-topbar-base-height) + env(safe-area-inset-top)); padding: env(safe-area-inset-top) 0 0; display: grid; grid-template-columns: minmax(44px, 1fr) minmax(0, auto) minmax(44px, 1fr); align-items: center; gap: 4px; background: var(--surface); border-bottom: 1px solid var(--border-subtle); }
.topbar__left, .topbar__center, .topbar__right { display: flex; min-width: 0; align-items: center; } .topbar__left, .topbar__center, .topbar__right { display: flex; min-width: 0; align-items: center; }
.topbar__center { justify-content: center; } .topbar__center { justify-content: center; }
.topbar__right { justify-content: flex-end; } .topbar__right { justify-content: flex-end; }
@@ -16,7 +16,7 @@
.topbar__back svg { width: 24px; height: 24px; stroke-width: 2.2; } .topbar__back svg { width: 24px; height: 24px; stroke-width: 2.2; }
.topbar__action svg { width: 22px; height: 22px; } .topbar__action svg { width: 22px; height: 22px; }
/* Корневые разделы (Чаты, Каналы, Связи, Уведомления, Профиль) – заголовок по центру, как на всех экранах, но крупнее. */ /* Корневые разделы (Чаты, Каналы, Связи, Уведомления, Профиль) – заголовок по центру, как на всех экранах, но крупнее. */
.topbar--root .topbar__title { font-size: 1.5rem; line-height: 1.875rem; font-weight: 700; } .topbar--root .topbar__title { font-size: 1.375rem; line-height: 1.75rem; font-weight: 700; letter-spacing: -0.01em; }
/* Шапка-визитка: аватар и две строки слева (канал, собеседник) */ /* Шапка-визитка: аватар и две строки слева (канал, собеседник) */
.topbar--identity { grid-template-columns: auto minmax(0, 1fr) auto; } .topbar--identity { grid-template-columns: auto minmax(0, 1fr) auto; }
@@ -119,6 +119,10 @@
.channel-message-card--threads .channel-message-head-row { flex-wrap: nowrap; min-height: 22px; } .channel-message-card--threads .channel-message-head-row { flex-wrap: nowrap; min-height: 22px; }
.channel-message-card--threads .channel-message-author-tile { gap: 0; min-height: 22px; } .channel-message-card--threads .channel-message-author-tile { gap: 0; min-height: 22px; }
.channel-message-card--threads .avatar.channel-message-avatar { position: absolute; top: 14px; left: 0; } .channel-message-card--threads .avatar.channel-message-avatar { position: absolute; top: 14px; left: 0; }
/* Общий :hover кнопок – filter: brightness(); фильтр делает плитку автора контейнером для
абсолютного аватара, и при наведении (на телефоне – после касания) аватар прыгал на текст. */
.channel-message-card--threads .channel-message-author-tile:is(:hover, :active) { filter: none; }
.channel-message-card--threads .channel-message-author-tile:hover .author-line-login { color: var(--accent); }
.channel-message-card--threads .avatar.channel-profile-avatar { width: 36px; height: 36px; min-width: 36px; min-height: 36px; border-radius: 10px; font-size: 15px; } .channel-message-card--threads .avatar.channel-profile-avatar { width: 36px; height: 36px; min-width: 36px; min-height: 36px; border-radius: 10px; font-size: 15px; }
.channel-message-card--threads .author-line-login { font-size: .9375rem; } .channel-message-card--threads .author-line-login { font-size: .9375rem; }
.channel-message-card--threads .channel-message-author .channel-message-time::before { content: none; } .channel-message-card--threads .channel-message-author .channel-message-time::before { content: none; }
+1 -1
View File
@@ -1276,6 +1276,6 @@
text-underline-offset: 3px; text-underline-offset: 3px;
} }
.screen-content.preauth-flow:not(:has(> .auth-screen--welcome)) .topbar { min-height: 56px; margin-bottom: calc(var(--page-top-gap) - 10px); /* + промежуток .stack 10px */ grid-template-columns: 44px minmax(0, 1fr) 44px; } .screen-content.preauth-flow:not(:has(> .auth-screen--welcome)) .topbar { min-height: var(--app-topbar-base-height, 52px); margin-bottom: calc(var(--page-top-gap) - 10px); /* + промежуток .stack 10px */ grid-template-columns: 44px minmax(0, 1fr) 44px; }