Files
stack/src/llm/web/pdf.html
2026-11-14 11:12:38 -05:00

766 lines
37 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Library Document</title>
<link rel="icon" type="image/png" sizes="32x32" href="//dashboard.fhirworx.io/fav32.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Source+Serif+4:wght@400;600&family=JetBrains+Mono:wght@500&display=swap">
<style>
:root {
--background: #F7F5F0; --foreground: #1A1A18; --card: #FAFAF7;
--primary: #1C2B3A; --primary-fg: #F7F5F0; --secondary: #EDEBE6;
--muted-fg: #6B6B68; --border: #D4D0C8; --accent: #2E3D8F;
--destructive: #C0392B; --highlight: rgba(255, 214, 0, .45);
--font-display: "Playfair Display", Georgia, serif;
--font-body: "Source Serif 4", Georgia, serif;
--font-mono: "JetBrains Mono", "Fira Code", monospace;
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0; display: flex; flex-direction: column; overflow: hidden;
background: var(--background); color: var(--foreground);
font-family: var(--font-body); font-size: 15px;
}
header {
flex: 0 0 auto; background: var(--primary); color: var(--primary-fg);
border-bottom: 3px solid var(--foreground); padding: 10px 16px;
display: flex; align-items: center; gap: 12px; flex-wrap: wrap; min-width: 0;
}
header h1 {
font-family: var(--font-display); font-weight: 700; font-size: 16px; margin: 0;
white-space: nowrap;
}
header .title {
flex: 1 1 240px; min-width: 0; font-size: 13px; opacity: .85;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
header a.nav {
font-family: var(--font-mono); font-size: 11px; text-transform: uppercase;
letter-spacing: .08em; color: var(--primary-fg); text-decoration: underline dotted;
}
.toolbar {
flex: 0 0 auto; background: var(--secondary); border-bottom: 1px solid var(--border);
padding: 6px 12px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
font-family: var(--font-mono); font-size: 12px;
}
.toolbar .group { display: flex; align-items: center; gap: 4px; }
.toolbar button, .toolbar select, .toolbar input {
font-family: var(--font-mono); font-size: 12px; height: 28px;
border: 1px solid var(--border); border-radius: 3px; background: var(--card); color: var(--foreground);
}
.toolbar button { padding: 0 10px; cursor: pointer; min-width: 30px; }
.toolbar button:hover:not(:disabled) { background: #E2DFD8; }
.toolbar button:disabled { opacity: .4; cursor: default; }
.toolbar button.primary { background: var(--primary); color: var(--primary-fg); border-color: var(--primary); }
.toolbar input#pageno { width: 58px; text-align: right; padding: 0 6px; }
.toolbar input#find { width: 200px; padding: 0 8px; font-family: var(--font-body); font-size: 13px; }
.toolbar .count, .toolbar .zoom { color: var(--muted-fg); min-width: 44px; text-align: center; }
.toolbar select#file { max-width: 260px; text-overflow: ellipsis; }
.toolbar a.dl { color: var(--accent); text-decoration: underline dotted; font-size: 11px; }
.toolbar .spacer { flex: 1 1 auto; }
#progress { height: 3px; background: transparent; flex: 0 0 auto; }
#progress > div { height: 100%; width: 0; background: var(--accent); transition: width .2s ease; }
#viewer {
flex: 1 1 auto; overflow: auto; padding: 18px 12px 40px;
display: flex; flex-direction: column; align-items: center; gap: 14px;
-webkit-overflow-scrolling: touch; overscroll-behavior: contain;
}
.page {
position: relative; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.25);
flex: 0 0 auto; max-width: 100%;
}
.page canvas { display: block; width: 100%; height: 100%; }
.page .num {
position: absolute; right: 6px; bottom: 4px; font-family: var(--font-mono); font-size: 10px;
color: var(--muted-fg); background: rgba(255,255,255,.7); padding: 1px 4px; border-radius: 2px;
pointer-events: none;
}
.page .textLayer {
position: absolute; inset: 0; overflow: hidden; line-height: 1; opacity: 1;
text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0;
}
.page .textLayer span, .page .textLayer br {
color: transparent; position: absolute; white-space: pre; cursor: text; transform-origin: 0 0;
}
.page .textLayer ::selection { background: rgba(46, 61, 143, .35); }
.page .textLayer .endOfContent { display: block; position: absolute; inset: 100% 0 0; z-index: -1; cursor: default; user-select: none; }
.page .textLayer mark { background: var(--highlight); color: transparent; border-radius: 2px; }
.page .textLayer mark.current { background: rgba(255, 140, 0, .55); }
.page.pending { min-height: 300px; }
.page .placeholder {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
color: var(--muted-fg); font-family: var(--font-mono); font-size: 12px;
}
/* docx-preview output: each section is a page; zoom scales the wrapper */
#docxwrap { transform-origin: top center; }
#docxwrap .docx-wrapper { background: transparent; padding: 0; display: flex; flex-direction: column; align-items: center; gap: 14px; }
#docxwrap section.docx { box-shadow: 0 1px 3px rgba(0,0,0,.25); margin: 0 !important; background: #fff; overflow: hidden; }
#docxwrap mark, #textdoc mark { background: var(--highlight); border-radius: 2px; color: inherit; }
#docxwrap mark.current, #textdoc mark.current { background: rgba(255, 140, 0, .55); }
#textdoc {
background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.25); padding: 28px 32px; width: 100%; max-width: 860px;
font-family: var(--font-mono); font-size: 13px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; margin: 0;
}
.notice {
margin: 40px auto; max-width: 560px; padding: 16px 20px; border: 1px solid var(--border);
background: var(--card); border-radius: 3px; color: var(--muted-fg); font-style: italic;
}
.notice.err { color: var(--destructive); border-color: var(--destructive); font-style: normal; }
.notice a { color: var(--accent); }
header label.proto {
font-family: var(--font-mono); font-size: 11px; text-transform: uppercase;
letter-spacing: .06em; display: flex; align-items: center; gap: 6px;
}
header select#protocol {
font-family: var(--font-mono); font-size: 12px; height: 26px; max-width: 200px;
background: var(--card); color: var(--foreground); border: 1px solid var(--border); border-radius: 3px;
}
#stage { flex: 1 1 auto; display: flex; min-height: 0; min-width: 0; }
#focuspanel {
flex: 0 0 300px; overflow: auto; border-left: 1px solid var(--border);
background: var(--card); padding: 12px 12px 24px; font-size: 13.5px;
}
#focuspanel h2 {
font-family: var(--font-display); font-size: 16px; margin: 0 0 8px;
}
#focuspanel .focus-empty, #focuspanel .focus-status { color: var(--muted-fg); margin: 0 0 8px; }
#focuspanel .focus-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
#focuspanel li { border-top: 1px solid var(--border); padding-top: 8px; }
#focuspanel li.current { background: var(--secondary); margin: 0 -8px; padding: 8px; }
#focuspanel button, #focuspanel textarea, #focuspanel input {
font-family: var(--font-body); font-size: 13px; color: var(--foreground);
}
#focuspanel button.jump {
display: block; width: 100%; text-align: left; background: none; border: 0; padding: 0;
cursor: pointer; font-family: var(--font-body);
}
#focuspanel button.jump:hover { text-decoration: underline; }
#focuspanel textarea, #focuspanel input {
width: 100%; margin-top: 6px; border: 1px solid var(--border); border-radius: 3px;
background: var(--background); padding: 4px 6px; font-family: var(--font-body);
}
#focuspanel .focus-actions { display: flex; gap: 6px; margin-top: 6px; }
#focuspanel .focus-actions button, #focuspanel .focus-link-form button {
font-family: var(--font-mono); font-size: 11px; height: 26px; padding: 0 8px; cursor: pointer;
border: 1px solid var(--border); border-radius: 3px; background: var(--secondary);
}
#focuspanel .badge {
display: inline-block; margin-left: 6px; font-family: var(--font-mono); font-size: 10px;
text-transform: uppercase; letter-spacing: .06em; border: 1px solid var(--destructive);
color: var(--destructive); border-radius: 3px; padding: 0 4px;
}
#focusbar {
position: fixed; z-index: 20; display: flex; flex-wrap: wrap; gap: 4px; max-width: min(440px, 92vw);
background: var(--card); border: 1px solid var(--foreground); border-radius: 3px; padding: 6px;
box-shadow: 0 2px 8px rgba(0, 0, 0, .18);
}
#focusbar[hidden] { display: none; }
#focusbar button {
font-family: var(--font-body); font-size: 13px; padding: 4px 8px; cursor: pointer;
border: 1px solid var(--border); border-radius: 3px; background: var(--secondary); color: var(--foreground);
}
#focusbar button:hover { background: #E2DFD8; }
#focusbar kbd {
font-family: var(--font-mono); font-size: 10px; margin-right: 6px; padding: 0 4px;
border: 1px solid var(--border); border-radius: 2px; background: var(--card);
}
.hl {
position: absolute; pointer-events: none; border-radius: 2px; z-index: 2;
background: rgba(46, 61, 143, .28);
}
mark.focus-hl { background: rgba(46, 61, 143, .28); color: inherit; border-radius: 2px; }
.hl.lab-support, mark.focus-hl.lab-support { background: rgba(30, 122, 58, .32); }
.hl.lab-support-with-modifications, mark.focus-hl.lab-support-with-modifications { background: rgba(180, 120, 20, .34); }
.hl.lab-do-not-support, mark.focus-hl.lab-do-not-support { background: rgba(192, 57, 43, .32); }
.hl.lab-finalized-as-proposed, mark.focus-hl.lab-finalized-as-proposed { background: rgba(30, 122, 58, .32); }
.hl.lab-finalized-with-modifications, mark.focus-hl.lab-finalized-with-modifications { background: rgba(180, 120, 20, .34); }
.hl.lab-other, mark.focus-hl.lab-other { background: rgba(107, 107, 104, .35); }
@media (max-width: 640px) {
header { padding: 8px 10px; gap: 8px; }
header .title { flex-basis: 100%; }
.toolbar { padding: 6px 8px; gap: 6px; }
.toolbar input#find { width: 130px; }
.toolbar select#file { max-width: 160px; }
#viewer { padding: 10px 6px 30px; gap: 10px; }
#stage { flex-direction: column; }
#focuspanel { flex: 0 0 38%; border-left: 0; border-top: 1px solid var(--border); }
}
</style>
</head>
<body>
<header>
<h1>Library Document</h1>
<label class="proto" for="protocol">Protocol
<select id="protocol" title="Review protocol"></select>
</label>
<span class="title" id="title"></span>
<a class="nav" href="/">Chat</a>
<a class="nav" href="/ui/search">Search</a>
</header>
<div class="toolbar">
<div class="group">
<select id="file" title="Which PDF on file for this item" hidden></select>
</div>
<div class="group">
<button id="prev" title="Previous page (←)">‹</button>
<input id="pageno" type="number" min="1" value="1" title="Page">
<span class="count" id="count">/ –</span>
<button id="next" title="Next page (→)">›</button>
</div>
<div class="group">
<button id="zoomout" title="Zoom out (−)">−</button>
<span class="zoom" id="zoomlabel">fit</span>
<button id="zoomin" title="Zoom in (+)">+</button>
<button id="fit" title="Fit to width (0)">fit</button>
</div>
<div class="group">
<input id="find" type="search" placeholder="find in document" title="Find (Enter: next, Shift+Enter: previous)">
<span class="count" id="findcount"></span>
</div>
<span class="spacer"></span>
<a class="dl" id="download" href="#" download>download</a>
</div>
<div id="progress"><div id="bar"></div></div>
<div id="stage">
<div id="viewer" tabindex="0"></div>
<aside id="focuspanel" aria-label="Annotations"></aside>
</div>
<div id="focusbar" role="toolbar" aria-label="Apply a highlight label" hidden></div>
<script type="module">
// Everything below reads only this page's own URL and the JSON from
// /pdf/<key>; nothing from those ever reaches innerHTML.
const $ = id => document.getElementById(id);
const viewer = $('viewer'), bar = $('bar');
const params = new URLSearchParams(location.search);
const key = location.pathname.split('/').filter(Boolean).pop();
const wantFile = params.get('file') || '';
const wantPage = Math.max(1, parseInt(params.get('page') || '1', 10) || 1);
const wantQuery = (params.get('q') || '').trim();
function notice(text, err, downloadUrl) {
const d = document.createElement('div');
d.className = 'notice' + (err ? ' err' : '');
d.appendChild(document.createTextNode(text));
if (downloadUrl) {
d.appendChild(document.createTextNode(' '));
const a = document.createElement('a'); a.href = downloadUrl; a.textContent = 'Download the file instead.';
d.appendChild(a);
}
viewer.replaceChildren(d);
}
let pdfjs = null;
try {
pdfjs = await import('/ui/vendor/pdf.min.mjs');
pdfjs.GlobalWorkerOptions.workerSrc = '/ui/vendor/pdf.worker.min.mjs';
} catch (e) {
pdfjs = null;
}
async function show() {
// ── file list ──
let files = [];
try {
const r = await fetch('/pdf/' + encodeURIComponent(key));
if (!r.ok) throw new Error('lookup failed (' + r.status + ')');
const d = await r.json();
files = d.files || [];
$('title').textContent = d.title || key;
document.title = (d.title ? d.title + ' — ' : '') + 'Library Document';
} catch (e) {
notice('Could not look up the item: ' + e.message, true);
throw e;
}
if (!files.length) {
notice('No PDF is on file for this item.', false);
throw new Error('no files');
}
const sel = $('file');
for (const f of files) {
const o = document.createElement('option');
o.value = f.name; o.textContent = f.name + ' (' + Math.round(f.size / 1024) + ' KB' + (f.renderable === false ? ', download only' : '') + ')';
sel.appendChild(o);
}
if (files.length > 1) sel.hidden = false;
const current = files.find(f => f.name === wantFile) || files.find(f => f.renderable) || files[0];
sel.value = current.name;
const rawUrl = '/pdf/' + encodeURIComponent(key) + '/file?name=' + encodeURIComponent(current.name);
const fileUrl = current.url || rawUrl; // a Word file's LibreOffice rendering when the image has the converter
$('download').href = current.download_url || rawUrl; // the original bytes
if (current.converted) $('download').textContent = 'download original';
sel.addEventListener('change', () => {
const p = new URLSearchParams(location.search);
p.set('file', sel.value); p.delete('page');
location.search = p.toString();
});
const renderer = current.renderer || (current.renderable === false ? null : 'pdf');
if (!renderer) {
notice('"' + current.name + '" (' + (current.media_type || 'file') + ') has no in-page renderer — legacy Word .doc files open in Word or LibreOffice.', false, fileUrl);
throw new Error('not renderable');
}
// ── DOM-based find (docx and text panes): wrap matches in <mark>,
// step with Enter / Shift+Enter, the current match scrolls into view ──
function domFind(root) {
const state = { term: '', marks: [], idx: -1 };
const norm = s => s.replace(/\s+/g, ' ').toLowerCase();
function clear() {
for (const m of state.marks) { const t = document.createTextNode(m.textContent); m.replaceWith(t); }
state.marks = []; state.idx = -1; root.normalize();
}
function run(term) {
clear();
state.term = norm(term).trim();
$('findcount').textContent = '';
if (!state.term) return;
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const nodes = [];
for (let n = walker.nextNode(); n; n = walker.nextNode()) if (n.nodeValue.trim()) nodes.push(n);
for (const n of nodes) {
const text = n.nodeValue, low = norm(text);
let at = low.indexOf(state.term);
if (at === -1) continue;
const frag = document.createDocumentFragment();
let last = 0;
while (at !== -1) {
frag.appendChild(document.createTextNode(text.slice(last, at)));
const m = document.createElement('mark'); m.textContent = text.slice(at, at + state.term.length);
frag.appendChild(m); state.marks.push(m);
last = at + state.term.length; at = low.indexOf(state.term, last);
}
frag.appendChild(document.createTextNode(text.slice(last)));
n.parentNode.replaceChild(frag, n);
}
$('findcount').textContent = state.marks.length ? '0/' + state.marks.length : 'no matches';
if (state.marks.length) step(1);
}
function step(dir) {
if (!state.marks.length) return;
if (state.idx >= 0) state.marks[state.idx].classList.remove('current');
state.idx = (state.idx + dir + state.marks.length) % state.marks.length;
const m = state.marks[state.idx];
m.classList.add('current');
m.scrollIntoView({ block: 'center', behavior: 'smooth' });
$('findcount').textContent = (state.idx + 1) + '/' + state.marks.length;
}
let t = null;
$('find').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => run($('find').value), 250); });
$('find').addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); if (norm($('find').value).trim() !== state.term) run($('find').value); else step(e.shiftKey ? -1 : 1); }
if (e.key === 'Escape') { $('find').value = ''; run(''); viewer.focus(); }
});
return { run, step };
}
async function mountFocusPane(goToPage) {
try {
const { mountFocus } = await import('/ui/focus.js');
await mountFocus({ key, file: current.name, kind: renderer, viewer, goToPage });
} catch (e) {
console.warn('focus:', e && e.message || e);
}
}
function seedFind(find) {
if (!wantQuery) return;
const probe = wantQuery.split(/\s+/).slice(0, 6).join(' ');
$('find').value = probe;
find.run(probe);
}
// Page navigation over a list of page elements (docx sections, or the
// single text pane): prev/next/input, hash tracking, arrow keys.
function domPages(getPages) {
let cur = 1;
const count = () => getPages().length;
function goTo(n, smooth) {
const els = getPages();
n = Math.min(els.length, Math.max(1, n | 0));
if (!els.length) return;
viewer.scrollTo({ top: els[n - 1].offsetTop - 12, behavior: smooth ? 'smooth' : 'auto' });
cur = n; $('pageno').value = String(n); history.replaceState(null, '', '#page=' + n);
}
function update() {
const els = getPages();
const top = viewer.scrollTop + viewer.clientHeight / 3;
let best = 1, bestDist = Infinity;
els.forEach((el, i) => { const d = Math.abs(el.offsetTop - top); if (d < bestDist) { bestDist = d; best = i + 1; } });
if (best !== cur) { cur = best; $('pageno').value = String(best); history.replaceState(null, '', '#page=' + best); }
}
$('count').textContent = '/ ' + count();
$('pageno').max = String(count());
$('prev').addEventListener('click', () => goTo(cur - 1, true));
$('next').addEventListener('click', () => goTo(cur + 1, true));
$('pageno').addEventListener('change', () => goTo(parseInt($('pageno').value, 10) || 1, false));
viewer.addEventListener('scroll', () => requestAnimationFrame(update), { passive: true });
document.addEventListener('keydown', e => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
if (e.key === 'ArrowLeft' || e.key === 'PageUp') { e.preventDefault(); goTo(cur - 1, true); }
else if (e.key === 'ArrowRight' || e.key === 'PageDown') { e.preventDefault(); goTo(cur + 1, true); }
else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') { e.preventDefault(); $('find').focus(); $('find').select(); }
});
return { goTo, update, refresh() { $('count').textContent = '/ ' + count(); $('pageno').max = String(count()); } };
}
function loadScript(src) {
return new Promise((resolve, reject) => {
const sc = document.createElement('script');
sc.src = src; sc.onload = resolve; sc.onerror = () => reject(new Error('failed to load ' + src));
document.head.appendChild(sc);
});
}
// ── plain text ──
if (renderer === 'text') {
let text;
try {
const r = await fetch(fileUrl);
if (!r.ok) throw new Error('fetch failed (' + r.status + ')');
text = await r.text();
} catch (e) {
notice('Could not load the file: ' + e.message, true, fileUrl);
throw e;
}
const pre = document.createElement('pre'); pre.id = 'textdoc'; pre.textContent = text;
viewer.replaceChildren(pre);
for (const id of ['zoomout', 'zoomin', 'fit', 'zoomlabel']) $(id).hidden = true;
const nav = domPages(() => [pre]);
const find = domFind(pre);
nav.goTo(1, false);
seedFind(find);
await mountFocusPane(n => nav.goTo(n, false));
return;
}
// ── Word (.docx) via docx-preview: sections become pages; zoom scales
// the wrapper to the viewer width (fit) or a factor ──
if (renderer === 'docx') {
let blob;
try {
await loadScript('/ui/vendor/jszip.min.js');
await loadScript('/ui/vendor/docx-preview.min.js');
const r = await fetch(fileUrl);
if (!r.ok) throw new Error('fetch failed (' + r.status + ')');
blob = await r.blob();
} catch (e) {
notice('The Word renderer could not be loaded: ' + e.message, true, fileUrl);
throw e;
}
const wrap = document.createElement('div'); wrap.id = 'docxwrap';
viewer.replaceChildren(wrap);
try {
await window.docx.renderAsync(blob, wrap, null, {
className: 'docx', inWrapper: true, breakPages: true, ignoreLastRenderedPageBreak: false,
renderHeaders: true, renderFooters: true, renderFootnotes: true, renderEndnotes: true,
useBase64URL: true, experimental: true, trimXmlDeclaration: true,
});
} catch (e) {
notice('This Word file could not be rendered: ' + (e && e.message || e), true, fileUrl);
throw e;
}
const pagesOf = () => Array.from(wrap.querySelectorAll('section.docx'));
if (!pagesOf().length) { notice('The Word file rendered no pages.', true, fileUrl); throw new Error('no pages'); }
// fit / zoom: scale the wrapper; CSS zoom keeps layout metrics honest,
// transform is the fallback for engines without it
let fit = true, factor = 1;
const useZoom = CSS.supports('zoom', '1');
function applyZoom() {
const page = pagesOf()[0];
const natural = page.offsetWidth / (useZoom ? 1 : 1);
const cs = getComputedStyle(viewer);
const avail = viewer.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
const base = useZoom ? page.getBoundingClientRect().width / (parseFloat(wrap.style.zoom) || 1) : natural;
const s = fit ? Math.min(1.6, avail / base) : (avail / base) * factor;
if (useZoom) wrap.style.zoom = String(s);
else { wrap.style.transform = 'scale(' + s + ')'; wrap.style.width = base + 'px'; wrap.style.height = (wrap.scrollHeight * s) + 'px'; }
$('zoomlabel').textContent = fit ? 'fit' : Math.round(factor * 100) + '%';
}
$('zoomin').addEventListener('click', () => { factor = Math.min(4, (fit ? 1 : factor) * 1.25); fit = false; applyZoom(); });
$('zoomout').addEventListener('click', () => { factor = Math.max(0.3, (fit ? 1 : factor) / 1.25); fit = false; applyZoom(); });
$('fit').addEventListener('click', () => { fit = true; factor = 1; applyZoom(); });
document.addEventListener('keydown', e => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
if (e.key === '+' || e.key === '=') { e.preventDefault(); $('zoomin').click(); }
else if (e.key === '-') { e.preventDefault(); $('zoomout').click(); }
else if (e.key === '0') { e.preventDefault(); $('fit').click(); }
});
let rt2 = null;
new ResizeObserver(() => { clearTimeout(rt2); rt2 = setTimeout(applyZoom, 120); }).observe(viewer);
applyZoom();
const nav = domPages(pagesOf);
const find = domFind(wrap);
const hashPage = parseInt((location.hash.match(/page=(\d+)/) || [])[1] || '0', 10);
nav.goTo(hashPage || wantPage, false);
seedFind(find);
await mountFocusPane(n => nav.goTo(n, false));
return;
}
if (!pdfjs) {
notice('The in-page renderer could not be loaded.', true, fileUrl);
throw new Error('pdfjs missing');
}
// ── document ──
let doc;
try {
const task = pdfjs.getDocument({ url: fileUrl, rangeChunkSize: 1 << 18, disableAutoFetch: false });
task.onProgress = ({ loaded, total }) => { if (total) bar.style.width = Math.min(100, 100 * loaded / total) + '%'; };
doc = await task.promise;
bar.style.width = '0';
} catch (e) {
notice('This file could not be rendered as a PDF: ' + (e && e.message || e), true, fileUrl);
throw e;
}
const total = doc.numPages;
$('count').textContent = '/ ' + total;
$('pageno').max = String(total);
// ── layout: one placeholder per page, sized from page 1's ratio,
// rendered lazily as they scroll into view, re-rendered on resize ──
const pages = []; // {el, canvas, textLayer, num, viewportW, rendered, task, text}
let scale = 1; // CSS px per PDF unit at the current zoom
let fitMode = true; // fit to width until the user zooms
let zoomFactor = 1;
const first = await doc.getPage(1);
const baseW = first.getViewport({ scale: 1 }).width;
const baseH = first.getViewport({ scale: 1 }).height;
function availableWidth() {
const cs = getComputedStyle(viewer);
return viewer.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
}
function computeScale() {
const fit = Math.max(0.2, availableWidth() / baseW);
scale = fitMode ? fit : fit * zoomFactor;
$('zoomlabel').textContent = fitMode ? 'fit' : Math.round(zoomFactor * 100) + '%';
}
for (let n = 1; n <= total; n++) {
const el = document.createElement('div');
el.className = 'page pending'; el.dataset.page = String(n);
const ph = document.createElement('div'); ph.className = 'placeholder'; ph.textContent = 'page ' + n;
const num = document.createElement('span'); num.className = 'num'; num.textContent = String(n);
el.appendChild(ph); el.appendChild(num);
viewer.appendChild(el);
pages.push({ el, num: n, canvas: null, textLayer: null, rendered: 0, task: null, text: null, page: null });
}
function sizeAll() {
computeScale();
for (const p of pages) {
const pg = p.page;
const w = Math.floor((pg ? pg.getViewport({ scale: 1 }).width : baseW) * scale);
const h = Math.floor((pg ? pg.getViewport({ scale: 1 }).height : baseH) * scale);
p.el.style.width = w + 'px'; p.el.style.height = h + 'px';
}
}
async function render(p) {
if (p.rendered === scale) return;
if (p.task) { try { p.task.cancel(); } catch (e) {} p.task = null; }
if (!p.page) p.page = await doc.getPage(p.num);
const vp = p.page.getViewport({ scale });
const dpr = Math.min(window.devicePixelRatio || 1, 3);
let canvas = p.canvas;
if (!canvas) {
canvas = document.createElement('canvas'); p.canvas = canvas;
p.el.classList.remove('pending');
p.el.replaceChildren(canvas);
const num = document.createElement('span'); num.className = 'num'; num.textContent = String(p.num);
p.el.appendChild(num);
}
canvas.width = Math.floor(vp.width * dpr); canvas.height = Math.floor(vp.height * dpr);
p.el.style.width = Math.floor(vp.width) + 'px'; p.el.style.height = Math.floor(vp.height) + 'px';
const ctx = canvas.getContext('2d', { alpha: false });
const task = p.page.render({ canvasContext: ctx, viewport: vp, transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : null });
p.task = task;
const mine = scale;
try { await task.promise; } catch (e) { if (e && e.name === 'RenderingCancelledException') return; throw e; }
if (p.task !== task) return;
p.task = null; p.rendered = mine;
await paintText(p, vp);
}
async function paintText(p, vp) {
const unit = p.page.getViewport({ scale: 1 });
p.el.dataset.pw = String(unit.width);
p.el.dataset.ph = String(unit.height);
if (p.textLayer) p.textLayer.remove();
const layer = document.createElement('div');
layer.className = 'textLayer';
p.el.appendChild(layer); p.textLayer = layer;
try {
const content = await p.page.getTextContent();
p.text = content;
const tl = new pdfjs.TextLayer({ textContentSource: content, container: layer, viewport: vp });
await tl.render();
const end = document.createElement('div'); end.className = 'endOfContent'; layer.appendChild(end);
} catch (e) {
// no text layer (scanned page) — the canvas alone is fine
}
if (findState.term) highlight(p);
p.el.dispatchEvent(new CustomEvent('focus-page', { bubbles: true }));
}
// Lazy rendering: pages within ~1.5 screens of the viewport render,
// everything else stays a placeholder (and drops its canvas if far off).
const io = new IntersectionObserver(entries => {
for (const en of entries) {
const p = pages[parseInt(en.target.dataset.page, 10) - 1];
if (en.isIntersecting) render(p).catch(() => {});
}
}, { root: viewer, rootMargin: '150% 0px' });
for (const p of pages) io.observe(p.el);
// Current page = the page whose top is nearest the viewport's upper third.
let currentPage = 1;
function updateCurrent() {
const top = viewer.scrollTop + viewer.clientHeight / 3;
let best = 1, bestDist = Infinity;
for (const p of pages) {
const d = Math.abs(p.el.offsetTop - top);
if (d < bestDist) { bestDist = d; best = p.num; }
}
if (best !== currentPage) {
currentPage = best;
$('pageno').value = String(best);
history.replaceState(null, '', '#page=' + best);
}
}
viewer.addEventListener('scroll', () => requestAnimationFrame(updateCurrent), { passive: true });
function goTo(n, smooth) {
n = Math.min(total, Math.max(1, n | 0));
const p = pages[n - 1];
viewer.scrollTo({ top: p.el.offsetTop - 12, behavior: smooth ? 'smooth' : 'auto' });
currentPage = n; $('pageno').value = String(n);
history.replaceState(null, '', '#page=' + n);
}
$('prev').addEventListener('click', () => goTo(currentPage - 1, true));
$('next').addEventListener('click', () => goTo(currentPage + 1, true));
$('pageno').addEventListener('change', () => goTo(parseInt($('pageno').value, 10) || 1, false));
// Zoom: re-size every page now, re-render the visible ones; the
// scroll position keeps the same page in view.
function rezoom(fit, factor) {
const keep = currentPage;
fitMode = fit; zoomFactor = factor;
sizeAll();
for (const p of pages) if (p.canvas) p.rendered = 0;
goTo(keep, false);
for (const p of pages) {
const r = p.el.getBoundingClientRect(), v = viewer.getBoundingClientRect();
if (r.bottom > v.top - v.height && r.top < v.bottom + v.height) render(p).catch(() => {});
}
}
$('zoomin').addEventListener('click', () => rezoom(false, Math.min(4, (fitMode ? 1 : zoomFactor) * 1.25)));
$('zoomout').addEventListener('click', () => rezoom(false, Math.max(0.3, (fitMode ? 1 : zoomFactor) / 1.25)));
$('fit').addEventListener('click', () => rezoom(true, 1));
// Resize (window, orientation, sidebars): debounce, then re-fit.
let rt = null;
new ResizeObserver(() => {
clearTimeout(rt);
rt = setTimeout(() => rezoom(fitMode, zoomFactor), 120);
}).observe(viewer);
// Keyboard.
document.addEventListener('keydown', e => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
if (e.key === 'ArrowLeft' || e.key === 'PageUp') { e.preventDefault(); goTo(currentPage - 1, true); }
else if (e.key === 'ArrowRight' || e.key === 'PageDown') { e.preventDefault(); goTo(currentPage + 1, true); }
else if (e.key === '+' || e.key === '=') { e.preventDefault(); $('zoomin').click(); }
else if (e.key === '-') { e.preventDefault(); $('zoomout').click(); }
else if (e.key === '0') { e.preventDefault(); $('fit').click(); }
else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') { e.preventDefault(); $('find').focus(); $('find').select(); }
});
// ── find: whole-document text search over the text layers, page by page ──
const findState = { term: '', hits: [], idx: -1 };
function norm(s) { return s.replace(/\s+/g, ' ').toLowerCase(); }
async function pageText(p) {
if (!p.page) p.page = await doc.getPage(p.num);
if (!p.text) p.text = await p.page.getTextContent();
return p.text;
}
async function runFind(term) {
findState.term = norm(term); findState.hits = []; findState.idx = -1;
for (const p of pages) if (p.textLayer) unhighlight(p);
if (!findState.term) { $('findcount').textContent = ''; return; }
for (const p of pages) {
const content = await pageText(p);
const joined = norm(content.items.map(i => i.str).join(' '));
let at = joined.indexOf(findState.term);
while (at !== -1) { findState.hits.push({ page: p.num }); at = joined.indexOf(findState.term, at + findState.term.length); }
if (p.textLayer) highlight(p);
}
$('findcount').textContent = findState.hits.length ? '0/' + findState.hits.length : 'no matches';
if (findState.hits.length) stepFind(1);
}
function stepFind(dir) {
if (!findState.hits.length) return;
findState.idx = (findState.idx + dir + findState.hits.length) % findState.hits.length;
$('findcount').textContent = (findState.idx + 1) + '/' + findState.hits.length;
goTo(findState.hits[findState.idx].page, true);
}
function unhighlight(p) {
for (const m of p.textLayer.querySelectorAll('mark')) {
const t = document.createTextNode(m.textContent); m.replaceWith(t);
}
for (const span of p.textLayer.querySelectorAll('span')) span.normalize();
}
function highlight(p) {
// mark the term inside each text span it occurs in (cross-span
// matches are counted by runFind but only same-span runs light up)
const term = findState.term;
if (!term || !p.textLayer) return;
for (const span of p.textLayer.querySelectorAll('span')) {
if (span.querySelector('mark')) continue;
const text = span.textContent, low = norm(text);
let at = low.indexOf(term);
if (at === -1) continue;
const frag = document.createDocumentFragment();
let last = 0;
while (at !== -1) {
frag.appendChild(document.createTextNode(text.slice(last, at)));
const m = document.createElement('mark'); m.textContent = text.slice(at, at + term.length); frag.appendChild(m);
last = at + term.length; at = low.indexOf(term, last);
}
frag.appendChild(document.createTextNode(text.slice(last)));
span.replaceChildren(frag);
}
}
let ft = null;
$('find').addEventListener('input', () => { clearTimeout(ft); ft = setTimeout(() => runFind($('find').value), 250); });
$('find').addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); if (norm($('find').value) !== findState.term) runFind($('find').value); else stepFind(e.shiftKey ? -1 : 1); }
if (e.key === 'Escape') { $('find').value = ''; runFind(''); viewer.focus(); }
});
// ── start: size, jump to the requested page, seed the find box ──
sizeAll();
const hashPage = parseInt((location.hash.match(/page=(\d+)/) || [])[1] || '0', 10);
goTo(hashPage || wantPage, false);
updateCurrent();
if (wantQuery) {
// the snippet's first words are enough to land on the passage
const probe = wantQuery.split(/\s+/).slice(0, 6).join(' ');
$('find').value = probe;
runFind(probe);
}
await mountFocusPane(n => goTo(n, false));
}
show().catch(e => console.warn('viewer:', e && e.message || e));
</script>
</body>
</html>