lit-reader 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lit_reader/reader.js ADDED
@@ -0,0 +1,899 @@
1
+ /* lit_reader: reading controls. No network access, no dependencies.
2
+ Stores preferences, reading position and status in localStorage,
3
+ wrapped in try/catch so the page still works when storage is blocked. */
4
+ (function () {
5
+ "use strict";
6
+ window.litReaderRan = true; // the page's flag script checks this: without it, the no-script fallbacks show
7
+ var WPM = 200; // academic prose; an estimate, labelled as one
8
+ var root = document.documentElement;
9
+ var pid = document.body.getAttribute("data-pid") || "";
10
+
11
+ function load(key, dflt) {
12
+ try { var v = localStorage.getItem(key); return v === null ? dflt : JSON.parse(v); }
13
+ catch (e) { return dflt; }
14
+ }
15
+ function save(key, val) { try { localStorage.setItem(key, JSON.stringify(val)); return true; } catch (e) { return false; } }
16
+
17
+ /* ---------- preferences ---------- */
18
+ var PREF_KEY = "litreader.prefs";
19
+ var prefs = load(PREF_KEY, {});
20
+ var SIZES = [16, 17, 18, 19, 20, 21, 22, 24, 26];
21
+ var phone = window.matchMedia && matchMedia("(max-width: 600px)").matches;
22
+ var touch = window.matchMedia && matchMedia("(pointer: coarse)").matches;
23
+ var DEFAULT_SIZE = phone ? 18 : 20; // about 40 characters a line on a phone, rather than 35
24
+ var wideQuery = window.matchMedia ? matchMedia("(min-width: 981px)") : { matches: true };
25
+ function focusQuietly(el, byPointer) { // focus follows a jump, but a tap or click doesn't leave a ring behind
26
+ el.focus({ preventScroll: true });
27
+ if (byPointer && document.activeElement === el) { // only once focus has landed, or the ring could stay hidden for good
28
+ el.classList.add("quiet-focus");
29
+ el.addEventListener("blur", function () { el.classList.remove("quiet-focus"); }, { once: true });
30
+ }
31
+ }
32
+ function home(btn) { // on a phone the bar's Quotes and Aa are hidden: focus goes back to the contents button
33
+ if (btn && btn.getClientRects().length) return btn;
34
+ return document.getElementById("toc-toggle") || btn || document.body;
35
+ }
36
+ function barBottom() { var b = document.querySelector(".bar"); return (b ? b.offsetHeight : 44) + 12; } // keep clear of the top bar
37
+ var WIDTHS = { narrow: "47ch", medium: "54ch", wide: "62ch" };
38
+ var LHS = { tight: 1.4, normal: 1.5, loose: 1.7 };
39
+
40
+ function applyPrefs() {
41
+ if (prefs.theme && prefs.theme !== "auto") root.setAttribute("data-theme", prefs.theme);
42
+ else root.removeAttribute("data-theme");
43
+ if (prefs.font && prefs.font !== "literata") root.setAttribute("data-font", prefs.font);
44
+ else root.removeAttribute("data-font");
45
+ if (prefs.para === "orig") root.setAttribute("data-para", "orig");
46
+ else root.removeAttribute("data-para");
47
+ if (prefs.toc === "hidden") root.setAttribute("data-toc", "hidden");
48
+ else root.removeAttribute("data-toc");
49
+ root.style.setProperty("--size", (prefs.size || DEFAULT_SIZE) + "px");
50
+ root.style.setProperty("--measure", WIDTHS[prefs.width || "medium"]);
51
+ root.style.setProperty("--lh", LHS[prefs.lh || "normal"]);
52
+ document.querySelectorAll(".panel [data-pref]").forEach(function (b) {
53
+ var k = b.getAttribute("data-pref"), v = b.getAttribute("data-val");
54
+ var cur = prefs[k] || { theme: "auto", font: "literata", width: "medium", lh: "normal", para: "short" }[k];
55
+ b.setAttribute("aria-pressed", String(cur === v));
56
+ });
57
+ var sz = document.getElementById("size-now");
58
+ if (sz) sz.textContent = (prefs.size || DEFAULT_SIZE) + "px";
59
+ }
60
+ applyPrefs();
61
+
62
+ var panel = document.getElementById("panel");
63
+ var aa = document.getElementById("aa");
64
+ function setPanel(open, refocus) {
65
+ panel.hidden = !open;
66
+ aa.setAttribute("aria-expanded", String(open));
67
+ if (!open && refocus) home(aa).focus();
68
+ }
69
+ if (aa && panel) {
70
+ aa.addEventListener("click", function (e) { e.stopPropagation(); setPanel(panel.hidden); });
71
+ document.addEventListener("click", function (e) { if (!panel.hidden && !panel.contains(e.target)) setPanel(false); });
72
+ document.addEventListener("keydown", function (e) { if (e.key === "Escape" && !panel.hidden) setPanel(false, true); });
73
+ panel.addEventListener("click", function (e) {
74
+ var b = e.target.closest("button"); if (!b) return;
75
+ if (b.hasAttribute("data-pref")) prefs[b.getAttribute("data-pref")] = b.getAttribute("data-val");
76
+ if (b.id === "size-down" || b.id === "size-up") {
77
+ var i = SIZES.indexOf(prefs.size || DEFAULT_SIZE); if (i < 0) i = 4;
78
+ i = Math.max(0, Math.min(SIZES.length - 1, i + (b.id === "size-up" ? 1 : -1)));
79
+ prefs.size = SIZES[i];
80
+ }
81
+ var anchor = pid && latest && document.getElementById(latest.id); // the text you were reading stays where it is
82
+ var was = anchor ? anchor.getBoundingClientRect().top : 0;
83
+ save(PREF_KEY, prefs); applyPrefs();
84
+ if (anchor) window.scrollBy(0, anchor.getBoundingClientRect().top - was);
85
+ if (pid) { measure(); update(); }
86
+ });
87
+ }
88
+
89
+ if (!pid) {
90
+ // the index page: each paper's reading status and saved quotes, then every quote together
91
+ var rows = [].slice.call(document.querySelectorAll(".list li[data-pid]"));
92
+ rows.forEach(function (li) {
93
+ var st = load("litreader.status." + li.getAttribute("data-pid"), {});
94
+ var s = li.querySelector(".s"); if (!s) return;
95
+ var nq = li.hasAttribute("data-cite") ? indexClips(li.getAttribute("data-pid")).length : 0;
96
+ var bits = [];
97
+ if (st.state) bits.push(st.state === "done" ? "Finished" : "In progress");
98
+ if (nq) bits.push(nq === 1 ? "1 quote" : nq + " quotes");
99
+ s.textContent = bits.join(" · ");
100
+ if (st.state) s.className = "s " + (st.state === "done" ? "done" : "started");
101
+ });
102
+ indexQuotes(rows);
103
+ return;
104
+ }
105
+
106
+ function indexClips(p) { var v = load("litreader.clips." + p, []); return Array.isArray(v) ? v : []; }
107
+ /* Every saved quote from the papers on this page, to download or copy as one file.
108
+ Each paper's quotes stay where that paper keeps them; this only reads them. */
109
+ function indexQuotes(rows) {
110
+ var box = document.getElementById("bundle-quotes");
111
+ if (!box) return;
112
+ var seen = {}, papers = [];
113
+ rows.forEach(function (li) {
114
+ var p = li.getAttribute("data-pid");
115
+ if (seen[p] || !li.hasAttribute("data-cite")) return; // a paper listed twice keeps one set of quotes
116
+ seen[p] = true;
117
+ var c = indexClips(p);
118
+ if (c.length) papers.push({ pid: p, clips: c, title: li.getAttribute("data-title") || "",
119
+ cite: li.getAttribute("data-cite") || "", reference: li.getAttribute("data-reference") || "" });
120
+ });
121
+ if (!papers.length) return;
122
+ var heading = (document.querySelector("h1") || {}).textContent || "these papers";
123
+ var status = document.createElement("p"); status.className = "sr"; status.setAttribute("role", "status");
124
+ function exportedKey(pp) { return "litreader.clipsExported." + pp.pid; }
125
+ function notExported(pp) { var at = load(exportedKey(pp), ""); return pp.clips.filter(function (c) { return !at || c.at > at; }).length; }
126
+ function citeFor(pp, c) { return "(" + pp.cite + (c.page ? (c.page.indexOf("–") > 0 ? ", pp. " : ", p. ") + c.page : "") + ")"; }
127
+ function markdown() {
128
+ var out = ["# Quotes from " + heading, ""];
129
+ papers.forEach(function (pp) {
130
+ out.push("## " + pp.title, "", pp.reference, "");
131
+ pp.clips.forEach(function (c) { out.push("> " + c.text, "", citeFor(pp, c) + (c.sec ? " · " + c.sec : ""), ""); });
132
+ });
133
+ return out.join("\n");
134
+ }
135
+ function markExported(label) {
136
+ var now = new Date().toISOString();
137
+ papers.forEach(function (pp) { save(exportedKey(pp), now); }); // each paper's own reminder clears too
138
+ draw();
139
+ var b = [].filter.call(box.querySelectorAll("button"), function (x) { return x.textContent === label; })[0];
140
+ if (b) b.focus(); // the clicked button was redrawn
141
+ }
142
+ function download() {
143
+ var a = document.createElement("a");
144
+ a.href = URL.createObjectURL(new Blob([markdown()], { type: "text/markdown" }));
145
+ a.download = "quotes-" + (heading.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "papers") + ".md";
146
+ document.body.appendChild(a); a.click(); a.remove();
147
+ setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
148
+ markExported("Download as Markdown");
149
+ }
150
+ function copyAll() {
151
+ var text = markdown();
152
+ function fallback() {
153
+ var t = document.createElement("textarea"), ok = false; t.value = text; t.setAttribute("readonly", "");
154
+ t.style.position = "fixed"; t.style.opacity = "0"; document.body.appendChild(t); t.select();
155
+ try { ok = document.execCommand("copy"); } catch (e) {}
156
+ t.remove();
157
+ return ok;
158
+ }
159
+ function done(ok) {
160
+ if (ok) markExported("Copy all");
161
+ status.textContent = ok ? "Copied." : "Couldn't copy. Use Download as Markdown instead.";
162
+ if (!box.contains(status)) box.appendChild(status);
163
+ }
164
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(function () { done(true); }, function () { done(fallback()); });
165
+ else done(fallback());
166
+ }
167
+ function draw() {
168
+ box.innerHTML = "";
169
+ box.hidden = false;
170
+ var total = 0, left = 0;
171
+ papers.forEach(function (pp) { total += pp.clips.length; left += notExported(pp); });
172
+ var h = document.createElement("h2"); h.id = "bundle-quotes-h"; h.textContent = "Saved quotes";
173
+ var p = document.createElement("p"); p.className = "listnote";
174
+ p.textContent = (total === 1 ? "1 quote" : total + " quotes") + " from " + (papers.length === 1 ? "1 paper" : papers.length + " papers") +
175
+ ", kept only in this browser. " + (!left ? "All downloaded." : left === total ? "None downloaded yet." : left + " not downloaded yet.") +
176
+ " The file groups them by paper, each with its citation.";
177
+ var row = document.createElement("div"); row.className = "row";
178
+ [["Download as Markdown", download], ["Copy all", copyAll]].forEach(function (x, i) {
179
+ var b = document.createElement("button"); b.type = "button"; b.textContent = x[0];
180
+ if (i === 0) b.className = "primary";
181
+ b.addEventListener("click", x[1]); row.appendChild(b);
182
+ });
183
+ box.appendChild(h); box.appendChild(p); box.appendChild(row); box.appendChild(status);
184
+ }
185
+ draw();
186
+ }
187
+
188
+ /* ---------- contents: a sidebar that can be put away on wide screens,
189
+ a drawer on narrow ones ---------- */
190
+ var toc = document.querySelector("nav.toc");
191
+ var tocToggle = document.getElementById("toc-toggle");
192
+ function setToc(open, refocus) {
193
+ toc.classList.toggle("open", open);
194
+ tocToggle.setAttribute("aria-expanded", String(open));
195
+ if (open) { var first = toc.querySelector("a"); if (first) setTimeout(function () { first.focus(); }, 30); }
196
+ if (!open && refocus) tocToggle.focus();
197
+ }
198
+ function syncToc() { // the button says whether the contents are showing at this width
199
+ if (wideQuery.matches) { toc.classList.remove("open"); tocToggle.setAttribute("aria-expanded", String(prefs.toc !== "hidden")); }
200
+ else tocToggle.setAttribute("aria-expanded", String(toc.classList.contains("open")));
201
+ }
202
+ if (tocToggle && toc) {
203
+ syncToc();
204
+ if (wideQuery.addEventListener) wideQuery.addEventListener("change", syncToc);
205
+ tocToggle.addEventListener("click", function (e) {
206
+ e.stopPropagation();
207
+ if (!wideQuery.matches) { setToc(!toc.classList.contains("open")); return; }
208
+ prefs.toc = prefs.toc === "hidden" ? "shown" : "hidden";
209
+ save(PREF_KEY, prefs); applyPrefs(); syncToc();
210
+ measure(); update();
211
+ });
212
+ document.addEventListener("click", function (e) { // a tap beside the drawer closes it, and does nothing else
213
+ if (toc.classList.contains("open") && !toc.contains(e.target) && e.detail > 0) { // a key press still does what it was for
214
+ setToc(false); e.preventDefault(); e.stopPropagation();
215
+ }
216
+ }, true);
217
+ toc.addEventListener("click", function (e) {
218
+ var a = e.target.closest("a"); if (!a) return;
219
+ if (!wideQuery.matches) setToc(false);
220
+ var to = a.hash && document.getElementById(a.hash.slice(1)); // keyboard focus moves with the jump
221
+ if (to) { to.tabIndex = -1; setTimeout(function () { focusQuietly(to, e.detail > 0); }, 30); }
222
+ });
223
+ document.addEventListener("keydown", function (e) { if (e.key === "Escape" && toc.classList.contains("open")) setToc(false, true); });
224
+ toc.querySelectorAll("[data-proxy]").forEach(function (b) { // Quotes and Aa, kept in the drawer on a phone
225
+ b.addEventListener("click", function (e) {
226
+ e.stopPropagation(); // or the click would reach the page and close the panel it opens
227
+ var real = document.getElementById(b.getAttribute("data-proxy"));
228
+ setToc(false);
229
+ if (real) real.click();
230
+ var opened = real && document.getElementById(real.getAttribute("aria-controls") || "panel");
231
+ if (real && real.id === "aa" && opened && !opened.hidden) { // Quotes moves focus itself; settings would leave it in the closed drawer
232
+ var first = opened.querySelector("button, input, select, a[href]"); if (first) first.focus();
233
+ }
234
+ });
235
+ });
236
+ }
237
+
238
+ /* ---------- sidenotes on narrow screens ---------- */
239
+ document.addEventListener("click", function (e) {
240
+ var m = e.target.closest(".sn-mark"); if (!m) return;
241
+ var n = document.getElementById(m.getAttribute("data-for"));
242
+ if (!n) return;
243
+ if (getComputedStyle(n).float === "none") { m.setAttribute("aria-expanded", String(n.classList.toggle("open"))); return; }
244
+ n.classList.add("flash"); // already in the margin: show which note this mark belongs to
245
+ setTimeout(function () { n.classList.remove("flash"); }, 1600);
246
+ });
247
+ document.querySelectorAll(".sn-mark").forEach(function (m) {
248
+ var n = document.getElementById(m.getAttribute("data-for"));
249
+ if (n && getComputedStyle(n).float === "none") m.setAttribute("aria-expanded", "false");
250
+ });
251
+ document.addEventListener("keydown", function (e) {
252
+ var m = e.target.closest && e.target.closest(".sn-mark");
253
+ if (m && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); m.click(); }
254
+ if (m && e.key === "Escape") {
255
+ var n = document.getElementById(m.getAttribute("data-for"));
256
+ if (n && n.classList.contains("open")) { n.classList.remove("open"); m.setAttribute("aria-expanded", "false"); }
257
+ }
258
+ });
259
+
260
+ /* ---------- citation cards ---------- */
261
+ var card = null, cardFrom = null;
262
+ function closeCard(refocus) {
263
+ if (!card) return;
264
+ card.remove(); card = null;
265
+ if (refocus && cardFrom) cardFrom.focus();
266
+ }
267
+ document.querySelectorAll("a.cite").forEach(function (a) {
268
+ a.setAttribute("aria-haspopup", "dialog");
269
+ if (/^\d/.test(a.textContent)) a.setAttribute("aria-label", "Reference " + a.textContent);
270
+ });
271
+ function offerWayBack(li, from, fromY) { // a button under the reference, back to the citation it came from
272
+ document.querySelectorAll(".ref-back").forEach(function (b) { b.remove(); });
273
+ var b = document.createElement("button");
274
+ b.type = "button"; b.className = "ref-back"; b.textContent = "↩ Back to where you were";
275
+ b.addEventListener("click", function (e) {
276
+ e.stopPropagation(); b.remove();
277
+ if (from && from.getClientRects().length) from.scrollIntoView({ block: "center" }); // the citation itself: right even after the text size changed
278
+ else window.scrollTo(0, fromY);
279
+ if (from) focusQuietly(from, e.detail > 0);
280
+ });
281
+ li.appendChild(b);
282
+ }
283
+ function goToRef(li, byPointer) { // the default jump to #ref-… happens after, from the link itself
284
+ var from = cardFrom, fromY = window.scrollY;
285
+ closeCard(); li.classList.add("flash"); setTimeout(function () { li.classList.remove("flash"); }, 1600);
286
+ var det = li.closest("details"); if (det) det.open = true;
287
+ offerWayBack(li, from, fromY);
288
+ li.tabIndex = -1; setTimeout(function () { focusQuietly(li, byPointer); }, 30);
289
+ }
290
+ function openCard(a, moveFocus) {
291
+ closeCard();
292
+ cardFrom = a;
293
+ var ids = (a.getAttribute("data-ref") || "").split(" ").filter(Boolean);
294
+ if (!ids.length) return;
295
+ card = document.createElement("div");
296
+ card.className = "cite-card";
297
+ card.setAttribute("role", "dialog");
298
+ card.setAttribute("aria-label", "Reference");
299
+ card.tabIndex = -1;
300
+ ids.forEach(function (id, i) {
301
+ var li = document.getElementById("ref-" + id);
302
+ if (!li) return;
303
+ var d = document.createElement("div");
304
+ if (i) d.style.marginTop = ".6rem";
305
+ d.innerHTML = li.innerHTML; // our own sanitised reference list, not source HTML
306
+ d.querySelectorAll(".ref-back").forEach(function (b) { b.remove(); });
307
+ var go = document.createElement("a");
308
+ go.href = "#ref-" + id; go.className = "go"; go.textContent = "Go to reference list";
309
+ go.addEventListener("click", function (e) { goToRef(li, e.detail > 0); });
310
+ d.appendChild(go);
311
+ card.appendChild(d);
312
+ });
313
+ if (!card.childNodes.length) { card = null; return; }
314
+ document.body.appendChild(card);
315
+ var r = a.getBoundingClientRect();
316
+ var top = window.scrollY + r.bottom + 6;
317
+ if (r.bottom + 6 + card.offsetHeight > window.innerHeight) top = Math.max(window.scrollY + barBottom(), window.scrollY + r.top - card.offsetHeight - 6);
318
+ var left = Math.min(window.scrollX + r.left, window.scrollX + document.documentElement.clientWidth - card.offsetWidth - 12);
319
+ card.style.top = top + "px"; card.style.left = Math.max(8, left) + "px";
320
+ card.addEventListener("keydown", function (e) {
321
+ if (e.key !== "Tab") return;
322
+ var links = card.querySelectorAll("a"), last = links[links.length - 1];
323
+ if ((!e.shiftKey && document.activeElement === last) || (e.shiftKey && document.activeElement === card)) { e.preventDefault(); closeCard(true); }
324
+ });
325
+ if (moveFocus) card.focus();
326
+ }
327
+ var hoverTimer = null;
328
+ document.addEventListener("mouseover", function (e) {
329
+ if (touch) return; // a tap sends a mouseover too; the click opens the card
330
+ var a = e.target.closest && e.target.closest("a.cite");
331
+ if (a) { clearTimeout(hoverTimer); hoverTimer = setTimeout(function () { openCard(a); }, 250); }
332
+ });
333
+ document.addEventListener("mouseout", function (e) {
334
+ var a = e.target.closest && e.target.closest("a.cite");
335
+ if (a) clearTimeout(hoverTimer);
336
+ });
337
+ document.addEventListener("click", function (e) {
338
+ var a = e.target.closest("a.cite");
339
+ if (a && !touch && card && cardFrom === a && e.detail > 0) { // hovering already opened its card: a click goes on to the reference
340
+ var go = card.querySelector("a.go"), li = go && document.getElementById(go.getAttribute("href").slice(1));
341
+ if (li) { e.preventDefault(); goToRef(li, true);
342
+ if (location.hash === "#" + li.id) li.scrollIntoView(); else location.hash = li.id; // as the card's own link does
343
+ return; }
344
+ }
345
+ if (a) { e.preventDefault(); openCard(a, e.detail === 0); return; } // detail 0: opened from the keyboard
346
+ if (card && !card.contains(e.target)) closeCard();
347
+ });
348
+ document.addEventListener("keydown", function (e) { if (e.key === "Escape") closeCard(true); });
349
+
350
+ /* ---------- saved quotes ----------
351
+ Select text and choose "Save quote" (or press Q). Quotes stay in this
352
+ browser, per paper, with the section and printed page they came from. */
353
+ var CLIP_KEY = "litreader.clips." + pid;
354
+ function loadClips() { var v = load(CLIP_KEY, []); return Array.isArray(v) ? v : []; } // anything else in storage is ignored, not trusted
355
+ var clips = loadClips();
356
+ var clipsBtn = document.getElementById("clips");
357
+ var clipsPanel = document.getElementById("clips-panel");
358
+ var clipCount = document.getElementById("clip-count");
359
+ var cite = document.body.getAttribute("data-cite") || "";
360
+ var reference = document.body.getAttribute("data-reference") || document.title;
361
+ var saveBtn = null, pending = null, stored = true; // stored: false once the browser refuses to keep quotes
362
+ var removed = null; // the last quote removed, offered back until the panel closes
363
+
364
+ function quoteText(range) {
365
+ var div = document.createElement("div");
366
+ div.appendChild(range.cloneContents());
367
+ div.querySelectorAll(".sidenote, .sn-mark, .pg, details, button, .clip-save").forEach(function (n) { n.remove(); });
368
+ div.querySelectorAll("p, li, .chunk, h2, h3, h4, figcaption, td, th").forEach(function (n) { n.appendChild(document.createTextNode(" ")); });
369
+ return div.textContent.replace(/\s+/g, " ").trim();
370
+ }
371
+ function pageBefore(el) {
372
+ var pgs = document.querySelectorAll("main .pg"), found = "";
373
+ for (var i = 0; i < pgs.length; i++) {
374
+ if (pgs[i].compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) found = pgs[i].textContent.trim();
375
+ else break;
376
+ }
377
+ return found.replace(/^p\.\s*/, "");
378
+ }
379
+ function locate(range) {
380
+ var n = range.startContainer.nodeType === 1 ? range.startContainer : range.startContainer.parentNode;
381
+ var block = n.closest("main [data-w], main [data-sec], main section.abstract");
382
+ if (!block) { // a selection that starts between paragraphs: the first paragraph it reaches
383
+ var all = document.querySelectorAll("main [data-w]");
384
+ for (var k = 0; k < all.length && !block; k++) if (range.intersectsNode(all[k])) block = all[k];
385
+ }
386
+ var page = block ? pageBefore(block) : "";
387
+ var div = document.createElement("div");
388
+ div.appendChild(range.cloneContents());
389
+ var inner = div.querySelectorAll(".pg");
390
+ var last = inner.length ? inner[inner.length - 1].textContent.trim().replace(/^p\.\s*/, "") : "";
391
+ if (last && page && last !== page) page = page + "–" + last;
392
+ else if (last && !page) page = last;
393
+ return { block: block ? block.id : "", sec: block && block.classList.contains("abstract") ? (block.querySelector("h2") || {}).textContent || "Abstract"
394
+ : block && block.getAttribute("data-in") ? sectionTitle(block.getAttribute("data-in")) : "", page: page };
395
+ }
396
+ function citeFor(c) {
397
+ return "(" + cite + (c.page ? (c.page.indexOf("–") > 0 ? ", pp. " : ", p. ") + c.page : "") + ")";
398
+ }
399
+ function asText(c) { return "“" + c.text + "” " + citeFor(c); }
400
+ function asMarkdown() {
401
+ var out = ["# Quotes from " + document.title, "", reference, ""];
402
+ clips.forEach(function (c) {
403
+ out.push("> " + c.text, "", citeFor(c) + (c.sec ? " · " + c.sec : ""), "");
404
+ });
405
+ return out.join("\n");
406
+ }
407
+ function copy(text, then) {
408
+ function fallback() {
409
+ var t = document.createElement("textarea"), ok = false; t.value = text; t.setAttribute("readonly", "");
410
+ t.style.position = "fixed"; t.style.opacity = "0"; document.body.appendChild(t); t.select();
411
+ try { ok = document.execCommand("copy"); } catch (e) {}
412
+ t.remove();
413
+ return ok;
414
+ }
415
+ function done(ok) { if (ok && then) then(); toast(ok ? "<span>Copied.</span>" : "<span>Couldn't copy. Use Download as Markdown instead.</span>", ok ? 2500 : 5000); }
416
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(function () { done(true); }, function () { done(fallback()); });
417
+ else done(fallback());
418
+ }
419
+ var EXPORTED_KEY = "litreader.clipsExported." + pid; // when this paper's quotes were last downloaded or copied
420
+ var exportedAt = ""; // also kept here, for a browser that won't store it
421
+ function notExported() {
422
+ var at = load(EXPORTED_KEY, "") || exportedAt;
423
+ return clips.filter(function (c) { return !at || c.at > at; }).length;
424
+ }
425
+ function markExported() {
426
+ exportedAt = new Date().toISOString(); save(EXPORTED_KEY, exportedAt);
427
+ var open = clipsPanel && !clipsPanel.hidden, from = document.activeElement, label = from && from.textContent;
428
+ var inDone = doneQuotes && doneQuotes.contains(from);
429
+ renderClips();
430
+ if (open && !inDone) { // the clicked button was redrawn: back to the same one
431
+ var b = [].filter.call(clipsPanel.querySelectorAll(".row button"), function (x) { return x.textContent === label; })[0];
432
+ if (b) b.focus();
433
+ }
434
+ if (inDone && doneBtn) doneBtn.focus(); // the reminder and its button are gone
435
+ }
436
+ function download() {
437
+ var a = document.createElement("a");
438
+ a.href = URL.createObjectURL(new Blob([asMarkdown()], { type: "text/markdown" }));
439
+ a.download = "quotes-" + (document.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40) || "paper") + ".md";
440
+ a.addEventListener("click", function (e) { e.stopPropagation(); }); // not a click outside the Quotes panel
441
+ document.body.appendChild(a); a.click(); a.remove();
442
+ setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
443
+ markExported();
444
+ }
445
+ function quotesWord(n) { return n === 1 ? "1 quote" : n + " quotes"; }
446
+ // At the end of the main text: a reminder, only when there are quotes not yet downloaded.
447
+ var doneQuotes = null;
448
+ function showDoneQuotes() {
449
+ var box = document.querySelector(".done-box");
450
+ if (!box) return;
451
+ var n = notExported();
452
+ if (!n) { if (doneQuotes) { doneQuotes.remove(); doneQuotes = null; } return; }
453
+ if (!doneQuotes) {
454
+ doneQuotes = document.createElement("p"); doneQuotes.className = "done-quotes";
455
+ var s = document.createElement("span"), b = document.createElement("button");
456
+ b.type = "button"; b.textContent = "Download";
457
+ b.addEventListener("click", download);
458
+ doneQuotes.appendChild(s); doneQuotes.appendChild(document.createTextNode(" ")); doneQuotes.appendChild(b);
459
+ box.appendChild(doneQuotes);
460
+ }
461
+ doneQuotes.firstChild.textContent = "You saved " + quotesWord(n) + " from this paper that you haven't downloaded. " + (
462
+ !stored ? "This browser isn't keeping " + (n === 1 ? "it" : "them") + ": " + (n === 1 ? "it goes" : "they go") + " when you close this tab."
463
+ : (n === 1 ? "It's" : "They're") + " kept only in this browser.");
464
+ }
465
+ function hideSave() { if (saveBtn) { saveBtn.remove(); saveBtn = null; } pending = null; }
466
+ function saveClip() {
467
+ if (!pending) return;
468
+ var c = pending;
469
+ c.id = String(Date.now());
470
+ c.at = new Date().toISOString();
471
+ if (stored) clips = loadClips(); // another tab may have saved quotes since this one loaded
472
+ clips.push(c); stored = save(CLIP_KEY, clips);
473
+ hideSave();
474
+ var sel = window.getSelection(); if (sel) sel.removeAllRanges();
475
+ renderClips();
476
+ var first = !load(HINT_KEY, {}).saved;
477
+ save(HINT_KEY, { done: true, saved: true }); // they know about quotes now: no more tips
478
+ var n = notExported();
479
+ toast(!stored ? "<span>This browser won't keep quotes for local pages, so they last only until you close this tab. Open Quotes to copy or download them now.</span>"
480
+ : first ? "<span>Quote saved in this browser. Open Quotes in the top bar to copy it with its citation, or download your quotes as a file to keep.</span>"
481
+ : n >= 3 ? "<span>Quote saved. " + quotesWord(n) + " from this paper aren't downloaded yet. Open Quotes to download them.</span>"
482
+ : "<span>Quote saved.</span>", stored ? (first || n >= 3 ? 6000 : 2500) : 9000);
483
+ }
484
+ /* A tip, on the first few papers someone scrolls through, that passages can be saved.
485
+ Selecting text is the only way in, and nothing on the page shows it otherwise. */
486
+ var HINT_KEY = "litreader.quoteHint", hintChecked = false;
487
+ function maybeHint() {
488
+ if (hintChecked || !clipsBtn || !hintReady || window.scrollY < window.innerHeight * 1.5) return;
489
+ if (document.querySelector(".toast")) return; // after "Resumed where you left off", not instead of it
490
+ hintChecked = true;
491
+ var h = load(HINT_KEY, {}), seen = Array.isArray(h.papers) ? h.papers : [];
492
+ if (h.done || clips.length || seen.indexOf(pid) >= 0 || seen.length >= 3) return;
493
+ seen.push(pid); save(HINT_KEY, { papers: seen });
494
+ var t = toast(touch ? "<span>Tip: press and hold on a passage to select it, then tap Save quote. It keeps the page and citation.</span> <button type=\"button\">Got it</button>"
495
+ : "<span>Tip: select a passage and press Q, or choose Save quote, to keep it with its page and citation.</span> <button type=\"button\">Got it</button>", 12000);
496
+ t.querySelector("button").addEventListener("click", function () { save(HINT_KEY, { done: true }); t.remove(); });
497
+ }
498
+ var hintReady = false; // the jump back to a saved position isn't the reader scrolling
499
+ setTimeout(function () { hintReady = true; }, 2000);
500
+ if (clipsBtn) window.addEventListener("scroll", maybeHint, { passive: true });
501
+ function renderClips() {
502
+ if (clipCount) clipCount.textContent = clips.length ? "(" + clips.length + ")" : "";
503
+ document.querySelectorAll(".clip-count-n").forEach(function (n) { n.textContent = clips.length ? " (" + clips.length + ")" : ""; });
504
+ showDoneQuotes();
505
+ if (!clipsPanel) return;
506
+ clipsPanel.innerHTML = "";
507
+ var h = document.createElement("div"); h.className = "clips-head";
508
+ h.textContent = clips.length ? "Saved quotes" : "No saved quotes yet";
509
+ clipsPanel.appendChild(h);
510
+ if (!clips.length && !removed) {
511
+ var p = document.createElement("p"); p.className = "note";
512
+ p.textContent = touch ? "Select text in the paper, then tap Save quote. Quotes stay in this browser."
513
+ : "Select text in the paper, then choose Save quote or press Q. Quotes stay in this browser.";
514
+ clipsPanel.appendChild(p);
515
+ return;
516
+ }
517
+ if (clips.length) {
518
+ var n = notExported(), kept = document.createElement("p"); kept.className = "note clips-kept";
519
+ kept.textContent = !stored ? "This browser isn't keeping these: they go when you close this tab. Download them to keep them."
520
+ : n ? "These are kept only in this browser. " + (n === clips.length ? "None downloaded yet." : quotesWord(n) + " not downloaded yet.")
521
+ : "Kept in this browser, and all downloaded.";
522
+ clipsPanel.appendChild(kept);
523
+ }
524
+ var all = document.createElement("div"); all.className = "row";
525
+ if (!clips.length) all.hidden = true;
526
+ [["Download as Markdown", download],
527
+ ["Copy all", function () { copy(asMarkdown(), markExported); }]].forEach(function (x, i) {
528
+ var b = document.createElement("button"); b.type = "button"; b.textContent = x[0];
529
+ if (i === 0) b.className = "primary";
530
+ b.addEventListener("click", function (e) { e.stopPropagation(); x[1](); }); all.appendChild(b);
531
+ });
532
+ clipsPanel.appendChild(all);
533
+ var ol = document.createElement("ol"); ol.className = "clips";
534
+ function undoItem() { // above the list, so the quotes' numbers still match their place in it
535
+ var li = document.createElement("div"); li.className = "clip-removed";
536
+ var s = document.createElement("span"); s.textContent = "Quote removed.";
537
+ var b = document.createElement("button"); b.type = "button"; b.textContent = "Undo";
538
+ b.setAttribute("aria-label", "Undo removing the quote");
539
+ b.addEventListener("click", function (e) {
540
+ e.stopPropagation();
541
+ if (stored) clips = loadClips();
542
+ clips.splice(Math.min(removed.at, clips.length), 0, removed.clip);
543
+ if (stored) stored = save(CLIP_KEY, clips);
544
+ var id = removed.clip.id; removed = null;
545
+ renderClips();
546
+ var back = clipsPanel.querySelector('li[data-id="' + id + '"] button');
547
+ if (back) back.focus(); else home(clipsBtn).focus();
548
+ });
549
+ li.appendChild(s); li.appendChild(b);
550
+ return li;
551
+ }
552
+ if (removed) clipsPanel.appendChild(undoItem());
553
+ clips.forEach(function (c, i) {
554
+ var li = document.createElement("li");
555
+ li.setAttribute("data-id", c.id);
556
+ var q = document.createElement("blockquote"); q.textContent = c.text;
557
+ var m = document.createElement("div"); m.className = "note";
558
+ m.textContent = citeFor(c) + (c.sec ? " · " + c.sec : "");
559
+ var acts = document.createElement("div"); acts.className = "acts";
560
+ [["Copy", function () { copy(asText(c) + "\n\n" + reference); }],
561
+ ["Go to", function () {
562
+ setClips(false);
563
+ var el = document.getElementById(c.block); if (!el) return;
564
+ el.scrollIntoView({ block: "center" }); el.classList.add("flash-block");
565
+ setTimeout(function () { el.classList.remove("flash-block"); }, 1600);
566
+ el.tabIndex = -1; el.focus({ preventScroll: true });
567
+ }],
568
+ ["Remove", function () {
569
+ removed = { clip: c, at: i };
570
+ clips = (stored ? loadClips() : clips).filter(function (x) { return x.id !== c.id; });
571
+ if (stored) stored = save(CLIP_KEY, clips);
572
+ renderClips();
573
+ var u = clipsPanel.querySelector(".clip-removed button");
574
+ if (u) u.focus(); else home(clipsBtn).focus();
575
+ }]
576
+ ].forEach(function (x) {
577
+ var b = document.createElement("button"); b.type = "button"; b.textContent = x[0];
578
+ b.setAttribute("aria-label", x[0] + " quote " + (i + 1));
579
+ b.addEventListener("click", function (e) { e.stopPropagation(); x[1](); });
580
+ acts.appendChild(b);
581
+ });
582
+ li.appendChild(q); li.appendChild(m); li.appendChild(acts); ol.appendChild(li);
583
+ });
584
+ clipsPanel.appendChild(ol);
585
+ }
586
+ function setClips(open, refocus) {
587
+ if (!clipsPanel) return;
588
+ if (open) { setPanel(false); if (stored) clips = loadClips(); renderClips(); }
589
+ if (!open) removed = null;
590
+ clipsPanel.hidden = !open;
591
+ clipsBtn.setAttribute("aria-expanded", String(open));
592
+ if (open) { var f = clipsPanel.querySelector("button"); if (f) f.focus(); }
593
+ if (!open && refocus) home(clipsBtn).focus();
594
+ }
595
+ if (clipsBtn && clipsPanel) {
596
+ renderClips();
597
+ clipsBtn.addEventListener("click", function (e) { e.stopPropagation(); setClips(clipsPanel.hidden); });
598
+ document.addEventListener("click", function (e) { if (!clipsPanel.hidden && !clipsPanel.contains(e.target)) setClips(false); });
599
+ document.addEventListener("keydown", function (e) { if (e.key === "Escape" && !clipsPanel.hidden) setClips(false, true); });
600
+ if (aa) aa.addEventListener("click", function () { if (!clipsPanel.hidden) setClips(false); });
601
+ }
602
+ function checkSelection() {
603
+ var sel = window.getSelection();
604
+ if (!sel || sel.isCollapsed || !sel.rangeCount) { hideSave(); return; }
605
+ var range = sel.getRangeAt(0);
606
+ var main = document.querySelector("main");
607
+ var anc = range.commonAncestorContainer;
608
+ if (!main || !main.contains(anc) || (anc.nodeType === 1 ? anc : anc.parentNode).closest("header.paper, .references, .clip-save, footer, .done-box, .orig-page, .table-text")) { hideSave(); return; }
609
+ var text = quoteText(range);
610
+ if (text.length < 3) { hideSave(); return; }
611
+ pending = locate(range); pending.text = text;
612
+ if (!saveBtn) {
613
+ saveBtn = document.createElement("button");
614
+ saveBtn.type = "button"; saveBtn.className = "clip-save"; saveBtn.textContent = "Save quote";
615
+ if (!touch) { saveBtn.setAttribute("aria-keyshortcuts", "Q"); saveBtn.title = "Save quote (Q)"; }
616
+ saveBtn.addEventListener("mousedown", function (e) { e.preventDefault(); }); // keep the selection
617
+ saveBtn.addEventListener("click", function (e) { e.stopPropagation(); saveClip(); });
618
+ document.body.appendChild(saveBtn);
619
+ }
620
+ var r = range.getBoundingClientRect();
621
+ var top = window.scrollY + r.top - saveBtn.offsetHeight - 8;
622
+ if (touch) { // a phone puts its own copy menu above the selection: go below, past the drag handle
623
+ top = window.scrollY + r.bottom + 30;
624
+ if (r.bottom + 30 + saveBtn.offsetHeight > window.innerHeight - 8) top = window.scrollY + Math.max(barBottom(), r.top - saveBtn.offsetHeight - 56);
625
+ } else if (r.top - saveBtn.offsetHeight - 8 < barBottom()) top = window.scrollY + r.bottom + 8;
626
+ var left = Math.min(window.scrollX + r.left + r.width / 2 - saveBtn.offsetWidth / 2, window.scrollX + document.documentElement.clientWidth - saveBtn.offsetWidth - 12);
627
+ saveBtn.style.top = top + "px"; saveBtn.style.left = Math.max(8, left) + "px";
628
+ }
629
+ var selTimer = null;
630
+ if (clipsBtn) document.addEventListener("selectionchange", function () { clearTimeout(selTimer); selTimer = setTimeout(checkSelection, 150); });
631
+ if (clipsBtn) document.addEventListener("keydown", function (e) {
632
+ var tag = (e.target.tagName || "").toLowerCase();
633
+ if ((e.key === "q" || e.key === "Q") && !e.metaKey && !e.ctrlKey && !e.altKey && tag !== "input" && tag !== "textarea" && !e.target.isContentEditable) {
634
+ checkSelection(); // the selection may have changed in the last moment
635
+ if (pending) { e.preventDefault(); saveClip(); }
636
+ }
637
+ if (e.key === "Escape") hideSave();
638
+ });
639
+
640
+ /* ---------- figures: each image is a button. With a margin to spread
641
+ into, it widens the figure in place; on narrower screens it opens the
642
+ figure full screen, at a size where its text can be read. ---------- */
643
+ var marginQuery = window.matchMedia ? matchMedia("(min-width: 1261px)") : { matches: true };
644
+ var figBtns = [];
645
+ function figName(fig) {
646
+ var l = fig.querySelector("figcaption .label");
647
+ var img = fig.querySelector("img"), kind = img && /^Table\b/.test(img.alt) ? "Table" : "Figure"; // an unlabelled table is still a table
648
+ return (l ? l.textContent : "").replace(/[.:]\s*$/, "").trim() || kind;
649
+ }
650
+ document.querySelectorAll("main figure img").forEach(function (img) {
651
+ if (img.closest("figcaption, .tablewrap, table")) return; // an equation in a caption or cell is not the figure
652
+ var b = document.createElement("button");
653
+ b.type = "button"; b.className = "fig-zoom";
654
+ img.parentNode.insertBefore(b, img); b.appendChild(img);
655
+ figBtns.push(b);
656
+ });
657
+ function syncFigs() {
658
+ figBtns.forEach(function (b) {
659
+ var fig = b.closest("figure"), what = b.querySelector("img").alt || figName(fig); // arXiv's figures often have no alt
660
+ if (marginQuery.matches) {
661
+ b.removeAttribute("aria-haspopup"); b.setAttribute("aria-pressed", String(fig.classList.contains("wide")));
662
+ b.setAttribute("aria-label", what + " (widen into the margin)");
663
+ } else {
664
+ fig.classList.remove("wide"); b.removeAttribute("aria-pressed"); b.setAttribute("aria-haspopup", "dialog");
665
+ b.setAttribute("aria-label", what + " (open full screen)");
666
+ }
667
+ });
668
+ }
669
+ syncFigs();
670
+ if (marginQuery.addEventListener) marginQuery.addEventListener("change", syncFigs);
671
+
672
+ var viewer = null, viewerFrom = null, viewerByPointer = false;
673
+ var behind = [];
674
+ function closeViewer() {
675
+ if (!viewer) return;
676
+ viewer.remove(); viewer = null;
677
+ behind.forEach(function (el) { el.inert = false; });
678
+ behind = [];
679
+ root.style.overflow = "";
680
+ if (viewerFrom) focusQuietly(viewerFrom, viewerByPointer);
681
+ }
682
+ function openViewer(b, byPointer) {
683
+ var img = b.querySelector("img"), name = figName(b.closest("figure"));
684
+ setPanel(false); setClips(false); closeCard();
685
+ viewerFrom = b; viewerByPointer = byPointer;
686
+ viewer = document.createElement("div"); viewer.className = "viewer";
687
+ viewer.setAttribute("role", "dialog"); viewer.setAttribute("aria-modal", "true"); viewer.setAttribute("aria-label", name);
688
+ var head = document.createElement("div"); head.className = "viewer-bar";
689
+ var title = document.createElement("span"); title.className = "viewer-title"; title.textContent = name;
690
+ var size = document.createElement("button"); size.type = "button";
691
+ var close = document.createElement("button"); close.type = "button"; close.textContent = "Close";
692
+ head.appendChild(title); head.appendChild(size); head.appendChild(close);
693
+ var body = document.createElement("div"); body.className = "viewer-body"; body.tabIndex = 0;
694
+ body.setAttribute("role", "region"); body.setAttribute("aria-label", name + ", scrolls both ways");
695
+ var big = document.createElement("img"); big.src = img.src; big.alt = img.alt;
696
+ body.appendChild(big);
697
+ viewer.appendChild(head); viewer.appendChild(body);
698
+ document.body.appendChild(viewer);
699
+ behind = [].filter.call(document.body.children, function (el) { return el !== viewer && !el.inert; }); // everything else, toasts and the skip link too
700
+ behind.forEach(function (el) { el.inert = true; });
701
+ root.style.overflow = "hidden";
702
+ var natural = img.naturalWidth || +img.getAttribute("width") || 0;
703
+ var room = body.clientWidth - 24;
704
+ function setFull(on) {
705
+ viewer.classList.toggle("full", on);
706
+ big.style.width = on ? Math.min(natural, room * 3) + "px" : "";
707
+ size.textContent = on ? "Fit to screen" : "Full size";
708
+ }
709
+ if (natural > room * 1.2) setFull(true); // big enough that the full size is worth having: start there
710
+ else { setFull(false); size.hidden = true; }
711
+ size.addEventListener("click", function () { setFull(!viewer.classList.contains("full")); });
712
+ close.addEventListener("click", closeViewer);
713
+ viewer.addEventListener("keydown", function (e) { if (e.key === "Escape") { e.stopPropagation(); closeViewer(); } });
714
+ close.focus();
715
+ }
716
+ document.addEventListener("keydown", function (e) { if (viewer && e.key === "Escape") closeViewer(); }); // also when focus has dropped to the page
717
+ document.addEventListener("click", function (e) {
718
+ var b = e.target.closest(".fig-zoom"); if (!b) return;
719
+ if (marginQuery.matches) {
720
+ var fig = b.closest("figure");
721
+ b.setAttribute("aria-pressed", String(fig.classList.toggle("wide")));
722
+ } else openViewer(b, e.detail > 0);
723
+ });
724
+
725
+ /* ---------- position, progress and time left ---------- */
726
+ var blocks = [].slice.call(document.querySelectorAll("main [data-w]"));
727
+ var heads = [].slice.call(document.querySelectorAll("main [data-sec]"));
728
+ var tocLinks = {};
729
+ document.querySelectorAll("nav.toc a[href^='#']").forEach(function (a) { tocLinks[a.getAttribute("href").slice(1)] = a; });
730
+ var bodyEndEl = document.getElementById("end-of-body");
731
+ var where = document.getElementById("where");
732
+ var bar = document.getElementById("progress");
733
+ var geo = [];
734
+
735
+ function measure() {
736
+ geo = blocks.map(function (b) {
737
+ return { el: b, top: b.getBoundingClientRect().top + window.scrollY, w: +b.getAttribute("data-w"), sec: b.getAttribute("data-in") || "", body: b.getAttribute("data-body") === "1" };
738
+ });
739
+ }
740
+ function sectionTitle(id) {
741
+ var h = document.getElementById(id); if (!h) return "";
742
+ return h.getAttribute("data-title") || h.textContent;
743
+ }
744
+ var lastSaved = 0, ticking = false, latest = null, saveTimer = null, resumed = false;
745
+ var listed = {}, lastListed = ""; // a section too minor for the contents highlights its parent
746
+ heads.forEach(function (h) { if (tocLinks[h.id]) lastListed = h.id; listed[h.id] = lastListed; });
747
+ function update() {
748
+ ticking = false;
749
+ if (!geo.length) return;
750
+ var y = window.scrollY + Math.max(90, window.innerHeight * 0.3); // a third of the way down, as scroll trackers usually do
751
+ var i = 0; while (i < geo.length - 1 && geo[i + 1].top <= y) i++;
752
+ if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) i = geo.length - 1; // the end of the page counts as read
753
+ var cur = geo[i];
754
+ var secLeft = 0, bodyLeft = 0, bodyTotal = 0;
755
+ for (var j = 0; j < geo.length; j++) {
756
+ if (geo[j].body) { bodyTotal += geo[j].w; if (j >= i) bodyLeft += geo[j].w; }
757
+ if (j >= i && geo[j].sec === cur.sec) secLeft += geo[j].w;
758
+ }
759
+ var sm = Math.max(1, Math.round(secLeft / WPM)), bm = Math.round(bodyLeft / WPM);
760
+ var atStart = geo[0].top > y; // still on the title and abstract, before the first section
761
+ if (where && atStart) where.textContent = "About " + Math.max(1, bm) + " min of reading";
762
+ else if (where) {
763
+ var t = sectionTitle(cur.sec);
764
+ where.textContent = !secLeft ? t // the reference list has no reading time
765
+ : window.innerWidth < 560 ? sm + " min left in section" + (t ? " · " + t : "")
766
+ : (t ? t + " · " : "") + "about " + sm + " min left in section" + (cur.body && bm ? " · " + bm + " min to the end of the main text" : "");
767
+ }
768
+ if (bar && bodyTotal) bar.style.width = (100 * (1 - bodyLeft / bodyTotal)) + "%";
769
+ Object.keys(tocLinks).forEach(function (k) { var on = !atStart && k === (listed[cur.sec] || cur.sec);
770
+ tocLinks[k].classList.toggle("current", on);
771
+ if (on) tocLinks[k].setAttribute("aria-current", "location"); else tocLinks[k].removeAttribute("aria-current"); });
772
+ latest = { id: cur.el.id, started: bodyTotal && bodyLeft / bodyTotal < 0.97 };
773
+ clearTimeout(saveTimer);
774
+ if (Date.now() - lastSaved > 1500) savePosition();
775
+ else saveTimer = setTimeout(savePosition, 1500); // so the place where scrolling stops is the one kept
776
+ }
777
+ function savePosition() {
778
+ if (!latest || !resumed) return; // nothing is saved until the saved place has been restored
779
+ lastSaved = Date.now();
780
+ var st = load("litreader.status." + pid, {});
781
+ st.pos = latest.id; st.at = new Date().toISOString();
782
+ if (!st.state && latest.started) st.state = "started";
783
+ save("litreader.status." + pid, st);
784
+ }
785
+ window.addEventListener("pagehide", savePosition);
786
+ window.addEventListener("scroll", function () { if (!ticking) { ticking = true; requestAnimationFrame(update); } }, { passive: true });
787
+ window.addEventListener("resize", function () { measure(); update(); });
788
+
789
+ var live = document.createElement("div"); // present before it speaks, so screen readers announce the change
790
+ live.className = "sr"; live.setAttribute("role", "status");
791
+ document.body.appendChild(live);
792
+ function toast(html, ms) {
793
+ document.querySelectorAll(".toast").forEach(function (o) { o.remove(); }); // one at a time: they share a place
794
+ var t = document.createElement("div"); t.className = "toast"; t.innerHTML = html;
795
+ document.body.appendChild(t); setTimeout(function () { t.remove(); }, ms || 5000);
796
+ setTimeout(function () { live.textContent = t.firstChild.textContent; }, 100);
797
+ return t;
798
+ }
799
+
800
+ /* ---------- long author lists ---------- */
801
+ var auToggle = document.getElementById("au-toggle");
802
+ var auRest = document.getElementById("au-rest");
803
+ if (auToggle && auRest) auToggle.addEventListener("click", function () {
804
+ var open = auToggle.getAttribute("aria-expanded") !== "true";
805
+ auToggle.setAttribute("aria-expanded", String(open));
806
+ auRest.hidden = !open;
807
+ auToggle.querySelector(".au-label").textContent = open ? "Show fewer" : auToggle.getAttribute("data-more");
808
+ measure(); update();
809
+ });
810
+
811
+ /* ---------- finished marker ---------- */
812
+ var doneBtn = document.getElementById("mark-done");
813
+ function showDone() {
814
+ var st = load("litreader.status." + pid, {});
815
+ if (doneBtn) doneBtn.textContent = st.state === "done" ? "Finished ✓ (click to undo)" : "Mark as finished";
816
+ }
817
+ if (doneBtn) doneBtn.addEventListener("click", function () {
818
+ var st = load("litreader.status." + pid, {});
819
+ st.state = st.state === "done" ? "started" : "done"; save("litreader.status." + pid, st); showDone();
820
+ toast(st.state === "done" ? "<span>Marked as finished. It shows on the list of papers.</span>"
821
+ : "<span>No longer marked as finished.</span>", 3000);
822
+ });
823
+
824
+ /* ---------- back to the paper you came from ----------
825
+ Following a reference to another paper of the bundle leaves a note in
826
+ this tab, so that paper's bar can offer the way back to the citation. */
827
+ var FROM_KEY = "litreader.from";
828
+ function fileName(href) { return decodeURIComponent((href || "").split(/[?#]/)[0].split("/").pop()); }
829
+ document.addEventListener("click", function (e) {
830
+ var a = e.target.closest && e.target.closest(".in-bundle a");
831
+ if (!a || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button) return; // opening elsewhere leaves this tab where it is
832
+ var at = card && card.contains(a) && cardFrom ? cardFrom.closest("main [data-w]") : null; // the paragraph with the citation
833
+ var block = at ? at.id : (latest && latest.id) || "";
834
+ try { sessionStorage.setItem(FROM_KEY, JSON.stringify({ to: fileName(a.getAttribute("href")), back: fileName(location.pathname),
835
+ block: block, label: cite })); } catch (err) {}
836
+ }, true);
837
+ (function offerWayBack() {
838
+ var from = null;
839
+ try { from = JSON.parse(sessionStorage.getItem(FROM_KEY) || "null"); sessionStorage.removeItem(FROM_KEY); } catch (err) {}
840
+ if (!from || from.to !== fileName(location.pathname) || !from.back || !/^[\w.-]+\.html$/.test(from.back)) return;
841
+ var a = document.createElement("a");
842
+ a.className = "btn back-from";
843
+ a.href = from.back + (from.block && /^[\w-]+$/.test(from.block) ? "#" + from.block : "");
844
+ a.setAttribute("aria-label", "Back to " + (from.label || "the paper you came from"));
845
+ var arrow = document.createElement("span"); arrow.setAttribute("aria-hidden", "true"); arrow.textContent = "↩";
846
+ var lbl = document.createElement("span"); lbl.textContent = " " + (from.label || "Back");
847
+ a.appendChild(arrow); a.appendChild(lbl);
848
+ var bar = document.querySelector(".bar");
849
+ if (bar) bar.insertBefore(a, document.getElementById("toc-toggle"));
850
+ })();
851
+
852
+ /* ---------- on a phone, the top bar steps aside while you read on ----------
853
+ Scrolling down hides it; scrolling up, or reaching the top, brings it back.
854
+ Jumps the page makes itself, before you've touched it, don't count. */
855
+ (function barSteppingAside() {
856
+ var phoneNow = window.matchMedia ? matchMedia("(max-width: 600px)") : { matches: false };
857
+ var bar = document.querySelector(".bar"), lastY = window.scrollY, touched = false;
858
+ if (!bar) return;
859
+ ["touchstart", "wheel", "keydown", "mousedown"].forEach(function (t) {
860
+ window.addEventListener(t, function () { touched = true; }, { passive: true, once: true });
861
+ });
862
+ function show() { root.classList.remove("bar-away"); }
863
+ function busy() {
864
+ return (toc && toc.classList.contains("open")) || (panel && !panel.hidden) || (clipsPanel && !clipsPanel.hidden) || bar.contains(document.activeElement);
865
+ }
866
+ window.addEventListener("scroll", function () {
867
+ var y = window.scrollY;
868
+ if (!phoneNow.matches || !touched || y < 60 || busy()) { show(); lastY = y; return; }
869
+ if (y > lastY + 8) { root.classList.add("bar-away"); lastY = y; }
870
+ else if (y < lastY - 8) { show(); lastY = y; }
871
+ }, { passive: true });
872
+ bar.addEventListener("focusin", show);
873
+ })();
874
+
875
+ function start() {
876
+ measure(); showDone();
877
+ var st = load("litreader.status." + pid, {});
878
+ if (!location.hash && st.pos && st.pos !== (blocks[0] && blocks[0].id)) {
879
+ var el = document.getElementById(st.pos);
880
+ if (el) {
881
+ window.scrollTo(0, el.getBoundingClientRect().top + window.scrollY - Math.max(90, window.innerHeight * 0.3) + 1); // back on the line position is read from
882
+ el.classList.add("flash-block");
883
+ var t = toast("Resumed where you left off. <button type='button'>Back to the start</button>", 8000);
884
+ t.querySelector("button").addEventListener("click", function () { window.scrollTo(0, 0); t.remove(); });
885
+ }
886
+ }
887
+ resumed = true;
888
+ update();
889
+ }
890
+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(start); else window.addEventListener("load", start);
891
+ window.addEventListener("load", function () { measure(); update(); });
892
+ if (window.ResizeObserver) { // images and fonts move the text after the first measurement
893
+ var layoutTimer = null;
894
+ new ResizeObserver(function () {
895
+ clearTimeout(layoutTimer);
896
+ layoutTimer = setTimeout(function () { measure(); update(); }, 120);
897
+ }).observe(document.querySelector("main"));
898
+ }
899
+ })();