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
|
server.version=1.14.0
|
||||||
|
|||||||
+22
-9
@@ -39,7 +39,7 @@
|
|||||||
}());
|
}());
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<script>
|
||||||
window.__SHINE_BUILD_HASH__ = '20261012004500';
|
window.__SHINE_BUILD_HASH__ = '20261012092300';
|
||||||
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<script>
|
||||||
@@ -56,15 +56,28 @@ window.__SHINE_BUILD_HASH__ = '20261012004500';
|
|||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="initial-splash" class="initial-splash" aria-label="Сияние">
|
<!-- Заставка повторяет верх экрана входа (те же классы и раскладка): смена на него незаметна. -->
|
||||||
<div class="initial-splash__logo-wrap">
|
<div id="initial-splash" class="initial-splash">
|
||||||
<img
|
<div class="initial-splash__frame">
|
||||||
class="initial-splash__logo"
|
<section class="auth-screen auth-screen--welcome">
|
||||||
src="./img/shine-logo-transparent-final.png"
|
<div class="auth-logo-wrap">
|
||||||
alt="Логотип Сияние"
|
<img class="auth-logo" src="./img/shine-logo-transparent-final.png" alt="Логотип Сияние" />
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="initial-splash__brand">Сияние</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>
|
||||||
|
<script>
|
||||||
|
document.getElementById('initial-splash-host').textContent = window.location.host || 'shineup.me';
|
||||||
|
</script>
|
||||||
</div>
|
</div>
|
||||||
<div class="app-shell">
|
<div class="app-shell">
|
||||||
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
||||||
|
|||||||
+36
-1
@@ -3,6 +3,7 @@ import {
|
|||||||
getRoute,
|
getRoute,
|
||||||
PRE_AUTH_PAGES,
|
PRE_AUTH_PAGES,
|
||||||
syncTrackedRouteHistory,
|
syncTrackedRouteHistory,
|
||||||
|
consumeHistoryLayerPop,
|
||||||
} from './router.js';
|
} from './router.js';
|
||||||
import { renderToolbar } from './components/toolbar.js';
|
import { renderToolbar } from './components/toolbar.js';
|
||||||
import {
|
import {
|
||||||
@@ -204,6 +205,35 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
|||||||
let currentCleanup = null;
|
let currentCleanup = null;
|
||||||
let pingIntervalId = null;
|
let pingIntervalId = null;
|
||||||
let reconnectIntervalId = 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 sessionRuntimeStarted = false;
|
||||||
let connectionState = '';
|
let connectionState = '';
|
||||||
let connectionStatusText = '';
|
let connectionStatusText = '';
|
||||||
@@ -1543,6 +1573,7 @@ async function ensureSessionRuntimeStarted() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
startConnectionMonitor();
|
startConnectionMonitor();
|
||||||
|
startChannelsPrefetch();
|
||||||
|
|
||||||
if (reconnectIntervalId) {
|
if (reconnectIntervalId) {
|
||||||
window.clearInterval(reconnectIntervalId);
|
window.clearInterval(reconnectIntervalId);
|
||||||
@@ -1594,6 +1625,7 @@ async function init() {
|
|||||||
|
|
||||||
setSessionResetHandler(() => {
|
setSessionResetHandler(() => {
|
||||||
sessionRuntimeStarted = false;
|
sessionRuntimeStarted = false;
|
||||||
|
stopChannelsPrefetch();
|
||||||
startConnectionMonitor();
|
startConnectionMonitor();
|
||||||
clearKeepAliveEntries();
|
clearKeepAliveEntries();
|
||||||
if (reconnectIntervalId) {
|
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', () => {
|
document.addEventListener('pointerdown', () => {
|
||||||
void unlockHiddenDmAudio();
|
void unlockHiddenDmAudio();
|
||||||
}, { passive: true });
|
}, { passive: true });
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
|||||||
import { renderUserAvatar } from './avatar-image.js';
|
import { renderUserAvatar } from './avatar-image.js';
|
||||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||||
import { resolvePublicFileUrl } from '../services/public-file-service.js';
|
import { resolvePublicFileUrl } from '../services/public-file-service.js';
|
||||||
|
import { openHistoryLayer } from '../router.js';
|
||||||
|
|
||||||
const drafts = new Map();
|
const drafts = new Map();
|
||||||
|
|
||||||
@@ -301,19 +302,13 @@ export function openChannelEditor({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const openedUrl = location.href;
|
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
|
||||||
const historyId = `${Date.now()}:${Math.random()}`;
|
const historyLayer = openHistoryLayer(() => close({ fromHistory: true }));
|
||||||
history.pushState({ ...history.state, channelEditor: historyId }, '', openedUrl);
|
|
||||||
const viewport = window.visualViewport;
|
const viewport = window.visualViewport;
|
||||||
const updateViewport = () => {
|
const updateViewport = () => {
|
||||||
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
||||||
overlay.style.setProperty('--editor-top', `${viewport?.offsetTop || 0}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(() => {
|
const observer = new MutationObserver(() => {
|
||||||
if (!overlay.isConnected) close({ restoreFocus: false });
|
if (!overlay.isConnected) close({ restoreFocus: false });
|
||||||
});
|
});
|
||||||
@@ -327,14 +322,8 @@ export function openChannelEditor({
|
|||||||
viewport?.removeEventListener('resize', updateViewport);
|
viewport?.removeEventListener('resize', updateViewport);
|
||||||
viewport?.removeEventListener('scroll', updateViewport);
|
viewport?.removeEventListener('scroll', updateViewport);
|
||||||
window.removeEventListener('resize', updateViewport);
|
window.removeEventListener('resize', updateViewport);
|
||||||
window.removeEventListener('popstate', onBack, true);
|
|
||||||
overlay.remove();
|
overlay.remove();
|
||||||
if (!fromHistory && location.href === openedUrl && history.state?.channelEditor === historyId) {
|
if (!fromHistory) historyLayer.close();
|
||||||
window.addEventListener('popstate', (event) => {
|
|
||||||
if (location.href === openedUrl) event.stopImmediatePropagation();
|
|
||||||
}, { capture: true, once: true });
|
|
||||||
history.back();
|
|
||||||
}
|
|
||||||
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
||||||
};
|
};
|
||||||
overlay.cleanup = () => close({ restoreFocus: false });
|
overlay.cleanup = () => close({ restoreFocus: false });
|
||||||
@@ -450,7 +439,6 @@ export function openChannelEditor({
|
|||||||
});
|
});
|
||||||
submitButton.addEventListener('click', () => void submit());
|
submitButton.addEventListener('click', () => void submit());
|
||||||
document.addEventListener('keydown', onDocumentKeydown);
|
document.addEventListener('keydown', onDocumentKeydown);
|
||||||
window.addEventListener('popstate', onBack, true);
|
|
||||||
viewport?.addEventListener('resize', updateViewport);
|
viewport?.addEventListener('resize', updateViewport);
|
||||||
viewport?.addEventListener('scroll', updateViewport);
|
viewport?.addEventListener('scroll', updateViewport);
|
||||||
window.addEventListener('resize', updateViewport);
|
window.addEventListener('resize', updateViewport);
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { captureClientError } from '../services/client-error-reporter.js';
|
|||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
import {
|
import {
|
||||||
animatePress,
|
animatePress,
|
||||||
|
createLoadErrorCard,
|
||||||
createSkeletonRows,
|
createSkeletonRows,
|
||||||
SKELETON_DELAY_MS,
|
SKELETON_DELAY_MS,
|
||||||
formatPostStamp,
|
formatPostStamp,
|
||||||
@@ -21,7 +22,7 @@ import {
|
|||||||
showToast,
|
showToast,
|
||||||
softHaptic,
|
softHaptic,
|
||||||
} from '../services/channels-ux.js';
|
} from '../services/channels-ux.js';
|
||||||
import { getPreviousTrackedPath, parseRouteFromPath } from '../router.js';
|
import { getPreviousTrackedPath, parseRouteFromPath, toPrettyPath } from '../router.js';
|
||||||
import { renderAvatar, renderUserAvatar } from '../components/avatar-image.js';
|
import { renderAvatar, renderUserAvatar } from '../components/avatar-image.js';
|
||||||
import { openChannelEditor } from '../components/channel-editor.js';
|
import { openChannelEditor } from '../components/channel-editor.js';
|
||||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||||
@@ -35,6 +36,7 @@ import {
|
|||||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||||
import { extractLoginFromBlockchainName, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
import { extractLoginFromBlockchainName, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||||
import { parsePublicationOrdinal, publicationAtOrdinal, ordinalForPublication } from '../services/channel-message-ordinals.js';
|
import { parsePublicationOrdinal, publicationAtOrdinal, ordinalForPublication } from '../services/channel-message-ordinals.js';
|
||||||
|
import { dropPageData, pageDataAge, readPageData, writePageData } from '../services/page-data-cache.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'channel-thread-view', title: 'Обсуждение', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
export const pageMeta = { id: 'channel-thread-view', title: 'Обсуждение', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||||
const MSG_SUBTYPE_TEXT_POST = 10;
|
const MSG_SUBTYPE_TEXT_POST = 10;
|
||||||
@@ -1222,6 +1224,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
|||||||
if (String(window.getSelection?.() || '').trim()) return;
|
if (String(window.getSelection?.() || '').trim()) return;
|
||||||
handlers.onOpenThread(target);
|
handlers.onOpenThread(target);
|
||||||
});
|
});
|
||||||
|
item.addEventListener('pointerdown', () => handlers.prefetchThread?.(target), { passive: true });
|
||||||
return item;
|
return item;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1368,6 +1371,187 @@ function setThreadMuted(key, muted) {
|
|||||||
// Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа.
|
// Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа.
|
||||||
const THREAD_LOAD_DEPTH = 8;
|
const THREAD_LOAD_DEPTH = 8;
|
||||||
|
|
||||||
|
// Загрузка обсуждения без привязки к экрану: её же использует подгрузка заранее, по касанию записи.
|
||||||
|
async function loadThreadData(sel, cacheKey, isCurrent) {
|
||||||
|
let ordinal = sel?.publicationOrdinal || null;
|
||||||
|
let resolvedMessage = sel.message;
|
||||||
|
let cachedChannelPayload = null;
|
||||||
|
if (sel.short?.ownerBlockchainName && sel.short?.channelName) {
|
||||||
|
// Канал, уже открытый в этой вкладке, известен из его кэша – список подписок не нужен.
|
||||||
|
const knownChannel = readPageData('channel', cacheKey.replace(/\/[^/]+\/?$/, ''))?.data?.selector;
|
||||||
|
const knownRow = knownChannel?.ownerBlockchainName && Number.isFinite(Number(knownChannel.channelRootBlockNumber))
|
||||||
|
&& String(knownChannel.channelName || '').toLowerCase() === String(sel.short.channelName || '').toLowerCase()
|
||||||
|
? { channel: {
|
||||||
|
ownerBlockchainName: knownChannel.ownerBlockchainName,
|
||||||
|
channelRoot: { blockNumber: Number(knownChannel.channelRootBlockNumber), blockHash: knownChannel.channelRootBlockHash },
|
||||||
|
} }
|
||||||
|
: null;
|
||||||
|
const ownFeed = !knownRow && state.session.isAuthorized ? await authService.listSubscriptionsFeed(state.session.login, 1000) : {};
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
const allRows = [
|
||||||
|
...(Array.isArray(ownFeed?.ownedChannels) ? ownFeed.ownedChannels : []),
|
||||||
|
...(Array.isArray(ownFeed?.followedUsersChannels) ? ownFeed.followedUsersChannels : []),
|
||||||
|
...(Array.isArray(ownFeed?.followedChannels) ? ownFeed.followedChannels : []),
|
||||||
|
];
|
||||||
|
const ownerRaw = String(sel.short.ownerBlockchainName || '').trim();
|
||||||
|
const ownerNormalized = ownerRaw.toLowerCase();
|
||||||
|
const ownerLoginFromBch = extractLoginFromBlockchainName(ownerRaw);
|
||||||
|
const channelNameNormalized = String(sel.short.channelName || '').trim().toLowerCase();
|
||||||
|
let channel = knownRow || allRows.find((item) => (
|
||||||
|
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerNormalized
|
||||||
|
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
||||||
|
));
|
||||||
|
if (!channel) {
|
||||||
|
channel = allRows.find((item) => (
|
||||||
|
String(item?.channel?.ownerLogin || '').trim().toLowerCase() === ownerNormalized
|
||||||
|
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if (!channel && !looksLikeBlockchainName(ownerRaw)) {
|
||||||
|
try {
|
||||||
|
const ownerUser = await authService.getUser(ownerRaw);
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
const ownerBch = String(ownerUser?.blockchainName || '').trim().toLowerCase();
|
||||||
|
if (ownerBch) {
|
||||||
|
channel = allRows.find((item) => (
|
||||||
|
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBch
|
||||||
|
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore fallback lookup errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!channel && ownerLoginFromBch) {
|
||||||
|
try {
|
||||||
|
const ownerFeed = await authService.listSubscriptionsFeed(ownerLoginFromBch, 500);
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
const ownerRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
|
||||||
|
channel = ownerRows.find((item) => (
|
||||||
|
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerNormalized
|
||||||
|
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
||||||
|
));
|
||||||
|
} catch {
|
||||||
|
// ignore owner feed lookup errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!channel && ownerLoginFromBch) {
|
||||||
|
try {
|
||||||
|
const publicChannels = await authService.listUserProfileChannels(ownerLoginFromBch, 'owned', 500, 0, true);
|
||||||
|
const row = (Array.isArray(publicChannels?.channels) ? publicChannels.channels : []).find((item) =>
|
||||||
|
String(item?.slug || '').trim().toLowerCase() === channelNameNormalized);
|
||||||
|
if (row) channel = { channel: {
|
||||||
|
ownerBlockchainName: row.ownerBlockchainName,
|
||||||
|
channelRoot: { blockNumber: Number(row.rootBlockNumber), blockHash: normalizeRouteHash(row.rootBlockHashHex) },
|
||||||
|
} };
|
||||||
|
} catch { /* Public profile may be unavailable. */ }
|
||||||
|
}
|
||||||
|
const ownerBch = String(channel?.channel?.ownerBlockchainName || '').trim();
|
||||||
|
const rootNo = Number(channel?.channel?.channelRoot?.blockNumber);
|
||||||
|
const rootHash = normalizeRouteHash(channel?.channel?.channelRoot?.blockHash);
|
||||||
|
if (!ownerBch || !Number.isFinite(rootNo) || !ordinal) {
|
||||||
|
throw new Error('Канал или сообщение не найдено.');
|
||||||
|
}
|
||||||
|
sel.channel = {
|
||||||
|
ownerBlockchainName: ownerBch,
|
||||||
|
channelRootBlockNumber: rootNo,
|
||||||
|
channelRootBlockHash: rootHash,
|
||||||
|
};
|
||||||
|
|
||||||
|
// One-based channel publication ordinal -> original POST block reference.
|
||||||
|
// Editions are deliberately excluded by GetChannelMessages on the server.
|
||||||
|
cachedChannelPayload = await authService.getChannelMessages(sel.channel, null, 'asc', state.session.isAuthorized ? state.session.login : '');
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
const message = publicationAtOrdinal(cachedChannelPayload?.messages || [], ordinal);
|
||||||
|
const blockNumber = Number(message?.messageRef?.blockNumber);
|
||||||
|
const blockHash = normalizeMessageHash(message?.messageRef?.blockHash);
|
||||||
|
if (!Number.isSafeInteger(blockNumber) || blockNumber < 0 || !blockHash) {
|
||||||
|
throw new Error(`Публикация №${ordinal} не найдена в канале.`);
|
||||||
|
}
|
||||||
|
resolvedMessage = {
|
||||||
|
blockchainName: String(message?.authorBlockchainName || ownerBch),
|
||||||
|
blockNumber,
|
||||||
|
blockHash,
|
||||||
|
};
|
||||||
|
sel.message = { ...resolvedMessage };
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await authService.getMessageThread(resolvedMessage, 20, THREAD_LOAD_DEPTH, 50, state.session.login);
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
|
||||||
|
const focus = payload?.focus || null;
|
||||||
|
|
||||||
|
const focusHash = normalizeMessageHash(focus?.messageRef?.blockHash);
|
||||||
|
if (focusHash && sel?.message) {
|
||||||
|
sel.message.blockHash = focusHash;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((!sel?.channel?.ownerBlockchainName || sel?.channel?.channelRootBlockNumber == null) && payload) {
|
||||||
|
const context = extractChannelContextFromThreadPayload(payload);
|
||||||
|
if (context) {
|
||||||
|
sel.channel = {
|
||||||
|
ownerBlockchainName: context.ownerBlockchainName,
|
||||||
|
channelRootBlockNumber: context.channelRootBlockNumber,
|
||||||
|
channelRootBlockHash: normalizeRouteHash(context.channelRootBlockHash),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let resolvedChannelLabel = resolveChannelDisplayName(sel?.channel);
|
||||||
|
if (!resolvedChannelLabel && sel?.channel?.ownerBlockchainName && sel?.channel?.channelRootBlockNumber != null) {
|
||||||
|
resolvedChannelLabel = await resolveChannelDisplayNameFromServer(sel.channel);
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
}
|
||||||
|
const resolvedChannelTitle = resolvedChannelLabel || String(sel?.channel?.ownerBlockchainName || '').trim() || 'неизвестно';
|
||||||
|
const channelSlug = String(sel?.short?.channelName || (resolvedChannelLabel.includes('/') ? resolvedChannelLabel.split('/').slice(1).join('/') : '')).trim();
|
||||||
|
let title = channelTitleByLabel.get(resolvedChannelTitle) || channelSlug || resolvedChannelTitle;
|
||||||
|
let avatarAr = '';
|
||||||
|
let avatarSha256 = '';
|
||||||
|
// Метаданные канала доступны гостям: заголовок и аватар берём из того же API, что у ленты.
|
||||||
|
if (sel?.channel?.ownerBlockchainName && sel?.channel?.channelRootBlockNumber != null && Number.isFinite(Number(sel.channel.channelRootBlockNumber))) {
|
||||||
|
try {
|
||||||
|
const channelPayload = cachedChannelPayload || await authService.getChannelMessages(sel.channel, null, 'asc', state.session.isAuthorized ? state.session.login : '');
|
||||||
|
if (!isCurrent()) return null;
|
||||||
|
if (!ordinal && focus) {
|
||||||
|
ordinal = ordinalForPublication(channelPayload?.messages || [], {
|
||||||
|
blockchainName: String(focus?.authorBlockchainName || sel.channel.ownerBlockchainName),
|
||||||
|
blockNumber: focus?.messageRef?.blockNumber,
|
||||||
|
blockHash: focus?.messageRef?.blockHash,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const meta = channelPayload?.channel || {};
|
||||||
|
title = String(meta.displayName || meta.channelName || title).trim();
|
||||||
|
avatarAr = String(meta.avaAr || '').trim();
|
||||||
|
avatarSha256 = String(meta.avaSha256 || '').trim().toLowerCase();
|
||||||
|
if (!sel.short && meta.channelName) sel.short = { ownerBlockchainName: sel.channel.ownerBlockchainName, channelName: String(meta.channelName) };
|
||||||
|
} catch {
|
||||||
|
// Обсуждение должно открываться даже при временной недоступности метаданных канала.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { selector: sel, ordinal, payload, resolvedChannelLabel, title, avatarAr, avatarSha256, channelSlug };
|
||||||
|
}
|
||||||
|
|
||||||
|
const threadPrefetches = new Map();
|
||||||
|
const THREAD_PREFETCH_FRESH_MS = 30_000;
|
||||||
|
|
||||||
|
// Начинает загрузку обсуждения заранее (касание карточки до клика); экран потом подхватит тот же запрос.
|
||||||
|
export function prefetchThreadPage(path) {
|
||||||
|
const pathname = new URL(path, window.location.origin).pathname;
|
||||||
|
if (threadPrefetches.has(pathname) || pageDataAge('thread', pathname) < THREAD_PREFETCH_FRESH_MS) return;
|
||||||
|
const route = parseRouteFromPath(pathname);
|
||||||
|
const sel = route.pageId === 'channel-thread-view' ? parseThreadSelector(route) : null;
|
||||||
|
if (!sel) return;
|
||||||
|
const login = state.session.login;
|
||||||
|
const request = loadThreadData(sel, pathname, () => state.session.login === login)
|
||||||
|
.then((data) => {
|
||||||
|
if (data) writePageData('thread', pathname, data);
|
||||||
|
return data;
|
||||||
|
})
|
||||||
|
.finally(() => { threadPrefetches.delete(pathname); });
|
||||||
|
request.catch(() => {});
|
||||||
|
threadPrefetches.set(pathname, request);
|
||||||
|
}
|
||||||
|
|
||||||
export function render({ navigate, route, chrome }) {
|
export function render({ navigate, route, chrome }) {
|
||||||
let selector = parseThreadSelector(route);
|
let selector = parseThreadSelector(route);
|
||||||
const channelDisplayName = resolveChannelDisplayName(selector?.channel);
|
const channelDisplayName = resolveChannelDisplayName(selector?.channel);
|
||||||
@@ -1570,6 +1754,10 @@ export function render({ navigate, route, chrome }) {
|
|||||||
showStatus(toUserMessage(error, 'Не удалось транслировать ссылку.'));
|
showStatus(toUserMessage(error, 'Не удалось транслировать ссылку.'));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
prefetchThread: (target) => {
|
||||||
|
const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal);
|
||||||
|
if (routePath) prefetchThreadPage(`/${toPrettyPath(routePath)}`);
|
||||||
|
},
|
||||||
onOpenThread: (target) => {
|
onOpenThread: (target) => {
|
||||||
const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal);
|
const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal);
|
||||||
if (!routePath) {
|
if (!routePath) {
|
||||||
@@ -1636,184 +1824,17 @@ export function render({ navigate, route, chrome }) {
|
|||||||
return timerId;
|
return timerId;
|
||||||
};
|
};
|
||||||
|
|
||||||
refresh = async () => {
|
// Рисует обсуждение по готовым данным: и из кэша при возврате, и после загрузки с сервера.
|
||||||
if (disposed) return;
|
const paint = (data, restorePosition, seq) => {
|
||||||
const seq = ++refreshSeq;
|
selector = data.selector;
|
||||||
const hadContent = !!screen.querySelector('.thread-block');
|
focusOrdinal = data.ordinal;
|
||||||
const restorePosition = hadContent ? document.getElementById('app-screen')?.scrollTop : readChannelPosition(positionKey);
|
const { payload, resolvedChannelLabel, title, avatarAr, avatarSha256, channelSlug } = data;
|
||||||
if (!hadContent) clearContent();
|
activeResolvedChannelLabel = resolvedChannelLabel;
|
||||||
showStatus('');
|
|
||||||
selector = parseThreadSelector(route);
|
|
||||||
focusOrdinal = selector?.publicationOrdinal || null;
|
|
||||||
activeResolvedChannelLabel = resolveChannelDisplayName(selector?.channel);
|
|
||||||
threadHeaderChannel.textContent = '…';
|
|
||||||
threadHeaderButton.disabled = true;
|
|
||||||
threadHeaderButton.onclick = null;
|
|
||||||
threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove();
|
|
||||||
threadHeaderTitle.textContent = 'Обсуждение';
|
|
||||||
|
|
||||||
if (!selector) {
|
|
||||||
const invalid = document.createElement('div');
|
|
||||||
invalid.className = 'card meta-muted';
|
|
||||||
invalid.textContent = 'Обсуждение не найдено: неверная ссылка.';
|
|
||||||
screen.append(invalid);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const skeleton = hadContent ? null : renderSkeleton(screen);
|
|
||||||
|
|
||||||
try {
|
|
||||||
let resolvedMessage = selector.message;
|
|
||||||
let cachedChannelPayload = null;
|
|
||||||
if (selector.short?.ownerBlockchainName && selector.short?.channelName) {
|
|
||||||
const ownFeed = state.session.isAuthorized ? await authService.listSubscriptionsFeed(state.session.login, 1000) : {};
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
const allRows = [
|
|
||||||
...(Array.isArray(ownFeed?.ownedChannels) ? ownFeed.ownedChannels : []),
|
|
||||||
...(Array.isArray(ownFeed?.followedUsersChannels) ? ownFeed.followedUsersChannels : []),
|
|
||||||
...(Array.isArray(ownFeed?.followedChannels) ? ownFeed.followedChannels : []),
|
|
||||||
];
|
|
||||||
const ownerRaw = String(selector.short.ownerBlockchainName || '').trim();
|
|
||||||
const ownerNormalized = ownerRaw.toLowerCase();
|
|
||||||
const ownerLoginFromBch = extractLoginFromBlockchainName(ownerRaw);
|
|
||||||
const channelNameNormalized = String(selector.short.channelName || '').trim().toLowerCase();
|
|
||||||
let channel = allRows.find((item) => (
|
|
||||||
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerNormalized
|
|
||||||
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
|
||||||
));
|
|
||||||
if (!channel) {
|
|
||||||
channel = allRows.find((item) => (
|
|
||||||
String(item?.channel?.ownerLogin || '').trim().toLowerCase() === ownerNormalized
|
|
||||||
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if (!channel && !looksLikeBlockchainName(ownerRaw)) {
|
|
||||||
try {
|
|
||||||
const ownerUser = await authService.getUser(ownerRaw);
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
const ownerBch = String(ownerUser?.blockchainName || '').trim().toLowerCase();
|
|
||||||
if (ownerBch) {
|
|
||||||
channel = allRows.find((item) => (
|
|
||||||
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBch
|
|
||||||
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
|
||||||
));
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ignore fallback lookup errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!channel && ownerLoginFromBch) {
|
|
||||||
try {
|
|
||||||
const ownerFeed = await authService.listSubscriptionsFeed(ownerLoginFromBch, 500);
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
const ownerRows = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels : [];
|
|
||||||
channel = ownerRows.find((item) => (
|
|
||||||
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerNormalized
|
|
||||||
&& String(item?.channel?.channelName || '').trim().toLowerCase() === channelNameNormalized
|
|
||||||
));
|
|
||||||
} catch {
|
|
||||||
// ignore owner feed lookup errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!channel && ownerLoginFromBch) {
|
|
||||||
try {
|
|
||||||
const publicChannels = await authService.listUserProfileChannels(ownerLoginFromBch, 'owned', 500, 0, true);
|
|
||||||
const row = (Array.isArray(publicChannels?.channels) ? publicChannels.channels : []).find((item) =>
|
|
||||||
String(item?.slug || '').trim().toLowerCase() === channelNameNormalized);
|
|
||||||
if (row) channel = { channel: {
|
|
||||||
ownerBlockchainName: row.ownerBlockchainName,
|
|
||||||
channelRoot: { blockNumber: Number(row.rootBlockNumber), blockHash: normalizeRouteHash(row.rootBlockHashHex) },
|
|
||||||
} };
|
|
||||||
} catch { /* Public profile may be unavailable. */ }
|
|
||||||
}
|
|
||||||
const ownerBch = String(channel?.channel?.ownerBlockchainName || '').trim();
|
|
||||||
const rootNo = Number(channel?.channel?.channelRoot?.blockNumber);
|
|
||||||
const rootHash = normalizeRouteHash(channel?.channel?.channelRoot?.blockHash);
|
|
||||||
if (!ownerBch || !Number.isFinite(rootNo) || !focusOrdinal) {
|
|
||||||
throw new Error('Канал или сообщение не найдено.');
|
|
||||||
}
|
|
||||||
selector.channel = {
|
|
||||||
ownerBlockchainName: ownerBch,
|
|
||||||
channelRootBlockNumber: rootNo,
|
|
||||||
channelRootBlockHash: rootHash,
|
|
||||||
};
|
|
||||||
|
|
||||||
// One-based channel publication ordinal -> original POST block reference.
|
|
||||||
// Editions are deliberately excluded by GetChannelMessages on the server.
|
|
||||||
cachedChannelPayload = await authService.getChannelMessages(selector.channel, null, 'asc', state.session.isAuthorized ? state.session.login : '');
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
const message = publicationAtOrdinal(cachedChannelPayload?.messages || [], focusOrdinal);
|
|
||||||
const blockNumber = Number(message?.messageRef?.blockNumber);
|
|
||||||
const blockHash = normalizeMessageHash(message?.messageRef?.blockHash);
|
|
||||||
if (!Number.isSafeInteger(blockNumber) || blockNumber < 0 || !blockHash) {
|
|
||||||
throw new Error(`Публикация №${focusOrdinal} не найдена в канале.`);
|
|
||||||
}
|
|
||||||
resolvedMessage = {
|
|
||||||
blockchainName: String(message?.authorBlockchainName || ownerBch),
|
|
||||||
blockNumber,
|
|
||||||
blockHash,
|
|
||||||
};
|
|
||||||
selector.message = { ...resolvedMessage };
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = await authService.getMessageThread(resolvedMessage, 20, THREAD_LOAD_DEPTH, 50, state.session.login);
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
skeleton?.remove();
|
|
||||||
|
|
||||||
const ancestors = Array.isArray(payload?.ancestors) ? payload.ancestors : [];
|
const ancestors = Array.isArray(payload?.ancestors) ? payload.ancestors : [];
|
||||||
const focus = payload?.focus || null;
|
const focus = payload?.focus || null;
|
||||||
const descendants = Array.isArray(payload?.descendants) ? payload.descendants : [];
|
const descendants = Array.isArray(payload?.descendants) ? payload.descendants : [];
|
||||||
|
const resolvedChannelTitle = resolvedChannelLabel || String(selector?.channel?.ownerBlockchainName || '').trim() || 'неизвестно';
|
||||||
const focusHash = normalizeMessageHash(focus?.messageRef?.blockHash);
|
|
||||||
if (focusHash && selector?.message) {
|
|
||||||
selector.message.blockHash = focusHash;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((!selector?.channel?.ownerBlockchainName || selector?.channel?.channelRootBlockNumber == null) && payload) {
|
|
||||||
const context = extractChannelContextFromThreadPayload(payload);
|
|
||||||
if (context) {
|
|
||||||
selector.channel = {
|
|
||||||
ownerBlockchainName: context.ownerBlockchainName,
|
|
||||||
channelRootBlockNumber: context.channelRootBlockNumber,
|
|
||||||
channelRootBlockHash: normalizeRouteHash(context.channelRootBlockHash),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolvedChannelLabel = resolveChannelDisplayName(selector?.channel);
|
|
||||||
if (!resolvedChannelLabel && selector?.channel?.ownerBlockchainName && selector?.channel?.channelRootBlockNumber != null) {
|
|
||||||
resolvedChannelLabel = await resolveChannelDisplayNameFromServer(selector.channel);
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
}
|
|
||||||
activeResolvedChannelLabel = resolvedChannelLabel;
|
|
||||||
const fallbackChannel = String(selector?.channel?.ownerBlockchainName || '').trim() || 'неизвестно';
|
|
||||||
const resolvedChannelTitle = resolvedChannelLabel || fallbackChannel;
|
|
||||||
const channelOwner = extractLoginFromBlockchainName(selector?.channel?.ownerBlockchainName || focus?.channelInfo?.ownerBlockchainName || selector?.short?.ownerBlockchainName || '');
|
const channelOwner = extractLoginFromBlockchainName(selector?.channel?.ownerBlockchainName || focus?.channelInfo?.ownerBlockchainName || selector?.short?.ownerBlockchainName || '');
|
||||||
const channelSlug = String(selector?.short?.channelName || (resolvedChannelLabel.includes('/') ? resolvedChannelLabel.split('/').slice(1).join('/') : '')).trim();
|
|
||||||
let title = channelTitleByLabel.get(resolvedChannelTitle) || channelSlug || resolvedChannelTitle;
|
|
||||||
let avatarAr = '';
|
|
||||||
let avatarSha256 = '';
|
|
||||||
// Метаданные канала доступны гостям: заголовок и аватар берём из того же API, что у ленты.
|
|
||||||
if (selector?.channel?.ownerBlockchainName && selector?.channel?.channelRootBlockNumber != null && Number.isFinite(Number(selector.channel.channelRootBlockNumber))) {
|
|
||||||
try {
|
|
||||||
const channelPayload = cachedChannelPayload || await authService.getChannelMessages(selector.channel, null, 'asc', state.session.isAuthorized ? state.session.login : '');
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
if (!focusOrdinal && focus) {
|
|
||||||
focusOrdinal = ordinalForPublication(channelPayload?.messages || [], {
|
|
||||||
blockchainName: String(focus?.authorBlockchainName || selector.channel.ownerBlockchainName),
|
|
||||||
blockNumber: focus?.messageRef?.blockNumber,
|
|
||||||
blockHash: focus?.messageRef?.blockHash,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const meta = channelPayload?.channel || {};
|
|
||||||
title = String(meta.displayName || meta.channelName || title).trim();
|
|
||||||
avatarAr = String(meta.avaAr || '').trim();
|
|
||||||
avatarSha256 = String(meta.avaSha256 || '').trim().toLowerCase();
|
|
||||||
if (!selector.short && meta.channelName) selector.short = { ownerBlockchainName: selector.channel.ownerBlockchainName, channelName: String(meta.channelName) };
|
|
||||||
} catch {
|
|
||||||
// Обсуждение должно открываться даже при временной недоступности метаданных канала.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const shortName = String(selector?.short?.channelName || channelSlug).trim();
|
const shortName = String(selector?.short?.channelName || channelSlug).trim();
|
||||||
const visibleOwner = channelOwner || extractLoginFromBlockchainName(selector?.short?.ownerBlockchainName || '');
|
const visibleOwner = channelOwner || extractLoginFromBlockchainName(selector?.short?.ownerBlockchainName || '');
|
||||||
const number = focusOrdinal || (selector?.short ? null : Number(selector?.message?.blockNumber));
|
const number = focusOrdinal || (selector?.short ? null : Number(selector?.message?.blockNumber));
|
||||||
@@ -2090,20 +2111,75 @@ export function render({ navigate, route, chrome }) {
|
|||||||
focusWrap.scrollIntoView({ behavior: 'auto', block: 'start' });
|
focusWrap.scrollIntoView({ behavior: 'auto', block: 'start' });
|
||||||
}, 20));
|
}, 20));
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
refresh = async () => {
|
||||||
|
if (disposed) return;
|
||||||
|
const seq = ++refreshSeq;
|
||||||
|
const hadContent = !!screen.querySelector('.thread-block');
|
||||||
|
const restorePosition = hadContent ? document.getElementById('app-screen')?.scrollTop : readChannelPosition(positionKey);
|
||||||
|
if (!hadContent) clearContent();
|
||||||
|
showStatus('');
|
||||||
|
const sel = parseThreadSelector(route);
|
||||||
|
|
||||||
|
if (!sel) {
|
||||||
|
const invalid = document.createElement('div');
|
||||||
|
invalid.className = 'card meta-muted';
|
||||||
|
invalid.textContent = 'Обсуждение не найдено: неверная ссылка.';
|
||||||
|
screen.append(invalid);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheKey = window.location.pathname;
|
||||||
|
// При возврате к обсуждению сразу показываем прошлую загрузку, без заглушки и пустого кадра.
|
||||||
|
const cached = hadContent ? null : readPageData('thread', cacheKey);
|
||||||
|
let shown = hadContent;
|
||||||
|
if (cached) {
|
||||||
|
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
|
||||||
|
await Promise.resolve();
|
||||||
|
if (disposed || seq !== refreshSeq) return;
|
||||||
|
try {
|
||||||
|
paint(cached.data, restorePosition, seq);
|
||||||
|
shown = true;
|
||||||
|
} catch (error) {
|
||||||
|
logThreadRuntimeError('paint_cached', error);
|
||||||
|
dropPageData('thread', cacheKey);
|
||||||
|
clearContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!shown) {
|
||||||
|
selector = sel;
|
||||||
|
focusOrdinal = sel?.publicationOrdinal || null;
|
||||||
|
activeResolvedChannelLabel = resolveChannelDisplayName(sel?.channel);
|
||||||
|
threadHeaderChannel.textContent = '…';
|
||||||
|
threadHeaderButton.disabled = true;
|
||||||
|
threadHeaderButton.onclick = null;
|
||||||
|
threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove();
|
||||||
|
threadHeaderTitle.textContent = 'Обсуждение';
|
||||||
|
}
|
||||||
|
const skeleton = shown ? null : renderSkeleton(screen);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pending = threadPrefetches.get(cacheKey);
|
||||||
|
const data = pending
|
||||||
|
? await pending.catch(() => loadThreadData(sel, cacheKey, () => !disposed && seq === refreshSeq))
|
||||||
|
: await loadThreadData(sel, cacheKey, () => !disposed && seq === refreshSeq);
|
||||||
|
if (!data || disposed || seq !== refreshSeq) return;
|
||||||
|
const signature = writePageData('thread', cacheKey, data);
|
||||||
|
// Сервер вернул то же, что уже на экране, – ничего не трогаем.
|
||||||
|
if (cached && cached.signature === signature) return;
|
||||||
|
skeleton?.remove();
|
||||||
|
paint(data, shown ? document.getElementById('app-screen')?.scrollTop : restorePosition, seq);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (disposed || seq !== refreshSeq) return;
|
if (disposed || seq !== refreshSeq) return;
|
||||||
skeleton?.remove();
|
skeleton?.remove();
|
||||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить обсуждение.')); return; }
|
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить обсуждение.')); return; }
|
||||||
const failed = document.createElement('div');
|
threadHeaderChannel.textContent = '';
|
||||||
failed.className = 'card meta-muted';
|
screen.append(createLoadErrorCard({
|
||||||
failed.textContent = `Не удалось загрузить обсуждение: ${toUserMessage(error, 'неизвестная ошибка')}`;
|
title: 'Не удалось загрузить обсуждение',
|
||||||
const retry = document.createElement('button');
|
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
|
||||||
retry.type = 'button';
|
onRetry: () => void refresh(),
|
||||||
retry.className = 'primary-btn';
|
}));
|
||||||
retry.textContent = 'Повторить';
|
|
||||||
retry.addEventListener('click', () => void refresh());
|
|
||||||
failed.append(retry);
|
|
||||||
screen.append(failed);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
|||||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
import { iconHtml } from '../components/ui-icon.js';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.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 { attachMessageMenu } from '../components/message-menu.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import {
|
import {
|
||||||
@@ -15,6 +16,7 @@ import {
|
|||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
import {
|
import {
|
||||||
animatePress,
|
animatePress,
|
||||||
|
createLoadErrorCard,
|
||||||
createSkeletonRows,
|
createSkeletonRows,
|
||||||
SKELETON_DELAY_MS,
|
SKELETON_DELAY_MS,
|
||||||
dayKey,
|
dayKey,
|
||||||
@@ -51,6 +53,7 @@ import {
|
|||||||
makeShineChannelDonateRoute,
|
makeShineChannelDonateRoute,
|
||||||
} from '../services/shine-routes.js';
|
} from '../services/shine-routes.js';
|
||||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.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';
|
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'channel-view', title: 'Канал', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
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) {
|
function renderLoadError(screen, navigate, message, onRetry) {
|
||||||
const card = document.createElement('div');
|
screen.append(createLoadErrorCard({
|
||||||
card.className = 'card stack channels-status';
|
title: 'Не удалось загрузить канал',
|
||||||
card.innerHTML = `
|
message: message || 'Проверьте подключение и повторите попытку.',
|
||||||
<strong>Не удалось загрузить канал</strong>
|
onRetry,
|
||||||
<p class="meta-muted">${message || 'Проверьте подключение к серверу и повторите попытку.'}</p>
|
secondary: { label: 'Назад к каналам', onClick: () => navigate('channels-list') },
|
||||||
`;
|
}));
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDemoFallback(screen, navigate, error) {
|
function renderDemoFallback(screen, navigate, error) {
|
||||||
@@ -2123,6 +2111,11 @@ function renderPostCard(post, {
|
|||||||
openDiscussion();
|
openDiscussion();
|
||||||
});
|
});
|
||||||
card.classList.add('is-openable');
|
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');
|
const replyButton = document.createElement('button');
|
||||||
replyButton.type = '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) {
|
function renderSkeleton(screen) {
|
||||||
const wrap = document.createElement('div');
|
const wrap = document.createElement('div');
|
||||||
@@ -2960,37 +2963,8 @@ export function render({ navigate, route, chrome }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
refresh = async () => {
|
// Рисует канал по готовым данным: и из кэша при возврате, и после загрузки с сервера.
|
||||||
if (disposed) return;
|
const paint = (apiData, restorePosition) => {
|
||||||
const seq = ++refreshSeq;
|
|
||||||
const hadContent = !!screen.querySelector('.channel-feed');
|
|
||||||
// Прежнее место в ленте восстанавливаем только при возврате из обсуждения / «О канале».
|
|
||||||
// Открытие канала из списка или другого раздела ведёт к свежим постам (или к непрочитанным).
|
|
||||||
const previousPath = getPreviousTrackedPath() || '';
|
|
||||||
const returnedFromChannelPage = /^\/(SHiNE|thread)\//.test(previousPath) || /\/(about|donate)$/.test(previousPath);
|
|
||||||
const restorePosition = hadContent
|
|
||||||
? 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 skeleton = hadContent ? null : renderSkeleton(screen);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const apiData = await loadFromApi(route, channelId);
|
|
||||||
if (disposed || seq !== refreshSeq) return;
|
|
||||||
activeSelector = apiData?.selector || null;
|
activeSelector = apiData?.selector || null;
|
||||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||||
@@ -3049,7 +3023,6 @@ export function render({ navigate, route, chrome }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
skeleton?.remove();
|
|
||||||
clearContent();
|
clearContent();
|
||||||
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||||
chrome,
|
chrome,
|
||||||
@@ -3145,10 +3118,66 @@ export function render({ navigate, route, chrome }) {
|
|||||||
},
|
},
|
||||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||||
});
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
refresh = async () => {
|
||||||
|
if (disposed) return;
|
||||||
|
const seq = ++refreshSeq;
|
||||||
|
const hadContent = !!screen.querySelector('.channel-feed');
|
||||||
|
// Прежнее место в ленте восстанавливаем только при возврате из обсуждения / «О канале».
|
||||||
|
// Открытие канала из списка или другого раздела ведёт к свежим постам (или к непрочитанным).
|
||||||
|
const previousPath = getPreviousTrackedPath() || '';
|
||||||
|
const returnedFromChannelPage = /^\/(SHiNE|thread)\//.test(previousPath) || /\/(about|donate)$/.test(previousPath);
|
||||||
|
const restorePosition = hadContent
|
||||||
|
? getChannelScrollRoot()?.scrollTop
|
||||||
|
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
||||||
|
if (!hadContent) clearContent();
|
||||||
|
showStatus('');
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
const signature = writePageData('channel', cacheKey, apiData);
|
||||||
|
// Сервер вернул то же, что уже на экране, – ничего не трогаем, чтобы не дёргать ленту.
|
||||||
|
if (cached && cached.signature === signature) return;
|
||||||
|
skeleton?.remove();
|
||||||
|
paint(apiData, shown ? getChannelScrollRoot()?.scrollTop : restorePosition);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (disposed || seq !== refreshSeq) return;
|
if (disposed || seq !== refreshSeq) return;
|
||||||
skeleton?.remove();
|
skeleton?.remove();
|
||||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||||
|
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span>';
|
||||||
if (isChannelsDemoMode()) {
|
if (isChannelsDemoMode()) {
|
||||||
renderDemoFallback(screen, navigate, error);
|
renderDemoFallback(screen, navigate, error);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
|||||||
import { parseMessageAttachments } from '../services/attachment-format.js';
|
import { parseMessageAttachments } from '../services/attachment-format.js';
|
||||||
import {
|
import {
|
||||||
animatePress,
|
animatePress,
|
||||||
|
createLoadErrorCard,
|
||||||
createSkeletonRows,
|
createSkeletonRows,
|
||||||
SKELETON_DELAY_MS,
|
SKELETON_DELAY_MS,
|
||||||
formatListTime,
|
formatListTime,
|
||||||
@@ -21,6 +22,9 @@ import { createDropdownMenu } from '../components/dropdown-menu.js';
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.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' } };
|
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 };
|
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) {
|
function toListModel(groups) {
|
||||||
return [
|
return [
|
||||||
...(groups.ownChannels || []),
|
...(groups.ownChannels || []),
|
||||||
@@ -923,24 +956,11 @@ function renderSkeletonList(container, count = 4) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderErrorState(container, error, onRetry) {
|
function renderErrorState(container, error, onRetry) {
|
||||||
const errCard = document.createElement('div');
|
container.append(createLoadErrorCard({
|
||||||
errCard.className = 'card stack channels-status';
|
title: 'Не удалось загрузить каналы',
|
||||||
|
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
|
||||||
const title = document.createElement('strong');
|
onRetry,
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
||||||
@@ -1064,7 +1084,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
|||||||
}
|
}
|
||||||
|
|
||||||
const list = document.createElement('div');
|
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 });
|
const rerenderList = () => renderListContent({ screen, container, listState, navigate, refreshFeed });
|
||||||
|
|
||||||
|
|||||||
@@ -280,6 +280,9 @@ function renderItem(item, activeTab, navigate) {
|
|||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
|
||||||
|
let lastNotifications = null;
|
||||||
|
|
||||||
export function render({ navigate, chrome } = {}) {
|
export function render({ navigate, chrome } = {}) {
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack notifications-screen';
|
screen.className = 'stack notifications-screen';
|
||||||
@@ -382,8 +385,19 @@ export function render({ navigate, chrome } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
|
const seq=++requestSeq;
|
||||||
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
|
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);}
|
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);
|
const fresh = await loadUserProfileCard(login);
|
||||||
if (!screen.isConnected && card) return;
|
if (!screen.isConnected && card) return;
|
||||||
|
// Та же карточка – не перерисовываем, иначе аватар и счётчики мигают.
|
||||||
|
if (card && JSON.stringify(card) === JSON.stringify(fresh)) return;
|
||||||
card = fresh;
|
card = fresh;
|
||||||
cardCache.set(login.toLowerCase(), card);
|
cardCache.set(login.toLowerCase(), card);
|
||||||
renderProfile();
|
renderProfile();
|
||||||
|
|||||||
@@ -23,20 +23,14 @@ export function render({ navigate }) {
|
|||||||
logoWrap.append(logo);
|
logoWrap.append(logo);
|
||||||
|
|
||||||
const brandBlock = document.createElement('div');
|
const brandBlock = document.createElement('div');
|
||||||
brandBlock.className = 'stack';
|
brandBlock.className = 'stack auth-brand-block';
|
||||||
brandBlock.style.alignItems = 'center';
|
|
||||||
brandBlock.style.gap = '22px';
|
|
||||||
|
|
||||||
const title = document.createElement('h1');
|
const title = document.createElement('h1');
|
||||||
title.className = 'auth-brand';
|
title.className = 'auth-brand';
|
||||||
title.append(createShineWordmark());
|
title.append(createShineWordmark());
|
||||||
|
|
||||||
const siteName = document.createElement('p');
|
const siteName = document.createElement('p');
|
||||||
siteName.className = 'meta-muted';
|
siteName.className = 'meta-muted auth-site-name';
|
||||||
siteName.style.margin = '0';
|
|
||||||
siteName.style.fontSize = '18px';
|
|
||||||
siteName.style.letterSpacing = '0.045em';
|
|
||||||
siteName.style.lineHeight = '1.25';
|
|
||||||
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
||||||
|
|
||||||
brandBlock.append(title, siteName);
|
brandBlock.append(title, siteName);
|
||||||
@@ -73,5 +67,23 @@ export function render({ navigate }) {
|
|||||||
|
|
||||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||||
screen.append(logoWrap, brandBlock, actions);
|
screen.append(logoWrap, brandBlock, actions);
|
||||||
|
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
|
||||||
|
queueMicrotask(() => continueSplashAnimations(logoWrap));
|
||||||
return screen;
|
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'));
|
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) {
|
export function toPrettyPath(path) {
|
||||||
const raw = String(path || '').replace(/^\/+/, '').replace(/\/+$/, '');
|
const raw = String(path || '').replace(/^\/+/, '').replace(/\/+$/, '');
|
||||||
if (!raw) return '';
|
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) {
|
export function normalizeChannelDescription(value) {
|
||||||
const text = String(value == null ? '' : value).trim().replace(/\s+/g, ' ');
|
const text = String(value == null ? '' : value).trim().replace(/\s+/g, ' ');
|
||||||
@@ -320,3 +320,30 @@ export const REPOSTS_ENABLED = false;
|
|||||||
export function notifyRepostSoon() {
|
export function notifyRepostSoon() {
|
||||||
showToast('Репосты скоро появятся');
|
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);
|
background: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.channels-list-body-fade { animation: channels-fade-in 160ms ease-out; }
|
.channels-status p {
|
||||||
@keyframes channels-fade-in { from { opacity: 0; } to { opacity: 1; } }
|
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 {
|
.channels-search-suggest {
|
||||||
max-height: 240px;
|
max-height: 240px;
|
||||||
@@ -277,5 +286,5 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@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;
|
position: fixed;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
z-index: 10000;
|
z-index: 10000;
|
||||||
display: grid;
|
|
||||||
align-content: center;
|
|
||||||
justify-items: center;
|
|
||||||
gap: clamp(12px, 2.4vh, 20px);
|
|
||||||
padding: 24px;
|
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background:
|
background: var(--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);
|
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
visibility: visible;
|
visibility: visible;
|
||||||
transition: opacity 520ms ease, visibility 520ms ease;
|
transition: opacity 360ms ease, visibility 360ms ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -38,46 +29,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.initial-splash__logo-wrap {
|
/* Та же геометрия, что у оболочки и экрана входа: ширина оболочки, поля .screen-content.no-app-chrome. */
|
||||||
position: relative;
|
.initial-splash__frame {
|
||||||
isolation: isolate;
|
width: min(100vw, var(--shell-content-width, 640px));
|
||||||
width: clamp(156px, 42vw, 208px);
|
height: 100dvh;
|
||||||
aspect-ratio: 1;
|
margin: 0 auto;
|
||||||
|
padding: 0 16px calc(24px + env(safe-area-inset-bottom));
|
||||||
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.initial-splash__logo-wrap::before {
|
.initial-splash__actions { visibility: hidden; }
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
.auth-screen--welcome {
|
.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-actions,
|
||||||
.auth-footer-actions {
|
.auth-footer-actions {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -309,12 +285,6 @@
|
|||||||
|
|
||||||
|
|
||||||
@media (max-height: 760px) {
|
@media (max-height: 760px) {
|
||||||
.initial-splash__logo-wrap {
|
|
||||||
width: 206px;
|
|
||||||
}
|
|
||||||
.initial-splash__brand {
|
|
||||||
font-size: 40px;
|
|
||||||
}
|
|
||||||
.auth-logo-wrap {
|
.auth-logo-wrap {
|
||||||
width: 206px;
|
width: 206px;
|
||||||
}
|
}
|
||||||
@@ -331,8 +301,6 @@
|
|||||||
.initial-splash {
|
.initial-splash {
|
||||||
transition-duration: 1ms;
|
transition-duration: 1ms;
|
||||||
}
|
}
|
||||||
.initial-splash__logo,
|
|
||||||
.initial-splash__logo-wrap::before,
|
|
||||||
.auth-logo,
|
.auth-logo,
|
||||||
.auth-logo-wrap::before,
|
.auth-logo-wrap::before,
|
||||||
.auth-logo-wrap::after,
|
.auth-logo-wrap::after,
|
||||||
|
|||||||
Reference in New Issue
Block a user