SeeMedAI / app /ui /static /reader.js
raihan116's picture
Deploy build 897cd0cbed7f-20261108223422
1955620 verified
Raw History Blame Contribute Delete
8.61 kB
/* The citation reader (/books/read): a cited passage in the reviewed document it came from, highlighted, with the
chapter around it, its figures, and the page scans.
Parameters (after # or ?): book, part (the section's ordinal), rev (the revision the answer used), start/end
(character span in that revision), fig (a figure number to show), page (a PDF page), view (text | scan),
path and pages (labels from the citation). The chat's Sources panel opens it in a frame. */
(() => {
"use strict";
const P = new URLSearchParams((location.hash || location.search).slice(1));
const book = P.get("book"), part = Number(P.get("part"));
const rev = P.get("rev") ? Number(P.get("rev")) : null;
const start = P.get("start") !== null ? Number(P.get("start")) : null;
const end = P.get("end") !== null ? Number(P.get("end")) : null;
const fig = (P.get("fig") || "").toLowerCase();
const $ = (id) => document.getElementById(id);
const esc = window.SeeMedMd.esc;
const PAGE = /^<!--\s*PDF page\s+(\d+)/i;
const TOP = /^# /;
let pages = [], page = Number(P.get("page")) || null;
async function api(url) {
const r = await fetch(url, { credentials: "same-origin" });
if (!r.ok) {
let msg = r.statusText;
try { msg = (await r.json()).error.message; } catch (e) { /* not JSON */ }
throw new Error(r.status === 401 ? "Your session has ended. Reload the chat to sign in again." : msg);
}
return r.json();
}
function lineOf(text, offset) {
let n = 0;
for (let i = 0; i < offset && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
return n;
}
/* The lines to show: the chapter (or section part before its first chapter) around the cited lines. */
function around(lines, first, last) {
let from = 0, to = lines.length;
for (let i = Math.min(first, lines.length - 1); i >= 0; i--) if (TOP.test(lines[i])) { from = i; break; }
for (let i = Math.max(last + 1, from + 1); i < lines.length; i++) if (TOP.test(lines[i])) { to = i; break; }
return [from, to];
}
function pageAt(lines, line) {
for (let i = Math.min(line, lines.length - 1); i >= 0; i--) {
const m = PAGE.exec(lines[i].trim());
if (m) return Number(m[1]);
}
return null;
}
function show(view) {
document.querySelectorAll(".seg button").forEach((b) => b.classList.toggle("on", b.dataset.view === view));
$("r-text").hidden = view !== "text";
$("r-scan").hidden = view !== "scan";
if (view === "scan") showPage(page);
}
function showPage(n) {
if (!pages.length) {
$("pg-label").textContent = "No page scans for this section";
$("pg-img").removeAttribute("src");
return;
}
const i = Math.max(0, pages.findIndex((p) => p.pdf_page === n));
const p = pages[i];
page = p.pdf_page;
const printed = p.printed_labels && p.printed_labels.length ? ` · printed ${p.printed_labels.join(", ")}` : "";
$("pg-label").textContent = `PDF page ${p.pdf_page}${printed}`;
$("pg-hint").textContent = "click to zoom";
$("pg-img").src = p.image_url;
$("pg-img").alt = `Scan of PDF page ${p.pdf_page}`;
$("pg-prev").disabled = i === 0;
$("pg-next").disabled = i === pages.length - 1;
}
function jump() {
const target = document.querySelector("#r-doc .cite-fig") || document.querySelector("#r-doc .cite");
if (target) target.scrollIntoView({ block: fig ? "center" : "start", behavior: "auto" });
}
async function load() {
if (!book || Number.isNaN(part)) throw new Error("This link does not point to a book passage.");
const base = `/v1/books/${book}/sections/${part}`;
const [info, sec, doc, figs, pageList] = await Promise.all([
api(`/v1/books/${book}`), api(base), api(`${base}/document${rev ? `?revision=${rev}` : ""}`),
api(`/v1/books/${book}/section-figures?ordinal=${part}`), api(`${base}/pages`).catch(() => []),
]);
pages = pageList;
const title = info.short_title || info.title;
document.title = `${title} · SeeMed AI`;
$("r-book").textContent = title + (info.edition ? `, ${info.edition} ed.` : "");
$("r-path").textContent = P.get("path") ? ` — ${P.get("path")}` : ` — ${sec.label}`;
if (P.get("pages")) $("r-pages").textContent = `p. ${P.get("pages")}`;
if (rev && rev !== sec.revision) {
const note = $("r-note");
note.hidden = false;
note.textContent = `Shown as cited: revision ${rev} of ${sec.label}. The section has been revised since ` +
`(now revision ${sec.revision}).`;
}
const text = doc.content_md;
const lines = text.split("\n");
let first = null, last = null;
if (start !== null && end !== null && end >= start) {
first = lineOf(text, start);
last = Math.max(first, lineOf(text, Math.max(start, end - 1)));
}
let figLine = null;
if (fig) {
const re = new RegExp(`^\\*\\*(FIGURE|TABLE)\\s+${fig.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
figLine = lines.findIndex((l) => re.test(l.trim()));
if (figLine < 0) figLine = null;
}
const anchorFirst = first ?? figLine ?? 0, anchorLast = last ?? figLine ?? 0;
const lo = Math.min(anchorFirst, figLine ?? anchorFirst), hi = Math.max(anchorLast, figLine ?? anchorLast);
const [from, to] = around(lines, lo, hi);
const images = {};
for (const f of figs) if (f.kind === "figure" && f.image_url) images[f.number.toLowerCase()] = f;
// The chapter's references, from the whole document: the shown text is rendered in pieces.
const ch = window.SeeMedMd.references(text).find((c) => from >= c.start && from < c.end);
const opts = (offset) => ({
lineOffset: offset,
chapter: ch && ch.chapter,
refs: ch && ch.refs,
figure: (n) => (images[n] ? { url: images[n].image_url, alt: images[n].alt_text || images[n].caption } : null),
});
const part_ = (a, b) => (b > a ? window.SeeMedMd.render(lines.slice(a, b).join("\n"), opts(a)) : "");
let html;
if (first !== null) {
html = part_(from, first) + `<section class="cite" aria-label="Cited passage">${part_(first, last + 1)}</section>`
+ part_(last + 1, to);
} else {
html = part_(from, to);
}
if (from > 0) html = `<p class="muted more">Earlier parts of ${esc(sec.label)} are above this chapter.</p>` + html;
$("r-doc").innerHTML = html;
if (figLine !== null) {
const el = document.querySelector(`#r-doc figure[data-figure="${CSS.escape(fig)}" i]`) ||
document.querySelector(`#r-doc [data-line="${figLine}"]`);
if (el) el.classList.add("cite-fig");
}
page = page || pageAt(lines, first ?? figLine ?? from) || (pages[0] && pages[0].pdf_page);
$("r-doc").addEventListener("click", (e) => {
const cite = e.target.closest("a.cite, a.xref"); // a reference, or a figure or table of the document
if (cite) { // a citation: show its reference (not a change of the URL's hash, which reloads the reader)
e.preventDefault();
const ref = document.getElementById(cite.getAttribute("href").slice(1));
if (ref) {
ref.scrollIntoView({ block: "center" });
ref.classList.add("flash");
setTimeout(() => ref.classList.remove("flash"), 2500);
}
return;
}
const a = e.target.closest("a[data-page]");
if (!a) return;
page = Number(a.dataset.page);
show("scan");
});
$("r-jump").hidden = first === null && figLine === null;
show(P.get("view") === "scan" ? "scan" : "text");
requestAnimationFrame(jump);
}
document.querySelectorAll(".seg button").forEach((b) => b.addEventListener("click", () => show(b.dataset.view)));
$("pg-prev").addEventListener("click", () => {
const i = pages.findIndex((p) => p.pdf_page === page);
if (i > 0) showPage(pages[i - 1].pdf_page);
});
$("pg-next").addEventListener("click", () => {
const i = pages.findIndex((p) => p.pdf_page === page);
if (i >= 0 && i < pages.length - 1) showPage(pages[i + 1].pdf_page);
});
$("r-jump").addEventListener("click", () => { show("text"); jump(); });
$("pg-img").addEventListener("click", () => $("pg-img").parentElement.classList.toggle("zoom"));
$("r-open").href = location.href;
window.addEventListener("hashchange", () => location.reload()); // another passage in the same frame
if (window.self === window.top) $("r-open").hidden = true;
load().catch((e) => {
$("r-book").textContent = "Cannot open this passage";
$("r-doc").innerHTML = `<p class="muted">${esc(e.message || String(e))}</p>`;
});
})();