Files
SHiNE-server/shine-UI/js/pages/channels-list.js
T

829 lines
34 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { t, th } from '../i18n/index.js';
import { iconHtml } from '../components/ui-icon.js';
import { channels as mockChannels } from '../mock-data.js';
import { authService, setChannelsFeed, state } from '../state.js';
import { toUserMessage } from '../services/ui-error-texts.js';
import { parseMessageAttachments } from '../services/attachment-format.js';
import {
animatePress,
createLoadErrorCard,
createSkeletonRows,
SKELETON_DELAY_MS,
formatListTime,
readChannelNotificationsState,
showToast,
softHaptic,
writeChannelNotificationsState,
} from '../services/channels-ux.js';
import { formatChannelAddress, makeShineChannelRoute, makeShineChannelShortRoute } from '../services/shine-routes.js';
import { renderAvatar } from '../components/avatar-image.js';
import { createTopBar } from '../components/topbar.js';
import { createTopBarFilterTitle } from '../components/topbar-filter-title.js';
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
import { pageDataAge } from '../services/page-data-cache.js';
import { toPrettyPath } from '../router.js';
import { prefetchChannelPage } from './channel-view.js';
export const pageMeta = { id: 'channels-list', get title() { return t('screens.channels_list.text_001'); }, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
const CREATE_CHANNEL_FLASH_KEY = 'shine-channels-create-success';
const CHANNEL_TYPE_STORIES = 0;
const CHANNEL_TYPE_PERSONAL = 100;
const DIARY_CHANNEL_NAME = 'diary';
const DIARY_DISPLAY_NAME = () => t('remaining.channels.diary_display_name');
const CHANNELS_VIEW_ALL = 'all';
const CHANNELS_VIEW_OWNED = 'owned';
const CHANNELS_VIEW_FOLLOWING = 'following';
const CHANNELS_VIEW_DELETED = 'deleted';
const listQueries = new Map();
function channelMenuIcon(name) {
const paths = {
search: '<circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4"/>',
add: '<path d="M12 5v14M5 12h14"/>',
all: '<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><rect x="14" y="14" width="6" height="6" rx="1"/>',
mine: '<circle cx="12" cy="8" r="4"/><path d="M5 21a7 7 0 0 1 14 0"/>',
following: '<path d="M12 21s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 11c0 5.6-7 10-7 10Z"/>',
subscribe: '<path d="M12 3a6 6 0 0 0-6 6c0 7-3 7-3 9h18c0-2-3-2-3-9a6 6 0 0 0-6-6Z"/><path d="M10 21h4"/>',
notifications: '<path d="M12 3a6 6 0 0 0-6 6c0 7-3 7-3 9h18c0-2-3-2-3-9a6 6 0 0 0-6-6Z"/><path d="M10 21h4"/>',
};
return `<svg class="channel-menu-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] || ''}</svg>`;
}
function cleanChannelMessagePreview(text) {
const parsed = parseMessageAttachments(text);
const dmParsed = parseDmTechBlocks(String(parsed.text || ''));
return String(dmParsed.displayText || dmParsed.visibleText || '').trim()
|| (parsed.attachments.length ? t('screens.channels_list.text_009') : t('screens.channels_list.text_010'));
}
// Keep the channel-list preview tolerant to small API naming changes. The current
// server uses lastMessage.text/createdAtMs; legacy/alternate payloads are accepted
// so the third line (last message + time) does not silently disappear.
function resolveChannelLastMessage(summary) {
const row = summary?.lastMessage || summary?.latestMessage || summary?.last_message || null;
if (!row || typeof row !== 'object') return { text: '', createdAtMs: 0 };
return {
text: String(row.text ?? row.messageText ?? row.preview ?? row.body ?? '').trim(),
createdAtMs: Number(row.createdAtMs ?? row.timeMs ?? row.created_at_ms ?? 0),
};
}
function isChannelsDemoMode() {
try {
const qs = new URLSearchParams(window.location.search);
if (qs.get('channelsDemo') === '1') return true;
return localStorage.getItem('shine-channels-demo') === '1';
} catch {
return false;
}
}
function normalizeHash(hash) {
const normalized = String(hash || '').trim().toLowerCase();
return normalized || '0';
}
function buildChannelRouteFromSummary(summary, fallbackId) {
const ownerBch = String(summary?.channel?.ownerBlockchainName || '').trim();
const ownerLogin = String(summary?.channel?.ownerLogin || '').trim();
const channelName = String(summary?.channel?.channelName || '').trim();
return makeShineChannelShortRoute({
ownerLogin,
ownerBlockchainName: ownerBch,
channelName: channelName || fallbackId || ownerLogin,
});
}
function isStoriesChannel(summaryOrChannel = null) {
const typeCode = Number(summaryOrChannel?.channel?.channelTypeCode ?? summaryOrChannel?.channelTypeCode ?? 1);
return typeCode === CHANNEL_TYPE_STORIES;
}
function isVisibleChannelSummary(summary) {
if (!summary?.channel) return false;
if (summary?.channel?.deleted) return false;
if (!isStoriesChannel(summary) && String(summary.channel.channelName || '').toLowerCase() === 'stories') return false;
const ownerLogin = String(summary.channel.ownerLogin || '').trim();
const channelName = String(summary.channel.channelName || '').trim();
return !!ownerLogin && !!channelName;
}
function avatarLetterFromName(name = '') {
const first = Array.from(String(name || '').trim())[0] || '#';
return first.toUpperCase();
}
function createChannelAvatar(channel = {}) {
return renderAvatar({
initials: channel.avatar || channel.initials || avatarLetterFromName(channel.displayTitle || channel.title || channel.name),
avatar: (channel.avaAr || channel.avaPr) ? { ar: String(channel.avaAr || '').trim(), pr: String(channel.avaPr || '').trim() } : null,
authorLogin: String(channel.ownerName || channel.ownerLogin || '').trim(),
size: 'lg',
className: 'avatar-plain',
title: channel.displayTitle || channel.title || channel.name || t('screens.channels_list.text_027'),
alt: t('screens.channels_list.text_002'),
});
}
function normalizeChannelsViewMode(route = null) {
const mode = String(route?.params?.mode || '').trim().toLowerCase();
const scope = String(route?.params?.scope || '').trim().toLowerCase();
if (mode === 'my' || scope === 'owned') return CHANNELS_VIEW_OWNED;
if (mode === 'following' || scope === 'following') return CHANNELS_VIEW_FOLLOWING;
if (mode === 'deleted' || scope === 'deleted') return CHANNELS_VIEW_DELETED;
return CHANNELS_VIEW_ALL;
}
function buildChannelsViewRoute(mode) {
if (mode === CHANNELS_VIEW_OWNED) return 'channels/my';
if (mode === CHANNELS_VIEW_FOLLOWING) return 'channels/following';
if (mode === CHANNELS_VIEW_DELETED) return 'channels/deleted';
return 'channels';
}
const CHANNEL_FILTERS = () => [
[CHANNELS_VIEW_ALL, t('screens.channels_list.text_042')],
[CHANNELS_VIEW_FOLLOWING, t('screens.channels_list.text_043')],
[CHANNELS_VIEW_OWNED, t('screens.channels_list.text_044')],
[CHANNELS_VIEW_DELETED, t('screens.channels_list.text_045')],
];
function mapMockGroups() {
const mapRow = (channel) => ({
...channel,
sourceBucket: channel.kind === 'subscribed'
? 'followedChannels'
: channel.kind === 'followed-user-channel'
? 'followedUsers'
: 'own',
route: makeShineChannelRoute({
ownerLogin: String(channel.ownerName || 'channel'),
ownerBlockchainName: String(channel.ownerName || ''),
channelName: String(channel.channelName || channel.title || channel.id),
}),
messagePreview: cleanChannelMessagePreview(channel.lastMessage),
isSubscribed: channel.kind !== 'own' && channel.kind !== 'own-personal',
isOwnChannel: channel.kind === 'own' || channel.kind === 'own-personal',
notificationsEnabled: false,
messagesCount: Number(channel.messagesCount || 0),
unreadCount: 0,
lastMessageAt: 0,
ownerName: String(channel.ownerName || t('screens.channels_list.text_034')),
channelName: String(channel.channelName || channel.title || ''),
title: String(channel.title || channel.channelName || ''),
});
const ownChannels = mockChannels
.filter((channel) => channel.kind === 'own-personal' || channel.kind === 'own')
.map((item) => mapRow(item))
.filter((item) => !isStoriesChannel(item));
const followedUserChannels = mockChannels
.filter((channel) => channel.kind === 'followed-user-channel')
.map((item) => mapRow(item))
.filter((item) => !isStoriesChannel(item));
const subscribedChannels = mockChannels
.filter((channel) => channel.kind === 'subscribed')
.map((item) => mapRow(item))
.filter((item) => !isStoriesChannel(item));
return { ownChannels, followedUserChannels, subscribedChannels, index: {} };
}
function mapApiChannelRow(summary, bucketKey, idx, index, notificationsState) {
const rowId = isStoriesChannel(summary) ? `${bucketKey}-publications-${String(summary?.channel?.ownerLogin || '').toLowerCase()}` : `${bucketKey}-${idx}`;
index[rowId] = summary;
const ownerLogin = summary?.channel?.ownerLogin || t('screens.channels_list.text_035');
const channelName = summary?.channel?.channelName || t('screens.channels_list.text_036');
const displayTitle = isStoriesChannel(summary) && bucketKey === 'own' ? t('remaining.channels.my_publications') : String(summary?.channel?.displayName || channelName).trim();
const channelDescription = String(summary?.channel?.channelDescription || '').trim();
const channelTypeCode = Number(summary?.channel?.channelTypeCode ?? 1);
const channelTypeVersion = Number(summary?.channel?.channelTypeVersion ?? 1);
const isOwn = bucketKey === 'own';
const title = displayTitle || channelName;
const technicalLabel = formatChannelAddress({ ownerLogin, channelName, channelRootBlockNumber: Number(summary?.channel?.channelRoot?.blockNumber) });
const lastMessage = resolveChannelLastMessage(summary);
return {
id: rowId,
sourceBucket: bucketKey,
route: buildChannelRouteFromSummary(summary, rowId),
ownerName: ownerLogin,
ownerBlockchainName: summary?.channel?.ownerBlockchainName || '',
channelRootBlockNumber: Number(summary?.channel?.channelRoot?.blockNumber),
channelRootBlockHash: normalizeHash(summary?.channel?.channelRoot?.blockHash),
avatar: avatarLetterFromName(displayTitle || channelName),
avaAr: String(summary?.channel?.avaAr || '').trim(),
avaPr: String(summary?.channel?.avaPr || '').trim(),
title,
technicalLabel,
channelName,
displayTitle,
channelDescription,
channelTypeCode,
channelTypeVersion,
messagePreview: cleanChannelMessagePreview(lastMessage.text),
messagesCount: Number(summary?.messagesCount || 0),
unreadCount: Number(summary?.unreadCount || 0),
lastMessageAt: Number(lastMessage.createdAtMs || summary?.channel?.metaUpdatedAtMs || 0),
isOwnChannel: isOwn,
isSubscribed: !isOwn,
notificationsEnabled: notificationsState[rowId] === true,
pending: false,
};
}
function mapDeletedOwnedChannels(payload, notificationsState = {}) {
const rows = Array.isArray(payload?.channels) ? payload.channels : [];
return rows.filter((item) => item?.deleted === true).map((item, idx) => {
const rowId = `own-deleted-${idx}`;
const ownerLogin = String(item?.ownerLogin || state.session.login || '').trim();
const channelName = String(item?.slug || '').trim();
const displayTitle = String(item?.displayName || channelName || t('screens.channels_list.text_037')).trim();
return {
id: rowId,
sourceBucket: 'ownDeleted',
route: makeShineChannelShortRoute({
ownerLogin,
ownerBlockchainName: String(item?.ownerBlockchainName || '').trim(),
channelName,
}),
ownerName: ownerLogin,
ownerBlockchainName: String(item?.ownerBlockchainName || '').trim(),
channelRootBlockNumber: Number(item?.rootBlockNumber),
channelRootBlockHash: normalizeHash(item?.rootBlockHashHex),
avatar: avatarLetterFromName(displayTitle),
avaAr: String(item?.avatarAr || '').trim(),
avaPr: String(item?.avatarPr || '').trim(),
title: displayTitle,
technicalLabel: formatChannelAddress({ ownerLogin, channelName }),
channelName,
displayTitle,
channelDescription: '',
channelTypeCode: 1,
channelTypeVersion: 1,
messagePreview: t('screens.channels_list.text_011'),
messagesCount: 0,
unreadCount: 0,
lastMessageAt: Number(item?.deletedAtMs || 0),
isOwnChannel: true,
isDeleted: true,
isSubscribed: false,
notificationsEnabled: notificationsState[rowId] === true,
pending: false,
};
});
}
function pullCreateSuccessFlash() {
try {
const value = String(sessionStorage.getItem(CREATE_CHANNEL_FLASH_KEY) || '').trim();
if (value) sessionStorage.removeItem(CREATE_CHANNEL_FLASH_KEY);
return value;
} catch {
return '';
}
}
function buildDiaryChannelRow(diaryPayload, ownRows = [], notificationsState = {}, index = {}) {
const messages = Array.isArray(diaryPayload?.messages) ? diaryPayload.messages : [];
if (!messages.length) return null;
const ownerBlockchainName = String(
diaryPayload?.channel?.ownerBlockchainName
|| ownRows[0]?.channel?.ownerBlockchainName
|| ''
).trim();
if (!ownerBlockchainName) return null;
const ownerLogin = String(diaryPayload?.channel?.ownerLogin || state.session.login || '').trim();
const lastMessage = messages[messages.length - 1] || null;
const rowId = 'own-diary';
index[rowId] = { diary: true, payload: diaryPayload };
return {
id: rowId,
sourceBucket: 'own',
route: makeShineChannelRoute({
ownerLogin,
ownerBlockchainName,
channelName: DIARY_CHANNEL_NAME,
}),
ownerName: ownerLogin || t('screens.channels_list.text_038'),
ownerBlockchainName,
channelRootBlockNumber: 0,
channelRootBlockHash: '0',
avatar: t('screens.channels_list.text_012'),
avaAr: '',
title: DIARY_DISPLAY_NAME(),
technicalLabel: t('screens.channels_list.text_013'),
channelName: DIARY_CHANNEL_NAME,
displayTitle: DIARY_DISPLAY_NAME(),
channelDescription: t('screens.channels_list.text_014'),
channelTypeCode: 900,
channelTypeVersion: 1,
messagePreview: String(lastMessage?.text || '').trim()
? cleanChannelMessagePreview(lastMessage?.text)
: t('screens.channels_list.text_015'),
messagesCount: messages.length,
unreadCount: 0,
lastMessageAt: Number(lastMessage?.createdAtMs || 0),
isOwnChannel: true,
isSubscribed: false,
notificationsEnabled: notificationsState[rowId] === true,
pending: false,
};
}
function mapApiFeed(feed, notificationsState, diaryPayload = null) {
const index = {};
const ownRows = (feed?.ownedChannels || []).filter(isVisibleChannelSummary);
const ownChannels = [
...ownRows.filter(isStoriesChannel).map(it => mapApiChannelRow(it, 'own', 0, index, notificationsState)),
...ownRows.filter(it => !isStoriesChannel(it)).map((it, idx) => mapApiChannelRow(it, 'own', idx, index, notificationsState)),
];
const diaryChannel = diaryPayload
? buildDiaryChannelRow(diaryPayload, feed?.ownedChannels || [], notificationsState, index)
: null;
if (diaryChannel) ownChannels.splice(ownChannels[0]?.channelTypeCode === 0 ? 1 : 0, 0, diaryChannel);
const seenRoots = new Set();
const followedUserChannels = (feed?.followedUsersChannels || [])
.filter(isVisibleChannelSummary)
.filter(it => { const key = String(it.channel.ownerLogin).toLowerCase(); if (seenRoots.has(key)) return false; seenRoots.add(key); return true; })
.map((it, idx) => mapApiChannelRow(it, 'followedUsers', idx, index, notificationsState));
const subscribedChannels = (feed?.followedChannels || [])
.filter(isVisibleChannelSummary)
.map((it, idx) => mapApiChannelRow(it, 'followedChannels', idx, index, notificationsState));
return { ownChannels, followedUserChannels, subscribedChannels, index };
}
const PREFETCH_CHANNELS = 6;
const PREFETCH_FRESH_MS = 50_000;
// Фоновое обновление ленты каналов и самых активных каналов: экран «Каналы» и сами каналы
// открываются сразу из памяти. Запросы идут по одному, чтобы не нагружать сервер.
export async function refreshChannelsInBackground({ isCurrent = () => true } = {}) {
if (!state.session.isAuthorized || state.session.isLocalDemo) return;
const login = state.session.login;
const feed = await authService.listSubscriptionsFeed(login, 200);
if (!isCurrent() || state.session.login !== login) return;
const groups = mapApiFeed(feed, {}, null);
setChannelsFeed(feed, groups.index);
const routes = toListModel(groups)
.filter((row) => row.route)
.sort((a, b) => Number(b.lastMessageAt || 0) - Number(a.lastMessageAt || 0))
.slice(0, PREFETCH_CHANNELS)
.map((row) => `/${toPrettyPath(row.route)}`);
for (const route of routes) {
if (!isCurrent() || state.session.login !== login) return;
const pathname = new URL(route, window.location.origin).pathname;
if (pathname === window.location.pathname || pageDataAge('channel', pathname) < PREFETCH_FRESH_MS) continue;
try {
await prefetchChannelPage(pathname);
} catch {
// Фоновая подгрузка не должна мешать: канал загрузится обычным путём при открытии.
}
}
}
function toListModel(groups) {
return [
...(groups.ownChannels || []),
...(groups.followedUserChannels || []),
...(groups.subscribedChannels || []),
];
}
function renderEmptyState(listState, navigate) {
const wrap = document.createElement('div');
wrap.className = 'channels-empty-state channels-empty-state--compact channels-empty-state--silent';
const heading = document.createElement('strong');
heading.textContent = listState.query ? t('dialogs.modals.channels_list.label_006') : listState.viewMode === CHANNELS_VIEW_DELETED ? t('screens.channels_list.text_016') : listState.viewMode === CHANNELS_VIEW_FOLLOWING ? t('screens.channels_list.text_017') : listState.viewMode === CHANNELS_VIEW_OWNED ? t('screens.channels_list.text_018') : t('screens.channels_list.text_019');
const text = document.createElement('p');
text.className = 'meta-muted';
text.textContent = listState.viewMode === CHANNELS_VIEW_DELETED ? t('dialogs.modals.channels_list.label_007') : state.session.isAuthorized ? t('screens.channels_list.text_020') : t('screens.channels_list.text_021');
const action = document.createElement('button');
action.type = 'button';
action.className = 'primary-btn';
action.textContent = t('dialogs.modals.channels_list.label_008');
action.addEventListener('click', () => navigate('search-view'));
wrap.append(heading, text, action);
return wrap;
}
function renderSkeletonList(container, count = 4) {
container.replaceChildren(createSkeletonRows('list', count));
}
function renderErrorState(container, error, onRetry) {
container.append(createLoadErrorCard({
title: t('screens.channels_list.text_003'),
message: toUserMessage(error, t('screens.channels_list.text_007')),
onRetry,
}));
}
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
const info = document.createElement('div');
info.className = 'card stack';
info.innerHTML = `
<strong>${localOnly ? t('screens.channels_list.text_022') : t('screens.channels_list.text_023')}</strong>
<p class="meta-muted">${localOnly
? t('screens.channels_list.text_024')
: t('screens.channels_list.text_025')}</p>
${localOnly ? '' : `<p class="meta-muted">${toUserMessage(error, t('screens.channels_list.text_008'))}</p>`}
`;
if (!localOnly && typeof onRetry === 'function') {
const retry = document.createElement('button');
retry.className = 'secondary-btn';
retry.type = 'button';
retry.textContent = t('dialogs.modals.channels_list.label_009');
retry.addEventListener('click', onRetry);
info.append(retry);
}
container.append(info);
const groups = mapMockGroups();
const list = document.createElement('div');
list.className = 'stack';
toListModel(groups).forEach((channel) => {
const row = document.createElement('article');
row.className = 'channel-row';
row.innerHTML = `
<div class="channel-row-main">
<strong class="channel-row-title">${channel.title || channel.displayName || channel.name}</strong>
<p class="channel-row-message">${channel.messagePreview || t('screens.channels_list.text_039')}</p>
</div>
<div class="channel-row-controls">
<span class="channel-row-time">–</span>
</div>
`;
row.prepend(createChannelAvatar(channel));
row.addEventListener('click', () => {
const route = channel.route || makeShineChannelRoute({
ownerLogin: String(channel.ownerName || 'channel'),
ownerBlockchainName: String(channel.ownerName || ''),
channelName: String(channel.channelName || channel.id),
});
if (route) navigate(route);
});
list.append(row);
});
container.append(list);
}
function renderChannelMain(channel) {
const main = document.createElement('div');
main.className = 'channel-row-main';
const titleLine = document.createElement('div');
titleLine.className = 'channel-row-title-line';
const title = document.createElement('strong');
title.className = 'channel-row-title';
title.textContent = channel.title;
const time = document.createElement('span');
time.className = 'channel-row-time';
time.textContent = channel.lastMessageAt ? formatListTime(channel.lastMessageAt) : '';
titleLine.append(title, time);
const technical = document.createElement('p');
technical.className = 'channel-row-technical';
technical.textContent = channel.technicalLabel || formatChannelAddress({ ownerLogin: channel.ownerName || t('dialogs.modals.channels_list.label_010'), channelName: channel.channelName });
// Системный адрес одинаково виден в собственных и чужих каналах.
if (channel.channelDescription) {
const desc = document.createElement('p');
desc.className = 'channel-row-description';
desc.textContent = channel.channelDescription;
main.append(desc);
}
const previewLine = document.createElement('div');
previewLine.className = 'channel-row-preview-line';
const preview = document.createElement('p');
preview.className = 'channel-row-message';
preview.textContent = channel.messagePreview || t('dialogs.modals.channels_list.label_011');
if (!channel.messagePreview) preview.classList.add('is-empty');
previewLine.append(preview);
const meta = document.createElement('p');
meta.className = 'channel-row-owner channel-counter-meta';
meta.textContent = t('screens.channels_list.text_040', { value1: channel.messagesCount || 0 });
main.prepend(titleLine, technical);
main.append(previewLine, meta);
return main;
}
function renderListContent({ screen, container, listState, navigate, refreshFeed }) {
container.innerHTML = '';
const allChannels = listState.channels || [];
const filtered = allChannels.filter((channel) => {
if (listState.viewMode === CHANNELS_VIEW_OWNED) return channel.isOwnChannel === true && channel.isDeleted !== true;
if (listState.viewMode === CHANNELS_VIEW_FOLLOWING) return channel.isSubscribed === true && !channel.isOwnChannel;
if (listState.viewMode === CHANNELS_VIEW_DELETED) return channel.isDeleted === true;
return channel.isDeleted !== true;
}).filter((channel) => {
const query = String(listState.query || '').trim().toLowerCase();
if (!query) return true;
return [channel.title, channel.ownerName, channel.channelName, channel.technicalLabel]
.some((value) => String(value || '').toLowerCase().includes(query));
});
if (!filtered.length) {
container.append(renderEmptyState(listState, navigate));
return;
}
const list = document.createElement('div');
list.className = 'stack channels-groups';
const rerenderList = () => renderListContent({ screen, container, listState, navigate, refreshFeed });
filtered.forEach((channel) => {
const row = document.createElement('button');
row.type = 'button';
row.className = 'channel-row';
const countersVisible = listState.revealedCounters.has(channel.id);
row.classList.toggle('is-counters-visible', countersVisible);
row.classList.toggle('has-unread', Number(channel.unreadCount || 0) > 0);
const avatar = createChannelAvatar(channel);
const main = renderChannelMain(channel);
const controls = document.createElement('div');
controls.className = 'channel-row-controls';
const count = document.createElement('span');
count.className = 'unread channel-row-count';
const unreadCount = Number(channel.unreadCount || 0);
count.hidden = unreadCount <= 0;
count.textContent = unreadCount > 0 ? String(unreadCount) : '';
count.classList.toggle('is-empty', unreadCount <= 0);
controls.append(count);
row.append(avatar, main, controls);
row.addEventListener('click', () => {
const route = channel.route || makeShineChannelRoute({
ownerLogin: String(channel.ownerName || 'channel'),
ownerBlockchainName: String(channel.ownerName || ''),
channelName: String(channel.channelName || channel.id),
});
if (route) navigate(route);
});
list.append(row);
});
container.append(list);
}
async function loadFeedAndRender({ screen, listState, contentEl, navigate, silent = false }) {
if (listState.disposed) return;
const seq = ++listState.loadSeq;
// Уже загруженный список показываем сразу и тихо обновляем; заглушка – только при долгой первой загрузке.
if (!silent && state.session.isAuthorized && state.channelsFeed && listState.viewMode !== CHANNELS_VIEW_DELETED) {
listState.channels = toListModel(mapApiFeed(state.channelsFeed, listState.notificationsState, null));
renderListContent({
screen,
container: contentEl,
listState,
navigate,
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
});
silent = true;
}
if (!silent) {
window.setTimeout(() => {
if (!listState.disposed && seq === listState.loadSeq && !contentEl.hasChildNodes()) renderSkeletonList(contentEl, 5);
}, SKELETON_DELAY_MS);
contentEl.replaceChildren();
}
if (!state.session.isAuthorized) {
setChannelsFeed(null, {});
listState.channels = [];
renderListContent({
screen,
container: contentEl,
listState,
navigate,
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
});
return;
}
if (state.session.isLocalDemo) {
setChannelsFeed(null, {});
listState.channels = [];
contentEl.innerHTML = '';
renderDemoFallback(contentEl, navigate, null, null, { localOnly: true });
return;
}
try {
if (listState.viewMode === CHANNELS_VIEW_DELETED) {
const payload = await authService.listUserProfileChannels(state.session.login, 'owned', 500, 0, true);
if (listState.disposed || seq !== listState.loadSeq) return;
listState.channels = mapDeletedOwnedChannels(payload, listState.notificationsState);
renderListContent({
screen,
container: contentEl,
listState,
navigate,
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
});
return;
}
const feed = await authService.listSubscriptionsFeed(state.session.login, 200);
if (listState.disposed || seq !== listState.loadSeq) return;
// FEATURE DISABLED: personal Diary is intentionally hidden from the Channels UI.
// The server/API implementation is preserved so the feature can be restored later.
// See: docs/закомментировано/Личный_дневник.md
// let diaryPayload = null;
// try {
// diaryPayload = await authService.getPersonalDiary(state.session.login, 200, 'asc');
// } catch {
// diaryPayload = null;
// }
const diaryPayload = null;
const groups = mapApiFeed(feed, listState.notificationsState, diaryPayload);
listState.channels = toListModel(groups);
setChannelsFeed(feed, groups.index);
renderListContent({
screen,
container: contentEl,
listState,
navigate,
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
});
if (Number.isFinite(listState.restorePosition)) {
restoreChannelPosition(listState.restorePosition);
listState.restorePosition = undefined;
}
} catch (error) {
if (listState.disposed || seq !== listState.loadSeq) return;
if (silent) return;
setChannelsFeed(null, {});
contentEl.innerHTML = '';
if (isChannelsDemoMode()) {
renderDemoFallback(contentEl, navigate, error, () => loadFeedAndRender({ screen, listState, contentEl, navigate }));
return;
}
renderErrorState(contentEl, error, () => loadFeedAndRender({ screen, listState, contentEl, navigate }));
}
}
export function render({ navigate, route, chrome }) {
const screen = document.createElement('section');
screen.className = 'stack channels-screen channels-screen--list';
const createSuccessFlash = pullCreateSuccessFlash();
const notificationsState = readChannelNotificationsState();
const isGuest = !state.session.isAuthorized;
const positionKey = `${state.session.login}:channels:${normalizeChannelsViewMode(route)}`;
const listState = {
restorePosition: readChannelPosition(positionKey),
disposed: false,
loadSeq: 0,
notificationsState,
revealedCounters: new Set(),
channels: [],
viewMode: normalizeChannelsViewMode(route),
query: listQueries.get(positionKey) || '',
};
const contentEl = document.createElement('div');
contentEl.className = 'channels-list-content';
const filterTitle = createTopBarFilterTitle({
section: t('screens.channels_list.text_026'),
choices: CHANNEL_FILTERS(),
value: listState.viewMode,
minWidth: 240,
onSelect: (mode) => {
if (mode !== listState.viewMode) navigate(buildChannelsViewRoute(mode));
},
});
const topBarEl = createTopBar({
center: filterTitle.element,
className: 'topbar--root topbar--section-filter',
actions: [
{
icon: 'moreVertical',
title: t('screens.channels_list.text_004'),
ariaLabel: t('screens.channels_list.text_005'),
className: 'channels-menu-btn',
menu: {
minWidth: 210,
items: () => [
{ label: t('screens.channels_list.text_006'), iconHtml: channelMenuIcon('add'), action: () => navigate('add-channel-view') },
],
},
},
],
});
topBarEl.addCleanup(() => filterTitle.destroy());
const controls = document.createElement('div');
controls.className = 'channels-list-controls';
const searchWrap = document.createElement('div');
searchWrap.className = 'channels-inline-search';
searchWrap.innerHTML = `<span class="channels-inline-search__icon" aria-hidden="true">${iconHtml('search')}</span><span class="sr-only">${th('screens.channels_list.text_041')}</span>`;
const searchInput = document.createElement('input');
searchInput.type = 'search';
searchInput.value = listState.query;
searchInput.placeholder = t('dialogs.modals.channels_list.label_012');
searchInput.setAttribute('aria-label', t('dialogs.modals.channels_list.label_013'));
const serverSearchButton = document.createElement('button');
serverSearchButton.type = 'button';
serverSearchButton.className = 'text-btn channels-server-search';
serverSearchButton.textContent = t('dialogs.modals.channels_list.label_014');
serverSearchButton.addEventListener('click', () => navigate('search-view'));
searchWrap.append(searchInput, serverSearchButton);
controls.append(searchWrap);
const reloadFeed = async () => loadFeedAndRender({ screen, listState, contentEl, navigate });
let countersRefreshTimer = null;
let lastChannelsUnreadCount = Math.max(0, Number(state.userCounters?.channelsUnreadCount || 0) || 0);
const unsubscribeCountersChanged = authService.onEvent('UserCountersChanged', (event) => {
const nextChannelsUnreadCount = Math.max(0, Number(event?.payload?.channelsUnreadCount || 0) || 0);
if (nextChannelsUnreadCount === lastChannelsUnreadCount) return;
lastChannelsUnreadCount = nextChannelsUnreadCount;
if (countersRefreshTimer) window.clearTimeout(countersRefreshTimer);
countersRefreshTimer = window.setTimeout(() => {
countersRefreshTimer = null;
void loadFeedAndRender({ screen, listState, contentEl, navigate, silent: true });
}, 120);
});
const rerenderList = () => {
listState.viewMode = normalizeChannelsViewMode({ params: route?.params || {} });
renderListContent({
screen,
container: contentEl,
listState,
navigate,
refreshFeed: reloadFeed,
});
};
searchInput.addEventListener('input', () => {
listState.restorePosition = undefined;
listState.query = searchInput.value;
rerenderList();
});
chrome?.setTopbar(topBarEl);
screen.append(controls, contentEl);
if (createSuccessFlash) {
showToast(createSuccessFlash);
}
// Применяем корректное состояние хедера сразу на первом рендере,
// чтобы не показывать лишние кнопки до первой перерисовки.
rerenderList();
loadFeedAndRender({ screen, listState, contentEl, navigate });
screen.cleanup = () => {
if (listState.disposed) return;
rememberChannelPosition(positionKey);
listQueries.set(positionKey, listState.query);
listState.disposed = true;
if (countersRefreshTimer) window.clearTimeout(countersRefreshTimer);
unsubscribeCountersChanged();
};
return screen;
}