// 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); } }