aboutsummaryrefslogtreecommitdiffstats
path: root/reader.html
blob: e38d2acd66203ed3b7cc21945be95b605a13cf6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
<!doctype html>
<!--
  book-reader: two-page image book viewer.
  Copyright (C) 2026 Danilo M. <danix@danix.xyz>
  SPDX-License-Identifier: GPL-2.0-only
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reader</title>
<style>
:root { --hud: 30px; --ar: .707; --dur: 650ms; --accent: #e8b86a; }
* { box-sizing: border-box; margin: 0; }
html, body { height: 100%; overflow: hidden; }
/* fit-width: pages span the screen, document scrolls vertically */
html.wide { overflow-y: auto; scrollbar-width: none; }
html.wide body { height: auto; min-height: 100%; overflow: visible; place-items: start center; }
body {
  background: #070607;
  color: #ddd; font: 14px/1.4 system-ui, sans-serif; user-select: none;
  display: grid; place-items: center; padding-bottom: var(--hud);   /* keep pages clear of the bar */
}
/* own fixed layer: stays put while scrolling, no repaint (unlike background-attachment: fixed) */
body::before {
  content: ""; position: fixed; inset: 0; z-index: -1;
  background: radial-gradient(ellipse at 50% 40%, #2a2522 0%, #121011 60%, #070607 100%);
}
#book {
  position: relative; display: flex; perspective: 2800px;
  filter: drop-shadow(0 30px 40px rgba(0,0,0,.6));
}
.page, #leaf { height: min(calc(100vh - var(--hud)), calc(50vw / var(--ar))); aspect-ratio: var(--ar); }
.wide .page, .wide #leaf { height: calc(50vw / var(--ar)); }
.page { position: relative; }
.page img, .face img { width: 100%; height: 100%; object-fit: contain; display: block; }
img:not([src]) { visibility: hidden; }
/* spine shading */
.page.left::after, .page.right::after { content: ""; position: absolute; inset: 0; pointer-events: none; }
.page.left::after { background: linear-gradient(to left, rgba(0,0,0,.35), transparent 6%); }
.page.right::after { background: linear-gradient(to right, rgba(0,0,0,.35), transparent 6%); }
#leaf {
  position: absolute; top: 0; transform-style: preserve-3d; visibility: hidden;
  will-change: transform;
}
.face { position: absolute; inset: 0; backface-visibility: hidden; }
.back { transform: rotateY(180deg); }
.shade { position: absolute; inset: 0; background: #000; opacity: 0; pointer-events: none; }

#hud {
  position: fixed; left: 0; right: 0; bottom: 0; height: var(--hud); z-index: 1;
  display: flex; gap: 12px; align-items: center; padding: 0 8px; font-size: 13px;
  background: rgba(14,12,13,.85); backdrop-filter: blur(8px); border-top: 1px solid rgba(255,255,255,.07);
}
body.idle { cursor: none; }
#title, #count { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#count { text-align: right; font-variant-numeric: tabular-nums; }
#bar { width: min(40vw, 480px); height: 4px; background: rgba(255,255,255,.12); border-radius: 2px; overflow: hidden; }
#fill { height: 100%; width: 0; background: var(--accent); transition: width .3s; }
button { background: none; border: 0; color: inherit; font: inherit; cursor: pointer; padding: 2px 6px; border-radius: 6px; }
button:hover, button:focus-visible { background: rgba(255,255,255,.1); outline: none; }

#shelf {
  position: fixed; inset: 0; padding: 6vh 6vw; overflow-y: auto;
  background: rgba(8,7,8,.88); backdrop-filter: blur(14px);
  opacity: 0; pointer-events: none; transition: opacity .25s;
}
#shelf.open { opacity: 1; pointer-events: auto; }
#top { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }
#top h1 { font-weight: 300; letter-spacing: .08em; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#back { font-size: 22px; }
#back[hidden] { display: none; }
#q { background: rgba(255,255,255,.08); border: 1px solid rgba(255,255,255,.12); color: inherit; font: inherit;
     padding: 6px 12px; border-radius: 999px; width: min(260px, 40vw); outline: none; }
#q:focus { border-color: var(--accent); }
#grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 28px; }
.card { text-align: left; padding: 0; transition: transform .2s; }
.card:hover, .card:focus-visible { transform: translateY(-4px); background: none; }
.card img { width: 100%; aspect-ratio: var(--ar); object-fit: cover; border-radius: 4px; box-shadow: 0 10px 25px rgba(0,0,0,.6); }
.card.current img { outline: 2px solid var(--accent); outline-offset: 3px; }
.card b { display: block; margin-top: 8px; font-weight: 500; }
.card small { color: #999; }
.card .p { height: 3px; background: rgba(255,255,255,.12); margin-top: 6px; }
.card .p i { display: block; height: 100%; background: var(--accent); }
#help { color: #888; margin-top: 30px; }
@media (prefers-reduced-motion: reduce) { :root { --dur: 0ms; } }
</style>
</head>
<body>
<div id="book">
  <div class="page left"><img alt=""></div>
  <div class="page right"><img alt=""></div>
  <div id="leaf">
    <div class="face front"><img alt=""><i class="shade"></i></div>
    <div class="face back"><img alt=""><i class="shade"></i></div>
  </div>
</div>

<div id="hud">
  <button id="books" title="Books (B)">☰</button>
  <span id="title"></span>
  <div id="bar"><div id="fill"></div></div>
  <span id="count"></span>
  <button id="fit" title="Fit width / height (W)">↔</button>
  <button id="fs" title="Fullscreen (F)">⛶</button>
</div>

<div id="shelf">
  <div id="top">
    <button id="back" title="Back (Esc)" hidden>←</button>
    <h1 id="where">Library</h1>
    <input id="q" type="search" placeholder="Search  /" aria-label="Search">
  </div>
  <div id="grid"></div>
  <p id="help">→ / Space / PgDn / wheel down: next · ← / PgUp / wheel up: previous · Home / End ·
    W: fit width / height (wheel and ↑↓ scroll, flip at page end) · C: toggle cover offset · F: fullscreen · B: library (/ search, Esc back) · click left/right half to flip</p>
</div>

<script>
const $ = s => document.querySelector(s);
const IMG = /\.(jpe?g|png|webp|gif|avif)$/i;
const coll = new Intl.Collator(undefined, { numeric: true });
const dec = s => decodeURIComponent(s);

let store = { pos: {}, last: null, cover: true, wide: false };
try { Object.assign(store, JSON.parse(localStorage.getItem('reader')) || {}); } catch {}
const save = () => { try { localStorage.setItem('reader', JSON.stringify(store)); } catch {} };

let books = [], book = null, s = 0, cur = null;
const L = $('.left img'), R = $('.right img'), leaf = $('#leaf');
const F = $('.front img'), B = $('.back img'), shades = document.querySelectorAll('.shade');

// Every directory holding images is a book, named after its folder; the first-level folder
// under the library is its series. Needs a server that lists dirs (rc.book-reader).
const ROOT = 'library/';
async function walk(path) {
  const html = await (await fetch(path)).text();
  const hrefs = [...new DOMParser().parseFromString(html, 'text/html').querySelectorAll('a[href]')]
    .map(a => a.getAttribute('href')).filter(h => !/^([?\/#]|\.\.|[a-z]+:)/i.test(h));
  const pages = hrefs.filter(h => IMG.test(h)).sort((a, b) => coll.compare(dec(a), dec(b))).map(h => path + h);
  const id = path.slice(ROOT.length), seg = id.split('/').filter(Boolean).map(dec);   // id: stable across LIBRARY moves
  const out = pages.length ? [{ id, name: seg.at(-1) || 'Library', series: seg[0] || 'Library', pages }] : [];
  const dirs = hrefs.filter(h => h.endsWith('/')).sort((a, b) => coll.compare(dec(a), dec(b)));
  return out.concat(...await Promise.all(dirs.map(d => walk(path + d))));
}
// series in library order, main book (the series folder itself) first since walk lists parents first
const seriesList = () => [...Map.groupBy(books, b => b.series)].map(([name, list]) => ({ name, books: list }));

const align = i => i - ((i + (store.cover ? 1 : 0)) % 2);   // left index of spread containing page i (may be -1)
const src = (img, i) => book.pages[i] ? img.src = book.pages[i] : img.removeAttribute('src');
const first = () => store.cover ? -1 : 0;

function show() {
  src(L, s); src(R, s + 1);
  const n = book.pages.length, a = Math.max(s, 0) + 1, b = Math.min(s + 2, n);
  $('#title').textContent = book.name === book.series ? book.name : `${book.series} / ${book.name}`;
  $('#count').textContent = (a === b ? `page ${a}` : `pages ${a}–${b}`) + ` of ${n}`;
  $('#fill').style.width = (b / n * 100) + '%';
  store.pos[book.id] = Math.max(s, 0); store.last = book.id; save();
  for (let i = s - 2; i < s + 6; i++) if (book.pages[i]) new Image().src = book.pages[i]; // preload
}

function finish() { if (cur) { cur.forEach(a => a.cancel()); cur = null; leaf.style.visibility = 'hidden'; show(); } }

function go(t) {
  finish();
  t = Math.max(first(), Math.min(align(t), align(book.pages.length - 1)));
  if (t === s) return;
  const fwd = t > s, old = s; s = t;
  scrollTo(0, fwd ? 0 : document.documentElement.scrollHeight);   // back: land at the bottom of the spread
  // base shows the halves that stay put during the turn; the leaf carries the turning page
  if (fwd) { src(R, t + 1); src(F, old + 1); src(B, t); }
  else     { src(L, t);     src(F, old);     src(B, t + 1); }
  Object.assign(leaf.style, { left: fwd ? '50%' : '0', transformOrigin: fwd ? 'left' : 'right', visibility: 'visible' });
  const opt = { duration: parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--dur')) || 0,
                easing: 'cubic-bezier(.645,.045,.355,1)', fill: 'forwards' };
  cur = [
    leaf.animate([{ transform: 'rotateY(0)' }, { transform: `rotateY(${fwd ? -180 : 180}deg)` }], opt),
    shades[0].animate([{ opacity: 0 }, { opacity: .5 }], opt),
    shades[1].animate([{ opacity: .5 }, { opacity: 0 }], opt),
  ];
  cur[0].onfinish = finish;
}

function open(b) {
  finish(); book = b; $('#shelf').classList.remove('open');
  const probe = new Image();
  probe.onload = () => document.documentElement.style.setProperty('--ar', probe.naturalWidth / probe.naturalHeight);
  probe.src = b.pages[0];
  s = align(store.pos[b.id] ?? 0); show();
}

const read = b => store.pos[b.id] == null ? 0 : Math.min(store.pos[b.id] + 2, b.pages.length);

function card(cover, title, sub, pct, current, onclick) {
  const c = document.createElement('button'), img = new Image(), name = document.createElement('b'),
        sm = document.createElement('small'), p = document.createElement('div'), pi = document.createElement('i');
  c.className = 'card' + (current ? ' current' : '');
  img.loading = 'lazy'; img.src = cover; img.alt = '';
  name.textContent = title; sm.textContent = sub;
  p.className = 'p'; pi.style.width = pct * 100 + '%';
  p.append(pi); c.append(img, name, sm, p); c.onclick = onclick; c.dataset.name = title.toLowerCase();
  return c;
}

let view = null;   // null: series grid; else the series being browsed
function shelf(v = view) {
  view = v;
  const g = $('#grid'), q = $('#q');
  g.replaceChildren(...(v ? v.books.map(b => card(b.pages[0], b.name,
      `${b.pages.length} pages` + (read(b) ? ` · at ${read(b)}` : ''), read(b) / b.pages.length, b === book, () => open(b)))
    : seriesList().map(sr => {
      const n = sr.books.reduce((a, b) => a + b.pages.length, 0), r = sr.books.reduce((a, b) => a + read(b), 0);
      return card(sr.books[0].pages[0], sr.name,
        (sr.books.length > 1 ? `${sr.books.length} books · ` : '') + `${n} pages`, r / n, book?.series === sr.name,
        () => sr.books.length > 1 ? shelf(sr) : open(sr.books[0]));
    })));
  $('#where').textContent = v ? v.name : 'Library';
  $('#back').hidden = !v;
  q.value = ''; filter();
  $('#shelf').classList.add('open');
  (g.querySelector('.current') || g.firstChild)?.focus();
}
function filter() {
  const t = $('#q').value.trim().toLowerCase();
  for (const c of $('#grid').children) c.hidden = !c.dataset.name.includes(t);
}
$('#q').oninput = filter;
$('#back').onclick = () => shelf(null);

const toggleShelf = () => $('#shelf').classList.contains('open') ? book && $('#shelf').classList.remove('open')
  : shelf(book && seriesList().find(sr => sr.name === book.series && sr.books.length > 1) || null);
// Esc: series -> library grid -> back to the open book
const shelfBack = () => view ? shelf(null) : toggleShelf();
const fullscreen = () => document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen();

addEventListener('keydown', e => {
  if (e.ctrlKey || e.metaKey || e.altKey) return;
  if (e.target === $('#q')) { if (e.key === 'Escape') { e.target.value ? (e.target.value = '', filter()) : e.target.blur(); } return; }
  if ($('#shelf').classList.contains('open')) {
    if (e.key === 'Escape' || e.key === 'Backspace') shelfBack();
    else if (e.key === 'b') toggleShelf();
    else if (e.key === '/') { e.preventDefault(); $('#q').focus(); }
    return;
  }
  const k = e.key, act = {
    ArrowRight: () => go(s + 2), PageDown: () => page(1), ' ': () => page(e.shiftKey ? -1 : 1), l: () => go(s + 2),
    ArrowLeft: () => go(s - 2), PageUp: () => page(-1), Backspace: () => go(s - 2), h: () => go(s - 2),
    Home: () => go(first()), End: () => go(book.pages.length - 1),
    c: () => { finish(); store.cover = !store.cover; s = align(Math.max(s, 0)); show(); },
    f: fullscreen, b: toggleShelf, w: fit,
  }[k];
  if (act) { e.preventDefault(); act(); }
});

const atEdge = d => d > 0 ? scrollY + innerHeight >= document.documentElement.scrollHeight - 2 : scrollY <= 0;
// fit-width: scroll a screen, flip only once the end of the spread is on screen
function page(d) {
  if (store.wide && !atEdge(d)) scrollBy({ top: d * innerHeight * .85, behavior: 'smooth' });
  else go(s + 2 * d);
}
function fit() {
  store.wide = !store.wide; save();
  document.documentElement.classList.toggle('wide', store.wide); scrollTo(0, 0);
}
document.documentElement.classList.toggle('wide', store.wide);

let lastWheel = 0, lastScroll = 0;
addEventListener('scroll', () => lastScroll = performance.now());
addEventListener('wheel', e => {
  if ($('#shelf').classList.contains('open') || !book) return;
  const now = performance.now();
  // fit-width: native scroll; flip needs a fresh push after the edge was reached (stops momentum from flipping)
  if (store.wide && (!atEdge(e.deltaY) || now - lastScroll < 400)) return;
  e.preventDefault();
  if (now - lastWheel < 350 || Math.abs(e.deltaY) < 4) return;   // ponytail: fixed throttle tames touchpad bursts
  lastWheel = now; go(s + (e.deltaY > 0 ? 2 : -2));
}, { passive: false });

$('#book').onclick = e => go(s + (e.clientX > innerWidth / 2 ? 2 : -2));
$('#books').onclick = toggleShelf; $('#fs').onclick = fullscreen; $('#fit').onclick = fit;

let idle;
addEventListener('mousemove', () => {
  document.body.classList.remove('idle'); clearTimeout(idle);
  idle = setTimeout(() => document.body.classList.add('idle'), 2500);
});

walk(ROOT).then(b => {
  books = b;
  if (!books.length) return $('#title').textContent = 'No images found under the library directory';
  open(books.find(x => x.id === store.last) || books[0]);
}).catch(() => $('#title').textContent = 'Directory listing failed: start rc.book-reader and open its URL, not file://');
</script>
</body>
</html>