Spaces:
Running
Running
Download citations.mjs from iankamar/fieldnotes-rag: direct link, hf CLI and curl.
- Browser
- Download file 1.46 kB
-
https://huggingface.co/spaces/iankamar/fieldnotes-rag/resolve/main/citations.mjs
- Command line
-
hf download hf://spaces/iankamar/fieldnotes-rag/citations.mjs
-
curl -L -o citations.mjs https://huggingface.co/spaces/iankamar/fieldnotes-rag/resolve/main/citations.mjs
1.46 kB
| // 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); | |
| } | |
| } | |