SHA256
UI: экраны без мелькания – кэш каналов и обсуждений, фоновая подгрузка, заставка как экран входа
- «Назад» при открытом редакторе закрывает только редактор: слой в истории ведёт роутер (openHistoryLayer), экран под ним больше не пересоздаётся. - Канал и обсуждение при возврате рисуются сразу из памяти (page-data-cache), свежие данные подтягиваются тихо и перерисовывают экран, только если что-то изменилось; место в ленте сохраняется. - Раз в минуту, пока вкладка на экране, обновляются лента каналов и шесть самых активных каналов. - Обсуждение начинает грузиться при касании записи или ответа, канал для него берётся из кэша. - Уведомления и профиль при повторном заходе без пустого кадра; убрано проявление списка каналов. - Заглушка – только если загрузка дольше 0,5 с. - Общая карточка «не удалось загрузить»: заголовок, причина в пару строк, крупная кнопка снизу. - Стартовая заставка повторяет экран входа (знак, надпись, раскладка, фаза сияния) – смена незаметна.
This commit is contained in:
+1
-1
@@ -1,2 +1,2 @@
|
||||
client.version=1.18.6
|
||||
client.version=1.18.7
|
||||
server.version=1.14.0
|
||||
|
||||
+22
-9
@@ -39,7 +39,7 @@
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
window.__SHINE_BUILD_HASH__ = '20261012004500';
|
||||
window.__SHINE_BUILD_HASH__ = '20261012092300';
|
||||
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
||||
</script>
|
||||
<script>
|
||||
@@ -56,15 +56,28 @@ window.__SHINE_BUILD_HASH__ = '20261012004500';
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="initial-splash" class="initial-splash" aria-label="Сияние">
|
||||
<div class="initial-splash__logo-wrap">
|
||||
<img
|
||||
class="initial-splash__logo"
|
||||
src="./img/shine-logo-transparent-final.png"
|
||||
alt="Логотип Сияние"
|
||||
/>
|
||||
<!-- Заставка повторяет верх экрана входа (те же классы и раскладка): смена на него незаметна. -->
|
||||
<div id="initial-splash" class="initial-splash">
|
||||
<div class="initial-splash__frame">
|
||||
<section class="auth-screen auth-screen--welcome">
|
||||
<div class="auth-logo-wrap">
|
||||
<img class="auth-logo" src="./img/shine-logo-transparent-final.png" alt="Логотип Сияние" />
|
||||
</div>
|
||||
<div class="stack auth-brand-block">
|
||||
<h1 class="auth-brand"><svg class="shine-wordmark" viewBox="52 -722 7294 744" role="img" aria-label="Сияние"><path fill="currentColor" d="M721 -129Q619 -33 479 -33Q401 -33 341 -60Q281 -87 241 -132Q201 -177 180.5 -236Q160 -295 160 -359Q160 -427 181.5 -483.5Q203 -540 242 -581Q281 -622 334.5 -645Q388 -668 451 -668Q494 -668 529.5 -658Q565 -648 592.5 -632Q620 -616 637.5 -595.5Q655 -575 662 -554H736Q721 -588 697.5 -617Q674 -646 639 -667Q604 -688 557 -700Q510 -712 450 -712Q363 -712 291.5 -687Q220 -662 169 -615.5Q118 -569 90 -503.5Q62 -438 62 -357Q62 -287 84.5 -220.5Q107 -154 154 -102.5Q201 -51 274 -19.5Q347 12 448 12Q512 12 562.5 0Q613 -12 650.5 -29.5Q688 -47 713 -67Q738 -87 751 -102ZM1542 -82V-700H1451V0H1542L1957 -625V0H2048V-700H1957ZM3316 -700V0H3225V-309H3181Q3153 -309 3134.5 -304Q3116 -299 3101 -287Q3086 -275 3073 -256Q3060 -237 3042 -209L2963 -92Q2948 -69 2933.5 -50Q2919 -31 2902 -17.5Q2885 -4 2863.5 4Q2842 12 2812 12Q2790 12 2776 10Q2762 8 2748 0V-37Q2753 -36 2758 -35.5Q2763 -35 2768 -35Q2789 -35 2805 -41Q2821 -47 2835 -58.5Q2849 -70 2862 -86.5Q2875 -103 2889 -124Q2931 -185 2954 -221.5Q2977 -258 2990.5 -278Q3004 -298 3012.5 -307Q3021 -316 3033 -322L3043 -327V-331Q2995 -334 2960.5 -352Q2926 -370 2904 -397Q2882 -424 2872 -455.5Q2862 -487 2862 -517Q2862 -544 2872.5 -576Q2883 -608 2908.5 -635.5Q2934 -663 2978 -681.5Q3022 -700 3089 -700ZM3225 -656H3124Q3086 -656 3055.5 -645Q3025 -634 3003 -614.5Q2981 -595 2969.5 -568Q2958 -541 2958 -509Q2958 -482 2968.5 -454.5Q2979 -427 3000 -404.5Q3021 -382 3051.5 -368Q3082 -354 3122 -354H3225ZM4197 -348H4616V0H4707V-700H4616V-394H4197V-700H4106V0H4197ZM5588 -82V-700H5497V0H5588L6003 -625V0H6094V-700H6003ZM6884 -700V0H7336V-55H6975V-346H7285V-394H6975V-645H7336V-700Z"/></svg></h1>
|
||||
<p class="meta-muted auth-site-name" id="initial-splash-host"></p>
|
||||
</div>
|
||||
<div class="auth-actions shine-actions initial-splash__actions" aria-hidden="true">
|
||||
<span class="shine-btn"></span>
|
||||
<span class="secondary-btn shine-btn--register"></span>
|
||||
<span class="text-btn start-language-link"></span>
|
||||
<span class="text-btn start-settings-link"></span>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="initial-splash__brand">Сияние</div>
|
||||
<script>
|
||||
document.getElementById('initial-splash-host').textContent = window.location.host || 'shineup.me';
|
||||
</script>
|
||||
</div>
|
||||
<div class="app-shell">
|
||||
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
||||
|
||||
+36
-1
@@ -3,6 +3,7 @@ import {
|
||||
getRoute,
|
||||
PRE_AUTH_PAGES,
|
||||
syncTrackedRouteHistory,
|
||||
consumeHistoryLayerPop,
|
||||
} from './router.js';
|
||||
import { renderToolbar } from './components/toolbar.js';
|
||||
import {
|
||||
@@ -204,6 +205,35 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
||||
let currentCleanup = null;
|
||||
let pingIntervalId = null;
|
||||
let reconnectIntervalId = null;
|
||||
let channelsPrefetchTimerId = null;
|
||||
let channelsPrefetchEpoch = 0;
|
||||
const CHANNELS_PREFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
// Раз в минуту, пока вкладка на экране, подтягиваем каналы в память, чтобы они открывались сразу.
|
||||
function startChannelsPrefetch() {
|
||||
stopChannelsPrefetch();
|
||||
const epoch = ++channelsPrefetchEpoch;
|
||||
let running = false;
|
||||
const tick = async () => {
|
||||
if (running || document.visibilityState !== 'visible' || !wsIsOpen()) return;
|
||||
running = true;
|
||||
try {
|
||||
await channelsList.refreshChannelsInBackground({ isCurrent: () => epoch === channelsPrefetchEpoch });
|
||||
} catch {
|
||||
// Сеть недоступна – попробуем на следующем круге.
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
channelsPrefetchTimerId = window.setInterval(() => void tick(), CHANNELS_PREFETCH_INTERVAL_MS);
|
||||
window.setTimeout(() => { if (epoch === channelsPrefetchEpoch) void tick(); }, 3_000);
|
||||
}
|
||||
|
||||
function stopChannelsPrefetch() {
|
||||
channelsPrefetchEpoch += 1;
|
||||
if (channelsPrefetchTimerId) window.clearInterval(channelsPrefetchTimerId);
|
||||
channelsPrefetchTimerId = null;
|
||||
}
|
||||
let sessionRuntimeStarted = false;
|
||||
let connectionState = '';
|
||||
let connectionStatusText = '';
|
||||
@@ -1543,6 +1573,7 @@ async function ensureSessionRuntimeStarted() {
|
||||
}
|
||||
|
||||
startConnectionMonitor();
|
||||
startChannelsPrefetch();
|
||||
|
||||
if (reconnectIntervalId) {
|
||||
window.clearInterval(reconnectIntervalId);
|
||||
@@ -1594,6 +1625,7 @@ async function init() {
|
||||
|
||||
setSessionResetHandler(() => {
|
||||
sessionRuntimeStarted = false;
|
||||
stopChannelsPrefetch();
|
||||
startConnectionMonitor();
|
||||
clearKeepAliveEntries();
|
||||
if (reconnectIntervalId) {
|
||||
@@ -1993,7 +2025,10 @@ async function init() {
|
||||
}
|
||||
})();
|
||||
|
||||
window.addEventListener('popstate', renderApp);
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (event.isTrusted && consumeHistoryLayerPop()) return;
|
||||
renderApp();
|
||||
});
|
||||
document.addEventListener('pointerdown', () => {
|
||||
void unlockHiddenDmAudio();
|
||||
}, { passive: true });
|
||||
|
||||
@@ -7,6 +7,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||
import { resolvePublicFileUrl } from '../services/public-file-service.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
const drafts = new Map();
|
||||
|
||||
@@ -301,19 +302,13 @@ export function openChannelEditor({
|
||||
});
|
||||
};
|
||||
|
||||
const openedUrl = location.href;
|
||||
const historyId = `${Date.now()}:${Math.random()}`;
|
||||
history.pushState({ ...history.state, channelEditor: historyId }, '', openedUrl);
|
||||
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
|
||||
const historyLayer = openHistoryLayer(() => close({ fromHistory: true }));
|
||||
const viewport = window.visualViewport;
|
||||
const updateViewport = () => {
|
||||
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
||||
overlay.style.setProperty('--editor-top', `${viewport?.offsetTop || 0}px`);
|
||||
};
|
||||
const onBack = (event) => {
|
||||
if (closed) return;
|
||||
event.stopImmediatePropagation();
|
||||
close({ fromHistory: true });
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!overlay.isConnected) close({ restoreFocus: false });
|
||||
});
|
||||
@@ -327,14 +322,8 @@ export function openChannelEditor({
|
||||
viewport?.removeEventListener('resize', updateViewport);
|
||||
viewport?.removeEventListener('scroll', updateViewport);
|
||||
window.removeEventListener('resize', updateViewport);
|
||||
window.removeEventListener('popstate', onBack, true);
|
||||
overlay.remove();
|
||||
if (!fromHistory && location.href === openedUrl && history.state?.channelEditor === historyId) {
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (location.href === openedUrl) event.stopImmediatePropagation();
|
||||
}, { capture: true, once: true });
|
||||
history.back();
|
||||
}
|
||||
if (!fromHistory) historyLayer.close();
|
||||
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
||||
};
|
||||
overlay.cleanup = () => close({ restoreFocus: false });
|
||||
@@ -450,7 +439,6 @@ export function openChannelEditor({
|
||||
});
|
||||
submitButton.addEventListener('click', () => void submit());
|
||||
document.addEventListener('keydown', onDocumentKeydown);
|
||||
window.addEventListener('popstate', onBack, true);
|
||||
viewport?.addEventListener('resize', updateViewport);
|
||||
viewport?.addEventListener('scroll', updateViewport);
|
||||
window.addEventListener('resize', updateViewport);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+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;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { parseMessageAttachments } from '../services/attachment-format.js';
|
||||
import {
|
||||
animatePress,
|
||||
createLoadErrorCard,
|
||||
createSkeletonRows,
|
||||
SKELETON_DELAY_MS,
|
||||
formatListTime,
|
||||
@@ -21,6 +22,9 @@ import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createTopBar } from '../components/topbar.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', title: 'Каналы', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
|
||||
@@ -892,6 +896,35 @@ function mapApiFeed(feed, notificationsState, diaryPayload = null) {
|
||||
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 || []),
|
||||
@@ -923,24 +956,11 @@ function renderSkeletonList(container, count = 4) {
|
||||
}
|
||||
|
||||
function renderErrorState(container, error, onRetry) {
|
||||
const errCard = document.createElement('div');
|
||||
errCard.className = 'card stack channels-status';
|
||||
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = 'Не удалось загрузить каналы';
|
||||
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
details.textContent = toUserMessage(error, 'Проверьте подключение к серверу и повторите попытку.');
|
||||
|
||||
const retry = document.createElement('button');
|
||||
retry.className = 'primary-btn';
|
||||
retry.type = 'button';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
|
||||
errCard.append(title, details, retry);
|
||||
container.append(errCard);
|
||||
container.append(createLoadErrorCard({
|
||||
title: 'Не удалось загрузить каналы',
|
||||
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
|
||||
onRetry,
|
||||
}));
|
||||
}
|
||||
|
||||
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
||||
@@ -1064,7 +1084,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack channels-groups channels-list-body-fade';
|
||||
list.className = 'stack channels-groups';
|
||||
|
||||
const rerenderList = () => renderListContent({ screen, container, listState, navigate, refreshFeed });
|
||||
|
||||
|
||||
@@ -280,6 +280,9 @@ function renderItem(item, activeTab, navigate) {
|
||||
return row;
|
||||
}
|
||||
|
||||
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
|
||||
let lastNotifications = null;
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notifications-screen';
|
||||
@@ -382,8 +385,19 @@ export function render({ navigate, chrome } = {}) {
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
|
||||
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
|
||||
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({});
|
||||
try {
|
||||
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
|
||||
const signature = JSON.stringify(fresh);
|
||||
lastNotifications = { login, payload: structuredClone(fresh), signature };
|
||||
updateToolbarBadge(fresh);
|
||||
if (cached?.signature === signature) return;
|
||||
payloadCache=fresh; await renderCurrent();
|
||||
}
|
||||
catch(error){ if(seq!==requestSeq)return; 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);}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,8 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
const fresh = await loadUserProfileCard(login);
|
||||
if (!screen.isConnected && card) return;
|
||||
// Та же карточка – не перерисовываем, иначе аватар и счётчики мигают.
|
||||
if (card && JSON.stringify(card) === JSON.stringify(fresh)) return;
|
||||
card = fresh;
|
||||
cardCache.set(login.toLowerCase(), card);
|
||||
renderProfile();
|
||||
|
||||
@@ -23,20 +23,14 @@ export function render({ navigate }) {
|
||||
logoWrap.append(logo);
|
||||
|
||||
const brandBlock = document.createElement('div');
|
||||
brandBlock.className = 'stack';
|
||||
brandBlock.style.alignItems = 'center';
|
||||
brandBlock.style.gap = '22px';
|
||||
brandBlock.className = 'stack auth-brand-block';
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'auth-brand';
|
||||
title.append(createShineWordmark());
|
||||
|
||||
const siteName = document.createElement('p');
|
||||
siteName.className = 'meta-muted';
|
||||
siteName.style.margin = '0';
|
||||
siteName.style.fontSize = '18px';
|
||||
siteName.style.letterSpacing = '0.045em';
|
||||
siteName.style.lineHeight = '1.25';
|
||||
siteName.className = 'meta-muted auth-site-name';
|
||||
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
||||
|
||||
brandBlock.append(title, siteName);
|
||||
@@ -73,5 +67,23 @@ export function render({ navigate }) {
|
||||
|
||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||
screen.append(logoWrap, brandBlock, actions);
|
||||
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
|
||||
queueMicrotask(() => continueSplashAnimations(logoWrap));
|
||||
return screen;
|
||||
}
|
||||
|
||||
// Заставка рисует тот же знак: продолжаем её сияние с той же фазы, чтобы при смене не было скачка.
|
||||
function continueSplashAnimations(logoWrap) {
|
||||
const splashWrap = document.querySelector('#initial-splash .auth-logo-wrap');
|
||||
if (!splashWrap || !logoWrap.isConnected) return;
|
||||
const keyOf = (animation) => {
|
||||
const target = animation.effect?.target;
|
||||
const part = target?.classList?.contains('auth-logo') ? 'logo' : 'wrap';
|
||||
return `${part}${animation.effect?.pseudoElement || ''}|${animation.animationName || ''}`;
|
||||
};
|
||||
const source = new Map(splashWrap.getAnimations({ subtree: true }).map((animation) => [keyOf(animation), animation]));
|
||||
logoWrap.getAnimations({ subtree: true }).forEach((animation) => {
|
||||
const match = source.get(keyOf(animation));
|
||||
if (match && match.currentTime != null) animation.currentTime = match.currentTime;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -472,6 +472,41 @@ export function navigate(path) {
|
||||
window.dispatchEvent(new PopStateEvent('popstate'));
|
||||
}
|
||||
|
||||
// Слой поверх экрана (редактор) кладёт в историю запись с тем же адресом, чтобы «назад» закрывало его.
|
||||
// Роутер разбирает такие возвраты первым: закрывает слой и не пересоздаёт экран под ним.
|
||||
const historyLayers = [];
|
||||
let ownLayerPops = 0;
|
||||
|
||||
export function openHistoryLayer(onBack) {
|
||||
const id = `${Date.now()}:${Math.random()}`;
|
||||
window.history.pushState({ ...window.history.state, shineLayer: id }, '', window.location.href);
|
||||
const layer = { onBack };
|
||||
historyLayers.push(layer);
|
||||
return {
|
||||
// Закрытие изнутри (крестик, отправка) убирает свою запись из истории.
|
||||
close() {
|
||||
const index = historyLayers.indexOf(layer);
|
||||
if (index < 0) return;
|
||||
historyLayers.splice(index, 1);
|
||||
if (window.history.state?.shineLayer === id) {
|
||||
ownLayerPops += 1;
|
||||
window.history.back();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function consumeHistoryLayerPop() {
|
||||
if (ownLayerPops > 0) {
|
||||
ownLayerPops -= 1;
|
||||
return true;
|
||||
}
|
||||
const layer = historyLayers.pop();
|
||||
if (!layer) return false;
|
||||
layer.onBack();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function toPrettyPath(path) {
|
||||
const raw = String(path || '').replace(/^\/+/, '').replace(/\/+$/, '');
|
||||
if (!raw) return '';
|
||||
|
||||
@@ -252,7 +252,7 @@ export function createSkeletonRows(kind = 'list', count = 4) {
|
||||
}
|
||||
|
||||
// Показать заглушку, только если загрузка заметно затянулась: быстрый ответ не должен мигать заглушкой.
|
||||
export const SKELETON_DELAY_MS = 250;
|
||||
export const SKELETON_DELAY_MS = 500;
|
||||
|
||||
export function normalizeChannelDescription(value) {
|
||||
const text = String(value == null ? '' : value).trim().replace(/\s+/g, ' ');
|
||||
@@ -320,3 +320,30 @@ export const REPOSTS_ENABLED = false;
|
||||
export function notifyRepostSoon() {
|
||||
showToast('Репосты скоро появятся');
|
||||
}
|
||||
|
||||
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
|
||||
export function createLoadErrorCard({ title, message, onRetry, secondary = null }) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channels-status';
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = title;
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
// Под текстом и так кнопка «Повторить» – совет «повторите попытку» в тексте лишний.
|
||||
details.textContent = String(message || '').replace(/\s*Повторите попытку[^.]*\.?\s*$/u, '').trim();
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
card.append(heading, details, retry);
|
||||
if (secondary) {
|
||||
const extra = document.createElement('button');
|
||||
extra.type = 'button';
|
||||
extra.className = 'secondary-btn';
|
||||
extra.textContent = secondary.label;
|
||||
extra.addEventListener('click', secondary.onClick);
|
||||
card.append(extra);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Последние загруженные данные экранов каналов и обсуждений – только в памяти вкладки.
|
||||
// При возврате на экран он сразу рисуется из кэша, а свежие данные подтягиваются тихо.
|
||||
import { state } from '../state.js';
|
||||
|
||||
const MAX_ENTRIES = 60;
|
||||
const entries = new Map();
|
||||
|
||||
function fullKey(kind, key) {
|
||||
return `${String(state.session.login || '').toLowerCase()}|${kind}|${String(key || '').toLowerCase()}`;
|
||||
}
|
||||
|
||||
export function readPageData(kind, key) {
|
||||
const id = fullKey(kind, key);
|
||||
const entry = entries.get(id);
|
||||
if (!entry) return null;
|
||||
// Свежепрочитанное поднимаем в конец, чтобы вытеснялось давно не открытое.
|
||||
entries.delete(id);
|
||||
entries.set(id, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
export function writePageData(kind, key, data) {
|
||||
const id = fullKey(kind, key);
|
||||
const signature = safeSignature(data);
|
||||
entries.delete(id);
|
||||
entries.set(id, { data, signature, savedAt: Date.now() });
|
||||
while (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value);
|
||||
return signature;
|
||||
}
|
||||
|
||||
export function pageDataAge(kind, key) {
|
||||
const entry = entries.get(fullKey(kind, key));
|
||||
return entry ? Date.now() - entry.savedAt : Infinity;
|
||||
}
|
||||
|
||||
export function dropPageData(kind, key) {
|
||||
entries.delete(fullKey(kind, key));
|
||||
}
|
||||
|
||||
// Подпись нужна, чтобы не перерисовывать экран, если сервер вернул то же самое.
|
||||
export function safeSignature(data) {
|
||||
try {
|
||||
return JSON.stringify(data);
|
||||
} catch {
|
||||
return `${Date.now()}:${Math.random()}`;
|
||||
}
|
||||
}
|
||||
@@ -207,8 +207,17 @@
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.channels-list-body-fade { animation: channels-fade-in 160ms ease-out; }
|
||||
@keyframes channels-fade-in { from { opacity: 0; } to { opacity: 1; } }
|
||||
.channels-status p {
|
||||
max-width: 30ch;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.channels-status .primary-btn,
|
||||
.channels-status .secondary-btn {
|
||||
width: min(100%, 280px);
|
||||
min-height: 48px;
|
||||
}
|
||||
|
||||
|
||||
.channels-search-suggest {
|
||||
max-height: 240px;
|
||||
@@ -277,5 +286,5 @@
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.channels-list-body-fade, .channel-row { animation: none; transition: none; }
|
||||
.channel-row { animation: none; transition: none; }
|
||||
}
|
||||
|
||||
@@ -14,20 +14,11 @@
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10000;
|
||||
display: grid;
|
||||
align-content: center;
|
||||
justify-items: center;
|
||||
gap: clamp(12px, 2.4vh, 20px);
|
||||
padding: 24px;
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(circle at 50% 18%, color-mix(in srgb, var(--warning) 8%, transparent), transparent 26%),
|
||||
radial-gradient(circle at 50% 67%, color-mix(in srgb, var(--accent) 6%, transparent), transparent 38%),
|
||||
var(--background);
|
||||
font-family: var(--font-main);
|
||||
background: var(--background);
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transition: opacity 520ms ease, visibility 520ms ease;
|
||||
transition: opacity 360ms ease, visibility 360ms ease;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,46 +29,17 @@
|
||||
}
|
||||
|
||||
|
||||
.initial-splash__logo-wrap {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
width: clamp(156px, 42vw, 208px);
|
||||
aspect-ratio: 1;
|
||||
/* Та же геометрия, что у оболочки и экрана входа: ширина оболочки, поля .screen-content.no-app-chrome. */
|
||||
.initial-splash__frame {
|
||||
width: min(100vw, var(--shell-content-width, 640px));
|
||||
height: 100dvh;
|
||||
margin: 0 auto;
|
||||
padding: 0 16px calc(24px + env(safe-area-inset-bottom));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
|
||||
.initial-splash__logo-wrap::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
/* Сияние гаснет в пределах ~четверти размера знака — не дотягивается до краёв экрана. */
|
||||
inset: -14%;
|
||||
z-index: -1;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(closest-side, color-mix(in srgb, var(--warning) 15%, transparent), color-mix(in srgb, var(--warning) 6%, transparent) 55%, transparent);
|
||||
animation: shine-halo-breathe 4.8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
|
||||
.initial-splash__logo {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
filter:
|
||||
drop-shadow(0 0 8px color-mix(in srgb, var(--warning) 72%, transparent))
|
||||
drop-shadow(0 8px 22px color-mix(in srgb, var(--warning) 38%, transparent));
|
||||
animation: shine-logo-breathe 5.3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
|
||||
.initial-splash__brand {
|
||||
margin-top: -2px;
|
||||
color: var(--text-primary);
|
||||
font-size: clamp(34px, 7vw, 46px);
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
text-shadow: 0 3px 22px color-mix(in srgb, var(--warning) 20%, transparent);
|
||||
}
|
||||
.initial-splash__actions { visibility: hidden; }
|
||||
|
||||
|
||||
.auth-screen--welcome {
|
||||
@@ -213,6 +175,20 @@
|
||||
}
|
||||
|
||||
|
||||
.auth-brand-block {
|
||||
align-items: center;
|
||||
gap: 22px;
|
||||
}
|
||||
|
||||
|
||||
.auth-site-name {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
letter-spacing: 0.045em;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
|
||||
.auth-actions,
|
||||
.auth-footer-actions {
|
||||
display: grid;
|
||||
@@ -309,12 +285,6 @@
|
||||
|
||||
|
||||
@media (max-height: 760px) {
|
||||
.initial-splash__logo-wrap {
|
||||
width: 206px;
|
||||
}
|
||||
.initial-splash__brand {
|
||||
font-size: 40px;
|
||||
}
|
||||
.auth-logo-wrap {
|
||||
width: 206px;
|
||||
}
|
||||
@@ -331,8 +301,6 @@
|
||||
.initial-splash {
|
||||
transition-duration: 1ms;
|
||||
}
|
||||
.initial-splash__logo,
|
||||
.initial-splash__logo-wrap::before,
|
||||
.auth-logo,
|
||||
.auth-logo-wrap::before,
|
||||
.auth-logo-wrap::after,
|
||||
|
||||
Reference in New Issue
Block a user