SPB Git

Repository Public

linkify.ts 1.5 KB 44 lines typescript

1// Splits plain text into text and URL segments so notes can be rendered as text nodes and <a> elements.2// No HTML is ever produced or parsed: callers render segments with React.34export type Segment = { kind: "text"; value: string } | { kind: "link"; value: string; href: string };56const URL_RE = /\bhttps?:\/\/[^\s<>"'`]+/gi;7const TRAILING = /[.,;:!?)\]}»]+$/;89export function linkify(text: string): Segment[] {10  const out: Segment[] = [];11  let last = 0;12  for (const m of text.matchAll(URL_RE)) {13    let raw = m[0];14    const start = m.index;15    const trail = raw.match(TRAILING)?.[0] ?? "";16    // keep a closing parenthesis that balances one inside the URL (Wikipedia-style links)17    let keep = 0;18    if (trail) {19      const body = raw.slice(0, raw.length - trail.length);20      let open = (body.match(/\(/g)?.length ?? 0) - (body.match(/\)/g)?.length ?? 0);21      for (const ch of trail) {22        if (ch === ")" && open > 0) {23          open--;24          keep++;25        } else break;26      }27      raw = body + trail.slice(0, keep);28    }29    let href: string;30    try {31      const u = new URL(raw);32      if (u.protocol !== "http:" && u.protocol !== "https:") continue;33      href = u.href;34    } catch {35      continue;36    }37    if (start > last) out.push({ kind: "text", value: text.slice(last, start) });38    out.push({ kind: "link", value: raw, href });39    last = start + raw.length;40  }41  if (last < text.length) out.push({ kind: "text", value: text.slice(last) });42  return out;43}44
Files main
Menu

Theme