UI: каналы и обсуждения в раскладке Threads

Лента канала: у записи аватар и название канала слева сверху, возраст записи
(«5 мин», «2 ч», «3 д») и «⋯» в шапке, текст и действия колонкой под названием,
порядок действий – лайк, обсуждение, поделиться.
Обсуждение: открытая запись с шапкой канала и крупным текстом; ответы деревом –
под каждым ответом его ветка со сдвигом и линией от аватара, ответ на ответ
помечен адресатом, если идёт не сразу после него; в ветке видно два ответа,
остальные по «Ещё N ответов». Дерево грузится на 8 уровней вместо 2 (раньше
ответы глубже второго уровня не показывались), что глубже – кнопкой открывается
обсуждением этого ответа.
This commit is contained in:
q
2026-10-11 20:05:37 +03:00
parent 07ddaf5e4c
commit 8b2012fad3
7 changed files with 243 additions and 65 deletions
+148 -43
View File
@@ -11,6 +11,7 @@ import {
animatePress,
createSkeletonCard,
formatPostStamp,
formatShortAge,
formatRelativeTime,
longPressFeel,
shareOrCopyLink,
@@ -658,7 +659,7 @@ function openEditMessageModal({ initialText = '', allowEmptyText = false, onSave
});
}
function renderNodeCard(node, heading, handlers, localNumber, { focusPost = false, channelOwnerBlockchainName = '' } = {}) {
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
@@ -736,7 +737,26 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
if (node?.createdAtMs) timestamp.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
authorBlock.append(title, timestamp);
authorTile.append(avatar, authorBlock);
if (isOwnerPost) authorTile.hidden = true;
// Запись канала в обсуждении – как открытый пост в Threads: аватар и название канала в шапке, текст на всю ширину.
const threadsLayout = isOwnerPost && Boolean(channel);
if (isOwnerPost) authorTile.hidden = !threadsLayout;
if (threadsLayout) {
card.classList.add('channel-message-card--threads', 'channel-message-card--threads-focus');
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',
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) {
@@ -909,7 +929,8 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
else handlers.onOpenThread(target);
});
// Тот же вид и порядок кнопок, что в ленте канала.
actions.append(likeButton, shareButton, discussionButton);
if (threadsLayout) actions.append(likeButton, discussionButton, shareButton);
else actions.append(likeButton, shareButton, discussionButton);
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
if (repostTarget) {
const originalButton = document.createElement('button');
@@ -988,7 +1009,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
}
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: versions }) });
attachMessageMenu(card, headRow, menuItems);
if (isOwnerPost) {
if (isOwnerPost && !threadsLayout) {
const meta = document.createElement('div');
meta.className = 'channel-message-meta';
const moreButton = headRow.querySelector('.channel-message-more');
@@ -1065,7 +1086,9 @@ function renderThreadContext(node, { onOpenPost, onNavigate }) {
return box;
}
function renderComment({ node, parent, focus, channelOwner, handlers }) {
// Ответ в обсуждении в раскладке Threads: аватар слева, имя и время сверху, «⋯» справа, под текстом – лайк и ответ.
// nested – ответ внутри ветки (меньший аватар, линия от родителя); mention – показать, кому ответ, если это не предыдущий в ветке.
function renderComment({ node, parent, focus, channelOwner, handlers, nested = false, mention = false }) {
const target = buildTargetFromNode(node);
const key = messageRefKey(target);
const author = String(node?.authorLogin || 'автор');
@@ -1074,50 +1097,52 @@ function renderComment({ node, parent, focus, channelOwner, handlers }) {
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';
item.className = `thread-comment channel-message-card${nested ? ' thread-comment--nested' : ''}`;
if (key) item.dataset.messageKey = key;
const person = document.createElement('div');
person.className = 'thread-comment__person';
const who = document.createElement('button');
who.type = 'button';
who.className = 'thread-comment__who';
who.append(renderUserAvatar({ login: author, size: 'xs', className: 'thread-comment__avatar' }));
const name = document.createElement('span');
who.setAttribute('aria-label', `Профиль ${author}`);
who.append(renderUserAvatar({ login: author, size: nested ? 'xs' : 'sm', className: 'thread-comment__avatar' }));
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 = author;
who.append(name);
who.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
person.append(who);
name.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
head.append(name);
if (channelOwner && author.toLowerCase() === channelOwner.toLowerCase()) {
const badge = document.createElement('span');
badge.className = 'thread-comment__badge';
badge.textContent = 'Автор';
person.append(badge);
head.append(badge);
}
const time = document.createElement('time');
time.textContent = formatPostStamp(node?.createdAtMs);
time.textContent = formatShortAge(node?.createdAtMs);
if (node?.createdAtMs) time.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
person.append(time);
item.append(person);
head.append(time);
main.append(head);
// Ответ на другой комментарий — цитата в две строки; нажатие ведёт к оригиналу
if (parent && parent !== focus) {
const quote = document.createElement('button');
quote.type = 'button';
quote.className = 'thread-quote';
const qa = document.createElement('strong');
qa.textContent = String(parent.authorLogin || '');
const qt = document.createElement('span');
qt.textContent = parseMessageAttachments(resolveNodeText(parent)).text || 'Вложение';
quote.append(qa, qt);
quote.setAttribute('aria-label', `Ответ на комментарий ${parent.authorLogin || ''}. Перейти к нему`);
quote.addEventListener('click', () => handlers.jumpTo(nodeKey(parent), key));
item.append(quote);
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) {
item.append(createAttachmentCarouselElement(parsed.attachments, {
main.append(createAttachmentCarouselElement(parsed.attachments, {
gateway: state.entrySettings.arweaveServer,
messageTimestampMs: node?.createdAtMs,
authorLogin: node?.authorLogin,
@@ -1128,15 +1153,10 @@ function renderComment({ node, parent, focus, channelOwner, handlers }) {
const text = document.createElement('p');
text.className = 'thread-comment__text';
appendShineMessageLinks(text, parsed.text, { navigate: handlers?.navigate });
item.append(text);
main.append(text);
const actions = document.createElement('div');
actions.className = 'thread-comment__actions';
const reply = document.createElement('button');
reply.type = 'button';
reply.className = 'thread-comment__reply';
reply.textContent = 'Ответить';
reply.addEventListener('click', () => handlers.setReplyTo(node));
setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked');
const liked = getMessageReactionState(target) === 'liked';
@@ -1154,6 +1174,14 @@ function renderComment({ node, parent, focus, channelOwner, handlers }) {
finally { if (like.isConnected) like.disabled = false; }
});
const replies = Number(node?.repliesCount || 0);
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';
@@ -1186,12 +1214,80 @@ function renderComment({ node, parent, focus, channelOwner, handlers }) {
}
const menu = createDropdownMenu({ anchorEl: more, items: menuItems });
item.cleanup = () => menu.destroy();
head.append(more);
actions.append(reply, like, more);
item.append(actions);
actions.append(like, reply);
main.append(actions);
item.append(who, main);
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';
@@ -1266,6 +1362,9 @@ function setThreadMuted(key, muted) {
try { localStorage.setItem(THREAD_MUTE_KEY, JSON.stringify(all)); } catch { /* приватный режим */ }
}
// Глубина дерева ответов за один запрос; что глубже – открывается обсуждением конкретного ответа.
const THREAD_LOAD_DEPTH = 8;
// Черновик и адресат ответа принадлежат конкретному обсуждению
const threadDrafts = new Map();
@@ -1758,7 +1857,7 @@ export function render({ navigate, route, chrome }) {
selector.message = { ...resolvedMessage };
}
const payload = await authService.getMessageThread(resolvedMessage, 20, 2, 50, state.session.login);
const payload = await authService.getMessageThread(resolvedMessage, 20, THREAD_LOAD_DEPTH, 50, state.session.login);
if (disposed || seq !== refreshSeq) return;
skeleton?.remove();
@@ -1881,7 +1980,11 @@ export function render({ navigate, route, chrome }) {
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 || '' }));
focusWrap.append(renderNodeCard(focus, '', handlers, focusOrdinal || Number(selector?.message?.blockNumber ?? 0), {
focusPost: true,
channelOwnerBlockchainName: selector?.channel?.ownerBlockchainName || '',
channel: { title, avatarAr, avatarSha256 },
}));
screen.append(focusWrap);
}
@@ -1916,6 +2019,7 @@ export function render({ navigate, route, chrome }) {
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;
@@ -1931,8 +2035,9 @@ export function render({ navigate, route, chrome }) {
};
if (comments.length) {
comments.forEach(({ node, parent }) => {
try { listWrap.append(renderComment({ node, parent, focus, channelOwner, handlers: commentHandlers })); }
descendants.forEach((branch) => {
if (!branch?.node) return;
try { listWrap.append(renderReplyGroup(branch, { focus, channelOwner, handlers: commentHandlers })); }
catch (error) { logThreadRuntimeError('render_comment', error); }
});
} else {
+19 -4
View File
@@ -20,6 +20,7 @@ import {
formatDayLabel,
formatPostStamp,
formatRelativeTime,
formatShortAge,
longPressFeel,
shareOrCopyLink,
showToast,
@@ -1871,6 +1872,7 @@ function renderPostCard(post, {
onRepost,
onShare,
onEdit,
channel = null,
isActive = () => true,
}) {
const versionsTotal = Number(post?.versionsTotal || 1);
@@ -1964,9 +1966,19 @@ function renderPostCard(post, {
&& !isDiarySelector(selector)
&& !!post.messageRef?.blockchainName
&& String(post.messageRef.blockchainName).trim().toLowerCase() === String(selector.ownerBlockchainName || '').trim().toLowerCase();
// Запись владельца – как пост в Threads: аватар и название канала слева сверху, текст и действия под названием.
const threadsLayout = isOwnerPost && Boolean(channel);
if (isOwnerPost) {
card.classList.add('channel-message-card--owner');
authorTile.hidden = true;
authorTile.hidden = !threadsLayout;
}
if (threadsLayout) {
card.classList.add('channel-message-card--threads');
const channelAvatar = createChannelAvatarElement(channel, 36);
channelAvatar.classList.add('channel-message-avatar');
avatar.replaceWith(channelAvatar);
loginEl.textContent = String(channel.displayTitle || channel.displayName || channel.name || post.authorLogin).trim();
if (post.timestampMs) timestamp.textContent = formatShortAge(post.timestampMs);
}
const isDeletedMessage = String(post.body || '').trim().toLowerCase() === 'удалено';
@@ -2137,8 +2149,10 @@ function renderPostCard(post, {
await onShare(route);
});
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа
actions.append(likeButton, shareButton, discussionButton);
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа.
// В раскладке Threads: лайк → обсуждение → поделиться, дата и «⋯» в шапке.
if (threadsLayout) actions.append(likeButton, discussionButton, shareButton);
else actions.append(likeButton, shareButton, discussionButton);
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
const streamRoute = makeShineChannelStreamRoute({
ownerBlockchainName: selector?.ownerBlockchainName,
@@ -2226,7 +2240,7 @@ function renderPostCard(post, {
}
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
attachMessageMenu(card, headRow, menuItems);
if (isOwnerPost) {
if (isOwnerPost && !threadsLayout) {
if (post.timestampMs) timestamp.textContent = formatPostStamp(post.timestampMs);
const meta = document.createElement('div');
meta.className = 'channel-message-meta';
@@ -2334,6 +2348,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
onRepost: handlers.onRepost,
onShare: handlers.onShare,
onEdit: handlers.onEdit,
channel: channelData.channel,
isActive: handlers.isActive,
});
const key = messageRefKey(item.post.messageRef);