UI: полные счётчики ответов, поле сообщения как в Telegram, переключатель «Связей», шапка

- Счётчик ответов – по всем уровням: обсуждение считает по дереву, лента берёт итог из обсуждения
  (кэш или фоновая подгрузка видимых записей, они же потом открываются сразу).
  Сервер пока отдаёт только прямые ответы.
- Чат: поле-«таблетка» растёт плавно (высота меряется по скрытой копии, без сброса в auto),
  смайлик внутри поля справа внизу, «Отправить» 44 px по низу; убраны правила перестройки
  в две колонки.
- «Связи»: фильтры – общий блок-переключатель (.tabs), как на других вкладках, всё помещается.
- Шапка: название крупнее и жирнее, подпись под ним компактнее.
This commit is contained in:
q
2026-10-12 09:45:08 +03:00
parent 9ea276ba77
commit 923f281bf6
10 changed files with 201 additions and 105 deletions
+40 -5
View File
@@ -677,7 +677,7 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
const likes = Number(node?.likesCount || 0);
const primaryLikes = Number(node?.primaryLikesCount || 0);
const shiningLikes = Number(node?.shiningLikesCount || 0);
const replies = Number(node?.repliesCount || 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);
@@ -1066,6 +1066,38 @@ function flattenDescendants(items, parent = null, 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));
}
@@ -1158,7 +1190,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
finally { if (like.isConnected) like.disabled = false; }
});
const replies = Number(node?.repliesCount || 0);
const replies = replyCountOf(node);
const reply = document.createElement('button');
reply.type = 'button';
reply.className = 'channel-action-item thread-comment__reply';
@@ -1537,10 +1569,11 @@ const THREAD_PREFETCH_FRESH_MS = 30_000;
// Начинает загрузку обсуждения заранее (касание карточки до клика); экран потом подхватит тот же запрос.
export function prefetchThreadPage(path) {
const pathname = new URL(path, window.location.origin).pathname;
if (threadPrefetches.has(pathname) || pageDataAge('thread', pathname) < THREAD_PREFETCH_FRESH_MS) return;
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;
if (!sel) return Promise.resolve(null);
const login = state.session.login;
const request = loadThreadData(sel, pathname, () => state.session.login === login)
.then((data) => {
@@ -1550,6 +1583,7 @@ export function prefetchThreadPage(path) {
.finally(() => { threadPrefetches.delete(pathname); });
request.catch(() => {});
threadPrefetches.set(pathname, request);
return request;
}
export function render({ navigate, route, chrome }) {
@@ -1833,6 +1867,7 @@ export function render({ navigate, route, chrome }) {
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();
@@ -1947,7 +1982,7 @@ export function render({ navigate, route, chrome }) {
listWrap.className = 'thread-block thread-block--replies';
const listTitle = document.createElement('h3');
listTitle.className = 'thread-section-title';
listTitle.textContent = `Комментарии · ${comments.length}`;
listTitle.textContent = `Комментарии · ${Math.max(totalReplies, comments.length)}`;
listWrap.append(listTitle);
// Возврат к ответу после перехода по цитате
+56 -2
View File
@@ -3,7 +3,7 @@ import { confirmDialog } from '../components/confirm-dialog.js';
import { iconHtml } from '../components/ui-icon.js';
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
import { getPreviousTrackedPath, parseRouteFromPath, toPrettyPath } from '../router.js';
import { prefetchThreadPage } from './channel-thread-view.js';
import { prefetchThreadPage, threadTotalReplies } from './channel-thread-view.js';
import { attachMessageMenu } from '../components/message-menu.js';
import { createTopBar } from '../components/topbar.js';
import {
@@ -2078,6 +2078,16 @@ function renderPostCard(post, {
}
});
// Сервер считает только прямые ответы; полное число по всем уровням берём из обсуждения (кэш или подгрузка).
if (Number(post.repliesCount || 0) > 0) {
const threadRoute = buildThreadRoute(post, selector);
if (threadRoute) {
const threadPath = new URL(`/${toPrettyPath(threadRoute)}`, window.location.origin).pathname;
card.dataset.threadPath = threadPath;
const known = readPageData('thread', threadPath)?.data;
if (known) post.repliesCount = threadTotalReplies(known);
}
}
const discussionButton = document.createElement('button');
discussionButton.type = 'button';
discussionButton.className = 'ui-button channel-action-item channel-action-discussion';
@@ -2494,6 +2504,45 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
};
}
// Полные счётчики ответов для видимых записей: обсуждения подгружаются по одному (они же потом открываются сразу).
function watchReplyTotals(screen) {
if (!('IntersectionObserver' in window)) return () => {};
let stopped = false;
const queue = [];
let running = false;
const setCount = (card, total) => {
card.querySelectorAll('.channel-action-discussion .channel-action-counter, .channel-action-reply .channel-action-counter')
.forEach((counter) => { counter.textContent = total ? String(total) : ''; });
};
const pump = async () => {
if (running) return;
running = true;
while (!stopped && queue.length) {
const card = queue.shift();
try {
const data = await prefetchThreadPage(card.dataset.threadPath);
if (!stopped && data && card.isConnected) setCount(card, threadTotalReplies(data));
} catch {
// Не удалось – остаётся серверный счётчик прямых ответов.
}
}
running = false;
};
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
observer.unobserve(entry.target);
queue.push(entry.target);
});
void pump();
}, { rootMargin: '200px 0px' });
screen.querySelectorAll('.channel-message-card[data-thread-path]').forEach((card) => observer.observe(card));
return () => {
stopped = true;
observer.disconnect();
};
}
// Фоновая подгрузка канала в кэш, чтобы он открывался сразу (вызывается из обхода ленты каналов).
export async function prefetchChannelPage(path) {
const pathname = new URL(path, window.location.origin).pathname;
@@ -3024,7 +3073,7 @@ export function render({ navigate, route, chrome }) {
};
}
clearContent();
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
const stopSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
chrome,
restorePosition,
scrollToMessageOrdinal,
@@ -3118,6 +3167,11 @@ export function render({ navigate, route, chrome }) {
},
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
});
const stopReplyTotals = watchReplyTotals(screen);
cleanupSeenTracking = () => {
if (typeof stopSeenTracking === 'function') stopSeenTracking();
stopReplyTotals();
};
};
refresh = async () => {
+24 -4
View File
@@ -626,10 +626,28 @@ function showTtsMissingConfigDialog() {
root.querySelector('#chat-tts-ok')?.addEventListener('click', close);
}
// Высоту меряем по скрытой копии поля: так поле не сбрасывается в auto и растёт плавно (transition в chat.css).
const composerMeasures = new WeakMap();
function autoResizeComposer(textarea) {
if (!textarea) return;
textarea.style.height = 'auto';
textarea.style.height = `${Math.min(180, Math.max(42, textarea.scrollHeight))}px`;
let measure = composerMeasures.get(textarea);
if (!measure || !measure.isConnected) {
measure = textarea.cloneNode(false);
measure.removeAttribute('name');
measure.removeAttribute('id');
measure.tabIndex = -1;
measure.setAttribute('aria-hidden', 'true');
measure.classList.add('dm-input-measure');
measure.removeAttribute('style');
textarea.after(measure);
composerMeasures.set(textarea, measure);
}
measure.style.width = `${textarea.offsetWidth}px`;
measure.value = textarea.value || ' ';
const style = getComputedStyle(textarea);
const borders = (Number.parseFloat(style.borderTopWidth) || 0) + (Number.parseFloat(style.borderBottomWidth) || 0);
const next = Math.min(180, Math.max(44, measure.scrollHeight + borders));
if (textarea.style.height !== `${next}px`) textarea.style.height = `${next}px`;
}
function createHeaderPhoneHandsetIcon() {
@@ -1566,11 +1584,13 @@ export function render({ navigate, route, chrome }) {
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</span>
<span class="dm-voice-recording-hint" id="chat-voice-recording-hint">↑ проведите вверх, чтобы закрепить</span>
</div>
<textarea class="input dm-input" name="message" rows="1" placeholder="Введите сообщение" maxlength="12000" enterkeyhint="enter"></textarea>
<div class="dm-field">
<textarea class="input dm-input" name="message" rows="1" placeholder="Сообщение" maxlength="12000" enterkeyhint="enter"></textarea>
<button class="ghost-btn dm-emoji-btn" type="button" id="chat-emoji-toggle" aria-label="Эмодзи" title="Эмодзи"><span class="dm-emoji-btn__glyph">☺</span></button>
</div>
<input id="chat-file-input" type="file" multiple hidden />
<div class="dm-actions-col">
<button class="ghost-btn dm-file-btn" type="button" id="chat-file-toggle" aria-label="Прикрепить файлы" title="Прикрепить файлы" hidden>📎</button>
<button class="ghost-btn dm-emoji-btn" type="button" id="chat-emoji-toggle" aria-label="Эмодзи" title="Эмодзи"><span class="dm-emoji-btn__glyph">☺</span></button>
<button class="primary-btn dm-send-btn dm-send-icon-btn" type="button" title="Записать голосовое сообщение" data-mode="voice" aria-label="Записать голосовое сообщение"></button>
</div>
`;
+27 -24
View File
@@ -896,13 +896,18 @@ export function render({ navigate, route, chrome } = {}) {
return true;
}
function syncToggle(button, pressed) {
button.classList.toggle('active', pressed);
button.setAttribute('aria-pressed', pressed ? 'true' : 'false');
}
function applyFilter(key) {
if (!FILTERS[key]) return;
if (activeFilters.has(key)) activeFilters.delete(key);
else activeFilters.add(key);
FILTER_ORDER.forEach((k) => {
const el = filterChips[k];
if (el) el.classList.toggle('is-active', activeFilters.has(k));
if (el) syncToggle(el, activeFilters.has(k));
});
if (engine) engine.setFilter(currentFilterPredicate);
}
@@ -931,8 +936,7 @@ export function render({ navigate, route, chrome } = {}) {
function updateHistoryChip() {
if (!(historyChip instanceof HTMLButtonElement)) return;
historyChip.textContent = historyDepth > 0 ? `Недавние · ${historyDepth}` : 'Недавние';
historyChip.classList.toggle('is-active', historyDepth > 0);
historyChip.setAttribute('aria-pressed', historyDepth > 0 ? 'true' : 'false');
syncToggle(historyChip, historyDepth > 0);
historyChip.disabled = x2Enabled;
historyChip.setAttribute('aria-disabled', x2Enabled ? 'true' : 'false');
historyChip.title = x2Enabled
@@ -954,8 +958,7 @@ export function render({ navigate, route, chrome } = {}) {
function updateX2Chip() {
if (!(x2Chip instanceof HTMLButtonElement)) return;
x2Chip.classList.toggle('is-active', x2Enabled);
x2Chip.setAttribute('aria-pressed', x2Enabled ? 'true' : 'false');
syncToggle(x2Chip, x2Enabled);
x2Chip.title = x2Enabled ? 'Показаны друзья друзей. Нажмите, чтобы скрыть.' : 'Показать друзей друзей.';
updateHistoryChip();
}
@@ -1329,35 +1332,35 @@ export function render({ navigate, route, chrome } = {}) {
}
}
// Панель фильтров слоёв (оверлей под шапкой)
// Панель фильтров слоёв (оверлей под шапкой) – тот же блок-переключатель, что на других вкладках;
// пункты независимые, поэтому у каждого своё нажатое состояние (aria-pressed).
const filterBar = document.createElement('div');
filterBar.className = 'fg-filter-bar app-top-tabs';
// Не даём нажатию на чип «провалиться» в сцену: иначе движок делает setPointerCapture на stage,
// Не даём нажатию на переключатель «провалиться» в сцену: иначе движок делает setPointerCapture на stage,
// а захват указателя перенаправляет нативный click со сцены — и кнопка фильтра не срабатывает.
filterBar.addEventListener('pointerdown', (e) => e.stopPropagation());
const filterTabs = document.createElement('div');
filterTabs.className = 'tabs tabs--dense fg-filter-tabs';
filterBar.append(filterTabs);
const makeToggle = (label, onClick) => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'tab-btn';
button.textContent = label;
button.addEventListener('click', onClick);
filterTabs.append(button);
return button;
};
FILTER_ORDER.forEach((key) => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = `fg-filter-chip${activeFilters.has(key) ? ' is-active' : ''}`;
chip.textContent = FILTERS[key].label;
chip.addEventListener('click', () => applyFilter(key));
const chip = makeToggle(FILTERS[key].label, () => applyFilter(key));
syncToggle(chip, activeFilters.has(key));
filterChips[key] = chip;
filterBar.append(chip);
});
historyChip = document.createElement('button');
historyChip.type = 'button';
historyChip.className = 'fg-filter-chip fg-history-chip';
historyChip.addEventListener('click', cycleHistoryDepth);
filterBar.append(historyChip);
historyChip = makeToggle('', cycleHistoryDepth);
updateHistoryChip();
x2Chip = document.createElement('button');
x2Chip.type = 'button';
x2Chip.className = 'fg-filter-chip fg-x2-chip';
x2Chip.textContent = 'Друзья друзей';
x2Chip.addEventListener('click', () => { void toggleX2(); });
filterBar.append(x2Chip);
x2Chip = makeToggle('Друзья друзей', () => { void toggleX2(); });
updateX2Chip();
chrome?.setTopbar(header);