Files
vue-chat-layer/app/lib/chatText.ts
Jakub Zych 5d581539b3 feat: port the chat store, realtime client and components
- realtime.ts: the page's one Centrifuge client, setRealtimeAuth, onUserEvent for user:{me} events the chat does not handle
- chatEvents, chatFormat, chatText, chatUnread, format, media, tabs ported; copy passed in localized
- useChat over useState: channels with join and leave, DMs, member list, unread and mention counts, read marks, typing, presence, polling fallback
- ChatPanel, ChatHeader, ChatMessage, ChatDmList, ChatMemberPicker, ChatMentionPopup, ChatAvatar, ChatIcon, ChatNotices
- EN and PL strings
2026-10-31 13:52:56 +01:00

144 lines
5.8 KiB
TypeScript

/**
* Chat message text (D-12, D-13): an inline-only renderer and the mention
* helpers of the composer.
*
* Safe by construction, like markdown.ts: every character of the message is
* HTML-escaped, and the only tags produced are code, strong, em, br, links
* (through safeUrl) and mention spans. Headings, lists, quotes, images and
* raw HTML never come out. The result is the only thing ever bound with
* v-html in the chat.
*/
import type { ChatMember } from './types'
import { shortName } from './chatFormat'
import { escapeHtml, formatSpans, safeUrl } from './markdown'
const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"'
/**
* @handle as golem15.chatchannels extracts it (mention_parser.go): not after
* a word character, a dot or another @, 2 to 255 of [A-Za-z0-9_.-].
*/
const MENTION_RE = /(?<![A-Za-z0-9_.@])@([A-Za-z0-9_.-]{2,255})/g
const CODE_RE = /`([^`\n]+)`/g
const LINK_RE = /\[([^\]\n]+)\]\(([^()\s]*(?:\([^()\s]*\)[^()\s]*)*)\)/g
const URL_RE = /(?<![\w/@.])https?:\/\/[^\s<>"'`]+/gi
/**
* A handle as written, or that handle without a trailing dot or dash when
* only that one is known ("dzięki @ola_k." ends a sentence).
*/
function resolveHandle(raw: string, known: (h: string) => boolean): { handle: string; rest: string } | null {
if (known(raw)) return { handle: raw, rest: '' }
const trimmed = raw.replace(/[.-]+$/, '')
if (trimmed.length >= 2 && trimmed !== raw && known(trimmed)) return { handle: trimmed, rest: raw.slice(trimmed.length) }
return null
}
/** Trailing punctuation after a bare URL stays text; a ")" stays only when the URL opened one. */
function splitUrl(raw: string): { url: string; rest: string } {
let url = raw
for (;;) {
const last = url.at(-1)
if (!last) break
if ('.,;:!?\'"]}'.includes(last)) {
url = url.slice(0, -1)
continue
}
if (last === ')' && (url.match(/\(/g)?.length ?? 0) < (url.match(/\)/g)?.length ?? 0)) {
url = url.slice(0, -1)
continue
}
break
}
return { url, rest: raw.slice(url.length) }
}
/**
* The HTML of a message body: code spans, [label](url), bare http(s) URLs,
* mentions of chat members (by handle), bold, italic and line breaks.
* External links open in a new tab without an opener or referrer.
*/
export function renderChatText(src: string | null | undefined, members: ReadonlyMap<string, ChatMember> = new Map()): string {
if (!src) return ''
const stash: string[] = []
// A held fragment may contain earlier placeholders (a code span inside a
// link label): they are expanded as it is stored, so the final single
// pass never leaves one behind.
const expand = (html: string) => html.replace(/\u0000(\d+)\u0000/g, (_, i: string) => stash[Number(i)] ?? '')
const hold = (html: string) => `\u0000${stash.push(expand(html)) - 1}\u0000`
// eslint-disable-next-line no-control-regex
let s = src.replace(/\r\n?/g, '\n').replace(/\u0000/g, '')
// Code spans first: their content stays literal.
s = s.replace(CODE_RE, (_, code: string) => hold(`<code>${escapeHtml(code)}</code>`))
// Links, before escaping so the URL is seen as written; an unsafe target leaves the label as text.
// A URL holding a code span is not a link at all: the text stays as written.
s = s.replace(LINK_RE, (whole: string, label: string, url: string) => {
if (url.includes('\u0000')) return whole
const safe = safeUrl(url)
const text = formatSpans(escapeHtml(label))
if (!safe) return hold(text)
const attrs = /^https?:/i.test(safe) ? EXTERNAL : ''
return hold(`<a href="${escapeHtml(safe)}"${attrs}>${text}</a>`)
})
// Bare URLs.
s = s.replace(URL_RE, (raw: string) => {
if (raw.includes('\u0000')) return raw
const { url, rest } = splitUrl(raw)
const safe = safeUrl(url)
if (!safe) return raw
return hold(`<a href="${escapeHtml(safe)}"${EXTERNAL}>${escapeHtml(url)}</a>`) + rest
})
// Mentions of chat members; the name shown comes from the member list, never from the text.
s = s.replace(MENTION_RE, (whole: string, raw: string) => {
const hit = resolveHandle(raw, (h) => members.has(h))
if (!hit) return whole
const m = members.get(hit.handle)
const name = `@${shortName(m)}`
return hold(`<span class="mention" title="@${escapeHtml(hit.handle)}">${escapeHtml(name)}</span>`) + hit.rest
})
s = formatSpans(escapeHtml(s)).replace(/\n/g, '<br>')
return expand(s)
}
/** The message mentions this handle (outside code spans), as the server would count it. */
export function mentionsHandle(src: string | null | undefined, handle: string | null | undefined): boolean {
if (!src || !handle) return false
const text = src.replace(CODE_RE, ' ')
for (const m of text.matchAll(MENTION_RE)) {
if (resolveHandle(m[1], (h) => h === handle)) return true
}
return false
}
/** An @ query being typed: where the @ is and what follows it up to the caret. */
export interface MentionQuery {
start: number
query: string
}
/**
* The mention being typed at the caret: an @ at the start of the text or
* after whitespace, followed by no whitespace up to the caret. null otherwise
* ("mail@x" is not a mention).
*/
export function mentionQuery(text: string, caret: number): MentionQuery | null {
const before = text.slice(0, Math.max(0, caret))
const m = /(^|\s)@([^\s@]*)$/u.exec(before)
if (!m) return null
return { start: before.length - m[2].length - 1, query: m[2] }
}
/** Replaces text[start, end) with "@handle " and gives the caret after the space. */
export function insertMention(text: string, range: { start: number; end: number }, handle: string): { text: string; caret: number } {
const head = text.slice(0, range.start)
const tail = text.slice(range.end)
const token = `@${handle}`
if (tail.startsWith(' ')) return { text: head + token + tail, caret: head.length + token.length + 1 }
return { text: `${head}${token} ${tail}`, caret: head.length + token.length + 1 }
}