// Ссылки — часть обычного текста; в блокчейне не нужен новый формат. // Внутренние 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); } }