diff --git a/VERSION.properties b/VERSION.properties index b039c700..2d7f9456 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.18.6 +client.version=1.18.7 server.version=1.14.0 diff --git a/shine-UI/index.html b/shine-UI/index.html index 38fbb4c8..93272e13 100644 --- a/shine-UI/index.html +++ b/shine-UI/index.html @@ -39,7 +39,7 @@ }()); -
-
- + +
+
+
+
+ +
+
+

+

+
+ +
-
Сияние
+
diff --git a/shine-UI/js/app.js b/shine-UI/js/app.js index 3ab9fc1f..42f76f78 100644 --- a/shine-UI/js/app.js +++ b/shine-UI/js/app.js @@ -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 }); diff --git a/shine-UI/js/components/channel-editor.js b/shine-UI/js/components/channel-editor.js index 77b98014..cbfd8e12 100644 --- a/shine-UI/js/components/channel-editor.js +++ b/shine-UI/js/components/channel-editor.js @@ -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); diff --git a/shine-UI/js/pages/channel-thread-view.js b/shine-UI/js/pages/channel-thread-view.js index 5cd54f4d..5b2da946 100644 --- a/shine-UI/js/pages/channel-thread-view.js +++ b/shine-UI/js/pages/channel-thread-view.js @@ -9,6 +9,7 @@ import { captureClientError } from '../services/client-error-reporter.js'; import { toUserMessage } from '../services/ui-error-texts.js'; import { animatePress, + createLoadErrorCard, createSkeletonRows, SKELETON_DELAY_MS, formatPostStamp, @@ -21,7 +22,7 @@ import { showToast, softHaptic, } 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 { openChannelEditor } from '../components/channel-editor.js'; import { createDropdownMenu } from '../components/dropdown-menu.js'; @@ -35,6 +36,7 @@ import { import { loadProfileSnapshot } from '../services/user-profile-params.js'; import { extractLoginFromBlockchainName, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.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' } }; 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; handlers.onOpenThread(target); }); + item.addEventListener('pointerdown', () => handlers.prefetchThread?.(target), { passive: true }); return item; } @@ -1368,6 +1371,187 @@ function setThreadMuted(key, muted) { // Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа. 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 }) { let selector = parseThreadSelector(route); const channelDisplayName = resolveChannelDisplayName(selector?.channel); @@ -1570,6 +1754,10 @@ export function render({ navigate, route, chrome }) { showStatus(toUserMessage(error, 'Не удалось транслировать ссылку.')); } }, + prefetchThread: (target) => { + const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal); + if (routePath) prefetchThreadPage(`/${toPrettyPath(routePath)}`); + }, onOpenThread: (target) => { const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal); if (!routePath) { @@ -1636,6 +1824,295 @@ export function render({ navigate, route, chrome }) { return timerId; }; + // Рисует обсуждение по готовым данным: и из кэша при возврате, и после загрузки с сервера. + const paint = (data, restorePosition, seq) => { + selector = data.selector; + focusOrdinal = data.ordinal; + const { payload, resolvedChannelLabel, title, avatarAr, avatarSha256, channelSlug } = data; + activeResolvedChannelLabel = resolvedChannelLabel; + const ancestors = Array.isArray(payload?.ancestors) ? payload.ancestors : []; + const focus = payload?.focus || null; + const descendants = Array.isArray(payload?.descendants) ? payload.descendants : []; + const resolvedChannelTitle = resolvedChannelLabel || String(selector?.channel?.ownerBlockchainName || '').trim() || 'неизвестно'; + const channelOwner = extractLoginFromBlockchainName(selector?.channel?.ownerBlockchainName || focus?.channelInfo?.ownerBlockchainName || selector?.short?.ownerBlockchainName || ''); + const shortName = String(selector?.short?.channelName || channelSlug).trim(); + const visibleOwner = channelOwner || extractLoginFromBlockchainName(selector?.short?.ownerBlockchainName || ''); + const number = focusOrdinal || (selector?.short ? null : Number(selector?.message?.blockNumber)); + const headerNumber = Number.isSafeInteger(number) && number > 0 ? ` · №${number}` : ''; + if (threadHeaderButton) { + threadHeaderTitle.textContent = `${title}${headerNumber}`; + threadHeaderChannel.textContent = `${visibleOwner ? `@${visibleOwner}` : ''}${visibleOwner && shortName ? ' / ' : ''}${shortName}`; + threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove(); + const avatar = renderAvatar({ + initials: (title[0] || 'К').toUpperCase(), + avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null, + authorLogin: visibleOwner, + size: 'xl', + className: 'channel-profile-avatar channel-thread-header-avatar', + title, + alt: 'Аватар канала', + }); + avatar.style.setProperty('--channel-avatar-size', '40px'); + threadHeaderButton.prepend(avatar); + threadHeaderButton.title = 'Открыть канал'; + threadHeaderButton.disabled = false; + threadHeaderButton.onclick = (event) => { + event.preventDefault(); + animatePress(event.currentTarget); + const routeToChannel = buildChannelRouteFromThread(selector, resolvedChannelLabel); + if (routeToChannel) navigate(routeToChannel); + else navigate('channels-list'); + }; + } + + clearContent(); + const openPost = () => { + const routeToChannel = buildChannelRouteFromThread(selector, resolvedChannelLabel); + if (routeToChannel) navigate(routeToChannel); + }; + const focusTarget = focus ? buildTargetFromNode(focus) : null; + threadMenuActions = () => { + const muted = isThreadMuted(routeKey); + return [ + { label: 'Перейти к записи', iconHtml: iconHtml('doc'), action: openPost }, + { label: muted ? 'Уведомлять об ответах' : 'Не уведомлять об ответах', iconHtml: iconHtml(muted ? 'bell' : 'bell-off'), action: () => { + setThreadMuted(routeKey, !muted); + showToast(muted ? 'Уведомления об ответах включены' : 'Ответы в этом обсуждении не будут приходить в уведомления'); + } }, + { label: 'Поделиться записью', iconHtml: iconHtml('share'), action: () => { + if (!focusTarget) return; + openShareSheet({ + title: 'Поделиться записью', + kicker: `${resolvedChannelTitle} · запись`, + text: parseMessageAttachments(resolveNodeText(focus)).text, + url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector, focusOrdinal)), + }); + } }, + ]; + }; + + const ancestorHandlers = { + ...handlers, + jumpTo: () => {}, + setReplyTo: (node) => handlers.openReplyEditor(node), + shareComment: (node) => openShareSheet({ + title: 'Поделиться', + kicker: `${node.authorLogin} · запись`, + text: parseMessageAttachments(resolveNodeText(node)).text, + url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(buildTargetFromNode(node), selector, null)), + }), + }; + // Над открытым ответом – цепочка до исходной записи, как в Threads: те же карточки, соединённые линией. + if (ancestors.length) { + const ancestorsWrap = document.createElement('div'); + ancestorsWrap.className = 'thread-block thread-block--ancestors'; + const ownerBch = String(selector?.channel?.ownerBlockchainName || '').toLowerCase(); + ancestors.forEach((node, index) => { + const isChannelPost = index === 0 && ownerBch && String(node?.authorBlockchainName || '').toLowerCase() === ownerBch; + let identity = null; + if (isChannelPost) { + const avatar = renderAvatar({ + initials: (title[0] || 'К').toUpperCase(), + avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null, + authorLogin: node?.authorLogin, + size: 'xl', + className: 'channel-profile-avatar thread-comment__avatar', + title, + alt: 'Аватар канала', + }); + avatar.style.setProperty('--channel-avatar-size', '36px'); + identity = { title, avatar }; + } + try { + const row = renderComment({ node, parent: null, focus: null, channelOwner, handlers: ancestorHandlers, identity }); + row.classList.add('thread-comment--ancestor'); + ancestorsWrap.append(row); + } catch (error) { logThreadRuntimeError('render_ancestor', error); } + }); + screen.append(ancestorsWrap); + } + if (focus) { + const focusWrap = document.createElement('div'); + focusWrap.className = 'thread-block thread-block--focus'; + focusWrap.append(renderNodeCard(focus, '', handlers, focusOrdinal || Number(selector?.message?.blockNumber ?? 0), { + focusPost: true, + channelOwnerBlockchainName: selector?.channel?.ownerBlockchainName || '', + channel: { title, avatarAr, avatarSha256 }, + })); + screen.append(focusWrap); + } + + const comments = flattenDescendants(descendants); + const listWrap = document.createElement('div'); + listWrap.className = 'thread-block thread-block--replies'; + const listTitle = document.createElement('h3'); + listTitle.className = 'thread-section-title'; + listTitle.textContent = `Комментарии · ${comments.length}`; + listWrap.append(listTitle); + + // Возврат к ответу после перехода по цитате + const returnBtn = document.createElement('button'); + returnBtn.type = 'button'; + returnBtn.className = 'thread-return'; + returnBtn.hidden = true; + returnBtn.textContent = 'Вернуться к ответу'; + let returnKey = ''; + const highlight = (el) => { + screen.querySelectorAll('.thread-comment.is-highlight').forEach((x) => x.classList.remove('is-highlight')); + el?.classList.add('is-highlight'); + }; + returnBtn.addEventListener('click', () => { + const el = listWrap.querySelector(`[data-message-key="${CSS.escape(returnKey)}"]`); + el?.scrollIntoView({ block: 'center', behavior: 'smooth' }); + highlight(el); + returnBtn.hidden = true; + }); + + const commentHandlers = { + ...handlers, + jumpTo: (key, fromKey) => { + const el = listWrap.querySelector(`[data-message-key="${CSS.escape(key)}"]`); + if (!el) return; + el.closest('.thread-replies')?.classList.add('is-expanded'); + el.scrollIntoView({ block: 'center', behavior: 'smooth' }); + highlight(el); + returnKey = fromKey; + returnBtn.hidden = false; + }, + shareComment: (node) => openShareSheet({ + title: 'Поделиться комментарием', + kicker: `${node.authorLogin} · комментарий`, + text: parseMessageAttachments(resolveNodeText(node)).text, + // Ссылка ведёт на обсуждение самого комментария – так же он открывается нажатием. + url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(buildTargetFromNode(node), selector, null)), + }), + }; + + if (comments.length) { + descendants.forEach((branch) => { + if (!branch?.node) return; + try { listWrap.append(renderReplyGroup(branch, { focus, channelOwner, handlers: commentHandlers })); } + catch (error) { logThreadRuntimeError('render_comment', error); } + }); + } else { + const empty = document.createElement('div'); + empty.className = 'empty-note thread-empty'; + empty.textContent = 'Пока нет комментариев. Можно начать разговор.'; + listWrap.append(empty); + } + screen.append(listWrap, returnBtn); + + // Ответ пишется в том же редакторе, что и запись канала; над полем – цепочка до исходной записи. + const parentByKey = new Map(); + const indexParents = (items, parent) => (Array.isArray(items) ? items : []).forEach((branch) => { + if (!branch?.node) return; + parentByKey.set(nodeKey(branch.node), parent); + indexParents(branch.children, branch.node); + }); + indexParents(descendants, focus); + const chainItem = (node) => { + const parsedNode = parseMessageAttachments(resolveNodeText(node)); + // Начало цепочки – запись канала: показываем её от имени канала, как в ленте. + const isRoot = ancestors.length ? node === ancestors[0] : node === focus; + const isChannelPost = isRoot && Boolean(selector?.channel?.ownerBlockchainName) + && String(node?.authorBlockchainName || '').toLowerCase() === String(selector.channel.ownerBlockchainName).toLowerCase(); + const item = { + author: String(node?.authorLogin || ''), + time: formatShortAge(node?.createdAtMs), + text: parsedNode.text, + attachmentLabel: parsedNode.attachments.length ? 'Вложение' : '', + }; + if (isChannelPost) { + item.title = title; + item.avatar = renderAvatar({ + initials: (title[0] || 'К').toUpperCase(), + avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null, + authorLogin: item.author, + size: 'xl', + className: 'channel-profile-avatar', + title, + alt: 'Аватар канала', + }); + item.avatar.style.setProperty('--channel-avatar-size', '40px'); + } + return item; + }; + replyEditorOpener = (node, { attach = false } = {}) => { + if (!node || disposed) return; + const path = []; + for (let cur = node; cur && cur !== focus; cur = parentByKey.get(nodeKey(cur))) path.unshift(cur); + const chain = [...ancestors, focus, ...path].filter(Boolean).map(chainItem); + openChannelEditor({ + id: 'thread-reply-modal', + title: 'Ответ', + submitLabel: 'Ответить', + placeholder: `Ответить ${node.authorLogin || ''}…`, + context: { chain }, + key: `thread-reply:${nodeKey(node)}`, + openAttachOnStart: attach, + isActive: () => !disposed, + onSubmit: ({ text }) => handlers.onReply(buildTargetFromNode(node), text), + }); + }; + commentHandlers.setReplyTo = (node) => { + if (!state.session.isAuthorized) { state.authReturnHash = window.location.pathname || '/channels'; navigate('login-view'); return; } + replyEditorOpener(node); + }; + if (focus) { + const bar = document.createElement('div'); + bar.className = 'channel-composer thread-composer'; + const open = document.createElement('div'); + if (state.session.isAuthorized) { + // Строка ответа как в Threads: аватар, «Ответьте …», прикрепить, развернуть – всё ведёт в общий редактор. + open.className = 'thread-reply-bar'; + const me = renderUserAvatar({ login: state.session.login, size: 'xs', className: 'thread-reply-bar__avatar' }); + const field = document.createElement('button'); + field.type = 'button'; + field.className = 'thread-reply-bar__field'; + field.textContent = `Ответьте ${focus.authorLogin || ''}…`; + field.addEventListener('click', () => replyEditorOpener(focus)); + const attach = document.createElement('button'); + attach.type = 'button'; + attach.className = 'thread-reply-bar__icon'; + attach.innerHTML = iconHtml('image'); + attach.setAttribute('aria-label', 'Ответ с фото, видео или файлом'); + attach.addEventListener('click', () => replyEditorOpener(focus, { attach: true })); + const expand = document.createElement('button'); + expand.type = 'button'; + expand.className = 'thread-reply-bar__icon'; + expand.innerHTML = iconHtml('expand'); + expand.setAttribute('aria-label', 'Открыть редактор ответа'); + expand.addEventListener('click', () => replyEditorOpener(focus)); + open.append(me, field, attach, expand); + } else { + const loginBtn = document.createElement('button'); + loginBtn.type = 'button'; + open.append(loginBtn); + open.className = 'thread-reply-guest'; + loginBtn.className = 'primary-btn channel-main-action'; + loginBtn.textContent = 'Войти, чтобы ответить'; + loginBtn.addEventListener('click', () => { state.authReturnHash = window.location.pathname || '/channels'; navigate('login-view'); }); + } + bar.append(open); + chrome?.setComposer(bar); + if (openEditorOnLoad && state.session.isAuthorized) { + openEditorOnLoad = false; + trackTimer(window.setTimeout(() => { if (!disposed) replyEditorOpener?.(focus); }, 60)); + } + } + const focusWrap = screen.querySelector('.thread-block--focus'); + + trackTimer(applyPendingScroll(screen, routeKey, () => !disposed && seq === refreshSeq)); + const hasPendingScroll = pendingThreadScroll.has(routeKey); + if (!hasPendingScroll && Number.isFinite(restorePosition)) restoreChannelPosition(restorePosition); + if (!hasPendingScroll && !Number.isFinite(restorePosition) && focusWrap) { + trackTimer(window.setTimeout(() => { + if (disposed || seq !== refreshSeq || !focusWrap.isConnected) return; + focusWrap.scrollIntoView({ behavior: 'auto', block: 'start' }); + }, 20)); + } + }; + refresh = async () => { if (disposed) return; const seq = ++refreshSeq; @@ -1643,16 +2120,9 @@ export function render({ navigate, route, chrome }) { const restorePosition = hadContent ? document.getElementById('app-screen')?.scrollTop : readChannelPosition(positionKey); if (!hadContent) clearContent(); 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 = 'Обсуждение'; + const sel = parseThreadSelector(route); - if (!selector) { + if (!sel) { const invalid = document.createElement('div'); invalid.className = 'card meta-muted'; invalid.textContent = 'Обсуждение не найдено: неверная ссылка.'; @@ -1660,450 +2130,56 @@ export function render({ navigate, route, chrome }) { return; } - const skeleton = hadContent ? null : renderSkeleton(screen); + 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 { - 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; + 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(); - - const ancestors = Array.isArray(payload?.ancestors) ? payload.ancestors : []; - const focus = payload?.focus || null; - const descendants = Array.isArray(payload?.descendants) ? payload.descendants : []; - - 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 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 visibleOwner = channelOwner || extractLoginFromBlockchainName(selector?.short?.ownerBlockchainName || ''); - const number = focusOrdinal || (selector?.short ? null : Number(selector?.message?.blockNumber)); - const headerNumber = Number.isSafeInteger(number) && number > 0 ? ` · №${number}` : ''; - if (threadHeaderButton) { - threadHeaderTitle.textContent = `${title}${headerNumber}`; - threadHeaderChannel.textContent = `${visibleOwner ? `@${visibleOwner}` : ''}${visibleOwner && shortName ? ' / ' : ''}${shortName}`; - threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove(); - const avatar = renderAvatar({ - initials: (title[0] || 'К').toUpperCase(), - avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null, - authorLogin: visibleOwner, - size: 'xl', - className: 'channel-profile-avatar channel-thread-header-avatar', - title, - alt: 'Аватар канала', - }); - avatar.style.setProperty('--channel-avatar-size', '40px'); - threadHeaderButton.prepend(avatar); - threadHeaderButton.title = 'Открыть канал'; - threadHeaderButton.disabled = false; - threadHeaderButton.onclick = (event) => { - event.preventDefault(); - animatePress(event.currentTarget); - const routeToChannel = buildChannelRouteFromThread(selector, resolvedChannelLabel); - if (routeToChannel) navigate(routeToChannel); - else navigate('channels-list'); - }; - } - - clearContent(); - const openPost = () => { - const routeToChannel = buildChannelRouteFromThread(selector, resolvedChannelLabel); - if (routeToChannel) navigate(routeToChannel); - }; - const focusTarget = focus ? buildTargetFromNode(focus) : null; - threadMenuActions = () => { - const muted = isThreadMuted(routeKey); - return [ - { label: 'Перейти к записи', iconHtml: iconHtml('doc'), action: openPost }, - { label: muted ? 'Уведомлять об ответах' : 'Не уведомлять об ответах', iconHtml: iconHtml(muted ? 'bell' : 'bell-off'), action: () => { - setThreadMuted(routeKey, !muted); - showToast(muted ? 'Уведомления об ответах включены' : 'Ответы в этом обсуждении не будут приходить в уведомления'); - } }, - { label: 'Поделиться записью', iconHtml: iconHtml('share'), action: () => { - if (!focusTarget) return; - openShareSheet({ - title: 'Поделиться записью', - kicker: `${resolvedChannelTitle} · запись`, - text: parseMessageAttachments(resolveNodeText(focus)).text, - url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector, focusOrdinal)), - }); - } }, - ]; - }; - - const ancestorHandlers = { - ...handlers, - jumpTo: () => {}, - setReplyTo: (node) => handlers.openReplyEditor(node), - shareComment: (node) => openShareSheet({ - title: 'Поделиться', - kicker: `${node.authorLogin} · запись`, - text: parseMessageAttachments(resolveNodeText(node)).text, - url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(buildTargetFromNode(node), selector, null)), - }), - }; - // Над открытым ответом – цепочка до исходной записи, как в Threads: те же карточки, соединённые линией. - if (ancestors.length) { - const ancestorsWrap = document.createElement('div'); - ancestorsWrap.className = 'thread-block thread-block--ancestors'; - const ownerBch = String(selector?.channel?.ownerBlockchainName || '').toLowerCase(); - ancestors.forEach((node, index) => { - const isChannelPost = index === 0 && ownerBch && String(node?.authorBlockchainName || '').toLowerCase() === ownerBch; - let identity = null; - if (isChannelPost) { - const avatar = renderAvatar({ - initials: (title[0] || 'К').toUpperCase(), - avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null, - authorLogin: node?.authorLogin, - size: 'xl', - className: 'channel-profile-avatar thread-comment__avatar', - title, - alt: 'Аватар канала', - }); - avatar.style.setProperty('--channel-avatar-size', '36px'); - identity = { title, avatar }; - } - try { - const row = renderComment({ node, parent: null, focus: null, channelOwner, handlers: ancestorHandlers, identity }); - row.classList.add('thread-comment--ancestor'); - ancestorsWrap.append(row); - } catch (error) { logThreadRuntimeError('render_ancestor', error); } - }); - screen.append(ancestorsWrap); - } - if (focus) { - const focusWrap = document.createElement('div'); - focusWrap.className = 'thread-block thread-block--focus'; - focusWrap.append(renderNodeCard(focus, '', handlers, focusOrdinal || Number(selector?.message?.blockNumber ?? 0), { - focusPost: true, - channelOwnerBlockchainName: selector?.channel?.ownerBlockchainName || '', - channel: { title, avatarAr, avatarSha256 }, - })); - screen.append(focusWrap); - } - - const comments = flattenDescendants(descendants); - const listWrap = document.createElement('div'); - listWrap.className = 'thread-block thread-block--replies'; - const listTitle = document.createElement('h3'); - listTitle.className = 'thread-section-title'; - listTitle.textContent = `Комментарии · ${comments.length}`; - listWrap.append(listTitle); - - // Возврат к ответу после перехода по цитате - const returnBtn = document.createElement('button'); - returnBtn.type = 'button'; - returnBtn.className = 'thread-return'; - returnBtn.hidden = true; - returnBtn.textContent = 'Вернуться к ответу'; - let returnKey = ''; - const highlight = (el) => { - screen.querySelectorAll('.thread-comment.is-highlight').forEach((x) => x.classList.remove('is-highlight')); - el?.classList.add('is-highlight'); - }; - returnBtn.addEventListener('click', () => { - const el = listWrap.querySelector(`[data-message-key="${CSS.escape(returnKey)}"]`); - el?.scrollIntoView({ block: 'center', behavior: 'smooth' }); - highlight(el); - returnBtn.hidden = true; - }); - - const commentHandlers = { - ...handlers, - jumpTo: (key, fromKey) => { - const el = listWrap.querySelector(`[data-message-key="${CSS.escape(key)}"]`); - if (!el) return; - el.closest('.thread-replies')?.classList.add('is-expanded'); - el.scrollIntoView({ block: 'center', behavior: 'smooth' }); - highlight(el); - returnKey = fromKey; - returnBtn.hidden = false; - }, - shareComment: (node) => openShareSheet({ - title: 'Поделиться комментарием', - kicker: `${node.authorLogin} · комментарий`, - text: parseMessageAttachments(resolveNodeText(node)).text, - // Ссылка ведёт на обсуждение самого комментария – так же он открывается нажатием. - url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(buildTargetFromNode(node), selector, null)), - }), - }; - - if (comments.length) { - descendants.forEach((branch) => { - if (!branch?.node) return; - try { listWrap.append(renderReplyGroup(branch, { focus, channelOwner, handlers: commentHandlers })); } - catch (error) { logThreadRuntimeError('render_comment', error); } - }); - } else { - const empty = document.createElement('div'); - empty.className = 'empty-note thread-empty'; - empty.textContent = 'Пока нет комментариев. Можно начать разговор.'; - listWrap.append(empty); - } - screen.append(listWrap, returnBtn); - - // Ответ пишется в том же редакторе, что и запись канала; над полем – цепочка до исходной записи. - const parentByKey = new Map(); - const indexParents = (items, parent) => (Array.isArray(items) ? items : []).forEach((branch) => { - if (!branch?.node) return; - parentByKey.set(nodeKey(branch.node), parent); - indexParents(branch.children, branch.node); - }); - indexParents(descendants, focus); - const chainItem = (node) => { - const parsedNode = parseMessageAttachments(resolveNodeText(node)); - // Начало цепочки – запись канала: показываем её от имени канала, как в ленте. - const isRoot = ancestors.length ? node === ancestors[0] : node === focus; - const isChannelPost = isRoot && Boolean(selector?.channel?.ownerBlockchainName) - && String(node?.authorBlockchainName || '').toLowerCase() === String(selector.channel.ownerBlockchainName).toLowerCase(); - const item = { - author: String(node?.authorLogin || ''), - time: formatShortAge(node?.createdAtMs), - text: parsedNode.text, - attachmentLabel: parsedNode.attachments.length ? 'Вложение' : '', - }; - if (isChannelPost) { - item.title = title; - item.avatar = renderAvatar({ - initials: (title[0] || 'К').toUpperCase(), - avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null, - authorLogin: item.author, - size: 'xl', - className: 'channel-profile-avatar', - title, - alt: 'Аватар канала', - }); - item.avatar.style.setProperty('--channel-avatar-size', '40px'); - } - return item; - }; - replyEditorOpener = (node, { attach = false } = {}) => { - if (!node || disposed) return; - const path = []; - for (let cur = node; cur && cur !== focus; cur = parentByKey.get(nodeKey(cur))) path.unshift(cur); - const chain = [...ancestors, focus, ...path].filter(Boolean).map(chainItem); - openChannelEditor({ - id: 'thread-reply-modal', - title: 'Ответ', - submitLabel: 'Ответить', - placeholder: `Ответить ${node.authorLogin || ''}…`, - context: { chain }, - key: `thread-reply:${nodeKey(node)}`, - openAttachOnStart: attach, - isActive: () => !disposed, - onSubmit: ({ text }) => handlers.onReply(buildTargetFromNode(node), text), - }); - }; - commentHandlers.setReplyTo = (node) => { - if (!state.session.isAuthorized) { state.authReturnHash = window.location.pathname || '/channels'; navigate('login-view'); return; } - replyEditorOpener(node); - }; - if (focus) { - const bar = document.createElement('div'); - bar.className = 'channel-composer thread-composer'; - const open = document.createElement('div'); - if (state.session.isAuthorized) { - // Строка ответа как в Threads: аватар, «Ответьте …», прикрепить, развернуть – всё ведёт в общий редактор. - open.className = 'thread-reply-bar'; - const me = renderUserAvatar({ login: state.session.login, size: 'xs', className: 'thread-reply-bar__avatar' }); - const field = document.createElement('button'); - field.type = 'button'; - field.className = 'thread-reply-bar__field'; - field.textContent = `Ответьте ${focus.authorLogin || ''}…`; - field.addEventListener('click', () => replyEditorOpener(focus)); - const attach = document.createElement('button'); - attach.type = 'button'; - attach.className = 'thread-reply-bar__icon'; - attach.innerHTML = iconHtml('image'); - attach.setAttribute('aria-label', 'Ответ с фото, видео или файлом'); - attach.addEventListener('click', () => replyEditorOpener(focus, { attach: true })); - const expand = document.createElement('button'); - expand.type = 'button'; - expand.className = 'thread-reply-bar__icon'; - expand.innerHTML = iconHtml('expand'); - expand.setAttribute('aria-label', 'Открыть редактор ответа'); - expand.addEventListener('click', () => replyEditorOpener(focus)); - open.append(me, field, attach, expand); - } else { - const loginBtn = document.createElement('button'); - loginBtn.type = 'button'; - open.append(loginBtn); - open.className = 'thread-reply-guest'; - loginBtn.className = 'primary-btn channel-main-action'; - loginBtn.textContent = 'Войти, чтобы ответить'; - loginBtn.addEventListener('click', () => { state.authReturnHash = window.location.pathname || '/channels'; navigate('login-view'); }); - } - bar.append(open); - chrome?.setComposer(bar); - if (openEditorOnLoad && state.session.isAuthorized) { - openEditorOnLoad = false; - trackTimer(window.setTimeout(() => { if (!disposed) replyEditorOpener?.(focus); }, 60)); - } - } - const focusWrap = screen.querySelector('.thread-block--focus'); - - trackTimer(applyPendingScroll(screen, routeKey, () => !disposed && seq === refreshSeq)); - const hasPendingScroll = pendingThreadScroll.has(routeKey); - if (!hasPendingScroll && Number.isFinite(restorePosition)) restoreChannelPosition(restorePosition); - if (!hasPendingScroll && !Number.isFinite(restorePosition) && focusWrap) { - trackTimer(window.setTimeout(() => { - if (disposed || seq !== refreshSeq || !focusWrap.isConnected) return; - focusWrap.scrollIntoView({ behavior: 'auto', block: 'start' }); - }, 20)); - } + paint(data, shown ? document.getElementById('app-screen')?.scrollTop : restorePosition, seq); } catch (error) { if (disposed || seq !== refreshSeq) return; skeleton?.remove(); - if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить обсуждение.')); return; } - const failed = document.createElement('div'); - failed.className = 'card meta-muted'; - failed.textContent = `Не удалось загрузить обсуждение: ${toUserMessage(error, 'неизвестная ошибка')}`; - const retry = document.createElement('button'); - retry.type = 'button'; - retry.className = 'primary-btn'; - retry.textContent = 'Повторить'; - retry.addEventListener('click', () => void refresh()); - failed.append(retry); - screen.append(failed); + if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить обсуждение.')); return; } + threadHeaderChannel.textContent = ''; + screen.append(createLoadErrorCard({ + title: 'Не удалось загрузить обсуждение', + message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'), + onRetry: () => void refresh(), + })); } }; diff --git a/shine-UI/js/pages/channel-view.js b/shine-UI/js/pages/channel-view.js index 9eac93a2..0d27182c 100644 --- a/shine-UI/js/pages/channel-view.js +++ b/shine-UI/js/pages/channel-view.js @@ -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 = ` - Не удалось загрузить канал -

${message || 'Проверьте подключение к серверу и повторите попытку.'}

- `; - - 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 = 'КаналЗагрузка…'; - 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 = 'КаналЗагрузка…'; + 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 = 'Канал'; if (isChannelsDemoMode()) { renderDemoFallback(screen, navigate, error); return; diff --git a/shine-UI/js/pages/channels-list.js b/shine-UI/js/pages/channels-list.js index 4621f64c..2f899b2a 100644 --- a/shine-UI/js/pages/channels-list.js +++ b/shine-UI/js/pages/channels-list.js @@ -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 }); diff --git a/shine-UI/js/pages/notifications-view.js b/shine-UI/js/pages/notifications-view.js index 53871a4d..b6e23e0a 100644 --- a/shine-UI/js/pages/notifications-view.js +++ b/shine-UI/js/pages/notifications-view.js @@ -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='Не удалось загрузить уведомления';const t=document.createElement('p');t.className='meta-muted';t.textContent=error?.message||'Ошибка запроса к серверу';card.append(t);list.replaceChildren(card);} } diff --git a/shine-UI/js/pages/profile-view.js b/shine-UI/js/pages/profile-view.js index e9129864..b33f1b4c 100644 --- a/shine-UI/js/pages/profile-view.js +++ b/shine-UI/js/pages/profile-view.js @@ -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(); diff --git a/shine-UI/js/pages/start-view.js b/shine-UI/js/pages/start-view.js index df274308..36470a00 100644 --- a/shine-UI/js/pages/start-view.js +++ b/shine-UI/js/pages/start-view.js @@ -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; + }); +} diff --git a/shine-UI/js/router.js b/shine-UI/js/router.js index 3e029611..98106eb0 100644 --- a/shine-UI/js/router.js +++ b/shine-UI/js/router.js @@ -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 ''; diff --git a/shine-UI/js/services/channels-ux.js b/shine-UI/js/services/channels-ux.js index dcb1dd96..649db301 100644 --- a/shine-UI/js/services/channels-ux.js +++ b/shine-UI/js/services/channels-ux.js @@ -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; +} diff --git a/shine-UI/js/services/page-data-cache.js b/shine-UI/js/services/page-data-cache.js new file mode 100644 index 00000000..06de6ca5 --- /dev/null +++ b/shine-UI/js/services/page-data-cache.js @@ -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()}`; + } +} diff --git a/shine-UI/styles/features/channels-list.css b/shine-UI/styles/features/channels-list.css index 43015cef..9f880176 100644 --- a/shine-UI/styles/features/channels-list.css +++ b/shine-UI/styles/features/channels-list.css @@ -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; } } diff --git a/shine-UI/styles/features/preauth.css b/shine-UI/styles/features/preauth.css index b03e1ce6..13f7a782 100644 --- a/shine-UI/styles/features/preauth.css +++ b/shine-UI/styles/features/preauth.css @@ -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,