From 8b2012fad3c7e1af604f44d5c92a2dca8f7a94b30d99ccde675887d97c51054f Mon Sep 17 00:00:00 2001 From: q Date: Sun, 11 Oct 2026 20:05:37 +0300 Subject: [PATCH 01/51] =?UTF-8?q?UI:=20=D0=BA=D0=B0=D0=BD=D0=B0=D0=BB?= =?UTF-8?q?=D1=8B=20=D0=B8=20=D0=BE=D0=B1=D1=81=D1=83=D0=B6=D0=B4=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=B2=20=D1=80=D0=B0=D1=81=D0=BA=D0=BB?= =?UTF-8?q?=D0=B0=D0=B4=D0=BA=D0=B5=20Threads?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Лента канала: у записи аватар и название канала слева сверху, возраст записи («5 мин», «2 ч», «3 д») и «⋯» в шапке, текст и действия колонкой под названием, порядок действий – лайк, обсуждение, поделиться. Обсуждение: открытая запись с шапкой канала и крупным текстом; ответы деревом – под каждым ответом его ветка со сдвигом и линией от аватара, ответ на ответ помечен адресатом, если идёт не сразу после него; в ветке видно два ответа, остальные по «Ещё N ответов». Дерево грузится на 8 уровней вместо 2 (раньше ответы глубже второго уровня не показывались), что глубже – кнопкой открывается обсуждением этого ответа. --- VERSION.properties | 2 +- shine-UI/index.html | 2 +- shine-UI/js/pages/channel-thread-view.js | 191 ++++++++++++++----- shine-UI/js/pages/channel-view.js | 23 ++- shine-UI/js/services/channels-ux.js | 16 ++ shine-UI/styles/features/channel-thread.css | 49 +++-- shine-UI/styles/features/channels-common.css | 25 +++ 7 files changed, 243 insertions(+), 65 deletions(-) diff --git a/VERSION.properties b/VERSION.properties index 61b2129a..72412dee 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.18.0 +client.version=1.18.1 server.version=1.14.0 diff --git a/shine-UI/index.html b/shine-UI/index.html index a4d3bc7e..4d6be514 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, From 9ea276ba77e81b5fc102c6a707ff64a8b0d8dedf48f1b12dc897ca3ce64fefdb Mon Sep 17 00:00:00 2001 From: q Date: Mon, 12 Oct 2026 09:37:32 +0300 Subject: [PATCH 08/51] =?UTF-8?q?UI:=20=D1=81=D0=B8=D1=8F=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B2=20=D0=BF=D1=80=D0=BE=D1=84=D0=B8=D0=BB=D0=B5,?= =?UTF-8?q?=20=D1=81=D0=B2=D1=8F=D0=B7=D1=8C=20=D0=B1=D0=B5=D0=B7=20=D1=81?= =?UTF-8?q?=D0=B4=D0=B2=D0=B8=D0=B3=D0=B0=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=B0,=20=D0=B0=D0=B2=D0=B0=D1=82=D0=B0=D1=80=D1=8B=20=D0=BA?= =?UTF-8?q?=D0=B0=D0=BD=D0=B0=D0=BB=D0=BE=D0=B2=20=D0=B1=D0=B5=D0=B7=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BB=D1=8C=D1=86=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Профиль: золотая «дышащая» аура вокруг аватара сияющего, бейджи «Сияющий» / «Официальный» под именем, разделы «Сияние» и «Официальный аккаунт» со списками «кто подтвердил» и «кого подтвердил» (видны у сияющих и у всех, у кого есть подтверждения). - Кнопки подтверждения на экране связи – по тем же правилам, что проверяет сервер (голосует основной аккаунт, за сияние – основной и сияющий; цель не отказалась). - Экран связи: сохранение показывается на нажатой кнопке, без строки «Сохранение…», которая сдвигала экран; после выбора – сообщение и возврат на страницу пользователя. - В каналах и обсуждениях аватары без стеклянного кольца «Связей» (готовый avatar-plain). - Локальный сервер UI отдаёт Cache-Control: no-cache – иначе браузер брал старый router.js. --- scripts/local_spa_server.py | 6 ++ shine-UI/js/components/profile-card.js | 86 +++++++++++------- shine-UI/js/pages/channel-about-view.js | 6 +- shine-UI/js/pages/channel-thread-view.js | 12 +-- shine-UI/js/pages/channel-view.js | 4 +- shine-UI/js/pages/profile-view.js | 1 + shine-UI/js/pages/user-profile-view.js | 1 + .../js/pages/user-relation-manage-view.js | 61 +++++++++---- shine-UI/styles/features/profile-page.css | 91 +++++++------------ shine-UI/styles/features/profile.css | 2 - 10 files changed, 150 insertions(+), 120 deletions(-) diff --git a/scripts/local_spa_server.py b/scripts/local_spa_server.py index 0199eeab..370edea1 100644 --- a/scripts/local_spa_server.py +++ b/scripts/local_spa_server.py @@ -14,6 +14,12 @@ class SpaHandler(SimpleHTTPRequestHandler): rel = Path(translated).relative_to(Path.cwd()) return str(ROOT / rel) + def end_headers(self): + # Локальная разработка: модули без версии в адресе (./router.js) иначе берутся из эвристического + # кэша браузера – новый app.js встречается со старым router.js и приложение не стартует. + self.send_header("Cache-Control", "no-cache") + super().end_headers() + def do_GET(self): file_path = Path(self.translate_path(self.path.split("?", 1)[0])) if file_path.exists() and file_path.is_file(): diff --git a/shine-UI/js/components/profile-card.js b/shine-UI/js/components/profile-card.js index 3d91a2a5..25e0c60a 100644 --- a/shine-UI/js/components/profile-card.js +++ b/shine-UI/js/components/profile-card.js @@ -12,29 +12,35 @@ export function escapeProfileHtml(text) { const esc = escapeProfileHtml; -function statusCardHtml({ kind, title, received, given }) { +// Раздел статуса («Сияние», «Официальный»): кто подтвердил этот аккаунт и кого подтвердил он сам. +function statusSectionHtml({ kind, title, received, given, receivedLabel, givenLabel }) { const receivedCount = Number(received || 0); const givenCount = Number(given || 0); const isOfficial = kind === 'primary'; - const receivedKind = isOfficial ? 'primary_received' : 'shine_received'; - const givenKind = isOfficial ? 'primary_given' : 'shine_given'; - const receivedTitle = isOfficial ? 'Кто подтвердил этот официальный аккаунт' : 'Кто подтвердил, что этот аккаунт сияющий'; - const givenTitle = isOfficial ? 'Какие официальные аккаунты подтвердил этот пользователь' : 'Кого этот пользователь подтвердил как сияющего'; - return ` -
-
${esc(title)}
- - +
+ +
`; } +function peopleCount(count) { + if (!count) return 'Пока никого'; + const mod10 = count % 10; + const mod100 = count % 100; + const word = mod10 === 1 && mod100 !== 11 ? 'человек' : (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) ? 'человека' : 'человек'; + return `${count} ${word}`; +} + function statHtml({ kind, label, valueHtml, ariaLabel }) { return ` `).join(''); } -function officialBlockHtml(flags = {}) { +function officialBlockHtml(flags = {}, targetIsOfficial = false) { return `
Основной аккаунт - Этот аккаунт — основной + ${targetIsOfficial ? 'Этот аккаунт отмечен как основной' : 'Подтвердите, если это основной аккаунт этого человека'}
${flags.outOfficialAccount ? '
✓ Вы подтвердили его основной аккаунт
' : ''} @@ -79,12 +81,12 @@ function officialBlockHtml(flags = {}) {
`; } -function shineBlockHtml(flags = {}) { +function shineBlockHtml(flags = {}, targetIsShining = false) { return `
Сияющий - Этот аккаунт — сияющий + ${targetIsShining ? 'Этот человек отмечен как сияющий' : 'Подтвердите, если считаете этого человека сияющим'}
${flags.outShineConfirmed ? '
✓ Вы подтверждаете его сияющим
' : ''} @@ -152,8 +154,11 @@ export function render({ route, chrome }) { } function renderBody() { - const canPrimary = selfCard?.accountRole === 'primary' && targetCard?.accountRole === 'primary'; - const canShine = selfCard?.shineStatus === 'shining' && targetCard?.shineStatus === 'shining'; + // Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует основной аккаунт, + // за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений. + const selfPrimary = selfCard?.accountRole === 'primary'; + const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting'; + const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested'; body.innerHTML = `
- ${canPrimary ? officialBlockHtml(flags) : ''} - ${canShine ? shineBlockHtml(flags) : ''} + ${canPrimary ? officialBlockHtml(flags, targetCard?.accountRole === 'primary') : ''} + ${canShine ? shineBlockHtml(flags, targetCard?.shineStatus === 'shining') : ''} `; } async function refresh({ loading = true } = {}) { - if (loading) { - status.className = 'status-line relation-manage-status'; - status.textContent = 'Загрузка...'; - } + // «Загрузка…» – только если ответ задержался, иначе строка мелькает и сдвигает экран. + const loadingTimer = loading ? window.setTimeout(() => { + if (screen.isConnected && !body.childElementCount) status.textContent = 'Загрузка…'; + }, 500) : 0; [selfCard, targetCard, flags] = await Promise.all([ loadUserProfileCard(selfLogin), loadUserProfileCard(targetLogin), loadRelationsForPair({ currentLogin: selfLogin, targetLogin }), ]); + window.clearTimeout(loadingTimer); renderBody(); status.className = 'status-line relation-manage-status'; status.textContent = ''; } + const SOCIAL_DONE = { + none: 'Связь убрана', + contact: 'Добавлен в контакты', + friend: 'Добавлен в друзья', + close_friend: 'Добавлен в близкие друзья', + }; + + // Выбор сохраняется прямо на нажатой кнопке (без строки статуса, которая сдвигала экран), + // после сохранения – короткое сообщение и возврат на страницу пользователя. body.addEventListener('click', async (event) => { const button = event.target.closest('button'); if (!button || busy) return; @@ -193,24 +208,36 @@ export function render({ route, chrome }) { const social = button.dataset.socialKind; const confirm = button.dataset.confirm; if (!social && !confirm) return; + if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; } busy = true; body.classList.add('is-busy'); - status.className = 'status-line relation-manage-status'; - status.textContent = 'Сохранение...'; + body.querySelectorAll('button').forEach((item) => { item.disabled = true; }); + const label = button.textContent; + button.classList.add('is-pending'); + button.textContent = 'Сохраняем…'; try { + let done = ''; if (social) { await changeSocial(social); + done = SOCIAL_DONE[social] || 'Связь сохранена'; } else if (confirm === 'official_account') { await setKind('official_account', !flags.outOfficialAccount); + done = flags.outOfficialAccount ? 'Подтверждение убрано' : 'Вы подтвердили официальный аккаунт'; } else if (confirm === 'shine_confirmed') { await setKind('shine_confirmed', !flags.outShineConfirmed); + done = flags.outShineConfirmed ? 'Подтверждение убрано' : 'Вы подтвердили сияние'; } - await refresh({ loading: false }); + if (!screen.isConnected) return; + showToast(done); + navigateBack(); } catch (error) { - status.className = 'status-line relation-manage-status is-unavailable'; - status.textContent = `Ошибка: ${error?.message || 'Не удалось изменить связь'}`; + if (!screen.isConnected) return; + showToast(toUserMessage(error, 'Не удалось изменить связь'), { kind: 'error', timeoutMs: 4000 }); + button.textContent = label; + button.classList.remove('is-pending'); + body.querySelectorAll('button').forEach((item) => { item.disabled = false; }); } finally { busy = false; body.classList.remove('is-busy'); diff --git a/shine-UI/styles/features/profile-page.css b/shine-UI/styles/features/profile-page.css index 7d54b303..ba715e9e 100644 --- a/shine-UI/styles/features/profile-page.css +++ b/shine-UI/styles/features/profile-page.css @@ -6,57 +6,6 @@ .user-profile-screen .user-profile-status:empty { display: none; } .user-profile-screen .pf-hero { display: grid; justify-items: center; gap: var(--space-1); text-align: center; } -.user-profile-screen .pf-identity { - width: min(100%, 420px); - display: grid; - grid-template-columns: minmax(72px, 1fr) 96px minmax(72px, 1fr); - align-items: center; - gap: 10px; -} -.user-profile-screen .pf-status-card-slot { min-width: 0; display: grid; align-items: center; } -.user-profile-screen .pf-status-card-slot--left { justify-items: end; } -.user-profile-screen .pf-status-card-slot--right { justify-items: start; } -.user-profile-screen .pf-status-card { - width: min(100%, 106px); - aspect-ratio: 1; - display: grid; - grid-template-rows: auto minmax(0, 1fr) minmax(0, 1fr); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-lg); - background: var(--surface); - overflow: hidden; -} -.user-profile-screen .pf-status-card--primary { border-color: color-mix(in srgb, var(--rel-family) 55%, var(--border-subtle)); } -.user-profile-screen .pf-status-card--shine { border-color: color-mix(in srgb, var(--rel-shining) 55%, var(--border-subtle)); } -.user-profile-screen .pf-status-card-title { - min-height: 27px; - padding: 7px 5px 5px; - display: grid; - place-items: center; - color: var(--text-primary); - font-size: 11px; - line-height: 1.1; - font-weight: var(--weight-bold); -} -.user-profile-screen .pf-status-card-count { - min-width: 0; - padding: 3px 2px; - display: grid; - place-items: center; - align-content: center; - gap: 0; - border: 0; - border-top: 1px solid var(--border-subtle); - background: transparent; - color: var(--text-primary); - font: inherit; - cursor: pointer; -} -.user-profile-screen .pf-status-card-count:hover, -.user-profile-screen .pf-status-card-count:active { background: var(--surface-selected); } -.user-profile-screen .pf-status-card-count:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: -2px; } -.user-profile-screen .pf-status-card-count strong { font-size: var(--text-md); line-height: 1.05; font-weight: var(--weight-bold); } -.user-profile-screen .pf-status-card-count span { color: var(--text-secondary); font-size: 9px; line-height: 1.05; } .user-profile-screen .pf-avatar { position: relative; width: 96px; height: 96px; display: grid; place-items: center; justify-self: center; } .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar, .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar-image { width: 96px; height: 96px; min-width: 96px; min-height: 96px; font-size: 36px; } @@ -64,17 +13,45 @@ .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar-framed > .avatar-photo { width: 100%; height: 100%; } .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar-framed::after, .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar-glow::before { content: none; } +/* Сияющий: тёплая золотая аура вокруг аватара, медленно «дышит» – как сияние знака на заставке. */ +.user-profile-screen .pf-avatar.is-shining { isolation: isolate; } +.user-profile-screen .pf-avatar.is-shining::before { + content: ""; + position: absolute; + inset: -30%; + z-index: -1; + border-radius: 50%; + background: radial-gradient(closest-side, color-mix(in srgb, var(--warning) 46%, transparent) 55%, color-mix(in srgb, var(--warning) 16%, transparent) 78%, transparent); + filter: blur(8px); + animation: pf-shine-breathe 5.3s ease-in-out infinite; + pointer-events: none; +} +.user-profile-screen .pf-avatar.is-shining .user-profile-hero-avatar { box-shadow: 0 0 0 2px color-mix(in srgb, var(--warning) 85%, transparent); border-radius: 50%; } +@keyframes pf-shine-breathe { + 0%, 100% { opacity: 0.7; transform: scale(0.96); } + 50% { opacity: 1; transform: scale(1.04); } +} +@media (prefers-reduced-motion: reduce) { .user-profile-screen .pf-avatar.is-shining::before { animation: none; } } + +.user-profile-screen .pf-badges { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-1); margin-top: var(--space-1); } +.user-profile-screen .pf-badge { + padding: 3px 10px; + border-radius: 999px; + font-size: var(--text-xs); + line-height: var(--leading-xs); + font-weight: var(--weight-bold); +} +.user-profile-screen .pf-badge--shine { color: var(--warning); background: color-mix(in srgb, var(--warning) 14%, transparent); } +.user-profile-screen .pf-badge--official { color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); } +.user-profile-screen .pf-status-section .nav-list__title { margin-top: 0; } + .user-profile-screen .pf-name { margin: var(--space-2) 0 0; color: var(--text-primary); font-size: var(--text-xl); line-height: var(--leading-xl); font-weight: var(--weight-bold); overflow-wrap: anywhere; } .user-profile-screen .pf-login { color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-sm); } @media (max-width: 360px) { - .user-profile-screen .pf-identity { grid-template-columns: minmax(66px, 1fr) 88px minmax(66px, 1fr); gap: 7px; } .user-profile-screen .pf-avatar, .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar, .user-profile-screen .pf-avatar .user-profile-hero-avatar.avatar-image { width: 88px; height: 88px; min-width: 88px; min-height: 88px; } - .user-profile-screen .pf-status-card { width: min(100%, 96px); } - .user-profile-screen .pf-status-card-title { font-size: 10px; } - .user-profile-screen .pf-status-card-count span { font-size: 8px; } } .user-profile-screen .pf-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); background: var(--surface); overflow: hidden; } @@ -144,7 +121,9 @@ .relation-manage-screen { gap: var(--space-3); } .relation-manage-status:empty { display: none; } .relation-manage-body { gap: var(--space-3); } -.relation-manage-body.is-busy { opacity: .72; pointer-events: none; } +.relation-manage-body.is-busy { pointer-events: none; } +.relation-manage-body.is-busy button:not(.is-pending) { opacity: .5; } +.relation-manage-body button.is-pending { border-color: var(--accent); color: var(--accent); opacity: 1; } .relation-manage-card { gap: var(--space-3); } .relation-manage-card-head { display: grid; gap: 2px; } .relation-manage-card-head > strong { color: var(--text-primary); font-size: var(--text-md); } diff --git a/shine-UI/styles/features/profile.css b/shine-UI/styles/features/profile.css index 2f912548..73ac4f78 100644 --- a/shine-UI/styles/features/profile.css +++ b/shine-UI/styles/features/profile.css @@ -760,8 +760,6 @@ .user-profile-avatar-slot { - grid-column: 2; - grid-row: 1 / 3; width: var(--user-profile-avatar-size); height: var(--user-profile-avatar-size); display: grid; From 923f281bf6e52d81c0ecc39b1abb45623d13fb786bb1d85f6a5db5418b8402ed Mon Sep 17 00:00:00 2001 From: q Date: Mon, 12 Oct 2026 09:45:08 +0300 Subject: [PATCH 09/51] =?UTF-8?q?UI:=20=D0=BF=D0=BE=D0=BB=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D1=81=D1=87=D1=91=D1=82=D1=87=D0=B8=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BE=D1=82=D0=B2=D0=B5=D1=82=D0=BE=D0=B2,=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D0=B5=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=BA=D0=B0=D0=BA=20=D0=B2=20Telegram,=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BA=D0=BB=D1=8E=D1=87=D0=B0=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=20=C2=AB=D0=A1=D0=B2=D1=8F=D0=B7=D0=B5=D0=B9=C2=BB,=20?= =?UTF-8?q?=D1=88=D0=B0=D0=BF=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Счётчик ответов – по всем уровням: обсуждение считает по дереву, лента берёт итог из обсуждения (кэш или фоновая подгрузка видимых записей, они же потом открываются сразу). Сервер пока отдаёт только прямые ответы. - Чат: поле-«таблетка» растёт плавно (высота меряется по скрытой копии, без сброса в auto), смайлик внутри поля справа внизу, «Отправить» 44 px по низу; убраны правила перестройки в две колонки. - «Связи»: фильтры – общий блок-переключатель (.tabs), как на других вкладках, всё помещается. - Шапка: название крупнее и жирнее, подпись под ним компактнее. --- VERSION.properties | 2 +- shine-UI/index.html | 2 +- shine-UI/js/pages/channel-thread-view.js | 45 ++++++++++-- shine-UI/js/pages/channel-view.js | 58 ++++++++++++++- shine-UI/js/pages/chat-view.js | 28 ++++++-- shine-UI/js/pages/network-view.js | 51 +++++++------- shine-UI/styles/components/topbar.css | 4 +- shine-UI/styles/features/chat.css | 90 +++++++++++------------- shine-UI/styles/features/messages.css | 12 ---- shine-UI/styles/features/network.css | 14 ++-- 10 files changed, 201 insertions(+), 105 deletions(-) diff --git a/VERSION.properties b/VERSION.properties index 2d7f9456..2ca096b0 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.18.7 +client.version=1.18.8 server.version=1.14.0 diff --git a/shine-UI/index.html b/shine-UI/index.html index 93272e13..4b05f6a4 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 3439dc31..38fa853a 100644 --- a/shine-UI/js/app.js +++ b/shine-UI/js/app.js @@ -103,6 +103,8 @@ import * as solanaRpcCheckView from './pages/solana-rpc-check-view.js'; import * as messagesList from './pages/messages-list.js?v=202609260900'; import * as contactSearchView from './pages/contact-search-view.js'; import * as chatView from './pages/chat-view.js?v=202609260900'; +import * as chatMediaView from './pages/chat-media-view.js'; +import { isDmChatMuted } from './services/dm-chat-prefs.js'; import * as userProfileView from './pages/user-profile-view.js'; import * as userProfileListView from './pages/user-profile-list-view.js'; import * as userRelationManageView from './pages/user-relation-manage-view.js'; @@ -175,6 +177,7 @@ const routes = { 'messages-list': messagesList, 'contact-search-view': contactSearchView, 'chat-view': chatView, + 'chat-media-view': chatMediaView, user: userProfileView, 'user-profile-list-view': userProfileListView, 'user-relation-manage-view': userRelationManageView, @@ -1818,7 +1821,8 @@ async function init() { if (added && isIncomingForCurrent) { shouldRefreshToolbarUnread = true; } - if (added && isIncomingForCurrent && !payload.backlog) { + // Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления. + if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) { const parsedText = parseDmTechBlocks(text); const displayText = String(parsedText.displayText || ''); const suppressHiddenNotification = parsedText.callSummary?.status === 'completed'; diff --git a/shine-UI/js/components/dm-attachments.js b/shine-UI/js/components/dm-attachments.js new file mode 100644 index 00000000..1635db08 --- /dev/null +++ b/shine-UI/js/components/dm-attachments.js @@ -0,0 +1,95 @@ +// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать». +// Общие для ленты чата и экрана «Медиа и файлы». +import { decryptDmFileToBlob, downloadAndDecryptDmFile, formatDmFileSize } from '../services/dm-file-service.js'; +import { getAttachmentKind } from '../services/attachment-format.js'; +import { showToast } from '../services/channels-ux.js'; + +// Картинки и видео в личке показываются так же, как в каналах (карусель + просмотрщик), +// только файл сначала расшифровывается. Большие файлы остаются карточками со «Скачать», +// чтобы не тратить трафик на автозагрузку. +const DM_INLINE_MEDIA_MAX_BYTES = 20 * 1024 * 1024; +const DM_MEDIA_MIME = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp', svg: 'image/svg+xml', mp4: 'video/mp4', m4v: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg' }; +const dmMediaBlobs = new Map(); +const DM_MEDIA_CACHE_LIMIT = 40; + +export function isDmInlineMedia(attachment) { + if (attachment?.kind === 'voice') return false; + const size = Number(attachment?.size || 0); + if (!(size > 0 && size <= DM_INLINE_MEDIA_MAX_BYTES)) return false; + const kind = getAttachmentKind(attachment); + return kind === 'image' || kind === 'video'; +} + +// Расшифрованный файл держим в памяти: лента перерисовывается на каждое новое сообщение, +// и без кэша картинка расшифровывалась бы и мигала заново. +export function resolveDmMediaUrl(attachment) { + const key = String(attachment?.id || attachment?.url || ''); + let pending = dmMediaBlobs.get(key); + if (!pending) { + const ext = String(attachment?.name || '').split('.').pop().toLowerCase(); + pending = decryptDmFileToBlob(attachment) + .then((blob) => new Blob([blob], { type: DM_MEDIA_MIME[ext] || blob.type || 'application/octet-stream' })); + pending.catch(() => dmMediaBlobs.delete(key)); + dmMediaBlobs.set(key, pending); + if (dmMediaBlobs.size > DM_MEDIA_CACHE_LIMIT) dmMediaBlobs.delete(dmMediaBlobs.keys().next().value); + } + return pending.then((blob) => ({ url: URL.createObjectURL(blob), objectUrl: true })); +} + +export function createDmFileAttachmentCard(attachment) { + const fileCard = document.createElement('div'); + fileCard.className = 'dm-file-card'; + + const fileIcon = document.createElement('span'); + fileIcon.className = 'dm-file-card__icon'; + fileIcon.textContent = '📎'; + + const fileCopy = document.createElement('span'); + fileCopy.className = 'dm-file-card__copy'; + const fileName = document.createElement('strong'); + fileName.className = 'dm-file-card__name'; + fileName.textContent = attachment.name || 'file'; + const fileMeta = document.createElement('span'); + fileMeta.className = 'dm-file-card__meta'; + const metaParts = [formatDmFileSize(attachment.size)]; + if (Number(attachment?.version || 1) >= 2) metaParts.push('BitTorrent v2'); + fileMeta.textContent = metaParts.join(' · '); + fileCopy.append(fileName, fileMeta); + + const downloadBtn = document.createElement('button'); + downloadBtn.type = 'button'; + downloadBtn.className = 'ui-button dm-file-card__download'; + downloadBtn.textContent = 'Скачать'; + downloadBtn.addEventListener('click', async (event) => { + event.stopPropagation(); + if (downloadBtn.disabled) return; + downloadBtn.disabled = true; + const previousLabel = downloadBtn.textContent; + downloadBtn.textContent = 'Скачивание…'; + try { + const result = await downloadAndDecryptDmFile(attachment, { + onProgress: ({ processedBytes, totalBytes }) => { + if (!totalBytes) return; + const percent = Math.min(100, Math.max(0, Math.round((processedBytes / totalBytes) * 100))); + downloadBtn.textContent = `${percent}%`; + }, + }); + if (!result?.cancelled) { + showToast( + result?.streamed + ? 'Файл расшифрован по частям и сохранён напрямую на диск' + : 'Файл расшифрован и передан браузеру для сохранения', + { timeoutMs: 1800 }, + ); + } + } catch (error) { + showToast(error?.message || 'Не удалось скачать файл', { kind: 'error', timeoutMs: 2800 }); + } finally { + downloadBtn.disabled = false; + downloadBtn.textContent = previousLabel; + } + }); + + fileCard.append(fileIcon, fileCopy, downloadBtn); + return fileCard; +} diff --git a/shine-UI/js/components/person-note-sheet.js b/shine-UI/js/components/person-note-sheet.js new file mode 100644 index 00000000..a5da4174 --- /dev/null +++ b/shine-UI/js/components/person-note-sheet.js @@ -0,0 +1,91 @@ +// Шторка «Заметка о человеке»: текст и цветная метка, видны только владельцу аккаунта. +// Открывается с карты связей и из профиля человека; хранение – services/people-notes.js. +import { openSheet } from './sheet.js'; +import { NOTE_MARKS, PERSON_NOTE_MAX_TEXT, getPersonNote, setPersonNote } from '../services/people-notes.js'; + +export function openPersonNoteSheet({ login, name = '', onClose = null } = {}) { + const current = getPersonNote(login); + let mark = current?.mark || ''; + return openSheet({ + title: `Заметка: ${name || login}`, + className: 'person-note-sheet', + onClose, + content: (sheet) => { + const wrap = document.createElement('div'); + wrap.className = 'stack person-note'; + const hint = document.createElement('p'); + hint.className = 'meta-muted person-note__hint'; + hint.textContent = 'Видна только вам. Пока хранится на этом устройстве.'; + const textarea = document.createElement('textarea'); + textarea.className = 'input person-note__text'; + textarea.rows = 5; + textarea.maxLength = PERSON_NOTE_MAX_TEXT; + textarea.placeholder = 'Кто это, откуда знакомы, о чём договорились…'; + textarea.value = current?.text || ''; + textarea.setAttribute('aria-label', 'Текст заметки'); + textarea.autofocus = true; + + const marksLabel = document.createElement('div'); + marksLabel.className = 'person-note__label'; + marksLabel.id = `person-note-marks-${Math.random().toString(36).slice(2, 8)}`; + marksLabel.textContent = 'Метка на карте связей'; + const marks = document.createElement('div'); + marks.className = 'person-note__marks'; + marks.setAttribute('role', 'radiogroup'); + marks.setAttribute('aria-labelledby', marksLabel.id); + const markButtons = []; + const syncMarks = () => markButtons.forEach((button) => button.setAttribute('aria-checked', String(button.dataset.mark === mark))); + for (const option of [{ id: '', label: 'Без метки' }, ...NOTE_MARKS]) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'person-note__mark'; + button.dataset.mark = option.id; + button.setAttribute('role', 'radio'); + button.setAttribute('aria-label', option.label); + button.title = option.label; + button.addEventListener('click', () => { mark = option.id; syncMarks(); }); + markButtons.push(button); + marks.append(button); + } + syncMarks(); + wrap.append(hint, textarea, marksLabel, marks); + + if (current) { + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'ghost-btn person-note__remove'; + remove.textContent = 'Удалить'; + remove.addEventListener('click', () => { + setPersonNote(login, { text: '', mark: '' }); + sheet.close(); + }); + sheet.footer.append(remove); + } + const save = document.createElement('button'); + save.type = 'button'; + save.className = 'primary-btn person-note__save'; + save.textContent = 'Сохранить'; + save.addEventListener('click', () => { + setPersonNote(login, { text: textarea.value, mark }); + sheet.close(); + }); + sheet.footer.append(save); + return wrap; + }, + }); +} + +// Готовый блок заметки (для карточки на карте и профиля); null, если заметки нет. +export function createPersonNotePreview(note, { className = '', onClick = null } = {}) { + if (!note) return null; + const el = document.createElement(onClick ? 'button' : 'div'); + if (onClick) { + el.type = 'button'; + el.title = 'Изменить заметку'; + el.addEventListener('click', onClick); + } + el.className = `person-note-preview${className ? ` ${className}` : ''}`; + if (note.mark) el.dataset.mark = note.mark; + el.textContent = note.text.trim() || 'Метка без текста'; + return el; +} diff --git a/shine-UI/js/components/ui-icon.js b/shine-UI/js/components/ui-icon.js index a5c829ab..be12e682 100644 --- a/shine-UI/js/components/ui-icon.js +++ b/shine-UI/js/components/ui-icon.js @@ -15,7 +15,8 @@ const paths = { emoji: '', send: '', mic: '', - image: '', + camera: '', + image: '', list: '', doc: '', close: '', @@ -35,6 +36,10 @@ const paths = { check: '', open: '', chevron: '', + 'chevron-up': '', + 'chevron-down': '', + calendar: '', + pin: '', back: '', down: '', edit: '', @@ -47,6 +52,9 @@ const paths = { repost: '', expand: '', clip: '', + minus: '', + fit: '', + focus: '', }; export function iconHtml(name, filled = false, className = '') { diff --git a/shine-UI/js/pages/chat-media-view.js b/shine-UI/js/pages/chat-media-view.js new file mode 100644 index 00000000..e729b57a --- /dev/null +++ b/shine-UI/js/pages/chat-media-view.js @@ -0,0 +1,244 @@ +// «Медиа и файлы» личной переписки: сетка фото и видео и список документов по месяцам. +// История догружается с сервера целиком; превью расшифровываются, только когда плитка видна. +import { createTopBar } from '../components/topbar.js'; +import { iconHtml } from '../components/ui-icon.js'; +import { openMediaViewer } from '../components/media-viewer.js'; +import { createDmFileAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js'; +import { getAttachmentKind } from '../services/attachment-format.js'; +import { parseDmTechBlocks } from '../services/dm-tech-blocks.js'; +import { loadFullDmHistory, resolveMessageTimeMs } from '../services/dm-history.js'; +import { formatClockTime, formatDayLabel } from '../services/channels-ux.js'; +import { getChatMessages, getRememberedDmPeer, normalizeDmChatId } from '../state.js'; +import { navigateUp } from '../router.js'; + +export const pageMeta = { id: 'chat-media-view', title: 'Медиа и файлы' }; + +const monthTitle = new Intl.DateTimeFormat('ru-RU', { month: 'long', year: 'numeric' }); + +// Все вложения переписки, от новых к старым. +function collectAttachments(chatId) { + const media = []; + const files = []; + for (const msg of getChatMessages(chatId)) { + if (msg?.deleted) continue; + const parsed = parseDmTechBlocks(String(msg?.text || '')); + const list = Array.isArray(parsed.fileAttachments) ? parsed.fileAttachments : (parsed.fileAttachment ? [parsed.fileAttachment] : []); + for (const attachment of list) { + if (attachment?.kind === 'voice') continue; + const entry = { attachment, timeMs: resolveMessageTimeMs(msg), from: msg?.from }; + (isDmInlineMedia(attachment) ? media : files).push(entry); + } + } + const newestFirst = (a, b) => b.timeMs - a.timeMs; + return { media: media.sort(newestFirst), files: files.sort(newestFirst) }; +} + +function groupByMonth(entries) { + const groups = []; + for (const entry of entries) { + const raw = entry.timeMs ? monthTitle.format(new Date(entry.timeMs)) : 'Без даты'; + const label = raw.charAt(0).toUpperCase() + raw.slice(1); + const last = groups[groups.length - 1]; + if (last?.label === label) last.items.push(entry); + else groups.push({ label, items: [entry] }); + } + return groups; +} + +export function render({ navigate, route, chrome }) { + const chatId = normalizeDmChatId(route?.params?.chatId); + const peer = getRememberedDmPeer(chatId); + const peerName = [peer?.firstName, peer?.lastName].map((x) => String(x || '').trim()).filter(Boolean).join(' ') || chatId; + const chatPath = `chat/${encodeURIComponent(chatId)}`; + + const screen = document.createElement('section'); + screen.className = 'stack chat-media-screen'; + let disposed = false; + let activeTab = 'media'; + let loading = true; + let loadFailed = false; + const objectUrls = new Set(); + const tileUrls = new Map(); // id файла → url для просмотрщика + const fileKey = (attachment) => String(attachment?.id || attachment?.url || ''); + + chrome?.setTopbar(createTopBar({ + title: 'Медиа и файлы', + back: { + onClick: () => navigateUp((r) => r.pageId === 'chat-view' && normalizeDmChatId(r.params?.chatId) === chatId, chatPath), + }, + })); + + const subtitle = document.createElement('p'); + subtitle.className = 'meta-muted chat-media-peer'; + subtitle.textContent = `Переписка с ${peerName}`; + + const tabs = document.createElement('div'); + tabs.className = 'tabs tabs--auto tabs--dense chat-media-tabs'; + tabs.setAttribute('role', 'radiogroup'); + tabs.setAttribute('aria-label', 'Что показать'); + const tabButtons = new Map(); + for (const [value, label] of [['media', 'Медиа'], ['files', 'Файлы']]) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'tab-btn'; + button.dataset.tab = value; + button.setAttribute('role', 'radio'); + button.addEventListener('click', () => { + if (activeTab === value) return; + activeTab = value; + renderBody(); + }); + tabButtons.set(value, { button, label }); + tabs.append(button); + } + + const status = document.createElement('div'); + status.className = 'chat-media-status'; + const body = document.createElement('div'); + body.className = 'stack chat-media-body'; + screen.append(subtitle, tabs, status, body); + + const thumbObserver = typeof IntersectionObserver === 'function' + ? new IntersectionObserver((entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue; + thumbObserver.unobserve(entry.target); + entry.target.__loadThumb?.(); + } + }, { rootMargin: '300px 0px' }) + : null; + + const createTile = (entry, openAt) => { + const { attachment } = entry; + const kind = getAttachmentKind(attachment); + const tile = document.createElement('button'); + tile.type = 'button'; + tile.className = `chat-media-tile is-loading${kind === 'video' ? ' chat-media-tile--video' : ''}`; + tile.setAttribute('aria-label', `${kind === 'video' ? 'Видео' : 'Фото'} ${attachment.name || ''}, ${formatDayLabel(entry.timeMs)}`); + tile.__loadThumb = () => { + resolveDmMediaUrl(attachment).then(({ url }) => { + objectUrls.add(url); + if (disposed) return; + tileUrls.set(fileKey(attachment), url); + const media = document.createElement(kind === 'video' ? 'video' : 'img'); + media.className = 'chat-media-tile__media'; + if (kind === 'video') { + media.muted = true; + media.preload = 'metadata'; + media.playsInline = true; + // Кадр чуть позже начала: первый часто чёрный. + media.src = `${url}#t=0.1`; + } else { + media.alt = ''; + media.decoding = 'async'; + media.src = url; + } + tile.prepend(media); + tile.classList.remove('is-loading'); + }).catch(() => { + if (!disposed) tile.classList.replace('is-loading', 'is-failed'); + }); + }; + if (kind === 'video') { + const badge = document.createElement('span'); + badge.className = 'chat-media-tile__badge'; + badge.innerHTML = iconHtml('video'); + tile.append(badge); + } + tile.addEventListener('click', () => openAt(attachment)); + if (thumbObserver) thumbObserver.observe(tile); + else tile.__loadThumb(); + return tile; + }; + + const openViewerAt = async (allMedia, attachment) => { + if (!tileUrls.has(fileKey(attachment))) { + try { + const { url } = await resolveDmMediaUrl(attachment); + objectUrls.add(url); + tileUrls.set(fileKey(attachment), url); + } catch { + return; + } + } + if (disposed) return; + // В просмотрщик – уже расшифрованные: остальные догрузятся, когда до них долистают в сетке. + const entries = allMedia + .filter((entry) => tileUrls.has(fileKey(entry.attachment))) + .map((entry) => ({ kind: getAttachmentKind(entry.attachment), url: tileUrls.get(fileKey(entry.attachment)), name: entry.attachment.name, attachment: entry.attachment })); + openMediaViewer(entries, Math.max(0, entries.findIndex((entry) => fileKey(entry.attachment) === fileKey(attachment)))); + }; + + const renderEmpty = (text) => { + const empty = document.createElement('p'); + empty.className = 'empty-note'; + empty.textContent = text; + body.append(empty); + }; + + function renderBody() { + if (disposed) return; + const { media, files } = collectAttachments(chatId); + for (const [value, { button, label }] of tabButtons) { + const count = value === 'media' ? media.length : files.length; + button.textContent = count ? `${label} · ${count}` : label; + button.setAttribute('aria-checked', String(value === activeTab)); + } + status.hidden = !loading && !loadFailed; + status.classList.toggle('is-error', loadFailed); + status.innerHTML = loadFailed + ? 'Не удалось загрузить всю историю – показано то, что уже есть на устройстве.' + : 'Загружаю историю переписки…'; + thumbObserver?.disconnect(); + body.replaceChildren(); + + const entries = activeTab === 'media' ? media : files; + if (!entries.length) { + if (!loading) renderEmpty(activeTab === 'media' ? 'В этой переписке пока нет фото и видео.' : 'В этой переписке пока нет файлов.'); + return; + } + for (const group of groupByMonth(entries)) { + const heading = document.createElement('h2'); + heading.className = 'chat-media-month'; + heading.textContent = group.label; + body.append(heading); + if (activeTab === 'media') { + const grid = document.createElement('div'); + grid.className = 'chat-media-grid'; + group.items.forEach((entry) => grid.append(createTile(entry, (attachment) => void openViewerAt(media, attachment)))); + body.append(grid); + } else { + const list = document.createElement('div'); + list.className = 'stack chat-media-files'; + for (const entry of group.items) { + const row = document.createElement('div'); + row.className = 'chat-media-file'; + const meta = document.createElement('span'); + meta.className = 'meta-muted chat-media-file__meta'; + meta.textContent = `${entry.from === 'out' ? 'Вы' : peerName} · ${formatDayLabel(entry.timeMs)}, ${formatClockTime(entry.timeMs)}`; + row.append(createDmFileAttachmentCard(entry.attachment), meta); + list.append(row); + } + body.append(list); + } + } + } + + renderBody(); + loadFullDmHistory(chatId) + .catch(() => { loadFailed = true; }) + .finally(() => { + loading = false; + renderBody(); + }); + + screen.cleanup = () => { + if (disposed) return; + disposed = true; + thumbObserver?.disconnect(); + // Просмотрщик мог остаться открытым поверх: его картинки живут, пока он не закрыт. + window.setTimeout(() => objectUrls.forEach((url) => URL.revokeObjectURL(url)), 60000); + }; + + return screen; +} diff --git a/shine-UI/js/pages/chat-view.js b/shine-UI/js/pages/chat-view.js index 459e49a3..6847dcdf 100644 --- a/shine-UI/js/pages/chat-view.js +++ b/shine-UI/js/pages/chat-view.js @@ -18,6 +18,8 @@ import { markReadReceiptSentByBaseKey, normalizeDmChatId, authService, + getRememberedDmPeer, + rememberDmPeer, setContacts, state, } from '../state.js'; @@ -35,13 +37,24 @@ import { buildDmFileTechBlock, buildDmReplyTechBlock, parseDmTechBlocks, sanitiz import { isDmFileTransferEnabled } from '../services/feature-settings.js'; import { decryptDmFileToBlob, - downloadAndDecryptDmFile, encryptAndUploadDmFile, - formatDmFileSize, DM_MAX_ATTACHMENTS_PER_MESSAGE, } from '../services/dm-file-service.js'; +import { createAttachmentCarouselElement } from '../services/attachment-format.js'; +import { createDmFileAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js'; +import { + DM_HISTORY_PAGE_SIZE, + isDmHistoryFullyLoaded, + loadFullDmHistory, + markDmHistoryFullyLoaded, + mergeDirectMessagesPage, + parseBaseKey, + resolveMessageTimeMs, +} from '../services/dm-history.js'; +import { isDmChatMuted, isDmChatPinned, setDmChatMuted, setDmChatPinned } from '../services/dm-chat-prefs.js'; import { loadProfileSnapshot } from '../services/user-profile-params.js'; import { makeProfileLinksRoute, makeProfileRoute } from '../services/shine-routes.js'; +import { openHistoryLayer } from '../router.js'; export const pageMeta = { id: 'chat-view', @@ -96,6 +109,7 @@ function createChatHeaderParts(login, navigate) { avatar: null, relationType: 'none', }; + let muted = false; const identityButton = document.createElement('button'); identityButton.type = 'button'; @@ -119,6 +133,13 @@ function createChatHeaderParts(login, navigate) { const lastName = String(currentPeer?.lastName || '').trim(); const fullName = [firstName, lastName].filter(Boolean).join(' '); nameEl.textContent = fullName || cleanLogin; + if (muted) { + const mutedIcon = document.createElement('span'); + mutedIcon.className = 'chat-header-muted'; + mutedIcon.title = 'Без звука'; + mutedIcon.innerHTML = iconHtml('bell-off'); + nameEl.append(mutedIcon); + } const relation = chatRelationLabel(currentPeer?.relationType); // Статус аккаунта, а не «в сети»: присутствие сервер не сообщает, выдумывать его нельзя const shining = String(currentPeer?.shineStatus || '').toLowerCase() === 'shining' ? '✧ сияющий аккаунт' : ''; @@ -175,6 +196,10 @@ function createChatHeaderParts(login, navigate) { return { center: identityButton, updatePeer, + setMuted: (value) => { + muted = Boolean(value); + renderPeer(); + }, getPeer: () => ({ ...currentPeer }), cleanup: () => identityMenu.destroy(), }; @@ -198,7 +223,7 @@ function openDeleteMessageConfirmModal({ onConfirm }) { if (!root) return; root.innerHTML = `