SHA256
Добавить текстовые ссылки SHiNE
This commit is contained in:
@@ -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