SHA256
Добавить текстовые ссылки SHiNE
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { mountPublicChannelSidebar } from '../services/public-channel-sidebar.js';
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
softHaptic,
|
||||
} from '../services/channels-ux.js';
|
||||
import { getPreviousTrackedPath, parseRouteFromPath } from '../router.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { renderAvatar, renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { openChannelEditor } from '../components/channel-editor.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createEmojiPicker } from '../components/emoji-picker.js';
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from '../services/attachment-format.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { extractLoginFromBlockchainName, makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { parsePublicationOrdinal, publicationAtOrdinal, ordinalForPublication } from '../services/channel-message-ordinals.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-thread-view', title: 'Обсуждение', hideToolbar: true, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
const MSG_SUBTYPE_TEXT_POST = 10;
|
||||
@@ -159,16 +160,17 @@ function buildAbsoluteRouteUrl(routePath = '') {
|
||||
|
||||
function parseThreadSelector(route) {
|
||||
const params = route?.params || {};
|
||||
if (params.ownerBlockchainName && params.channelName && params.messageBlockNumber) {
|
||||
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: toSafeInt(params.messageBlockNumber),
|
||||
blockHash: normalizeRouteHash(params.messageBlockHash),
|
||||
blockNumber: null,
|
||||
blockHash: '',
|
||||
},
|
||||
channel: {
|
||||
ownerBlockchainName: '',
|
||||
@@ -323,13 +325,20 @@ async function resolveChannelDisplayNameFromServer(channelSelector) {
|
||||
}
|
||||
}
|
||||
|
||||
function buildThreadRouteFromTarget(target, selector) {
|
||||
function buildThreadRouteFromTarget(target, selector, focusOrdinal = null) {
|
||||
if (!target) return '';
|
||||
const ownerBch = String(selector?.short?.ownerBlockchainName || selector?.channel?.ownerBlockchainName || '').trim();
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -649,9 +658,12 @@ function openEditMessageModal({ initialText = '', allowEmptyText = false, onSave
|
||||
});
|
||||
}
|
||||
|
||||
function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
function renderNodeCard(node, heading, handlers, localNumber, { focusPost = false, channelOwnerBlockchainName = '' } = {}) {
|
||||
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 : [];
|
||||
@@ -724,6 +736,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
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;
|
||||
headRow.append(authorTile);
|
||||
const typeMeta = getChannelMessageTypeMeta(node?.msgSubType);
|
||||
if (typeMeta) {
|
||||
@@ -781,7 +794,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
}
|
||||
const body = document.createElement('p');
|
||||
body.className = 'channel-message-body';
|
||||
body.textContent = parsedText.text;
|
||||
appendShineMessageLinks(body, parsedText.text, { navigate: handlers?.navigate });
|
||||
card.append(body);
|
||||
}
|
||||
|
||||
@@ -803,7 +816,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
|
||||
const likeButton = document.createElement('button');
|
||||
likeButton.type = 'button';
|
||||
likeButton.className = 'ui-button channel-action-item thread-like-btn';
|
||||
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>
|
||||
@@ -845,6 +858,11 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
replyButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
animatePress(event.currentTarget);
|
||||
if (!state.session.isAuthorized) {
|
||||
state.authReturnHash = window.location.pathname || '/channels';
|
||||
handlers.navigate('login-view');
|
||||
return;
|
||||
}
|
||||
openReplyModal({
|
||||
onSubmit: async (textValue) => handlers.onReply(target, textValue),
|
||||
isActive: handlers.isActive,
|
||||
@@ -861,7 +879,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
|
||||
const shareButton = document.createElement('button');
|
||||
shareButton.type = 'button';
|
||||
shareButton.className = 'ui-button channel-action-item thread-share-btn';
|
||||
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>
|
||||
@@ -877,11 +895,22 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
// Точка возврата: docs/Future_Features/2026-05-24_1140_репосты_в_каналах_и_тредах.md
|
||||
const discussionButton = document.createElement('button');
|
||||
discussionButton.type = 'button';
|
||||
discussionButton.className = 'ui-button channel-action-item';
|
||||
discussionButton.innerHTML = `<span class="channel-action-icon">${iconHtml('message')}</span>${Number(replies) > 0 ? `<span>${replies}</span>` : ''}`;
|
||||
discussionButton.setAttribute('aria-label', `Открыть обсуждение, ответов: ${replies}`);
|
||||
discussionButton.addEventListener('click', () => handlers.onOpenThread(target));
|
||||
actions.append(likeButton, discussionButton, shareButton, replyButton);
|
||||
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) card.closest('.channels-screen')?.querySelector('.thread-block--replies')?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
else handlers.onOpenThread(target);
|
||||
});
|
||||
// Тот же вид и порядок кнопок, что в ленте канала.
|
||||
actions.append(likeButton, shareButton, discussionButton);
|
||||
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
|
||||
if (repostTarget) {
|
||||
const originalButton = document.createElement('button');
|
||||
originalButton.type = 'button';
|
||||
@@ -959,6 +988,15 @@ function renderNodeCard(node, heading, handlers, localNumber) {
|
||||
}
|
||||
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: versions }) });
|
||||
attachMessageMenu(card, headRow, menuItems);
|
||||
if (isOwnerPost) {
|
||||
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();
|
||||
@@ -986,13 +1024,13 @@ function nodeKey(node) {
|
||||
}
|
||||
|
||||
// Исходная запись сверху: две строки, «Развернуть» — только если текст правда обрезан
|
||||
function renderThreadContext(node, { onOpenPost }) {
|
||||
function renderThreadContext(node, { onOpenPost, onNavigate }) {
|
||||
const parsed = parseMessageAttachments(resolveNodeText(node));
|
||||
const box = document.createElement('section');
|
||||
box.className = 'thread-context';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'thread-context__text';
|
||||
text.textContent = parsed.text || (parsed.attachments.length ? 'Запись с вложением' : '');
|
||||
appendShineMessageLinks(text, parsed.text || (parsed.attachments.length ? 'Запись с вложением' : ''), { navigate: onNavigate });
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'thread-context__meta';
|
||||
const time = document.createElement('span');
|
||||
@@ -1089,7 +1127,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers }) {
|
||||
}
|
||||
const text = document.createElement('p');
|
||||
text.className = 'thread-comment__text';
|
||||
text.textContent = parsed.text;
|
||||
appendShineMessageLinks(text, parsed.text, { navigate: handlers?.navigate });
|
||||
item.append(text);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
@@ -1238,7 +1276,7 @@ function createThreadComposer({ draftKey, isAuthorized, onLogin, onSend }) {
|
||||
const login = document.createElement('button');
|
||||
login.type = 'button';
|
||||
login.className = 'primary-btn channel-main-action';
|
||||
login.textContent = 'Войти и ответить';
|
||||
login.textContent = 'Войти / зарегистрироваться';
|
||||
login.addEventListener('click', onLogin);
|
||||
root.append(login);
|
||||
return { root, setReplyTo() {} };
|
||||
@@ -1339,8 +1377,11 @@ function createThreadComposer({ draftKey, isAuthorized, onLogin, onSend }) {
|
||||
export function render({ navigate, route, chrome }) {
|
||||
let selector = parseThreadSelector(route);
|
||||
const channelDisplayName = resolveChannelDisplayName(selector?.channel);
|
||||
const routeKey = `${selector?.message?.blockchainName || ''}:${selector?.message?.blockNumber || ''}:${selector?.message?.blockHash || ''}`;
|
||||
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';
|
||||
@@ -1371,7 +1412,7 @@ export function render({ navigate, route, chrome }) {
|
||||
const header = createTopBar({
|
||||
center: threadHeaderButton,
|
||||
className: 'topbar--identity',
|
||||
back: { label: '<', onClick: () => navigate(resolveThreadPreviousInChannels(selector, activeResolvedChannelLabel)) },
|
||||
back: state.session.isAuthorized ? { label: '<', onClick: () => navigate(resolveThreadPreviousInChannels(selector, activeResolvedChannelLabel)) } : null,
|
||||
actions: [{
|
||||
label: '⋯',
|
||||
ariaLabel: 'Меню обсуждения',
|
||||
@@ -1416,6 +1457,11 @@ export function render({ navigate, route, chrome }) {
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onToggleLike: async (target, action) => {
|
||||
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;
|
||||
@@ -1511,7 +1557,7 @@ export function render({ navigate, route, chrome }) {
|
||||
},
|
||||
onShare: async (target) => {
|
||||
try {
|
||||
const routePath = buildThreadRouteFromTarget(target, selector);
|
||||
const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal);
|
||||
if (!routePath) throw new Error('Не удалось подготовить ссылку на обсуждение.');
|
||||
const result = await shareOrCopyLink({
|
||||
title: 'Сияние · Обсуждение',
|
||||
@@ -1527,7 +1573,7 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
},
|
||||
onOpenThread: (target) => {
|
||||
const routePath = buildThreadRouteFromTarget(target, selector);
|
||||
const routePath = buildThreadRouteFromTarget(target, selector, focusOrdinal);
|
||||
if (!routePath) {
|
||||
showStatus('Не удалось определить ссылку на обсуждение.');
|
||||
return;
|
||||
@@ -1600,10 +1646,13 @@ export function render({ navigate, route, chrome }) {
|
||||
if (!hadContent) clearContent();
|
||||
showStatus('');
|
||||
selector = parseThreadSelector(route);
|
||||
focusOrdinal = selector?.publicationOrdinal || null;
|
||||
activeResolvedChannelLabel = resolveChannelDisplayName(selector?.channel);
|
||||
threadHeaderChannel.textContent = '…';
|
||||
threadHeaderButton.disabled = true;
|
||||
threadHeaderButton.onclick = null;
|
||||
threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove();
|
||||
threadHeaderTitle.textContent = 'Обсуждение';
|
||||
|
||||
if (!selector) {
|
||||
const invalid = document.createElement('div');
|
||||
@@ -1617,6 +1666,7 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
try {
|
||||
let resolvedMessage = selector.message;
|
||||
let cachedChannelPayload = null;
|
||||
if (selector.short?.ownerBlockchainName && selector.short?.channelName) {
|
||||
const ownFeed = state.session.isAuthorized ? await authService.listSubscriptionsFeed(state.session.login, 1000) : {};
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
@@ -1681,7 +1731,7 @@ export function render({ navigate, route, chrome }) {
|
||||
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) || !Number.isFinite(resolvedMessage?.blockNumber)) {
|
||||
if (!ownerBch || !Number.isFinite(rootNo) || !focusOrdinal) {
|
||||
throw new Error('Канал или сообщение не найдено.');
|
||||
}
|
||||
selector.channel = {
|
||||
@@ -1690,11 +1740,22 @@ export function render({ navigate, route, chrome }) {
|
||||
channelRootBlockHash: rootHash,
|
||||
};
|
||||
|
||||
// One-based channel publication ordinal -> original POST block reference.
|
||||
// Editions are deliberately excluded by GetChannelMessages on the server.
|
||||
cachedChannelPayload = await authService.getChannelMessages(selector.channel, null, 'asc', state.session.isAuthorized ? state.session.login : '');
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
const message = publicationAtOrdinal(cachedChannelPayload?.messages || [], focusOrdinal);
|
||||
const blockNumber = Number(message?.messageRef?.blockNumber);
|
||||
const blockHash = normalizeMessageHash(message?.messageRef?.blockHash);
|
||||
if (!Number.isSafeInteger(blockNumber) || blockNumber < 0 || !blockHash) {
|
||||
throw new Error(`Публикация №${focusOrdinal} не найдена в канале.`);
|
||||
}
|
||||
resolvedMessage = {
|
||||
blockchainName: ownerBch,
|
||||
blockNumber: resolvedMessage.blockNumber,
|
||||
blockHash: normalizeMessageHash(resolvedMessage?.blockHash),
|
||||
blockchainName: String(message?.authorBlockchainName || ownerBch),
|
||||
blockNumber,
|
||||
blockHash,
|
||||
};
|
||||
selector.message = { ...resolvedMessage };
|
||||
}
|
||||
|
||||
const payload = await authService.getMessageThread(resolvedMessage, 20, 2, 50, state.session.login);
|
||||
@@ -1729,8 +1790,51 @@ export function render({ navigate, route, chrome }) {
|
||||
activeResolvedChannelLabel = resolvedChannelLabel;
|
||||
const fallbackChannel = String(selector?.channel?.ownerBlockchainName || '').trim() || 'неизвестно';
|
||||
const resolvedChannelTitle = resolvedChannelLabel || fallbackChannel;
|
||||
const channelOwner = extractLoginFromBlockchainName(selector?.channel?.ownerBlockchainName || focus?.channelInfo?.ownerBlockchainName || selector?.short?.ownerBlockchainName || '');
|
||||
const channelSlug = String(selector?.short?.channelName || (resolvedChannelLabel.includes('/') ? resolvedChannelLabel.split('/').slice(1).join('/') : '')).trim();
|
||||
let title = channelTitleByLabel.get(resolvedChannelTitle) || channelSlug || resolvedChannelTitle;
|
||||
let avatarAr = '';
|
||||
let avatarSha256 = '';
|
||||
// Метаданные канала доступны гостям: заголовок и аватар берём из того же API, что у ленты.
|
||||
if (selector?.channel?.ownerBlockchainName && selector?.channel?.channelRootBlockNumber != null && Number.isFinite(Number(selector.channel.channelRootBlockNumber))) {
|
||||
try {
|
||||
const channelPayload = cachedChannelPayload || await authService.getChannelMessages(selector.channel, null, 'asc', state.session.isAuthorized ? state.session.login : '');
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
if (!focusOrdinal && focus) {
|
||||
focusOrdinal = ordinalForPublication(channelPayload?.messages || [], {
|
||||
blockchainName: String(focus?.authorBlockchainName || selector.channel.ownerBlockchainName),
|
||||
blockNumber: focus?.messageRef?.blockNumber,
|
||||
blockHash: focus?.messageRef?.blockHash,
|
||||
});
|
||||
}
|
||||
const meta = channelPayload?.channel || {};
|
||||
title = String(meta.displayName || meta.channelName || title).trim();
|
||||
avatarAr = String(meta.avaAr || '').trim();
|
||||
avatarSha256 = String(meta.avaSha256 || '').trim().toLowerCase();
|
||||
if (!selector.short && meta.channelName) selector.short = { ownerBlockchainName: selector.channel.ownerBlockchainName, channelName: String(meta.channelName) };
|
||||
} catch {
|
||||
// Обсуждение должно открываться даже при временной недоступности метаданных канала.
|
||||
}
|
||||
}
|
||||
const shortName = String(selector?.short?.channelName || channelSlug).trim();
|
||||
const visibleOwner = channelOwner || extractLoginFromBlockchainName(selector?.short?.ownerBlockchainName || '');
|
||||
const number = focusOrdinal || (selector?.short ? null : Number(selector?.message?.blockNumber));
|
||||
const headerNumber = Number.isSafeInteger(number) && number > 0 ? ` · №${number}` : '';
|
||||
if (threadHeaderButton) {
|
||||
threadHeaderChannel.textContent = channelTitleByLabel.get(resolvedChannelTitle) || resolvedChannelTitle;
|
||||
threadHeaderTitle.textContent = `${title}${headerNumber}`;
|
||||
threadHeaderChannel.textContent = `${visibleOwner ? `@${visibleOwner}` : ''}${visibleOwner && shortName ? ' / ' : ''}${shortName}`;
|
||||
threadHeaderButton.querySelector('.channel-thread-header-avatar')?.remove();
|
||||
const avatar = renderAvatar({
|
||||
initials: (title[0] || 'К').toUpperCase(),
|
||||
avatar: (avatarAr || avatarSha256) ? { ar: avatarAr, sha256Hex: avatarSha256 } : null,
|
||||
authorLogin: visibleOwner,
|
||||
size: 'xl',
|
||||
className: 'channel-profile-avatar channel-thread-header-avatar',
|
||||
title,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
avatar.style.setProperty('--channel-avatar-size', '40px');
|
||||
threadHeaderButton.prepend(avatar);
|
||||
threadHeaderButton.title = 'Открыть канал';
|
||||
threadHeaderButton.disabled = false;
|
||||
threadHeaderButton.onclick = (event) => {
|
||||
@@ -1743,13 +1847,6 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
|
||||
clearContent();
|
||||
const channelOwner = extractLoginFromBlockchainName(selector?.channel?.ownerBlockchainName || focus?.channelInfo?.ownerBlockchainName || '');
|
||||
if (!state.session.isAuthorized) mountPublicChannelSidebar(screen, {
|
||||
owner: channelOwner,
|
||||
channel: resolvedChannelTitle,
|
||||
subscribers: payload?.channel?.subscribersCount ?? payload?.focus?.channelInfo?.subscribersCount ?? null,
|
||||
navigate,
|
||||
});
|
||||
const openPost = () => {
|
||||
const routeToChannel = buildChannelRouteFromThread(selector, resolvedChannelLabel);
|
||||
if (routeToChannel) navigate(routeToChannel);
|
||||
@@ -1769,7 +1866,7 @@ export function render({ navigate, route, chrome }) {
|
||||
title: 'Поделиться записью',
|
||||
kicker: `${resolvedChannelTitle} · запись`,
|
||||
text: parseMessageAttachments(resolveNodeText(focus)).text,
|
||||
url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector)),
|
||||
url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector, focusOrdinal)),
|
||||
});
|
||||
} },
|
||||
];
|
||||
@@ -1778,13 +1875,13 @@ export function render({ navigate, route, chrome }) {
|
||||
if (ancestors.length) {
|
||||
const ancestorsWrap = document.createElement('div');
|
||||
ancestorsWrap.className = 'thread-block thread-block--ancestors';
|
||||
ancestors.forEach((node) => ancestorsWrap.append(renderThreadContext(node, { onOpenPost: openPost })));
|
||||
ancestors.forEach((node) => ancestorsWrap.append(renderThreadContext(node, { onOpenPost: openPost, onNavigate: navigate })));
|
||||
screen.append(ancestorsWrap);
|
||||
}
|
||||
if (focus) {
|
||||
const focusWrap = document.createElement('div');
|
||||
focusWrap.className = 'thread-block thread-block--focus';
|
||||
focusWrap.append(renderThreadContext(focus, { onOpenPost: openPost }));
|
||||
focusWrap.append(renderNodeCard(focus, '', handlers, focusOrdinal || Number(selector?.message?.blockNumber ?? 0), { focusPost: true, channelOwnerBlockchainName: selector?.channel?.ownerBlockchainName || '' }));
|
||||
screen.append(focusWrap);
|
||||
}
|
||||
|
||||
@@ -1829,7 +1926,7 @@ export function render({ navigate, route, chrome }) {
|
||||
title: 'Поделиться комментарием',
|
||||
kicker: `${node.authorLogin} · комментарий`,
|
||||
text: parseMessageAttachments(resolveNodeText(node)).text,
|
||||
url: `${buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector))}#comment-${node?.messageRef?.blockNumber ?? ''}`,
|
||||
url: `${buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector, focusOrdinal))}#comment-${node?.messageRef?.blockNumber ?? ''}`,
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mountPublicChannelSidebar } from '../services/public-channel-sidebar.js';
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
makeShineChannelDonateRoute,
|
||||
} from '../services/shine-routes.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', hideToolbar: true, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
const CHANNEL_TYPE_STORIES = 0;
|
||||
@@ -238,14 +239,16 @@ function buildSelectorFromRoute(route, channelId) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadRoute(messageRef, selector) {
|
||||
function buildThreadRoute(post, selector) {
|
||||
const messageRef = post?.messageRef;
|
||||
if (!messageRef || !selector) return '';
|
||||
const ownerLogin = extractLoginFromBlockchainName(selector.ownerBlockchainName);
|
||||
return makeShineMessageRoute({
|
||||
ownerLogin,
|
||||
messageBlockchainName: messageRef.blockchainName,
|
||||
messageBlockNumber: messageRef.blockNumber,
|
||||
channelName: selector.channelName,
|
||||
messageOrdinal: selector.publicOrdinalUrlsAllowed ? post.localNumber : '',
|
||||
channelName: selector.publicOrdinalUrlsAllowed ? selector.channelName : '',
|
||||
channelOwnerBlockchainName: selector.ownerBlockchainName,
|
||||
});
|
||||
}
|
||||
@@ -1487,6 +1490,9 @@ async function loadFromApi(route, channelId) {
|
||||
const ownerLogin = String(payload.channel?.ownerLogin || '').trim();
|
||||
const channelName = String(payload.channel?.channelName || '').trim();
|
||||
const channelTypeCode = Number(payload.channel?.channelTypeCode ?? 1);
|
||||
// Channel-publication URLs are only unambiguous for public channels, not merged private chats.
|
||||
selector.channelName = String(payload.channel?.channelName || selector.channelName || '').trim();
|
||||
selector.publicOrdinalUrlsAllowed = channelTypeCode !== CHANNEL_TYPE_STORIES && channelTypeCode !== CHANNEL_TYPE_PERSONAL;
|
||||
if (channelTypeCode === CHANNEL_TYPE_STORIES) {
|
||||
throw new Error('Канал stories скрыт из пользовательского интерфейса.');
|
||||
}
|
||||
@@ -1520,16 +1526,9 @@ async function loadFromApi(route, channelId) {
|
||||
}
|
||||
}
|
||||
|
||||
const posts = mergedMessages
|
||||
.map((message, index) => mapApiMessageToPost(message, selector, index + 1))
|
||||
.sort((a, b) => {
|
||||
const byTime = Number(a?.timestampMs || 0) - Number(b?.timestampMs || 0);
|
||||
if (byTime !== 0) return byTime;
|
||||
const aNum = Number(a?.messageRef?.blockNumber || 0);
|
||||
const bNum = Number(b?.messageRef?.blockNumber || 0);
|
||||
return aNum - bNum;
|
||||
})
|
||||
.map((post, index) => ({ ...post, localNumber: index + 1 }));
|
||||
const posts = sortedChannelPublications(
|
||||
mergedMessages.map((message, index) => mapApiMessageToPost(message, selector, index + 1)),
|
||||
).map((post, index) => ({ ...post, localNumber: index + 1 }));
|
||||
const isOwnChannel = ownerLogin.toLowerCase() === currentSessionLogin.toLowerCase();
|
||||
const followedRows = Array.isArray(state.channelsFeed?.followedChannels) ? state.channelsFeed.followedChannels : [];
|
||||
const isSubscribed = isAuthorized && followedRows.some((row) => (
|
||||
@@ -2028,7 +2027,7 @@ function renderPostCard(post, {
|
||||
}
|
||||
const body = document.createElement('p');
|
||||
body.className = 'channel-message-body';
|
||||
body.textContent = parsedBody.text;
|
||||
appendShineMessageLinks(body, parsedBody.text, { navigate, viewMode: 'feed' });
|
||||
card.append(body);
|
||||
}
|
||||
|
||||
@@ -2093,7 +2092,7 @@ function renderPostCard(post, {
|
||||
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${post.repliesCount || 0}`);
|
||||
discussionButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
const route = buildThreadRoute(post.messageRef, selector);
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (route) navigate(route);
|
||||
});
|
||||
|
||||
@@ -2134,17 +2133,17 @@ function renderPostCard(post, {
|
||||
shareButton.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
animatePress(event.currentTarget);
|
||||
const route = buildThreadRoute(post.messageRef, selector);
|
||||
const route = buildThreadRoute(post, selector);
|
||||
await onShare(route);
|
||||
});
|
||||
|
||||
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа
|
||||
actions.append(likeButton, shareButton, discussionButton);
|
||||
if (post.messageRef?.blockNumber != null) {
|
||||
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
|
||||
const streamRoute = makeShineChannelStreamRoute({
|
||||
ownerBlockchainName: selector?.ownerBlockchainName,
|
||||
channelName: selector?.channelName || '',
|
||||
messageBlockNumber: post.messageRef.blockNumber,
|
||||
messageOrdinal: post.localNumber,
|
||||
});
|
||||
if (streamRoute) menuItems.unshift({ label: 'Ссылка на сообщение в ленте', iconHtml: iconHtml('share'), action: () => onShare(streamRoute) });
|
||||
}
|
||||
@@ -2264,7 +2263,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
const actionButton = document.createElement('button');
|
||||
actionButton.type = 'button';
|
||||
actionButton.className = 'primary-btn channel-main-action';
|
||||
actionButton.innerHTML = `${iconHtml('bell')}<span>${state.session.isAuthorized ? 'Подписаться' : 'Войти и подписаться'}</span>`;
|
||||
actionButton.innerHTML = `${iconHtml('bell')}<span>${state.session.isAuthorized ? 'Подписаться' : 'Войти / зарегистрироваться'}</span>`;
|
||||
|
||||
const addMessageButton = document.createElement('button');
|
||||
addMessageButton.type = 'button';
|
||||
@@ -2380,13 +2379,12 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
screen.append(feed);
|
||||
}
|
||||
|
||||
const requestedBlock = String(handlers.scrollToMessageBlockNumber || '').trim();
|
||||
if (/^[0-9]+$/.test(requestedBlock)) {
|
||||
const card = [...screen.querySelectorAll('.channel-message-card[data-message-key]')].find((el) => {
|
||||
const parts = String(el.dataset.messageKey || '').split(':');
|
||||
return parts.length >= 3 && parts[parts.length - 2] === requestedBlock;
|
||||
});
|
||||
const requestedOrdinal = Number(handlers.scrollToMessageOrdinal);
|
||||
if (Number.isSafeInteger(requestedOrdinal) && requestedOrdinal > 0) {
|
||||
const card = [...screen.querySelectorAll('.channel-message-card[data-local-number]')]
|
||||
.find((el) => Number(el.dataset.localNumber) === requestedOrdinal);
|
||||
if (card) pendingScrollByRoute.set(routeKey, card.dataset.messageKey);
|
||||
else showStatus(`Публикация №${requestedOrdinal} не найдена в канале.`);
|
||||
}
|
||||
const hasPendingScrollTarget = pendingScrollByRoute.has(routeKey);
|
||||
const restorePosition = handlers.restorePosition;
|
||||
@@ -2462,7 +2460,7 @@ function renderSkeleton(screen) {
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const channelId = route.params.channelId || '';
|
||||
const scrollToMessageBlockNumber = route.params.scrollToMessageBlockNumber || '';
|
||||
const scrollToMessageOrdinal = route.params.scrollToMessageOrdinal || '';
|
||||
const routeSelector = buildSelectorFromRoute(route, channelId);
|
||||
const routeKey = `${routeSelector?.ownerBlockchainName || ''}:${routeSelector?.channelRootBlockNumber || ''}:${routeSelector?.channelRootBlockHash || ''}`;
|
||||
|
||||
@@ -2507,7 +2505,7 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
const header = createTopBar({
|
||||
center: channelHeaderButton,
|
||||
back: { onClick: () => navigate('channels-list') },
|
||||
back: state.session.isAuthorized ? { onClick: () => navigate('channels-list') } : null,
|
||||
className: 'channel-view-topbar topbar--identity',
|
||||
actions: [
|
||||
{
|
||||
@@ -2958,9 +2956,9 @@ export function render({ navigate, route, chrome }) {
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Короткий адрес канала и число подписчиков; владелец и полный путь — в «О канале»
|
||||
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const subs = Number(apiData?.channel?.subscribersCount || 0);
|
||||
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
@@ -2969,7 +2967,7 @@ export function render({ navigate, route, chrome }) {
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : [slug ? `@${slug}` : '', subs ? String(subs) : ''].filter(Boolean).join(' · ');
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
@@ -3005,7 +3003,7 @@ export function render({ navigate, route, chrome }) {
|
||||
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
scrollToMessageBlockNumber,
|
||||
scrollToMessageOrdinal,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
@@ -3096,10 +3094,6 @@ export function render({ navigate, route, chrome }) {
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
if (!state.session.isAuthorized && !apiData?.isDiary) mountPublicChannelSidebar(screen, {
|
||||
owner: apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName),
|
||||
channel: titleLabel, subscribers: apiData?.channel?.subscribersCount, navigate,
|
||||
});
|
||||
} catch (error) {
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
skeleton?.remove();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
@@ -819,7 +820,7 @@ function scrollToLatestMessage(list) {
|
||||
window.setTimeout(apply, 260);
|
||||
}
|
||||
|
||||
function renderMessageText(textNode, messageText) {
|
||||
function renderMessageText(textNode, messageText, chatNavigate) {
|
||||
const text = String(messageText || '');
|
||||
const emoji = text.trim();
|
||||
if (text === emoji && hasTwemojiAsset(emoji)) {
|
||||
@@ -827,9 +828,16 @@ function renderMessageText(textNode, messageText) {
|
||||
textNode.append(createTwemojiAsset(emoji, { className: 'chat-twemoji' }));
|
||||
return;
|
||||
}
|
||||
if (appendTwemojiText(textNode, text, { className: 'chat-twemoji chat-twemoji--inline' })) {
|
||||
textNode.classList.add('bubble-text--twemoji-inline');
|
||||
}
|
||||
appendShineMessageLinks(textNode, text, {
|
||||
navigate: chatNavigate,
|
||||
appendText: (root, part) => {
|
||||
const fragment = document.createDocumentFragment();
|
||||
if (appendTwemojiText(fragment, part, { className: 'chat-twemoji chat-twemoji--inline' })) {
|
||||
textNode.classList.add('bubble-text--twemoji-inline');
|
||||
}
|
||||
root.append(fragment);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function isTwemojiOnlyMessage(messageText) {
|
||||
@@ -1062,6 +1070,7 @@ function renderLog(
|
||||
chatId,
|
||||
{
|
||||
onOpenActions,
|
||||
navigate,
|
||||
markAsRead = true,
|
||||
scrollMode = 'latest',
|
||||
showUnreadSeparator = true,
|
||||
@@ -1165,7 +1174,7 @@ function renderLog(
|
||||
|
||||
const textNode = document.createElement('div');
|
||||
textNode.className = 'bubble-text';
|
||||
renderMessageText(textNode, parsedText.displayText || '');
|
||||
renderMessageText(textNode, parsedText.displayText || '', navigate);
|
||||
if (parsedText.replyRef) {
|
||||
const replyTarget = findMessageByBaseKey(messages, parsedText.replyRef.baseKey);
|
||||
if (replyTarget) {
|
||||
@@ -1348,6 +1357,7 @@ export function render({ navigate, route, chrome }) {
|
||||
const renderChatLog = ({ scrollMode = 'latest', markAsRead = true } = {}) => {
|
||||
renderLog(log, chatId, {
|
||||
onOpenActions: handleOpenActions,
|
||||
navigate,
|
||||
markAsRead,
|
||||
scrollMode,
|
||||
showUnreadSeparator: unreadSeparatorVisible,
|
||||
@@ -2627,6 +2637,7 @@ export function render({ navigate, route, chrome }) {
|
||||
chrome?.setComposer(form);
|
||||
renderLog(log, chatId, {
|
||||
onOpenActions: handleOpenActions,
|
||||
navigate,
|
||||
markAsRead: false,
|
||||
scrollMode: hasUnreadIncoming ? 'unread' : 'latest',
|
||||
showUnreadSeparator: unreadSeparatorVisible,
|
||||
|
||||
@@ -150,18 +150,18 @@ export function parseRouteFromPath(pathname = '') {
|
||||
const ownerBlockchainName = shineLogin;
|
||||
const channelName = decodePart(segments[baseOffset] || '');
|
||||
const streamMode = decodePart(segments[baseOffset + 1] || '').toLowerCase() === 's';
|
||||
const streamBlockNumber = streamMode ? decodePart(segments[baseOffset + 2] || '') : '';
|
||||
if (ownerBlockchainName && channelName && streamMode && /^[0-9]+$/.test(streamBlockNumber) && segments.length === baseOffset + 3) {
|
||||
return { pageId: 'channel-view', params: { ownerBlockchainName, channelName, channelId: '', scrollToMessageBlockNumber: streamBlockNumber } };
|
||||
const streamOrdinal = streamMode ? decodePart(segments[baseOffset + 2] || '') : '';
|
||||
if (ownerBlockchainName && channelName && streamMode && /^[1-9][0-9]*$/.test(streamOrdinal) && segments.length === baseOffset + 3) {
|
||||
return { pageId: 'channel-view', params: { ownerBlockchainName, channelName, channelId: '', scrollToMessageOrdinal: streamOrdinal } };
|
||||
}
|
||||
const messageBlockNumber = segments[baseOffset + 1] || '';
|
||||
if (ownerBlockchainName && channelName && messageBlockNumber) {
|
||||
const messageOrdinal = segments[baseOffset + 1] || '';
|
||||
if (ownerBlockchainName && channelName && /^[1-9][0-9]*$/.test(messageOrdinal) && segments.length === baseOffset + 2) {
|
||||
return {
|
||||
pageId: 'channel-thread-view',
|
||||
params: {
|
||||
ownerBlockchainName,
|
||||
channelName,
|
||||
messageBlockNumber,
|
||||
messageOrdinal,
|
||||
messageBlockHash: '',
|
||||
messageBlockchainName: '',
|
||||
channelOwnerBlockchainName: ownerBlockchainName,
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Public channel URLs use one-based publication positions, not blockchain block numbers.
|
||||
// Order must match the channel feed: message time, then original block number.
|
||||
function messageTimestamp(message) {
|
||||
const value = Number(message?.timestampMs ?? message?.createdAtMs ?? 0);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
function blockNumber(message) {
|
||||
const value = Number(message?.messageRef?.blockNumber);
|
||||
return Number.isSafeInteger(value) ? value : 0;
|
||||
}
|
||||
|
||||
export function sortedChannelPublications(messages = []) {
|
||||
return [...messages].sort((a, b) => {
|
||||
const byTime = messageTimestamp(a) - messageTimestamp(b);
|
||||
return byTime !== 0 ? byTime : blockNumber(a) - blockNumber(b);
|
||||
});
|
||||
}
|
||||
|
||||
export function parsePublicationOrdinal(value) {
|
||||
const text = String(value ?? '').trim();
|
||||
if (!/^[1-9][0-9]*$/.test(text)) return null;
|
||||
const number = Number(text);
|
||||
return Number.isSafeInteger(number) ? number : null;
|
||||
}
|
||||
|
||||
export function publicationAtOrdinal(messages, ordinal) {
|
||||
const value = parsePublicationOrdinal(ordinal);
|
||||
if (!value) return null;
|
||||
return sortedChannelPublications(messages)[value - 1] || null;
|
||||
}
|
||||
|
||||
export function ordinalForPublication(messages, reference) {
|
||||
if (!reference) return null;
|
||||
const number = Number(reference.blockNumber);
|
||||
const hash = String(reference.blockHash || '').trim().toLowerCase();
|
||||
const owner = String(reference.blockchainName || '').trim().toLowerCase();
|
||||
const i = sortedChannelPublications(messages).findIndex((item) => {
|
||||
const ref = item?.messageRef;
|
||||
if (Number(ref?.blockNumber) !== number) return false;
|
||||
if (hash && String(ref?.blockHash || '').trim().toLowerCase() !== hash) return false;
|
||||
if (owner && String(item?.authorBlockchainName || '').trim().toLowerCase() !== owner) return false;
|
||||
return true;
|
||||
});
|
||||
return i < 0 ? null : i + 1;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Ссылки — часть обычного текста; в блокчейне не нужен новый формат.
|
||||
// Внутренние SHiNE-адреса открываются на текущем сервере доступа.
|
||||
const LINK_PATTERN = /(?:https?:\/\/|www\.|\/?SHiNE\/)[^\s<>"'`]+/gi;
|
||||
const TRAILING_PUNCTUATION = /[.,!?;:»”。,!?;:]$/u;
|
||||
const POSITIVE_ORDINAL = /^[1-9][0-9]*$/;
|
||||
|
||||
function trimLinkEnd(source) {
|
||||
let end = source.length;
|
||||
while (end > 0) {
|
||||
const last = source[end - 1];
|
||||
if (TRAILING_PUNCTUATION.test(last)) {
|
||||
end -= 1;
|
||||
continue;
|
||||
}
|
||||
// Закрывающую скобку считаем частью URL лишь при наличии парной открывающей.
|
||||
const opening = last === ')' ? '(' : last === ']' ? '[' : null;
|
||||
if (opening && source.slice(0, end).split(last).length > source.slice(0, end).split(opening).length) {
|
||||
end -= 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return source.slice(0, end);
|
||||
}
|
||||
|
||||
// Для /SHiNE/owner/channel/N сохраняем контекст, /s/N всегда принудительно ведёт в ленту.
|
||||
export function resolveShineTextLink(raw, { viewMode = 'thread' } = {}) {
|
||||
const value = String(raw || '');
|
||||
if (/^(?:https?:\/\/|www\.)/i.test(value)) {
|
||||
try {
|
||||
const url = new URL(/^www\./i.test(value) ? `https://${value}` : value);
|
||||
if ((url.protocol !== 'https:' && url.protocol !== 'http:') || !url.hostname) return null;
|
||||
if (/^www\./i.test(value) && !/^www\.[^./]+\.[^/]+/i.test(value)) return null;
|
||||
return { type: 'external', href: url.href };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const route = value.replace(/^\//, '');
|
||||
const parts = route.split('/');
|
||||
if (parts.length < 2 || !/^shine$/i.test(parts[0]) || parts.slice(1).some((part) => !part || /[?#]/.test(part))) return null;
|
||||
const cleanRoute = `SHiNE/${parts.slice(1).join('/')}`;
|
||||
let destination = cleanRoute;
|
||||
if (viewMode === 'feed' && parts.length === 4 && POSITIVE_ORDINAL.test(parts[3])
|
||||
&& Number.isSafeInteger(Number(parts[3]))) {
|
||||
destination = `SHiNE/${parts[1]}/${parts[2]}/s/${parts[3]}`;
|
||||
}
|
||||
return { type: 'internal', route: destination, href: `/${destination}` };
|
||||
}
|
||||
|
||||
// Чистая функция для UI и тестов: сохраняет все символы, кроме ссылок ничего не преобразует.
|
||||
export function tokenizeShineMessageLinks(text, options = {}) {
|
||||
const source = String(text ?? '');
|
||||
const tokens = [];
|
||||
let cursor = 0;
|
||||
LINK_PATTERN.lastIndex = 0;
|
||||
for (const found of source.matchAll(LINK_PATTERN)) {
|
||||
const start = found.index;
|
||||
// Не выделяем подстроки чужих путей, доменов или идентификаторов.
|
||||
if (start > 0 && /[\p{L}\p{N}_/@.\-]/u.test(source[start - 1])) continue;
|
||||
const candidate = trimLinkEnd(found[0]);
|
||||
const target = candidate && resolveShineTextLink(candidate, options);
|
||||
if (!target) continue;
|
||||
if (start > cursor) tokens.push({ type: 'text', value: source.slice(cursor, start) });
|
||||
tokens.push({ ...target, type: target.type, value: candidate });
|
||||
cursor = start + candidate.length;
|
||||
}
|
||||
if (cursor < source.length) tokens.push({ type: 'text', value: source.slice(cursor) });
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function appendShineMessageLinks(root, text, { navigate, viewMode = 'thread', appendText } = {}) {
|
||||
for (const token of tokenizeShineMessageLinks(text, { viewMode })) {
|
||||
if (token.type === 'text') {
|
||||
if (typeof appendText === 'function') appendText(root, token.value);
|
||||
else root.append(document.createTextNode(token.value));
|
||||
continue;
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
link.className = 'shine-inline-link';
|
||||
link.textContent = token.value;
|
||||
link.href = token.href;
|
||||
if (token.type === 'external') {
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
}
|
||||
link.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
if (token.type === 'internal' && typeof navigate === 'function'
|
||||
&& event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) {
|
||||
event.preventDefault();
|
||||
navigate(token.route);
|
||||
}
|
||||
});
|
||||
root.append(link);
|
||||
}
|
||||
}
|
||||
@@ -76,20 +76,22 @@ export function makeShineChannelShortRoute({ ownerLogin = '', ownerBlockchainNam
|
||||
return `${SHINE_ROUTE_SEGMENT}/${encodeRoutePart(cleanOwnerLogin)}/${encodeRoutePart(chName)}`;
|
||||
}
|
||||
|
||||
export function makeShineChannelStreamRoute({ ownerLogin = '', ownerBlockchainName = '', channelName = '', messageBlockNumber = '' }) {
|
||||
export function makeShineChannelStreamRoute({ ownerLogin = '', ownerBlockchainName = '', channelName = '', messageOrdinal = '' }) {
|
||||
const base = makeShineChannelShortRoute({ ownerLogin, ownerBlockchainName, channelName });
|
||||
const no = String(messageBlockNumber || '').trim();
|
||||
return base && /^[0-9]+$/.test(no) ? `${base}/s/${no}` : '';
|
||||
const no = String(messageOrdinal ?? '').trim();
|
||||
return base && /^[1-9][0-9]*$/.test(no) && Number.isSafeInteger(Number(no)) ? `${base}/s/${no}` : '';
|
||||
}
|
||||
|
||||
export function makeShineMessageRoute({ ownerLogin = '', messageBlockchainName = '', messageBlockNumber = '', channelName = '', channelOwnerBlockchainName = '' }) {
|
||||
export function makeShineMessageRoute({ ownerLogin = '', messageBlockchainName = '', messageBlockNumber = '', messageOrdinal = '', channelName = '', channelOwnerBlockchainName = '' }) {
|
||||
const msgBch = String(messageBlockchainName || '').trim();
|
||||
const msgNo = String(messageBlockNumber || '').trim();
|
||||
if (!msgBch || !msgNo) return '';
|
||||
if (channelName) {
|
||||
const ordinal = String(messageOrdinal ?? '').trim();
|
||||
if (channelName && /^[1-9][0-9]*$/.test(ordinal) && Number.isSafeInteger(Number(ordinal))) {
|
||||
const base = makeShineChannelShortRoute({ ownerLogin, ownerBlockchainName: channelOwnerBlockchainName || msgBch, channelName });
|
||||
if (base) return `${base}/${encodeRoutePart(msgNo)}`;
|
||||
if (base) return `${base}/${encodeRoutePart(ordinal)}`;
|
||||
}
|
||||
// Technical URLs remain valid for non-channel messages (replies, notifications, old links).
|
||||
if (!msgBch || !/^[0-9]+$/.test(msgNo)) return '';
|
||||
return `${SHINE_ROUTE_SEGMENT}/${encodeRoutePart(msgBch)}/${encodeRoutePart(msgNo)}`;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user