File size: 1,458 Bytes
9dd41f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Only application-created source anchors become links; all other content stays text.
export function citationParts(text, count, prefix = "source") {
  const parts = [];
  let cursor = 0;
  for (const m of text.matchAll(/\[(\d+)\]/g)) {
    if (m.index > cursor) parts.push({ text: text.slice(cursor, m.index) });
    const n = Number(m[1]);
    parts.push(
      n >= 1 && n <= count
        ? { text: m[0], href: `#${prefix}-${n}` }
        : { text: m[0] },
    );
    cursor = m.index + m[0].length;
  }
  if (cursor < text.length) parts.push({ text: text.slice(cursor) });
  return parts;
}
export function renderCitations(element, text, count, prefix = "source") {
  element.replaceChildren();
  for (const part of citationParts(text, count, prefix)) {
    if (!part.href) {
      element.append(document.createTextNode(part.text));
      continue;
    }
    const a = document.createElement("a");
    a.href = part.href;
    a.className = "citation";
    a.textContent = part.text;
    a.setAttribute("aria-label", `View source ${part.text}`);
    a.addEventListener("click", (event) => {
      const target = document.getElementById(part.href.slice(1));
      if (!target) return;
      event.preventDefault();
      const detail = target.closest("details");
      if (detail) detail.open = true;
      target.scrollIntoView({ behavior: "smooth", block: "center" });
      target.focus({ preventScroll: true });
    });
    element.append(a);
  }
}