Files
vue-chat-layer/app/lib/linkEmbeds.ts
Jakub Zych 269c75b5dd feat: threads, pins, reactions, attachments, link embeds and the command picker
- threads: reply counts, ChatThreadPane with replies, live replies and thread mute
- channel pins in ChatPinsPanel; a refused pin hides the action for the session
- reactions, attachments with upload progress and bearer downloads, inline edits, the delete dialog (moderators also in channels)
- link cards with the registerEmbedRenderer registry; linkify for escaped text
- slash commands: the command picker over chatbots, dispatch with sender-only answers
- slots conversation-actions (DMs only) and sidebar-footer
- chat-tokens.css and chat-base.css, EN and PL copy, README
2026-10-31 14:04:54 +01:00

118 lines
3.8 KiB
TypeScript

// Links in chat text and the link-embed renderer registry.
//
// The chat has no unfurl backend: a message with an http(s) URL shows a
// card with the URL's host and path (ChatLinkEmbed), fetched from nowhere.
// A host renders its own links (its entity pages, for example) by
// registering a component for the URLs it recognises:
//
// registerEmbedRenderer((url) => url.hostname === location.hostname && url.pathname.startsWith('/blog/'), BlogCard)
//
// The component gets the URL as the `url` prop (a URL object). The first
// registered renderer that matches wins; ChatLinkEmbed is the fallback.
import type { Component } from 'vue'
import { escapeHtml } from './markdown'
const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"'
/** A bare http(s) URL as the chat text renderer finds it. */
const URL_RE = /(?<![\w/@.])https?:\/\/[^\s<>"'`]+/gi
/** 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 URL when it parses as http(s), else null. */
function parseHttp(raw: string): URL | null {
try {
const u = new URL(raw)
return u.protocol === 'http:' || u.protocol === 'https:' ? u : null
} catch {
return null
}
}
function unescapeHtml(s: string): string {
return s.replace(/&(amp|lt|gt|quot|#39);/g, (_, e: string) => ({ amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'" })[e] ?? '')
}
/**
* linkify turns the bare http(s) URLs of already-escaped text into links
* that open in a new tab without an opener or referrer. Nothing else is
* produced, so the result stays as safe as its input.
*/
export function linkify(escaped: string): string {
return escaped.replace(/https?:\/\/[^\s<>"'`]+/gi, (raw: string) => {
const plain = unescapeHtml(raw)
const { url, rest } = splitUrl(plain)
const parsed = parseHttp(url)
if (!parsed) return raw
return `<a href="${escapeHtml(url)}"${EXTERNAL}>${escapeHtml(url)}</a>${escapeHtml(rest)}`
})
}
/** The distinct http(s) URLs of a message text (outside code spans), in order. */
export function messageUrls(text: string | null | undefined): URL[] {
if (!text) return []
const plain = text.replace(/`[^`\n]+`/g, ' ')
const out: URL[] = []
const seen = new Set<string>()
// [label](url) links count too: their URL is matched like a bare one.
for (const m of plain.matchAll(URL_RE)) {
const { url } = splitUrl(m[0])
const parsed = parseHttp(url)
if (!parsed || seen.has(parsed.href)) continue
seen.add(parsed.href)
out.push(parsed)
}
return out
}
export type EmbedMatcher = (url: URL) => boolean
interface Renderer {
match: EmbedMatcher
component: Component
}
const renderers: Renderer[] = []
/**
* registerEmbedRenderer renders the URLs `match` accepts with `component`
* (props: url). Returns the function that removes the registration.
*/
export function registerEmbedRenderer(match: EmbedMatcher, component: Component): () => void {
const entry: Renderer = { match, component }
renderers.push(entry)
return () => {
const i = renderers.indexOf(entry)
if (i >= 0) renderers.splice(i, 1)
}
}
/** The registered renderer of a URL, or null for the generic card. */
export function embedRendererFor(url: URL): Component | null {
for (const r of renderers) {
try {
if (r.match(url)) return r.component
} catch {
/* a failing matcher matches nothing */
}
}
return null
}