Files
SHiNE-server/shine-UI/js/pages/channel-thread-view.js
T

2235 lines
100 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { appendShineMessageLinks } from '../services/shine-message-links.js';
import { confirmDialog } from '../components/confirm-dialog.js';
import { confirmLikeAction } from '../components/like-action-sheet.js';
import { iconHtml } from '../components/ui-icon.js';
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
import { attachMessageMenu } from '../components/message-menu.js';
import { createTopBar } from '../components/topbar.js';
import { authService, getMessageReactionState, setMessageReactionState, state } from '../state.js';
import { captureClientError } from '../services/client-error-reporter.js';
import { toUserMessage } from '../services/ui-error-texts.js';
import {
animatePress,
createLoadErrorCard,
createSkeletonRows,
SKELETON_DELAY_MS,
formatPostStamp,
formatShortAge,
formatRelativeTime,
notifyRepostSoon,
REPOSTS_ENABLED,
longPressFeel,
shareOrCopyLink,
showToast,
softHaptic,
} from '../services/channels-ux.js';
import { navigateUp, 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';
import { openShareSheet } from '../components/share-sheet.js';
import {
composeMessageWithAttachments,
createAttachmentCarouselElement,
escapeHtml,
parseMessageAttachments,
} from '../services/attachment-format.js';
import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { extractLoginFromBlockchainName, formatChannelAddress, 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';
import { scrollNodeIntoContainer } from '../services/scroll-utils.js';
export const pageMeta = { id: 'channel-thread-view', title: 'Обсуждение', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
const MSG_SUBTYPE_TEXT_POST = 10;
const MSG_SUBTYPE_TEXT_RATING = 30;
const MSG_SUBTYPE_TEXT_ENTRYPOINT = 100;
const MSG_SUBTYPE_TEXT_EXERCISE = 110;
const MSG_SUBTYPE_TEXT_SERVICE = 120;
const MSG_SUBTYPE_TEXT_COURSE = 130;
const pendingReactionActions = new Set();
const pendingThreadScroll = new Map();
const threadAvatarSnapshotCache = new Map();
const threadAvatarPendingByLogin = new Map();
async function loadThreadAvatarSnapshot(login) {
const cleanLogin = String(login || '').trim();
if (!cleanLogin) return null;
const key = cleanLogin.toLowerCase();
if (threadAvatarSnapshotCache.has(key)) return threadAvatarSnapshotCache.get(key);
if (threadAvatarPendingByLogin.has(key)) return threadAvatarPendingByLogin.get(key);
const pending = loadProfileSnapshot(cleanLogin)
.then((snapshot) => {
threadAvatarSnapshotCache.set(key, snapshot || null);
threadAvatarPendingByLogin.delete(key);
return snapshot || null;
})
.catch(() => {
threadAvatarSnapshotCache.set(key, null);
threadAvatarPendingByLogin.delete(key);
return null;
});
threadAvatarPendingByLogin.set(key, pending);
return pending;
}
function createThreadAvatar(login) {
const cleanLogin = String(login || '').trim();
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
const avatarEl = renderUserAvatar({
login: cleanLogin || 'unknown',
size: 'sm',
className: 'channel-message-avatar avatar-plain',
title,
});
if (!cleanLogin) return avatarEl;
void loadThreadAvatarSnapshot(cleanLogin).then((snapshot) => {
if (!avatarEl.isConnected) return;
const upgraded = renderUserAvatar({
login: cleanLogin,
avatar: snapshot?.avatar?.source
? {
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
sha256Hex: String(snapshot?.avatar?.sha256Hex || '').trim().toLowerCase(),
}
: null,
size: 'sm',
className: 'channel-message-avatar avatar-plain',
title,
});
avatarEl.replaceWith(upgraded);
});
return avatarEl;
}
function logThreadRuntimeError(stage, error, context = {}) {
const message = String(error?.message || error || 'thread runtime error');
console.error(`[channel-thread-view:${stage}]`, error, context);
captureClientError({
kind: 'channels_thread_runtime',
message,
stack: error?.stack || '',
context: { stage, ...context },
});
}
function encodeRoutePart(value = '') {
return encodeURIComponent(String(value));
}
function normalizeRouteHash(hash) {
const normalized = String(hash || '').trim().toLowerCase();
return normalized || '0';
}
function normalizeMessageHash(hash) {
const normalized = String(hash || '').trim().toLowerCase();
if (!/^[0-9a-f]{64}$/.test(normalized)) return '';
if (/^0+$/.test(normalized)) return '';
return normalized;
}
function toSafeInt(value) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
function looksLikeBlockchainName(value) {
const raw = String(value || '').trim();
return /^[^-]+-\d+$/.test(raw);
}
function makeReactionActionKey(messageRef) {
const login = String(state.session.login || '').trim().toLowerCase();
const blockchainName = String(messageRef?.blockchainName || '').trim();
const blockNumber = Number(messageRef?.blockNumber);
const blockHash = normalizeMessageHash(messageRef?.blockHash);
if (!login || !blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0 || !blockHash) return '';
return `${login}|${blockchainName}|${blockNumber}|${blockHash}`;
}
function messageRefKey(messageRef) {
const blockchainName = String(messageRef?.blockchainName || '').trim();
const blockNumber = Number(messageRef?.blockNumber);
const blockHash = normalizeMessageHash(messageRef?.blockHash);
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0 || !blockHash) return '';
return `${blockchainName}:${blockNumber}:${blockHash}`;
}
function buildAbsoluteRouteUrl(routePath = '') {
const cleanRoute = String(routePath || '').replace(/^#?\/?/, '');
const url = new URL(window.location.href);
url.pathname = `/${cleanRoute}`;
url.hash = '';
return url.toString();
}
function parseThreadSelector(route) {
const params = route?.params || {};
if (params.ownerBlockchainName && params.channelName && params.messageOrdinal) {
return {
short: {
ownerBlockchainName: String(params.ownerBlockchainName || '').trim(),
channelName: String(params.channelName || '').trim(),
},
publicationOrdinal: parsePublicationOrdinal(params.messageOrdinal),
message: {
blockchainName: '',
blockNumber: null,
blockHash: '',
},
channel: {
ownerBlockchainName: '',
channelRootBlockNumber: null,
channelRootBlockHash: '0',
},
};
}
const blockNumber = toSafeInt(params.messageBlockNumber);
if (!params.messageBlockchainName || blockNumber == null) return null;
return {
message: {
blockchainName: String(params.messageBlockchainName),
blockNumber,
blockHash: normalizeRouteHash(params.messageBlockHash),
},
channel: {
ownerBlockchainName: String(params.channelOwnerBlockchainName || ''),
channelRootBlockNumber: toSafeInt(params.channelRootBlockNumber),
channelRootBlockHash: normalizeRouteHash(params.channelRootBlockHash),
},
};
}
function allFeedSummaries() {
const feed = state.channelsFeed || {};
return [
...(feed.ownedChannels || []),
...(feed.followedUsersChannels || []),
...(feed.followedChannels || []),
].filter((summary) => {
const typeCode = Number(summary?.channel?.channelTypeCode ?? 1);
const channelName = String(summary?.channel?.channelName || '').trim().toLowerCase();
return typeCode !== 0 && channelName !== 'stories';
});
}
const channelTitleByLabel = new Map();
function rememberChannelTitle(label, channel) {
const title = String(channel?.displayName || channel?.displayTitle || '').trim();
if (label && title) channelTitleByLabel.set(label, title);
}
function resolveChannelDisplayName(channelSelector) {
const rootNumber = channelSelector?.channelRootBlockNumber ?? channelSelector?.rootBlockNumber;
const rootHashRaw = channelSelector?.channelRootBlockHash ?? channelSelector?.rootBlockHash;
if (!channelSelector?.ownerBlockchainName || rootNumber == null) return '';
const ownerBch = String(channelSelector.ownerBlockchainName);
const rootNo = Number(rootNumber);
const rootHash = normalizeRouteHash(rootHashRaw);
const found = allFeedSummaries().find((summary) => (
String(summary?.channel?.ownerBlockchainName || '') === ownerBch
&& Number(summary?.channel?.channelRoot?.blockNumber) === rootNo
&& normalizeRouteHash(summary?.channel?.channelRoot?.blockHash) === rootHash
));
if (!found) return '';
const label = `${found.channel?.ownerLogin || 'неизвестно'}/${found.channel?.channelName || 'канал'}`;
rememberChannelTitle(label, found.channel);
return label;
}
function resolveChannelHeadingFromNode(node) {
const info = node?.channelInfo;
const ownerBch = String(info?.ownerBlockchainName || '').trim();
const rootBlockNumber = Number(info?.channelRoot?.blockNumber);
if (!ownerBch || !Number.isFinite(rootBlockNumber) || rootBlockNumber < 0) return '';
if (rootBlockNumber === 0) return 'История пользователя';
const label = resolveChannelDisplayName({
ownerBlockchainName: ownerBch,
channelRootBlockNumber: rootBlockNumber,
channelRootBlockHash: '0',
});
const slashIndex = label.indexOf('/');
const channelName = slashIndex >= 0 ? label.slice(slashIndex + 1).trim() : label.trim();
if (!channelName) return 'Сообщение в канале';
return `Сообщение в канале ${channelName}`;
}
function getChannelMessageTypeMeta(msgSubType) {
switch (Number(msgSubType || 0)) {
case MSG_SUBTYPE_TEXT_EXERCISE:
return { label: 'Упражнение', actionable: true };
case MSG_SUBTYPE_TEXT_SERVICE:
return { label: 'Услуга', actionable: true };
case MSG_SUBTYPE_TEXT_COURSE:
return { label: 'Курс', actionable: true };
case MSG_SUBTYPE_TEXT_ENTRYPOINT:
return { label: 'Оглавление' };
default:
return null;
}
}
function isEditableAsChannelPostSubType(msgSubType) {
return Number(msgSubType || 0) === MSG_SUBTYPE_TEXT_POST
|| Number(msgSubType || 0) === MSG_SUBTYPE_TEXT_EXERCISE
|| Number(msgSubType || 0) === MSG_SUBTYPE_TEXT_SERVICE
|| Number(msgSubType || 0) === MSG_SUBTYPE_TEXT_COURSE;
}
function extractChannelContextFromThreadPayload(payload) {
const focusInfo = payload?.focus?.channelInfo;
if (focusInfo?.ownerBlockchainName && focusInfo?.channelRoot?.blockNumber != null) {
return {
ownerBlockchainName: String(focusInfo.ownerBlockchainName || '').trim(),
channelRootBlockNumber: Number(focusInfo.channelRoot.blockNumber),
channelRootBlockHash: '0',
};
}
const ancestors = Array.isArray(payload?.ancestors) ? payload.ancestors : [];
for (let i = ancestors.length - 1; i >= 0; i -= 1) {
const info = ancestors[i]?.channelInfo;
if (info?.ownerBlockchainName && info?.channelRoot?.blockNumber != null) {
return {
ownerBlockchainName: String(info.ownerBlockchainName || '').trim(),
channelRootBlockNumber: Number(info.channelRoot.blockNumber),
channelRootBlockHash: '0',
};
}
}
return null;
}
async function resolveChannelDisplayNameFromServer(channelSelector) {
const ownerBch = String(channelSelector?.ownerBlockchainName || '').trim();
const rootNo = Number(channelSelector?.channelRootBlockNumber);
if (!ownerBch || !Number.isFinite(rootNo) || rootNo < 0) return '';
const ownerLogin = extractLoginFromBlockchainName(ownerBch);
if (!ownerLogin) return '';
try {
const feed = await authService.listSubscriptionsFeed(ownerLogin, 1000);
const rows = Array.isArray(feed?.ownedChannels) ? feed.ownedChannels : [];
const row = rows.find((item) => (
String(item?.channel?.ownerBlockchainName || '').trim().toLowerCase() === ownerBch.toLowerCase()
&& Number(item?.channel?.channelRoot?.blockNumber) === rootNo
));
if (!row?.channel?.channelName) return '';
channelSelector.channelRootBlockHash = normalizeRouteHash(row?.channel?.channelRoot?.blockHash);
const label = `${row.channel.ownerLogin || ownerLogin}/${row.channel.channelName}`;
rememberChannelTitle(label, row.channel);
return label;
} catch {
return '';
}
}
function buildThreadRouteFromTarget(target, selector, focusOrdinal = null) {
if (!target) return '';
const ownerBch = String(selector?.channel?.ownerBlockchainName || selector?.short?.ownerBlockchainName || '').trim();
const focus = selector?.message;
const sameFocus = !!focus && Number(focus.blockNumber) === Number(target.blockNumber)
&& String(focus.blockchainName || '').toLowerCase() === String(target.blockchainName || '').toLowerCase();
return makeShineMessageRoute({
ownerLogin: extractLoginFromBlockchainName(ownerBch) || extractLoginFromBlockchainName(target.blockchainName),
messageBlockchainName: target.blockchainName,
messageBlockNumber: target.blockNumber,
// A channel link needs the POST ordinal; replies still use their technical address.
messageOrdinal: sameFocus ? focusOrdinal : '',
channelName: sameFocus ? selector?.short?.channelName || '' : '',
channelOwnerBlockchainName: ownerBch,
});
}
function buildChannelRouteFromThread(selector, resolvedChannelLabel = '') {
const ownerBch = String(selector?.short?.ownerBlockchainName || selector?.channel?.ownerBlockchainName || '').trim();
if (selector?.short?.ownerBlockchainName && selector?.short?.channelName) {
return makeShineChannelRoute({
ownerLogin: extractLoginFromBlockchainName(ownerBch),
ownerBlockchainName: ownerBch,
channelName: selector.short.channelName,
});
}
const label = String(resolvedChannelLabel || '').trim();
const slashIndex = label.indexOf('/');
const channelName = slashIndex >= 0 ? label.slice(slashIndex + 1).trim() : '';
return makeShineChannelRoute({
ownerLogin: extractLoginFromBlockchainName(ownerBch),
ownerBlockchainName: ownerBch,
channelName,
});
}
function resolveThreadBackRoute(selector, resolvedChannelLabel = '') {
return buildChannelRouteFromThread(selector, resolvedChannelLabel) || 'channels-list';
}
function isChannelPage(route) {
return route?.pageId === 'channel-thread-view' || route?.pageId === 'channel-view';
}
function buildTargetFromNode(node) {
const blockchainName = String(node?.authorBlockchainName || '').trim();
const blockNumber = Number(node?.messageRef?.blockNumber);
const blockHash = normalizeMessageHash(node?.messageRef?.blockHash);
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0 || !blockHash) return null;
return { blockchainName, blockNumber, blockHash };
}
function buildRepostTargetFromNode(node) {
const blockchainName = String(node?.targetBlockchainName || '').trim();
const blockNumber = Number(node?.targetBlockNumber);
const blockHash = normalizeMessageHash(node?.targetBlockHash);
if (!blockchainName || !Number.isFinite(blockNumber) || blockNumber < 0 || !blockHash) return null;
return { blockchainName, blockNumber, blockHash };
}
function firstNonEmptyText(...candidates) {
for (const candidate of candidates) {
if (typeof candidate !== 'string') continue;
const trimmed = candidate.trim();
if (trimmed.length > 0) return candidate;
}
return '';
}
function latestVersionText(versions) {
if (!Array.isArray(versions) || !versions.length) return '';
const version = versions[versions.length - 1];
if (typeof version?.text === 'string') return version.text;
if (typeof version?.message === 'string') return version.message;
if (typeof version?.body === 'string') return version.body;
return '';
}
function bindSubmitOnPlainEnter(textarea, submit) {
if (!(textarea instanceof HTMLTextAreaElement) || typeof submit !== 'function') return;
textarea.addEventListener('keydown', (event) => {
if (event.key !== 'Enter') return;
if (event.shiftKey || event.ctrlKey) return;
event.preventDefault();
submit();
});
}
function setActionTitle(button, label) {
if (!button) return;
button.title = label;
button.setAttribute('aria-label', label);
const labelEl = button.querySelector('.channel-action-label');
if (labelEl) labelEl.textContent = label;
}
async function copyTextToClipboard(text) {
if (navigator?.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return true;
}
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.append(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return !!ok;
}
function buildBlockchainDetails({ target, authorLogin, timestampMs, text, raw, localNumber, msgSubType }) {
const source = raw && typeof raw === 'object' ? raw : {};
return {
authorLogin,
authorBlockchainName: target?.blockchainName || source.authorBlockchainName || '',
blockNumber: target?.blockNumber ?? source?.messageRef?.blockNumber ?? '',
blockHash: target?.blockHash || source?.messageRef?.blockHash || '',
localNumber,
msgSubType: msgSubType ?? source.msgSubType ?? '',
createdAtMs: timestampMs || source.createdAtMs || '',
text: String(text || ''),
signature: source.signature || source.blockSignature || source.authorSignature || 'нет в ответе сервера',
publicKey: source.publicKey || source.authorPublicKey || 'нет в ответе сервера',
raw,
};
}
function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
const root = document.getElementById('modal-root');
const rawText = JSON.stringify(details.raw || details, null, 2);
root.innerHTML = `
<div class="modal" id="thread-blockchain-details-modal">
<div class="modal-card stack blockchain-details-card">
<h3 class="modal-title">Данные блокчейна сообщения</h3>
<p class="meta-muted">Это технические данные записи Сияния. По ним можно увидеть цепочку автора, номер записи, хэш и подпись, если она есть в ответе сервера.</p>
<div class="blockchain-details-grid">
<span>Автор</span><strong>${escapeHtml(details.authorLogin)}</strong>
<span>Блокчейн</span><code>${escapeHtml(details.authorBlockchainName)}</code>
<span>Номер записи</span><code>${escapeHtml(details.blockNumber)}</code>
<span>Хэш</span><code>${escapeHtml(details.blockHash)}</code>
<span>Тип</span><code>${escapeHtml(details.msgSubType)}</code>
<span>Время</span><code>${escapeHtml(details.createdAtMs ? new Date(Number(details.createdAtMs)).toLocaleString('ru-RU') : '–')}</code>
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
<span>Подпись</span><code>${escapeHtml(details.signature)}</code>
</div>
<label class="field-label" for="thread-blockchain-details-text">Текст записи</label>
<textarea class="input" id="thread-blockchain-details-text" rows="4" readonly>${escapeHtml(details.text)}</textarea>
<pre class="blockchain-raw-block" id="thread-blockchain-raw-block" hidden>${escapeHtml(rawText)}</pre>
<div class="form-actions-grid">
<button class="secondary-btn" id="thread-blockchain-details-copy" type="button">Скопировать</button>
<button class="secondary-btn" id="thread-blockchain-details-raw" type="button">Показать сырой блок</button>
</div>
<button class="secondary-btn" id="thread-blockchain-details-close" type="button">Закрыть</button>
</div>
</div>
`;
root.querySelector('#thread-blockchain-details-close')?.addEventListener('click', () => {
root.innerHTML = '';
});
root.querySelector('#thread-blockchain-details-copy')?.addEventListener('click', async () => {
await copyTextToClipboard(rawText);
if (!isActive()) return;
showToast('Данные блокчейна скопированы');
});
root.querySelector('#thread-blockchain-details-raw')?.addEventListener('click', () => {
const rawEl = root.querySelector('#thread-blockchain-raw-block');
if (!rawEl) return;
rawEl.hidden = !rawEl.hidden;
});
}
function resolveNodeText(node) {
return firstNonEmptyText(
latestVersionText(node?.versions),
node?.text,
node?.message,
node?.body,
);
}
function openReplyModal({ onSubmit, mode = 'reply', isActive = () => true, context = null, draftKey = 'thread-reply' }) {
const isRating = mode === 'rating';
return openChannelEditor({
id: 'thread-reply-modal',
title: isRating ? 'Оценка' : 'Ответ',
submitLabel: isRating ? 'Отправить' : 'Ответить',
placeholder: isRating ? 'Напишите оценку' : 'Напишите ответ',
context,
key: `${draftKey}:${mode}`,
isActive,
onSubmit: ({ text }) => onSubmit(text),
});
}
function openRepostModal({ navigate, channels = [], onSubmit, isActive = () => true }) {
const root = document.getElementById('modal-root');
const options = (Array.isArray(channels) ? channels : [])
.filter((item) => item?.selector?.ownerBlockchainName && Number.isFinite(Number(item?.selector?.channelRootBlockNumber)))
.map((item, index) => {
const owner = String(item?.ownerLogin || '').trim();
const name = String(item?.channelName || '').trim();
const label = `${owner || 'my'}/${name || 'channel'}`;
return `<option value="${index}">${label}</option>`;
})
.join('');
root.innerHTML = `
<div class="modal" id="thread-repost-modal">
<div class="modal-card stack">
<h3 class="modal-title">Репост</h3>
<label class="meta-muted" for="thread-repost-channel-select">Канал</label>
<select id="thread-repost-channel-select" class="input">${options}</select>
<label class="meta-muted" for="thread-repost-comment">Комментарий</label>
<textarea id="thread-repost-comment" class="input" rows="5" maxlength="2000" placeholder="Комментарий к репосту"></textarea>
<div class="meta-muted inline-error" id="thread-repost-error"></div>
<div class="form-actions-grid">
<button class="secondary-btn" id="thread-repost-cancel" type="button">Отмена</button>
<button class="primary-btn" id="thread-repost-submit" type="button">Опубликовать репост</button>
</div>
</div>
</div>
`;
const selectEl = root.querySelector('#thread-repost-channel-select');
const textEl = root.querySelector('#thread-repost-comment');
const errorEl = root.querySelector('#thread-repost-error');
const submitEl = root.querySelector('#thread-repost-submit');
let inFlight = false;
const setBusy = (busy) => {
inFlight = !!busy;
if (selectEl) selectEl.disabled = inFlight;
if (textEl) textEl.disabled = inFlight;
if (submitEl) {
submitEl.disabled = inFlight;
submitEl.textContent = inFlight ? 'Публикуем...' : 'Опубликовать репост';
}
};
const close = () => {
root.innerHTML = '';
};
root.querySelector('#thread-repost-cancel')?.addEventListener('click', close);
submitEl?.addEventListener('click', async () => {
if (inFlight) return;
const idx = Number(selectEl?.value ?? -1);
if (!Number.isFinite(idx) || idx < 0 || idx >= channels.length) {
errorEl.textContent = 'Выберите канал для репоста.';
return;
}
const text = String(textEl?.value || '').trim();
if (!text) {
errorEl.textContent = 'Введите комментарий к репосту.';
return;
}
setBusy(true);
errorEl.textContent = '';
try {
await onSubmit({ channel: channels[idx].selector, text });
if (!isActive()) return;
close();
} catch (error) {
if (!isActive()) return;
setBusy(false);
errorEl.textContent = toUserMessage(error, 'Не удалось сделать репост.');
}
});
bindSubmitOnPlainEnter(textEl, () => submitEl?.click());
if (textEl) textEl.focus();
}
function openMessageHistoryModal({ versions = [], title = 'История изменений' }) {
const root = document.getElementById('modal-root');
const rows = Array.isArray(versions) ? versions : [];
root.innerHTML = `
<div class="modal" id="thread-history-modal">
<div class="modal-card stack">
<h3 class="modal-title">${title}</h3>
<div class="stack" id="thread-history-list"></div>
<div class="form-actions-grid">
<button class="secondary-btn" id="thread-history-close" type="button">Закрыть</button>
</div>
</div>
</div>
`;
const list = root.querySelector('#thread-history-list');
if (list) {
rows.forEach((item, index) => {
const row = document.createElement('div');
row.className = 'card stack';
const ts = Number(item?.createdAtMs || 0);
const text = String(item?.text || '').trim() || 'удалено';
row.innerHTML = `
<strong>Версия ${index + 1}</strong>
<div class="meta-muted">${ts > 0 ? new Date(ts).toLocaleString('ru-RU') : '–'}</div>
<p class="channel-message-body">${text}</p>
`;
list.append(row);
});
}
root.querySelector('#thread-history-close')?.addEventListener('click', () => {
root.innerHTML = '';
});
}
function openEditMessageModal({ initialText = '', allowEmptyText = false, onSave, isActive = () => true, draftKey }) {
return openChannelEditor({
id: 'thread-edit-modal', title: 'Редактирование', submitLabel: 'Сохранить',
placeholder: 'Текст сообщения', initialText, allowEmptyText,
key: draftKey, allowAttachments: false, rawText: true, isActive,
onSubmit: ({ text }) => onSave(text),
});
}
function renderNodeCard(node, heading, handlers, localNumber, { focusPost = false, channelOwnerBlockchainName = '', channel = null } = {}) {
const card = document.createElement('article');
card.className = 'card stack thread-node-card channel-message-card';
const isOwnerPost = focusPost && channelOwnerBlockchainName
&& String(node?.authorBlockchainName || '').trim().toLowerCase() === channelOwnerBlockchainName.trim().toLowerCase();
if (isOwnerPost) card.classList.add('channel-message-card--owner');
const author = node?.authorLogin || 'автор';
const versions = Array.isArray(node?.versions) ? node.versions : [];
const versionsTotal = Number(node?.versionsTotal || versions.length || 1);
const text = resolveNodeText(node) || (versionsTotal > 1 ? 'удалено' : '(пусто)');
const likes = Number(node?.likesCount || 0);
const primaryLikes = Number(node?.primaryLikesCount || 0);
const shiningLikes = Number(node?.shiningLikesCount || 0);
const replies = replyCountOf(node);
const ratings = Number(node?.ratingsCount || 0);
const isOwnMessage = Boolean(state.session.isAuthorized && state.session.login) && String(node?.authorLogin || '').trim().toLowerCase() === String(state.session.login).trim().toLowerCase();
const msgSubType = Number(node?.msgSubType || 0);
const isChannelPost = isEditableAsChannelPostSubType(msgSubType);
const isRating = msgSubType === MSG_SUBTYPE_TEXT_RATING;
const repostTarget = msgSubType === 50 ? buildRepostTargetFromNode(node) : null;
const parsedText = parseMessageAttachments(text);
if (isRating) card.classList.add('is-rating');
card.classList.add('is-counters-visible');
const headingText = String(heading || '').trim();
if (headingText) {
const headingEl = document.createElement('strong');
headingEl.className = 'thread-node-heading';
headingEl.textContent = headingText;
card.append(headingEl);
}
const authorTile = document.createElement('button');
authorTile.type = 'button';
authorTile.className = 'ui-button channel-message-author-tile';
const menuItems = [];
const headRow = document.createElement('div');
headRow.className = 'channel-message-head-row';
const avatar = createThreadAvatar(author);
const authorBlock = document.createElement('div');
authorBlock.className = 'channel-message-author';
const title = document.createElement('div');
title.className = 'channel-message-title author-line';
const titleMain = document.createElement('div');
titleMain.className = 'author-line-main';
const loginEl = document.createElement('span');
loginEl.className = 'author-line-login';
loginEl.textContent = author;
const numberEl = document.createElement('span');
numberEl.className = 'author-line-num';
numberEl.textContent = `· #${localNumber}`;
titleMain.append(loginEl, numberEl);
title.append(titleMain);
if (versionsTotal > 1) {
const editedMarker = document.createElement('span');
editedMarker.type = 'button';
editedMarker.className = 'ui-button message-edited-marker';
editedMarker.textContent = `изменено ${Math.max(1, versionsTotal - 1)}`;
editedMarker.title = 'Открыть историю редактирования';
editedMarker.addEventListener('click', (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
openMessageHistoryModal({
title: `История #${localNumber}`,
versions,
});
});
title.append(editedMarker);
}
const timestamp = document.createElement('div');
timestamp.className = 'channel-message-time';
timestamp.textContent = node?.createdAtMs ? formatRelativeTime(node.createdAtMs) : '–';
if (node?.createdAtMs) timestamp.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
authorBlock.append(title, timestamp);
authorTile.append(avatar, authorBlock);
// Запись канала в обсуждении – как открытый пост в Threads: аватар и название канала в шапке, текст на всю ширину.
const threadsLayout = focusPost && (!isOwnerPost || Boolean(channel));
if (isOwnerPost) authorTile.hidden = !threadsLayout;
if (threadsLayout) {
card.classList.add('channel-message-card--threads', 'channel-message-card--threads-focus');
if (node?.createdAtMs) timestamp.textContent = formatShortAge(node.createdAtMs);
}
if (threadsLayout && isOwnerPost) {
const title = String(channel.title || author).trim();
const channelAvatar = renderAvatar({
initials: (title[0] || 'К').toUpperCase(),
avatar: (channel.avatarAr || channel.avatarSha256) ? { ar: channel.avatarAr, sha256Hex: channel.avatarSha256 } : null,
authorLogin: author,
size: 'xl',
className: 'channel-profile-avatar channel-message-avatar avatar-plain',
title,
alt: 'Аватар канала',
});
channelAvatar.style.setProperty('--channel-avatar-size', '36px');
avatar.replaceWith(channelAvatar);
loginEl.textContent = title;
if (node?.createdAtMs) timestamp.textContent = formatShortAge(node.createdAtMs);
}
headRow.append(authorTile);
const typeMeta = getChannelMessageTypeMeta(node?.msgSubType);
if (typeMeta) {
const typeButton = document.createElement('button');
typeButton.type = 'button';
typeButton.className = 'ui-button channel-message-type-button';
typeButton.textContent = typeMeta.label;
if (typeMeta.actionable && typeof handlers?.onStatusAction === 'function') {
typeButton.addEventListener('click', (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
handlers.onStatusAction(node);
});
} else {
typeButton.classList.add('is-static');
typeButton.disabled = true;
}
headRow.append(typeButton);
}
const isDeletedMessage = String(text || '').trim().toLowerCase() === 'удалено';
if (isDeletedMessage) {
card.classList.add('channel-message-card--deleted-compact');
const deleted = document.createElement('button');
deleted.type = 'button';
deleted.className = 'ui-button deleted-message-pill';
deleted.textContent = `Удалённое сообщение от ${author}`;
deleted.title = 'Открыть историю изменений';
deleted.addEventListener('click', (event) => {
event.stopPropagation();
openMessageHistoryModal({
title: `История #${localNumber}`,
versions,
});
});
card.append(deleted);
return card;
} else {
card.append(headRow);
if (parsedText.attachments.length > 0) {
card.append(createAttachmentCarouselElement(parsedText.attachments, {
gateway: state.entrySettings.arweaveServer,
messageTimestampMs: node?.createdAtMs,
authorLogin: author,
solanaEndpoint: state.entrySettings.solanaServer,
fallbackServerLogin: state.entrySettings.shineServerLogin,
}));
}
if (isRating) {
const ratingBadge = document.createElement('span');
ratingBadge.className = 'channel-message-kind-badge channel-message-kind-badge--rating';
ratingBadge.textContent = 'Оценка';
card.append(ratingBadge);
}
const body = document.createElement('p');
body.className = 'channel-message-body';
appendShineMessageLinks(body, parsedText.text, { navigate: handlers?.navigate });
card.append(body);
}
const target = buildTargetFromNode(node);
const refKey = messageRefKey(target);
if (!target || !handlers) return card;
if (refKey) card.dataset.messageKey = refKey;
setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked');
const actionKey = makeReactionActionKey(target);
const isPending = actionKey ? pendingReactionActions.has(actionKey) : false;
const isLiked = getMessageReactionState(target) === 'liked';
const actions = document.createElement('div');
actions.className = 'thread-node-actions channel-message-actions';
const likeButton = document.createElement('button');
likeButton.type = 'button';
likeButton.className = 'ui-button channel-action-item channel-action-like thread-like-btn';
if (isLiked) likeButton.classList.add('is-liked');
likeButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
<span class="channel-action-label">${isPending ? 'Лайк...' : 'Лайк'}</span>
<span class="channel-action-counter">${Number(likes) > 0 ? likes : ''}</span>
`;
likeButton.setAttribute('aria-pressed', String(isLiked));
setActionTitle(likeButton, isPending ? 'Лайк…' : `${isLiked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${likes}`);
likeButton.disabled = isPending;
likeButton.addEventListener('click', async (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
if (isPending) return;
likeButton.disabled = true;
setActionTitle(likeButton, 'Лайк...');
try {
await handlers.onToggleLike(target, isLiked ? 'unlike' : 'like', node);
} catch (error) {
logThreadRuntimeError('like_click', error, {
action: isLiked ? 'unlike' : 'like',
targetBlockchainName: target?.blockchainName || '',
targetBlockNumber: target?.blockNumber,
});
handlers?.onActionError?.(error, isLiked ? 'unlike' : 'like');
} finally {
if (likeButton.isConnected) likeButton.disabled = false;
}
});
const replyButton = document.createElement('button');
replyButton.type = 'button';
replyButton.className = 'ui-button channel-action-item thread-reply-btn';
replyButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">${iconHtml('message')}</span>
<span class="channel-action-label">Ответить</span>
<span class="channel-action-counter">${Number(replies) > 0 ? replies : ''}</span>
`;
setActionTitle(replyButton, 'Ответить');
replyButton.addEventListener('click', (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
if (!state.session.isAuthorized) {
state.authReturnHash = window.location.pathname || '/channels';
handlers.navigate('login-view');
return;
}
if (focusPost && handlers.openReplyEditor) { handlers.openReplyEditor(node); return; }
openReplyModal({
onSubmit: async (textValue) => handlers.onReply(target, textValue),
isActive: handlers.isActive,
draftKey: `message:${refKey}`,
context: {
author,
text: parsedText.text,
attachmentLabel: parsedText.attachments[0]?.name || '',
},
});
});
// Rating/opinion action is intentionally hidden from UI for now.
// Backend/subtype/counters remain supported so the feature can be restored later.
const shareButton = document.createElement('button');
shareButton.type = 'button';
shareButton.className = 'ui-button channel-action-item channel-action-share thread-share-btn';
shareButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">${iconHtml('share')}</span>
<span class="channel-action-label">Отправить</span>
`;
setActionTitle(shareButton, 'Отправить');
shareButton.addEventListener('click', async (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
await handlers.onShare(target);
});
// Репосты временно отключены до будущей реализации.
// Точка возврата: docs/Future_Features/2026-05-24_1140_репосты_в_каналах_и_тредах.md
const discussionButton = document.createElement('button');
discussionButton.type = 'button';
discussionButton.className = 'ui-button channel-action-item channel-action-discussion';
discussionButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">${iconHtml('message')}</span>
<span class="channel-action-label">Обсуждение</span>
<span class="channel-action-counter">${replies || ''}</span>
`;
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${replies}`);
discussionButton.addEventListener('click', (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
if (focusPost) handlers.openReplyEditor?.(node);
else handlers.onOpenThread(target);
});
// Тот же вид и порядок кнопок, что в ленте канала.
const repostButton = document.createElement('button');
repostButton.type = 'button';
repostButton.className = 'ui-button channel-action-item channel-action-repost';
repostButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">${iconHtml('repost')}</span>
<span class="channel-action-label">Репост</span>
`;
setActionTitle(repostButton, 'Репост');
repostButton.addEventListener('click', (event) => {
event.stopPropagation();
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
void handlers.onRepost?.(target);
});
if (threadsLayout) actions.append(likeButton, discussionButton, repostButton, shareButton);
else actions.append(likeButton, shareButton, discussionButton);
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
// Те же действия, что у ответов в обсуждении.
menuItems.splice(1, 0, { label: 'Скопировать текст', iconHtml: iconHtml('copy'), action: async () => {
try { await copyTextToClipboard(parsedText.text); showToast('Текст скопирован'); }
catch { showToast('Не удалось скопировать', { kind: 'error' }); }
} });
if (repostTarget) {
const originalButton = document.createElement('button');
originalButton.type = 'button';
originalButton.className = 'ui-button channel-action-item';
originalButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">↪</span>
<span class="channel-action-label">Оригинал</span>
`;
setActionTitle(originalButton, 'Оригинал');
originalButton.addEventListener('click', (event) => {
event.stopPropagation();
const ownerLogin = extractLoginFromBlockchainName(repostTarget.blockchainName);
if (!ownerLogin) return;
handlers.navigate(makeShineMessageRoute({
ownerLogin,
messageBlockchainName: repostTarget.blockchainName,
messageBlockNumber: repostTarget.blockNumber,
}));
});
menuItems.push({ label: 'Оригинал', action: () => originalButton.click() });
}
const detailsButton = document.createElement('button');
detailsButton.type = 'button';
detailsButton.className = 'ui-button channel-action-item';
detailsButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">⛓</span>
<span class="channel-action-label">Данные блокчейна</span>
`;
setActionTitle(detailsButton, 'Данные блокчейна');
detailsButton.addEventListener('click', (event) => {
event.stopPropagation();
openBlockchainDetailsModal(buildBlockchainDetails({
target,
authorLogin: author,
timestampMs: node?.createdAtMs,
text,
raw: node,
localNumber,
msgSubType,
}), { isActive: handlers.isActive });
});
menuItems.push({ label: 'Данные блокчейна', action: () => detailsButton.click() });
if (isOwnMessage) {
const editButton = document.createElement('button');
editButton.type = 'button';
editButton.className = 'ui-button channel-action-item';
editButton.setAttribute('aria-label', 'Редактировать');
editButton.title = 'Редактировать';
editButton.innerHTML = `
<span class="channel-action-icon" aria-hidden="true">✏️</span>
`;
editButton.addEventListener('click', (event) => {
event.stopPropagation();
animatePress(event.currentTarget);
openEditMessageModal({
isActive: handlers.isActive,
draftKey: `edit:${messageRefKey(target)}`,
initialText: String(text || '').trim() === 'удалено' ? '' : parsedText.text,
allowEmptyText: parsedText.attachments.length > 0,
onSave: async (nextText) => handlers.onEdit(target, composeMessageWithAttachments(nextText, parsedText.attachments), { isChannelPost }),
onDelete: async () => handlers.onEdit(target, '', { isChannelPost, isDelete: true }),
});
});
menuItems.unshift({ label: 'Редактировать', action: () => editButton.click() });
menuItems.push({ label: 'Удалить', danger: true, action: async () => {
if (!await confirmDialog({
title: 'Удалить сообщение?',
text: 'Сообщение скроется из ленты. Предыдущие версии останутся в блокчейне и в истории изменений.',
confirmLabel: 'Удалить',
danger: true,
})) return;
try { await handlers.onEdit(target, '', { isChannelPost, isDelete: true }); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.'), { kind: 'error' }); }
} });
}
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: versions }) });
attachMessageMenu(card, headRow, menuItems);
if (isOwnerPost && !threadsLayout) {
const meta = document.createElement('div');
meta.className = 'channel-message-meta';
const moreButton = headRow.querySelector('.channel-message-more');
meta.append(timestamp);
if (moreButton) meta.append(moreButton);
actions.append(meta);
if (!headRow.querySelector('.channel-message-type-button')) headRow.hidden = true;
}
card.append(actions);
authorTile.addEventListener('click', (event) => {
event.stopPropagation();
const login = String(node?.authorLogin || '').trim();
if (!login) return;
handlers.navigate(makeProfileRoute(login));
});
return card;
}
// ===== Обсуждение в раскладке V4: контекст записи, плоский список комментариев, строка ввода =====
// Дерево ответов → плоский список в порядке чтения; у каждого — на что он отвечает
function flattenDescendants(items, parent = null, out = []) {
(Array.isArray(items) ? items : []).forEach((branch) => {
if (!branch?.node) return;
out.push({ node: branch.node, parent });
flattenDescendants(branch.children, branch.node, out);
});
return out;
}
// «Всего ответов в ветке»: сервер даёт только прямые ответы (repliesCount), а показывать нужно все уровни.
// Незагруженные глубже ветки учитываем по их прямому счётчику – это нижняя оценка.
function annotateReplyTotals(branches) {
let sum = 0;
(Array.isArray(branches) ? branches : []).forEach((branch) => {
if (!branch?.node) return;
const children = Array.isArray(branch.children) ? branch.children : [];
const loadedTotal = annotateReplyTotals(children);
const unloaded = Math.max(0, Number(branch.node.repliesCount || 0) - children.length);
branch.node.totalReplies = loadedTotal + unloaded;
sum += 1 + branch.node.totalReplies;
});
return sum;
}
function totalRepliesOfPayload(payload) {
const descendants = Array.isArray(payload?.descendants) ? payload.descendants : [];
const loaded = annotateReplyTotals(descendants);
const unloaded = Math.max(0, Number(payload?.focus?.repliesCount || 0) - descendants.length);
const total = loaded + unloaded;
if (payload?.focus) payload.focus.totalReplies = total;
return total;
}
export function threadTotalReplies(data) {
return totalRepliesOfPayload(data?.payload);
}
function replyCountOf(node) {
return Number(node?.totalReplies ?? node?.repliesCount ?? 0);
}
function nodeKey(node) {
return messageRefKey(buildTargetFromNode(node));
}
// Ответ в обсуждении в раскладке Threads: аватар слева, имя и время сверху, «⋯» справа, под текстом – лайк и ответ.
// nested – ответ внутри ветки (меньший аватар, линия от родителя); mention – показать, кому ответ, если это не предыдущий в ветке.
function renderComment({ node, parent, focus, channelOwner, handlers, nested = false, mention = false, identity = null }) {
const target = buildTargetFromNode(node);
const key = messageRefKey(target);
const author = String(node?.authorLogin || 'автор');
const parsed = parseMessageAttachments(resolveNodeText(node));
const versions = Array.isArray(node?.versions) ? node.versions : [];
const isOwn = Boolean(state.session.login) && author.toLowerCase() === String(state.session.login).toLowerCase();
const item = document.createElement('article');
item.className = `thread-comment channel-message-card${nested ? ' thread-comment--nested' : ''}`;
if (key) item.dataset.messageKey = key;
const who = document.createElement('button');
who.type = 'button';
who.className = 'thread-comment__who';
who.setAttribute('aria-label', `Профиль ${author}`);
who.append(identity?.avatar || renderUserAvatar({ login: author, size: nested ? 'xs' : 'sm', className: 'thread-comment__avatar avatar-plain' }));
who.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
const main = document.createElement('div');
main.className = 'thread-comment__main';
const head = document.createElement('div');
head.className = 'thread-comment__head';
const name = document.createElement('button');
name.type = 'button';
name.className = 'thread-comment__name';
name.textContent = identity?.title || author;
name.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
head.append(name);
if (!identity && channelOwner && author.toLowerCase() === channelOwner.toLowerCase()) {
const badge = document.createElement('span');
badge.className = 'thread-comment__badge';
badge.textContent = 'Автор';
head.append(badge);
}
const time = document.createElement('time');
time.textContent = formatShortAge(node?.createdAtMs);
if (node?.createdAtMs) time.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
head.append(time);
main.append(head);
if (mention && parent && parent !== focus) {
const to = document.createElement('button');
to.type = 'button';
to.className = 'thread-comment__mention';
to.innerHTML = iconHtml('reply');
to.append(String(parent.authorLogin || ''));
to.setAttribute('aria-label', `Ответ для ${parent.authorLogin || ''}. Перейти к его комментарию`);
to.addEventListener('click', () => handlers.jumpTo(nodeKey(parent), key));
main.append(to);
}
if (parsed.attachments.length) {
main.append(createAttachmentCarouselElement(parsed.attachments, {
gateway: state.entrySettings.arweaveServer,
messageTimestampMs: node?.createdAtMs,
authorLogin: node?.authorLogin,
solanaEndpoint: state.entrySettings.solanaServer,
fallbackServerLogin: state.entrySettings.shineServerLogin,
}));
}
const text = document.createElement('p');
text.className = 'thread-comment__text';
appendShineMessageLinks(text, parsed.text, { navigate: handlers?.navigate });
main.append(text);
const actions = document.createElement('div');
actions.className = 'thread-comment__actions';
setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked');
const liked = getMessageReactionState(target) === 'liked';
const likes = Number(node?.likesCount || 0);
const like = document.createElement('button');
like.type = 'button';
like.className = `channel-action-item thread-comment__like${liked ? ' is-liked' : ''}`;
like.innerHTML = `${iconHtml('heart', liked)}<span>${likes || ''}</span>`;
like.setAttribute('aria-pressed', String(liked));
like.setAttribute('aria-label', `${liked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${likes}`);
like.addEventListener('click', async () => {
like.disabled = true;
try { await handlers.onToggleLike(target, liked ? 'unlike' : 'like', node); }
catch (error) { handlers.onActionError(error, liked ? 'unlike' : 'like'); }
finally { if (like.isConnected) like.disabled = false; }
});
const replies = replyCountOf(node);
const reply = document.createElement('button');
reply.type = 'button';
reply.className = 'channel-action-item thread-comment__reply';
reply.innerHTML = `${iconHtml('message')}<span>${replies || ''}</span>`;
reply.setAttribute('aria-label', `Ответить ${author}`);
reply.addEventListener('click', () => handlers.setReplyTo(node));
const more = document.createElement('button');
more.type = 'button';
more.className = 'channel-action-item thread-comment__more';
more.innerHTML = iconHtml('more');
more.setAttribute('aria-label', `Действия с комментарием ${author}`);
const menuItems = [
{ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => handlers.setReplyTo(node) },
{ label: 'Поделиться комментарием', iconHtml: iconHtml('share'), action: () => handlers.shareComment(node) },
{ label: 'Скопировать текст', iconHtml: iconHtml('copy'), action: async () => {
try { await navigator.clipboard.writeText(parsed.text); showToast('Текст скопирован'); }
catch { showToast('Не удалось скопировать', { kind: 'error' }); }
} },
{ label: 'Данные публикации', iconHtml: iconHtml('info'), action: () => openBlockchainDetailsModal(buildBlockchainDetails({ target, authorLogin: author, timestampMs: node?.createdAtMs, text: resolveNodeText(node), raw: node, localNumber: 0, msgSubType: Number(node?.msgSubType || 0) }), { isActive: handlers.isActive }) },
];
if (versions.length > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions }) });
if (isOwn) {
menuItems.splice(1, 0, { label: 'Редактировать', iconHtml: iconHtml('edit'), action: () => openEditMessageModal({
isActive: handlers.isActive,
draftKey: `edit:${key}`,
initialText: parsed.text,
allowEmptyText: parsed.attachments.length > 0,
onSave: async (nextText) => handlers.onEdit(target, composeMessageWithAttachments(nextText, parsed.attachments), { isChannelPost: false }),
onDelete: async () => handlers.onEdit(target, '', { isChannelPost: false, isDelete: true }),
}) });
menuItems.push({ divider: true }, { label: 'Удалить', danger: true, iconHtml: iconHtml('trash'), action: async () => {
if (!await confirmDialog({ title: 'Удалить комментарий?', text: 'Он скроется из обсуждения. Прежние версии останутся в блокчейне.', confirmLabel: 'Удалить', danger: true })) return;
try { await handlers.onEdit(target, '', { isChannelPost: false, isDelete: true }); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить комментарий.'), { kind: 'error' }); }
} });
}
const menu = createDropdownMenu({ anchorEl: more, items: menuItems });
item.cleanup = () => menu.destroy();
head.append(more);
const share = document.createElement('button');
share.type = 'button';
share.className = 'channel-action-item thread-comment__share';
share.innerHTML = iconHtml('share');
share.setAttribute('aria-label', 'Поделиться комментарием');
share.addEventListener('click', () => handlers.shareComment(node));
const repost = document.createElement('button');
repost.type = 'button';
repost.className = 'channel-action-item thread-comment__repost';
repost.innerHTML = iconHtml('repost');
repost.setAttribute('aria-label', 'Репост');
repost.addEventListener('click', () => (REPOSTS_ENABLED ? handlers.onRepost?.(target) : notifyRepostSoon()));
// Ряд действий как у записи канала: лайк, ответы, репост, поделиться.
actions.append(like, reply, repost, share);
main.append(actions);
item.append(who, main);
// Как в Threads: нажатие на ответ открывает его обсуждение (кнопки, ссылки и вложения работают сами по себе).
item.addEventListener('click', (event) => {
if (event.target.closest('button, a, .message-attachment-carousel')) return;
if (String(window.getSelection?.() || '').trim()) return;
handlers.onOpenThread(target);
});
item.addEventListener('pointerdown', () => handlers.prefetchThread?.(target), { passive: true });
return item;
}
// Сколько ответов внутри ветки видно сразу; остальные – по «Ещё N ответов».
const THREAD_GROUP_VISIBLE_REPLIES = 2;
// Ветка ответа верхнего уровня: сам ответ и всё дерево под ним одной колонкой с линией, как в Threads.
// Ответы глубже, чем отдал сервер, открываются отдельным обсуждением этого ответа.
function renderReplyGroup(branch, { focus, channelOwner, handlers }) {
const group = document.createElement('div');
group.className = 'thread-group';
group.append(renderComment({ node: branch.node, parent: focus, focus, channelOwner, handlers }));
const nested = [];
const walk = (children, parent) => {
(Array.isArray(children) ? children : []).forEach((child) => {
if (!child?.node) return;
nested.push({ node: child.node, parent, loaded: Array.isArray(child.children) ? child.children.length : 0 });
walk(child.children, child.node);
});
};
walk(branch.children, branch.node);
if (!nested.length) return group;
group.classList.add('has-replies');
const list = document.createElement('div');
list.className = 'thread-replies';
let previous = branch.node;
nested.forEach(({ node, parent, loaded }, index) => {
const comment = renderComment({ node, parent, focus, channelOwner, handlers, nested: true, mention: parent !== previous });
if (index >= THREAD_GROUP_VISIBLE_REPLIES) comment.classList.add('is-collapsed');
list.append(comment);
const unloaded = Number(node?.repliesCount || 0) - loaded;
if (unloaded > 0) {
const deeper = document.createElement('button');
deeper.type = 'button';
deeper.className = 'thread-more thread-more--deeper';
if (index >= THREAD_GROUP_VISIBLE_REPLIES) deeper.classList.add('is-collapsed');
deeper.textContent = `Ответы на этот комментарий · ${unloaded}`;
deeper.addEventListener('click', () => handlers.onOpenThread(buildTargetFromNode(node)));
list.append(deeper);
}
previous = node;
});
const hidden = nested.length - THREAD_GROUP_VISIBLE_REPLIES;
if (hidden > 0) {
const expand = document.createElement('button');
expand.type = 'button';
expand.className = 'thread-more';
expand.textContent = `Ещё ${hidden} ${pluralRu(hidden, 'ответ', 'ответа', 'ответов')}`;
expand.addEventListener('click', () => {
list.classList.add('is-expanded');
expand.remove();
});
list.append(expand);
}
group.append(list);
return group;
}
function pluralRu(n, one, few, many) {
const mod10 = n % 10;
const mod100 = n % 100;
if (mod10 === 1 && mod100 !== 11) return one;
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return few;
return many;
}
function renderDescendants(items, handlers, nextNumber, depth = 0, parent = null) {
const wrap = document.createElement('div');
wrap.className = 'stack';
const normalized = Array.isArray(items) ? items : [];
normalized.forEach((branch, index) => {
try {
const nodeNumber = nextNumber();
const row = renderNodeCard(branch?.node, '', handlers, nodeNumber);
row.classList.add('thread-node-level');
if (parent) {
const context = document.createElement('p');
context.className = 'thread-reply-context';
const excerpt = parseMessageAttachments(resolveNodeText(parent)).text;
context.textContent = `В ответ ${parent.authorLogin || 'автору'} · ${excerpt.slice(0, 100) || 'Вложение'}`;
row.prepend(context);
}
wrap.append(row);
if (Array.isArray(branch?.children) && branch.children.length) {
wrap.append(renderDescendants(branch.children, handlers, nextNumber, depth + 1, branch.node));
}
} catch (error) {
logThreadRuntimeError('render_descendants_branch', error, { depth, index });
}
});
return wrap;
}
function applyPendingScroll(screen, routeKey, shouldContinue = () => true) {
const target = pendingThreadScroll.get(routeKey);
if (!target) return;
const doScroll = () => {
if (!shouldContinue()) return;
if (target === '__LAST_REPLY__') {
const cards = screen.querySelectorAll('.thread-block--replies [data-message-key]');
const last = cards[cards.length - 1];
if (last) {
scrollNodeIntoContainer(last, { behavior: 'smooth' });
}
pendingThreadScroll.delete(routeKey);
return;
}
const node = screen.querySelector(`[data-message-key="${target}"]`);
if (node) {
scrollNodeIntoContainer(node, { behavior: 'smooth' });
pendingThreadScroll.delete(routeKey);
}
};
return window.setTimeout(doScroll, 20);
}
// Место под заглушку занимаем сразу, а сами строки рисуем, только если загрузка затянулась.
function renderSkeleton(screen) {
const wrap = document.createElement('div');
screen.append(wrap);
window.setTimeout(() => { if (wrap.isConnected) wrap.append(createSkeletonRows('post', 3)); }, SKELETON_DELAY_MS);
return wrap;
}
// «Не уведомлять об ответах» — пока только на этом устройстве (серверной настройки нет, см. docs/UI-Design)
const THREAD_MUTE_KEY = 'shine-ui-thread-muted-v1';
function readMuted() { try { return JSON.parse(localStorage.getItem(THREAD_MUTE_KEY) || '{}') || {}; } catch { return {}; } }
function isThreadMuted(key) { return Boolean(readMuted()[key]); }
function setThreadMuted(key, muted) {
const all = readMuted();
if (muted) all[key] = Date.now(); else delete all[key];
try { localStorage.setItem(THREAD_MUTE_KEY, JSON.stringify(all)); } catch { /* приватный режим */ }
}
// Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа.
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)) return threadPrefetches.get(pathname);
if (pageDataAge('thread', pathname) < THREAD_PREFETCH_FRESH_MS) return Promise.resolve(readPageData('thread', pathname)?.data || null);
const route = parseRouteFromPath(pathname);
const sel = route.pageId === 'channel-thread-view' ? parseThreadSelector(route) : null;
if (!sel) return Promise.resolve(null);
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);
return request;
}
export function render({ navigate, route, chrome }) {
let selector = parseThreadSelector(route);
const channelDisplayName = resolveChannelDisplayName(selector?.channel);
const routeKey = selector?.publicationOrdinal
? `channel:${selector?.short?.ownerBlockchainName || ''}:${selector?.short?.channelName || ''}:${selector.publicationOrdinal}`
: `${selector?.message?.blockchainName || ''}:${selector?.message?.blockNumber || ''}:${selector?.message?.blockHash || ''}`;
let activeResolvedChannelLabel = channelDisplayName;
let focusOrdinal = selector?.publicationOrdinal || null;
const screen = document.createElement('section');
screen.className = 'stack channels-screen channels-screen--thread';
const positionKey = `${state.session.login}:thread:${routeKey}`;
let disposed = false;
let refreshSeq = 0;
let refresh = () => {};
const refreshTimers = new Set();
const threadHeaderButton = document.createElement('button');
threadHeaderButton.type = 'button';
threadHeaderButton.className = 'topbar-identity channel-header-route-btn';
const threadHeaderText = document.createElement('span');
threadHeaderText.className = 'topbar-identity__text';
const threadHeaderTitle = document.createElement('span');
threadHeaderTitle.className = 'topbar-identity__title';
threadHeaderTitle.textContent = 'Обсуждение';
const threadHeaderChannel = document.createElement('span');
threadHeaderChannel.className = 'topbar-identity__sub';
threadHeaderChannel.textContent = '…';
threadHeaderText.append(threadHeaderTitle, threadHeaderChannel);
threadHeaderButton.append(threadHeaderText);
threadHeaderButton.disabled = true;
// Меню обсуждения (V4): к записи, уведомления об ответах, поделиться записью
let threadMenuActions = null;
const header = createTopBar({
center: threadHeaderButton,
className: 'topbar--identity',
back: state.session.isAuthorized ? { label: '<', onClick: () => navigateUp(isChannelPage, resolveThreadBackRoute(selector, activeResolvedChannelLabel)) } : null,
actions: [{
label: '⋯',
ariaLabel: 'Меню обсуждения',
className: 'thread-menu-btn',
menu: { minWidth: 240, items: () => threadMenuActions?.() || [] },
}],
});
header.classList.add('channel-thread-topbar');
chrome?.setTopbar(header);
const statusBox = document.createElement('div');
statusBox.className = 'card status-line is-unavailable channels-status';
statusBox.style.display = 'none';
const ensureActive = () => {
if (disposed) throw new Error('Экран обсуждения уже закрыт.');
};
const showStatus = (message) => {
if (disposed) return;
if (!message) {
statusBox.style.display = 'none';
statusBox.textContent = '';
return;
}
statusBox.textContent = message;
statusBox.style.display = '';
};
const requireSigningSession = () => {
const login = state.session.login;
const storagePwd = state.session.storagePwdInMemory;
if (!login || !storagePwd) {
state.authReturnHash = window.location.pathname || '/channels';
navigate('login-view');
throw new Error('Для этого действия нужно войти');
}
return { login, storagePwd };
};
let replyEditorOpener = null;
// Пришли по «Обсуждение» из ленты – после первой загрузки сразу открыть редактор ответа.
let openEditorOnLoad = consumeReplyEditorOnOpen(window.location.pathname);
const handlers = {
navigate,
isActive: () => !disposed,
openReplyEditor: (node) => replyEditorOpener?.(node),
onToggleLike: async (target, action, counts = {}) => {
if (!state.session.isAuthorized) {
state.authReturnHash = window.location.pathname || '/channels';
navigate('login-view');
return;
}
const actionKey = makeReactionActionKey(target);
if (!actionKey) throw new Error('Некорректная ссылка на сообщение для реакции.');
if (pendingReactionActions.has(actionKey)) return;
const accepted = await confirmLikeAction({ liked: action === 'unlike', counts });
if (!accepted || disposed) return;
if (pendingReactionActions.has(actionKey)) return;
const previousReaction = getMessageReactionState(target);
const nextReaction = action === 'unlike' ? 'unliked' : 'liked';
pendingReactionActions.add(actionKey);
try {
const { login, storagePwd } = requireSigningSession();
if (action === 'unlike') {
await authService.addBlockUnlike({ login, storagePwd, message: target });
} else {
await authService.addBlockLike({ login, storagePwd, message: target });
}
if (disposed) return;
setMessageReactionState(target, nextReaction);
softHaptic(10);
void refresh();
} catch (error) {
if (disposed) return;
setMessageReactionState(target, previousReaction || 'unliked');
void refresh();
throw error;
} finally {
pendingReactionActions.delete(actionKey);
}
},
onReply: async (target, textValue) => {
const { login, storagePwd } = requireSigningSession();
await authService.addBlockReply({ login, storagePwd, message: target, text: textValue });
ensureActive();
pendingThreadScroll.set(routeKey, '__LAST_REPLY__');
softHaptic(15);
showToast('Ответ отправлен');
showStatus('');
void refresh();
},
onRating: async (target, textValue) => {
const { login, storagePwd } = requireSigningSession();
await authService.addBlockRating({ login, storagePwd, message: target, text: textValue });
ensureActive();
pendingThreadScroll.set(routeKey, '__LAST_REPLY__');
softHaptic(15);
showToast('Оценка отправлена');
showStatus('');
void refresh();
},
onRepost: async (target) => {
const { login, storagePwd } = requireSigningSession();
const feed = await authService.listSubscriptionsFeed(login, 1000);
if (disposed) return;
const channels = (Array.isArray(feed?.ownedChannels) ? feed.ownedChannels : [])
.map((row) => {
const selectorRow = {
ownerBlockchainName: String(row?.channel?.ownerBlockchainName || '').trim(),
channelRootBlockNumber: Number(row?.channel?.channelRoot?.blockNumber),
channelRootBlockHash: normalizeRouteHash(row?.channel?.channelRoot?.blockHash),
};
if (!selectorRow.ownerBlockchainName || !Number.isFinite(selectorRow.channelRootBlockNumber) || selectorRow.channelRootBlockNumber < 0) {
return null;
}
return {
ownerLogin: String(row?.channel?.ownerLogin || '').trim(),
channelName: String(row?.channel?.channelName || '').trim(),
channelTypeCode: Number(row?.channel?.channelTypeCode ?? 1),
selector: selectorRow,
};
})
.filter(Boolean)
.filter((item) => Number(item.channelTypeCode) !== 0 && String(item.channelName || '').trim().toLowerCase() !== 'stories');
if (!channels.length) throw new Error('У вас пока нет каналов для репоста.');
openRepostModal({
navigate,
channels,
isActive: () => !disposed,
onSubmit: async ({ channel, text }) => {
await authService.addBlockRepost({
login,
storagePwd,
channel,
message: target,
text,
});
ensureActive();
softHaptic(12);
showToast('Репост опубликован');
showStatus('');
},
});
},
onShare: async (target) => {
try {
const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal);
if (!routePath) throw new Error('Не удалось подготовить ссылку на обсуждение.');
const result = await shareOrCopyLink({
title: 'Сияние · Обсуждение',
text: 'Сообщение из обсуждения в Сиянии',
url: buildAbsoluteRouteUrl(routePath),
});
if (disposed) return;
if (result === 'copied') showToast('Ссылка скопирована');
if (result === 'shared') showToast('Ссылка передана');
if (result === 'copied' || result === 'shared') softHaptic(10);
} catch (error) {
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) {
showStatus('Не удалось определить ссылку на обсуждение.');
return;
}
navigate(routePath);
},
onActionError: (error, action) => {
const fallback = action === 'unlike'
? 'Не удалось убрать лайк.'
: action === 'repost'
? 'Не удалось сделать репост.'
: 'Не удалось поставить лайк.';
showStatus(toUserMessage(error, fallback));
},
onEdit: async (target, textValue, meta = {}) => {
const { login, storagePwd } = requireSigningSession();
await authService.addBlockEditMessage({
login,
storagePwd,
message: target,
text: textValue,
isChannelPost: meta?.isChannelPost === true,
channel: selector?.channel || null,
});
ensureActive();
softHaptic(12);
showToast('Сообщение обновлено');
showStatus('');
void refresh();
},
};
screen.append(statusBox);
const clearContent = () => {
chrome?.setComposer(null);
screen.querySelectorAll('.channel-message-card').forEach((card) => card.cleanup?.());
for (const timerId of refreshTimers) window.clearTimeout(timerId);
refreshTimers.clear();
Array.from(screen.children).forEach((child) => {
if (child !== statusBox) child.remove();
});
};
const clearOwnedModal = () => {
const modalRoot = document.getElementById('modal-root');
if (!modalRoot) return;
if (modalRoot.querySelector([
'#thread-blockchain-details-modal',
'#thread-edit-modal',
'#thread-history-modal',
'#thread-reply-modal',
'#thread-repost-modal',
].join(','))) {
modalRoot.querySelectorAll('.channel-editor-overlay').forEach((editor) => editor.cleanup?.());
modalRoot.innerHTML = '';
}
};
const trackTimer = (timerId) => {
if (timerId) refreshTimers.add(timerId);
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 totalReplies = totalRepliesOfPayload(payload);
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 = formatChannelAddress({ ownerLogin: visibleOwner, channelName: 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 avatar-plain',
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 avatar-plain',
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 = `Комментарии · ${Math.max(totalReplies, 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)}"]`);
scrollNodeIntoContainer(el, { 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');
scrollNodeIntoContainer(el, { 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 avatar-plain',
title,
alt: 'Аватар канала',
});
item.avatar.style.setProperty('--channel-avatar-size', '40px');
}
return item;
};
// Запись канала показывается от имени канала – и обращаемся к ней по названию канала.
const replyTargetName = (node) => {
const rootNode = ancestors.length ? ancestors[0] : focus;
const byOwner = Boolean(selector?.channel?.ownerBlockchainName)
&& String(node?.authorBlockchainName || '').toLowerCase() === String(selector.channel.ownerBlockchainName).toLowerCase();
return node === rootNode && byOwner ? title : String(node?.authorLogin || '');
};
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: `Ответить ${replyTargetName(node)}…`,
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 avatar-plain' });
const field = document.createElement('button');
field.type = 'button';
field.className = 'thread-reply-bar__field';
field.textContent = `Ответьте ${replyTargetName(focus)}…`;
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;
scrollNodeIntoContainer(focusWrap, { block: 'start' });
}, 20));
}
};
refresh = async () => {
if (disposed) return;
const seq = ++refreshSeq;
const hadContent = !!screen.querySelector('.thread-block');
const restorePosition = hadContent ? document.getElementById('app-screen')?.scrollTop : readChannelPosition(positionKey);
if (!hadContent) clearContent();
showStatus('');
const sel = parseThreadSelector(route);
if (!sel) {
const invalid = document.createElement('div');
invalid.className = 'card meta-muted';
invalid.textContent = 'Обсуждение не найдено: неверная ссылка.';
screen.append(invalid);
return;
}
const cacheKey = window.location.pathname;
// При возврате к обсуждению сразу показываем прошлую загрузку, без заглушки и пустого кадра.
const cached = hadContent ? null : readPageData('thread', cacheKey);
let shown = hadContent;
if (cached) {
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
await Promise.resolve();
if (disposed || seq !== refreshSeq) return;
try {
paint(cached.data, restorePosition, seq);
shown = true;
} catch (error) {
logThreadRuntimeError('paint_cached', error);
dropPageData('thread', cacheKey);
clearContent();
}
}
if (!shown) {
selector = sel;
focusOrdinal = sel?.publicationOrdinal || null;
activeResolvedChannelLabel = resolveChannelDisplayName(sel?.channel);
threadHeaderChannel.textContent = '…';
threadHeaderButton.disabled = true;
threadHeaderButton.onclick = null;
threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove();
threadHeaderTitle.textContent = 'Обсуждение';
}
const skeleton = shown ? null : renderSkeleton(screen);
try {
const pending = threadPrefetches.get(cacheKey);
const data = pending
? await pending.catch(() => loadThreadData(sel, cacheKey, () => !disposed && seq === refreshSeq))
: await loadThreadData(sel, cacheKey, () => !disposed && seq === refreshSeq);
if (!data || disposed || seq !== refreshSeq) return;
const signature = writePageData('thread', cacheKey, data);
// Сервер вернул то же, что уже на экране, – ничего не трогаем.
if (cached && cached.signature === signature) return;
skeleton?.remove();
paint(data, shown ? document.getElementById('app-screen')?.scrollTop : restorePosition, seq);
} catch (error) {
if (disposed || seq !== refreshSeq) return;
skeleton?.remove();
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить обсуждение.')); return; }
threadHeaderChannel.textContent = '';
screen.append(createLoadErrorCard({
title: 'Не удалось загрузить обсуждение',
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
onRetry: () => void refresh(),
}));
}
};
screen.refresh = refresh;
screen.cleanup = () => {
if (disposed) return;
rememberChannelPosition(positionKey);
disposed = true;
refreshSeq += 1;
clearContent();
clearOwnedModal();
};
void refresh();
return screen;
}