SHA256
UI: экраны без мелькания – кэш каналов и обсуждений, фоновая подгрузка, заставка как экран входа
- «Назад» при открытом редакторе закрывает только редактор: слой в истории ведёт роутер (openHistoryLayer), экран под ним больше не пересоздаётся. - Канал и обсуждение при возврате рисуются сразу из памяти (page-data-cache), свежие данные подтягиваются тихо и перерисовывают экран, только если что-то изменилось; место в ленте сохраняется. - Раз в минуту, пока вкладка на экране, обновляются лента каналов и шесть самых активных каналов. - Обсуждение начинает грузиться при касании записи или ответа, канал для него берётся из кэша. - Уведомления и профиль при повторном заходе без пустого кадра; убрано проявление списка каналов. - Заглушка – только если загрузка дольше 0,5 с. - Общая карточка «не удалось загрузить»: заголовок, причина в пару строк, крупная кнопка снизу. - Стартовая заставка повторяет экран входа (знак, надпись, раскладка, фаза сияния) – смена незаметна.
This commit is contained in:
+218
-189
@@ -2,7 +2,8 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { getPreviousTrackedPath } from '../router.js';
|
||||
import { getPreviousTrackedPath, parseRouteFromPath, toPrettyPath } from '../router.js';
|
||||
import { prefetchThreadPage } from './channel-thread-view.js';
|
||||
import { attachMessageMenu } from '../components/message-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
animatePress,
|
||||
createLoadErrorCard,
|
||||
createSkeletonRows,
|
||||
SKELETON_DELAY_MS,
|
||||
dayKey,
|
||||
@@ -51,6 +53,7 @@ import {
|
||||
makeShineChannelDonateRoute,
|
||||
} from '../services/shine-routes.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { dropPageData, readPageData, writePageData } from '../services/page-data-cache.js';
|
||||
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
@@ -1571,27 +1574,12 @@ async function loadFromApi(route, channelId) {
|
||||
}
|
||||
|
||||
function renderLoadError(screen, navigate, message, onRetry) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channels-status';
|
||||
card.innerHTML = `
|
||||
<strong>Не удалось загрузить канал</strong>
|
||||
<p class="meta-muted">${message || 'Проверьте подключение к серверу и повторите попытку.'}</p>
|
||||
`;
|
||||
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
|
||||
const back = document.createElement('button');
|
||||
back.type = 'button';
|
||||
back.className = 'secondary-btn';
|
||||
back.textContent = 'Назад к каналам';
|
||||
back.addEventListener('click', () => navigate('channels-list'));
|
||||
|
||||
card.append(retry, back);
|
||||
screen.append(card);
|
||||
screen.append(createLoadErrorCard({
|
||||
title: 'Не удалось загрузить канал',
|
||||
message: message || 'Проверьте подключение и повторите попытку.',
|
||||
onRetry,
|
||||
secondary: { label: 'Назад к каналам', onClick: () => navigate('channels-list') },
|
||||
}));
|
||||
}
|
||||
|
||||
function renderDemoFallback(screen, navigate, error) {
|
||||
@@ -2123,6 +2111,11 @@ function renderPostCard(post, {
|
||||
openDiscussion();
|
||||
});
|
||||
card.classList.add('is-openable');
|
||||
// Обсуждение начинаем грузить уже при касании – к моменту клика оно обычно готово.
|
||||
card.addEventListener('pointerdown', () => {
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (route) prefetchThreadPage(`/${toPrettyPath(route)}`);
|
||||
}, { passive: true });
|
||||
|
||||
const replyButton = document.createElement('button');
|
||||
replyButton.type = 'button';
|
||||
@@ -2501,6 +2494,16 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
};
|
||||
}
|
||||
|
||||
// Фоновая подгрузка канала в кэш, чтобы он открывался сразу (вызывается из обхода ленты каналов).
|
||||
export async function prefetchChannelPage(path) {
|
||||
const pathname = new URL(path, window.location.origin).pathname;
|
||||
const route = parseRouteFromPath(pathname);
|
||||
if (route.pageId !== 'channel-view') return false;
|
||||
const data = await loadFromApi(route, route.params.channelId || '');
|
||||
writePageData('channel', pathname, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Место под заглушку занимаем сразу, а сами строки рисуем, только если загрузка затянулась.
|
||||
function renderSkeleton(screen) {
|
||||
const wrap = document.createElement('div');
|
||||
@@ -2960,6 +2963,163 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
// Рисует канал по готовым данным: и из кэша при возврате, и после загрузки с сервера.
|
||||
const paint = (apiData, restorePosition) => {
|
||||
activeSelector = apiData?.selector || null;
|
||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||
const openEntrypointHistory = () => {
|
||||
openEntrypointHistoryModal({
|
||||
channelTitle: titleLabel,
|
||||
posts: apiData?.posts,
|
||||
onSelect: (post) => {
|
||||
if (!flashAndScrollToMessage(post?.messageRef)) {
|
||||
showToast('Не удалось найти запись оглавления в ленте');
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
const titleNode = document.createElement('span');
|
||||
titleNode.className = 'topbar-identity__title';
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
channelHeaderButton.disabled = false;
|
||||
channelHeaderButton.onclick = (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
const aboutRoute = makeShineChannelAboutRoute({
|
||||
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
|
||||
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
|
||||
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
|
||||
});
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
activeChannelData = apiData;
|
||||
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
channelEntrypointButton.disabled = !canShowEntrypointButton;
|
||||
channelEntrypointButton.onclick = () => {
|
||||
const latestEntrypoint = entrypointPosts[0];
|
||||
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
|
||||
showToast('Не удалось найти актуальное оглавление');
|
||||
}
|
||||
};
|
||||
}
|
||||
clearContent();
|
||||
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
scrollToMessageOrdinal,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
onToggleLike: async (messageRef, action) => {
|
||||
try {
|
||||
await onToggleLike(messageRef, action);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
|
||||
}
|
||||
},
|
||||
onReply: async (messageRef, text) => {
|
||||
try {
|
||||
await onReply(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
|
||||
}
|
||||
},
|
||||
onRating: async (messageRef, text) => {
|
||||
try {
|
||||
await onRating(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
|
||||
}
|
||||
},
|
||||
onStatusAction: async (post) => {
|
||||
try {
|
||||
await onStatusAction(post);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
|
||||
}
|
||||
},
|
||||
onOpenEntrypointMenu: () => {
|
||||
openEntrypointMenuModal({
|
||||
onShowHistory: openEntrypointHistory,
|
||||
});
|
||||
},
|
||||
onRepost: async (messageRef) => {
|
||||
try {
|
||||
await onRepost(messageRef);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
|
||||
}
|
||||
},
|
||||
onAddPost: async (bodyText) => {
|
||||
try {
|
||||
await onAddPost(bodyText);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
onShare: onShare,
|
||||
onEdit: async (messageRef, text) => {
|
||||
try {
|
||||
await onEditPost(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
|
||||
}
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
};
|
||||
|
||||
refresh = async () => {
|
||||
if (disposed) return;
|
||||
const seq = ++refreshSeq;
|
||||
@@ -2972,183 +3132,52 @@ export function render({ navigate, route, chrome }) {
|
||||
? getChannelScrollRoot()?.scrollTop
|
||||
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
||||
if (!hadContent) clearContent();
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
activeSelector = null;
|
||||
showStatus('');
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
channelHeaderButton.onclick = null;
|
||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
channelEntrypointButton.onclick = null;
|
||||
const cacheKey = window.location.pathname;
|
||||
// При возврате на канал сразу показываем прошлую загрузку, без заглушки и пустого кадра.
|
||||
const cached = hadContent ? null : readPageData('channel', cacheKey);
|
||||
let shown = hadContent;
|
||||
if (cached) {
|
||||
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
|
||||
await Promise.resolve();
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
try {
|
||||
paint(cached.data, restorePosition);
|
||||
shown = true;
|
||||
} catch (error) {
|
||||
dropPageData('channel', cacheKey);
|
||||
clearContent();
|
||||
}
|
||||
}
|
||||
|
||||
const skeleton = hadContent ? null : renderSkeleton(screen);
|
||||
if (!shown) {
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
activeSelector = null;
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
channelHeaderButton.onclick = null;
|
||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
channelEntrypointButton.onclick = null;
|
||||
}
|
||||
}
|
||||
const skeleton = shown ? null : renderSkeleton(screen);
|
||||
|
||||
try {
|
||||
const apiData = await loadFromApi(route, channelId);
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
activeSelector = apiData?.selector || null;
|
||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||
const openEntrypointHistory = () => {
|
||||
openEntrypointHistoryModal({
|
||||
channelTitle: titleLabel,
|
||||
posts: apiData?.posts,
|
||||
onSelect: (post) => {
|
||||
if (!flashAndScrollToMessage(post?.messageRef)) {
|
||||
showToast('Не удалось найти запись оглавления в ленте');
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
const titleNode = document.createElement('span');
|
||||
titleNode.className = 'topbar-identity__title';
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
channelHeaderButton.disabled = false;
|
||||
channelHeaderButton.onclick = (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
const aboutRoute = makeShineChannelAboutRoute({
|
||||
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
|
||||
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
|
||||
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
|
||||
});
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
activeChannelData = apiData;
|
||||
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
channelEntrypointButton.disabled = !canShowEntrypointButton;
|
||||
channelEntrypointButton.onclick = () => {
|
||||
const latestEntrypoint = entrypointPosts[0];
|
||||
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
|
||||
showToast('Не удалось найти актуальное оглавление');
|
||||
}
|
||||
};
|
||||
}
|
||||
const signature = writePageData('channel', cacheKey, apiData);
|
||||
// Сервер вернул то же, что уже на экране, – ничего не трогаем, чтобы не дёргать ленту.
|
||||
if (cached && cached.signature === signature) return;
|
||||
skeleton?.remove();
|
||||
clearContent();
|
||||
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
scrollToMessageOrdinal,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
onToggleLike: async (messageRef, action) => {
|
||||
try {
|
||||
await onToggleLike(messageRef, action);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
|
||||
}
|
||||
},
|
||||
onReply: async (messageRef, text) => {
|
||||
try {
|
||||
await onReply(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
|
||||
}
|
||||
},
|
||||
onRating: async (messageRef, text) => {
|
||||
try {
|
||||
await onRating(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
|
||||
}
|
||||
},
|
||||
onStatusAction: async (post) => {
|
||||
try {
|
||||
await onStatusAction(post);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
|
||||
}
|
||||
},
|
||||
onOpenEntrypointMenu: () => {
|
||||
openEntrypointMenuModal({
|
||||
onShowHistory: openEntrypointHistory,
|
||||
});
|
||||
},
|
||||
onRepost: async (messageRef) => {
|
||||
try {
|
||||
await onRepost(messageRef);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
|
||||
}
|
||||
},
|
||||
onAddPost: async (bodyText) => {
|
||||
try {
|
||||
await onAddPost(bodyText);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
onShare: onShare,
|
||||
onEdit: async (messageRef, text) => {
|
||||
try {
|
||||
await onEditPost(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
|
||||
}
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
paint(apiData, shown ? getChannelScrollRoot()?.scrollTop : restorePosition);
|
||||
} catch (error) {
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
skeleton?.remove();
|
||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span>';
|
||||
if (isChannelsDemoMode()) {
|
||||
renderDemoFallback(screen, navigate, error);
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user