forked from johnfactotum/foliate-js
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathfixed-layout.js
More file actions
1826 lines (1744 loc) · 79.2 KB
/
Copy pathfixed-layout.js
File metadata and controls
1826 lines (1744 loc) · 79.2 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'construct-style-sheets-polyfill'
const parseViewport = str => str
?.split(/[,;\s]/) // NOTE: technically, only the comma is valid
?.filter(x => x)
?.map(x => x.split('=').map(x => x.trim()))
export const getViewport = (doc, viewport) => {
// use `viewBox` for SVG
if (doc.documentElement.localName === 'svg') {
const [, , width, height] = doc.documentElement
.getAttribute('viewBox')?.split(/\s/) ?? []
return { width, height }
}
// get `viewport` `meta` element
const meta = parseViewport(doc.querySelector('meta[name="viewport"]')
?.getAttribute('content'))
if (meta) {
const props = Object.fromEntries(meta)
// A bitmap spine item is loaded as the browser's own image document,
// whose synthetic meta (`width=device-width, minimum-scale=0.1`) has no
// page size; only a numeric width and height describe a fixed page
if (parseFloat(props.width) > 0 && parseFloat(props.height) > 0) return props
}
// fallback to book's viewport
if (typeof viewport === 'string') return parseViewport(viewport)
if (viewport?.width && viewport.height) return viewport
// if no viewport (possibly with image directly in spine), get image size
const img = doc.querySelector('img')
if (img) return { width: img.naturalWidth, height: img.naturalHeight }
// just show *something*, i guess...
console.warn(new Error('Missing viewport properties'))
return { width: 1000, height: 2000 }
}
const clamp = (value, min, max) => Math.min(max, Math.max(min, value))
export const captureScrollModeAnchor = (pages, scrollPos, fallbackIndex = -1) => {
const fallbackPage = pages.find(page => page.index === fallbackIndex)
const currentPage = pages.find(page =>
page.size > 0
&& scrollPos >= page.start
&& scrollPos < page.start + page.size)
?? fallbackPage
?? pages.find(page => page.size > 0)
if (!currentPage) return null
return {
index: currentPage.index,
fraction: currentPage.size > 0
? clamp((scrollPos - currentPage.start) / currentPage.size, 0, 1)
: 0,
scrollPos,
}
}
export const restoreScrollModeAnchor = (pages, anchor, maxScrollPos) => {
if (!anchor) return 0
const page = pages.find(candidate => candidate.index === anchor.index)
if (!page || page.size <= 0) return clamp(anchor.scrollPos, 0, maxScrollPos)
return clamp(page.start + page.size * anchor.fraction, 0, maxScrollPos)
}
export const scrollGapToCss = (value) => {
const n = parseFloat(value)
return Number.isFinite(n) && n >= 0 ? `${n}px` : null
}
// Decide which scroll-mode pages to begin loading and which to evict, given the
// reader's current page and each page's load state. `visible` is set by the
// IntersectionObserver (true while the page sits within the widened preload
// margin). Visible idle pages closest to the reader load first, bounded by how
// many loads may run at once; loaded pages farthest from the reader are evicted
// once over the in-memory cap, but a visible page is never torn out from under
// the reader. Prioritising the nearest page and bounding concurrency keeps a
// fast fling from kicking off a full-resolution canvas render for every page it
// flies past — that thrashes the main thread and spikes WebView memory
// (readest#4795), the same pressure the PDF range-read throttle guards against
// (readest#3470).
export const planScrollModePages = ({
pages, currentIndex, maxLoaded, maxConcurrent, loadingCount,
}) => {
const dist = page => Math.abs(page.index - currentIndex)
const budget = Math.max(0, maxConcurrent - loadingCount)
const load = budget === 0 ? [] : pages
.filter(page => page.visible && page.state === 'idle')
.sort((a, b) => dist(a) - dist(b))
.slice(0, budget)
.map(page => page.index)
const loaded = pages.filter(page => page.state === 'loaded')
const evict = loaded.length <= maxLoaded ? [] : loaded
.filter(page => !page.visible)
.sort((a, b) => dist(b) - dist(a))
.slice(0, loaded.length - maxLoaded)
.map(page => page.index)
return { load, evict }
}
// Live CSS transform for a scroll-mode pinch gesture. Scroll mode has no single
// spread frame to scale, so the whole scroll container is scaled for immediate
// visual feedback while the fingers move (instead of only re-rendering on
// release). The scale is anchored at the centre of the viewport (in the
// container's coordinate space); the post-pinch re-render then scrolls the
// centre page back to the rect it occupied in this preview (see
// #restorePinchAnchor), so the committed zoom lands without a jump.
export const computeScrollPinchTransform = ({
ratio, scrollLeft, scrollTop, viewportWidth, viewportHeight,
}) => ({
transform: `scale(${ratio})`,
transformOrigin: `${scrollLeft + viewportWidth / 2}px ${scrollTop + viewportHeight / 2}px`,
})
// Scroll offsets to apply to the host (`overflow:auto`) after rendering a
// paginated page. Horizontal is always re-centered so the page sits in the
// middle of the viewport. Vertical is reset to the top only on a page turn:
// a tall fit-width page overflows the host vertically, and without the reset the
// freshly-shown page inherits the previous page's offset and opens scrolled to
// the bottom (#4683). Plain re-renders (resize, zoom, theme) keep the reader's
// current vertical position within the page.
export const computePaginatedScroll = ({ elementWidth, containerWidth, scrollTop, pageTurn }) => ({
scrollLeft: (elementWidth - containerWidth) / 2,
scrollTop: pageTurn ? 0 : scrollTop,
})
// Translate a vertical wheel tick into a horizontal scroll delta for
// horizontal scroll mode (pdf.js behavior, readest#4995). Returns null when
// the tick belongs to native scrolling instead: vertical mode, pinch zoom
// (ctrl+wheel), horizontal-dominant trackpad pans, or a strip with vertical
// overflow to consume (a zoomed page pans vertically first). Translating is
// safe with respect to the readest#4727 double-scroll: with no vertical
// overflow the browser cannot natively consume a vertical delta, so the
// translated scroll cannot stack on a native one.
export const computeScrollWheelDelta = ({
deltaX, deltaY, ctrlKey, horizontal, rtl, verticalOverflow,
}) => {
if (!horizontal || ctrlKey || verticalOverflow) return null
if (Math.abs(deltaY) <= Math.abs(deltaX)) return null
return { left: rtl ? -deltaY : deltaY }
}
// Visual shift (CSS px) to apply to the right page of a two-page spread to hide
// the one-pixel white spine seam (#4857). The two page iframes are independent
// compositor layers, each scaled by a (usually non-integer) factor. At a
// fractional devicePixelRatio the spine between them lands on a fractional
// device pixel, so each layer's edge there is anti-aliased against transparency
// and the reader background bleeds through as a thin white seam. Pulling the
// top-most (right) page onto the left by exactly one device pixel makes each
// soft edge sit over the neighbour's opaque content instead of the background.
// Returns 0 for layouts with no touching spine (single/centred/portrait page or
// a blank-padded slot). The pages stay adjacent at every zoom, so the overlap
// applies at sub-100% zoom too.
export const computeSpreadSpineOverlap = ({
center = false, portrait = false, leftBlank = false, rightBlank = false,
devicePixelRatio = 1,
} = {}) => {
if (center || portrait || leftBlank || rightBlank) return 0
return -1 / (devicePixelRatio || 1)
}
// Inline margins for the two pages of a spread. In landscape both pages are
// shown and pushed together at the spine: the left page hugs the right edge
// (`margin-inline-start: auto`) and the right page hugs the left edge
// (`margin-inline-end: auto`), so the pair sits centred. In portrait only one
// page of the spread is shown; a one-sided auto margin would strand that lone
// page in one half of the viewport whenever it is narrower than the viewport
// (readest#4984), so both margins are auto to centre it. Both inline margins are
// always set explicitly (the opposite side cleared to '') so a re-render after
// an orientation change fully overwrites the previous layout's margins — frames
// are re-styled in place, not recreated, on rotation.
export const computeSpreadInlineMargins = (portrait) => portrait
? {
left: { marginInlineStart: 'auto', marginInlineEnd: 'auto' },
right: { marginInlineStart: 'auto', marginInlineEnd: 'auto' },
}
: {
left: { marginInlineStart: 'auto', marginInlineEnd: '' },
right: { marginInlineStart: '', marginInlineEnd: 'auto' },
}
// Align the SVG overlayer's coord system with the iframe's unscaled content.
// When the iframe is visually scaled via CSS transform (non-PDF path),
// getClientRects() inside the iframe returns positions in the iframe's native
// coord system, so the SVG must use a matching viewBox to scale rects to the
// on-screen size. PDFs re-render their text layer at scale via onZoom, so
// rects are already in scaled coords and no viewBox is needed.
export const applyOverlayerViewBox = (frame, overlayer) => {
if (!overlayer?.element) return
const el = overlayer.element
if (frame?.onZoom) {
el.removeAttribute('viewBox')
el.removeAttribute('preserveAspectRatio')
} else {
const w = frame?.width ?? frame?.vpWidth
const h = frame?.height ?? frame?.vpHeight
if (w && h) {
el.setAttribute('viewBox', `0 0 ${w} ${h}`)
el.setAttribute('preserveAspectRatio', 'none')
}
}
}
export class FixedLayout extends HTMLElement {
static observedAttributes = ['zoom', 'scale-factor', 'spread', 'flow', 'scroll-gap', 'scroll-direction']
#root = this.attachShadow({ mode: 'open' })
#observer = new ResizeObserver(() => this.#render())
#spreads
#index = -1
defaultViewport
spread
#portrait = false
#left
#right
#center
#side
#zoom
#scaleFactor = 1.0
#totalScaleFactor = 1.0
#scrollLocked = false
#isOverflowX = false
#isOverflowY = false
#preloadCache = new Map()
#prerenderedSpreads = new Map()
#spreadAccessTime = new Map()
#maxConcurrentPreloads = 1
#numPrerenderedSpreads = 1
#maxCachedSpreads = 2
#overlayers = new Map()
#pageColors = {}
#preloadQueue = []
#activePreloads = 0
// Scroll mode fields
#scrollMode = false
#scrollHorizontal = false
#scrollPages = []
#scrollObserver = null
#scrollContainer = null
#scrollLoadGen = new Map()
// Live rendered-canvas cap. Each PDF page canvas is sized to the on-screen
// page box × devicePixelRatio (~7 MB at dpr 3), so this is the dominant
// memory ceiling — keep it just above the visible window plus preload lead.
#scrollMaxLoaded = 12
// Cap on concurrent page loads. A fast fling crosses many pages; without a
// bound it would start a full-resolution render for every one, thrashing the
// main thread and spiking memory. Nearest-to-viewport pages load first.
#scrollMaxConcurrent = 3
#scrollLoadingCount = 0
#scrollIdleTimer = null
#scrollCurrentIndex = -1
// True while the host is actively scrolling. Pages load interactive only
// when idle so a page that finishes loading mid-scroll can't flip its iframe
// interactive and let its own pointer handlers hijack the native scroll.
#scrolling = false
// True while a pinch gesture is live. Suppresses page load/eviction so the
// placeholder layout (and thus scrollTop) can't drift mid-pinch, which would
// make the live preview and the committed zoom land in different places.
#pinching = false
// On-screen rect of the page under the viewport centre, captured from the
// live (still-transformed) preview at pinch end ({ index, top, left }). The
// commit re-render scrolls that page back to this exact rect, so the zoom
// lands where the preview showed it. Using the real getBoundingClientRect
// (not fraction maths) sidesteps gap/page-boundary and header-offset errors.
#pinchAnchor = null
#captureCenterPageRect() {
const hostRect = this.getBoundingClientRect()
const c = this.#scrollHorizontal
? hostRect.left + this.clientWidth / 2
: hostRect.top + this.clientHeight / 2
for (const page of this.#scrollPages) {
const rect = page.el.getBoundingClientRect()
const lo = this.#scrollHorizontal ? rect.left : rect.top
const hi = this.#scrollHorizontal ? rect.right : rect.bottom
if (lo <= c && hi > c) {
return { index: page.index, top: rect.top, left: rect.left }
}
}
return null
}
// Scroll so the captured page sits back at its pre-commit on-screen rect.
#restorePinchAnchor(anchor) {
const page = this.#scrollPages.find(p => p.index === anchor.index)
if (!page) return
const rect = page.el.getBoundingClientRect()
const maxTop = Math.max(0, this.scrollHeight - this.clientHeight)
const maxLeft = Math.max(0, this.scrollWidth - this.clientWidth)
this.scrollTop = clamp(this.scrollTop + (rect.top - anchor.top), 0, maxTop)
this.scrollLeft = clamp(this.scrollLeft + (rect.left - anchor.left), 0, maxLeft)
}
#getScrollModePageMetrics() {
return this.#scrollPages.map(page => ({
index: page.index,
start: this.#scrollHorizontal ? page.el.offsetLeft : page.el.offsetTop,
size: this.#scrollHorizontal ? page.el.offsetWidth : page.el.offsetHeight,
}))
}
#captureScrollModeAnchor() {
if (!this.#scrollPages.length) return null
const fallbackIndex = this.#scrollCurrentIndex >= 0
? this.#scrollCurrentIndex : this.#getScrollIndex()
return captureScrollModeAnchor(
this.#getScrollModePageMetrics(),
this.#scrollContentPos(),
fallbackIndex,
)
}
#restoreScrollModeAnchor(anchor) {
if (!anchor || !this.#scrollPages.length) return
const maxScrollPos = Math.max(0, this.#scrollTotalLength() - this.#scrollViewLength())
const restoredPos = restoreScrollModeAnchor(
this.#getScrollModePageMetrics(),
anchor,
maxScrollPos,
)
// Only write when the position actually moves. Assigning scrollLeft/Top
// unconditionally aborts any in-progress `behavior: 'smooth'` scroll
// (e.g. a next()/prev() page turn) even when the value lands on the
// exact spot the animation is already at — and #render()'s mandatory
// initial ResizeObserver callback can land in the same tick as a page
// turn requested right after open(), silently freezing it.
if (Math.abs(restoredPos - this.#scrollContentPos()) > 0.5) {
this.#setScrollContentPos(restoredPos)
}
this.#scrollCurrentIndex = anchor.index
}
// Length of the viewport along the scroll axis.
#scrollViewLength() {
return this.#scrollHorizontal ? this.clientWidth : this.clientHeight
}
// Total scrollable length along the scroll axis.
#scrollTotalLength() {
return this.#scrollHorizontal ? this.scrollWidth : this.scrollHeight
}
// Position of the viewport's leading edge in content coordinates (0 = the
// content's top/left edge). RTL horizontal scrolls into negative
// scrollLeft (direction: rtl container), so shift by the max offset to
// stay in the same coordinate space as offsetLeft page metrics.
#scrollContentPos() {
if (!this.#scrollHorizontal) return this.scrollTop
return this.rtl
? this.scrollWidth - this.clientWidth + this.scrollLeft
: this.scrollLeft
}
#setScrollContentPos(pos) {
if (!this.#scrollHorizontal) {
this.scrollTop = pos
return
}
this.scrollLeft = this.rtl ? pos - (this.scrollWidth - this.clientWidth) : pos
}
// Distance read from the book start along the reading direction. Equals
// content position except for RTL horizontal, where reading starts at the
// right edge and progresses into negative scrollLeft.
#scrollProgression() {
if (!this.#scrollHorizontal) return this.scrollTop
return this.rtl ? -this.scrollLeft : this.scrollLeft
}
constructor() {
super()
const sheet = new CSSStyleSheet()
this.#root.adoptedStyleSheets = [sheet]
sheet.replaceSync(`:host {
width: 100%;
height: 100%;
display: flex;
justify-content: flex-start;
align-items: center;
overflow: auto;
}
@supports (justify-content: safe center) {
:host {
justify-content: safe center;
}
}
:host([flow="scrolled"]) {
display: block;
overflow-y: auto;
/* auto (not hidden) so a zoomed page wider than the viewport can be
panned horizontally; collapses to no scrollbar when pages fit. */
overflow-x: auto;
/* Keep one-finger pan (native scroll) but reserve two-finger
gestures for JS so a pinch is delivered instead of triggering the
browser's own pinch-zoom or being swallowed by the scroller. */
touch-action: pan-x pan-y;
}
:host([flow="scrolled"]) .scroll-page {
touch-action: pan-x pan-y;
}
:host([flow="scrolled"]) .scroll-container {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100%;
/* Grow to the widest (zoomed) page so the host can scroll across its
full width, but stay at least viewport-wide so unzoomed pages stay
centered. Without max-content the centered overflow is unreachable
(the flexbox centered-overflow scroll trap). */
width: max-content;
min-width: 100%;
background-color: var(--scroll-bg-color);
background-opacity: var(--scroll-bg-opacity);
}
:host([flow="scrolled"]) .scroll-page {
position: relative;
flex-shrink: 0;
overflow: hidden;
/* Scale the gap with the zoom so the committed layout matches the
pinch preview, whose transform scales the whole container (gaps
included). Without this the gap snaps back to a fixed px on
release and the pages shift. */
margin: calc(var(--scroll-page-gap, 4px) * var(--scroll-zoom, 1)) 0;
}
:host([flow="scrolled"]) .scroll-page iframe {
pointer-events: none;
}
:host([flow="scrolled"][scroll-direction="horizontal"]) .scroll-container {
flex-direction: row;
height: max-content;
min-height: 100%;
}
:host([flow="scrolled"][scroll-direction="horizontal"]) .scroll-page {
margin: 0 calc(var(--scroll-page-gap, 4px) * var(--scroll-zoom, 1));
}`)
this.#observer.observe(this)
}
attributeChangedCallback(name, _, value) {
switch (name) {
case 'zoom':
this.#zoom = value !== 'fit-width' && value !== 'fit-page'
? parseFloat(value) : value
this.#render()
break
case 'scale-factor':
this.#scaleFactor = parseFloat(value) / 100
this.#render()
break
case 'spread':
this.#respread(value)
break
case 'flow':
if (value === 'scrolled' && !this.#scrollMode) {
// Capture index from paginated mode BEFORE setting scroll flag
const savedIndex = this.index
this.#scrollMode = true
if (this.book) this.#initScrollMode(savedIndex)
} else if (value !== 'scrolled' && this.#scrollMode) {
this.#destroyScrollMode()
this.#scrollMode = false
this.#render()
}
break
case 'scroll-gap': {
const css = scrollGapToCss(value)
const anchor = this.#scrollMode ? this.#captureScrollModeAnchor() : null
if (css === null) this.style.removeProperty('--scroll-page-gap')
else this.style.setProperty('--scroll-page-gap', css)
if (anchor) this.#restoreScrollModeAnchor(anchor)
break
}
case 'scroll-direction': {
const horizontal = value === 'horizontal'
if (horizontal === this.#scrollHorizontal) break
this.#scrollHorizontal = horizontal
if (this.#scrollMode && this.book) {
// Rebuild the strip on the new axis, preserving the page.
const savedIndex = this.#scrollCurrentIndex >= 0 ? this.#scrollCurrentIndex : 0
this.#destroyScrollMode(false)
this.#initScrollMode(savedIndex)
}
break
}
}
}
async #createFrame({ index, src: srcOption, detached = false }) {
const srcOptionIsString = typeof srcOption === 'string'
const src = srcOptionIsString ? srcOption : srcOption?.src
const data = srcOptionIsString ? null : srcOption?.data
const onZoom = srcOptionIsString ? null : srcOption?.onZoom
const element = document.createElement('div')
element.setAttribute('dir', 'ltr')
element.style.position = 'relative'
const iframe = document.createElement('iframe')
element.append(iframe)
Object.assign(iframe.style, {
border: '0',
display: 'none',
overflow: 'hidden',
})
// `allow-scripts` is needed for events because of WebKit bug
// https://bugs.webkit.org/show_bug.cgi?id=218086
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
iframe.setAttribute('scrolling', 'no')
iframe.setAttribute('part', 'filter')
this.#root.append(element)
if (detached) {
Object.assign(element.style, {
position: 'absolute',
visibility: 'hidden',
pointerEvents: 'none',
})
}
if (!src) return { blank: true, element, iframe }
return new Promise(resolve => {
iframe.addEventListener('load', () => {
const doc = iframe.contentDocument
iframe.dataset.sectionIndex = index
this.dispatchEvent(new CustomEvent('load', { detail: { doc, index } }))
const { width, height } = getViewport(doc, this.defaultViewport)
resolve({
element, iframe,
width: parseFloat(width),
height: parseFloat(height),
onZoom,
detached,
})
}, { once: true })
if (data) {
iframe.srcdoc = data
} else {
iframe.src = src
}
})
}
#render(side = this.#side, pageTurn = false) {
if (this.#scrollMode) {
this.#renderScrollMode()
return []
}
if (!side) return []
const left = this.#left ?? {}
const right = this.#center ?? this.#right ?? {}
const target = side === 'left' ? left : right
const { width, height } = this.getBoundingClientRect()
// for unfolded devices with slightly taller height than width also use landscape layout
const portrait = this.spread !== 'both' && this.spread !== 'portrait'
&& height > width * 1.2
this.#portrait = portrait
const blankWidth = left.width ?? right.width ?? 0
const blankHeight = left.height ?? right.height ?? 0
let scale = typeof this.#zoom === 'number' && !isNaN(this.#zoom)
? this.#zoom
: (this.#zoom === 'fit-width'
? (portrait || this.#center
? width / (target.width ?? blankWidth)
: width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)))
: (portrait || this.#center
? Math.min(
width / (target.width ?? blankWidth),
height / (target.height ?? blankHeight))
: Math.min(
width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)),
height / Math.max(
left.height ?? blankHeight,
right.height ?? blankHeight)))
) || 1
scale *= this.#scaleFactor
this.#totalScaleFactor = scale
const renderPromises = []
const transform = ({frame, styles}) => {
let { element, iframe, width, height, blank, onZoom } = frame
if (!iframe) return
if (onZoom) {
const p = onZoom({ doc: frame.iframe.contentDocument, scale, pageColors: this.#pageColors })
if (p?.then) {
// onZoom (e.g. pdf.js) may rebuild the text layer DOM,
// invalidating Range objects stored in the overlayer. After
// the rebuild, re-emit create-overlayer so listeners can
// re-anchor annotations against the fresh DOM.
const refreshed = p.then(() => this.#refreshOverlayerForFrame(frame))
renderPromises.push(refreshed)
}
}
const iframeScale = onZoom ? scale : 1
const zoomedOut = this.#scaleFactor < 1.0
// Centering a zoomed-out page inside its box only works for the PDF
// path, whose iframe is natively sized to the (scaled) box. Non-PDF
// fixed layout keeps the iframe at its native size and shrinks it
// with `transform: scale`, so flex-centering the un-scaled iframe
// pushes it out of view and blanks the page (#4857). Keep those in
// normal block flow at every zoom.
const centerInBox = zoomedOut && onZoom
Object.assign(iframe.style, {
width: `${width * iframeScale}px`,
height: `${height * iframeScale}px`,
transform: onZoom ? 'none' : `scale(${scale})`,
transformOrigin: 'top left',
display: blank ? 'none' : 'block',
})
Object.assign(element.style, {
width: `${(width ?? blankWidth) * scale}px`,
height: `${(height ?? blankHeight) * scale}px`,
flexShrink: '0',
display: centerInBox ? 'flex' : 'block',
marginBlock: centerInBox ? undefined : 'auto',
alignItems: centerInBox ? 'center' : undefined,
justifyContent: centerInBox ? 'center' : undefined,
...styles,
})
if (portrait && frame !== target) {
element.style.display = 'none'
}
// position and redraw overlayer to match the scaled iframe
const sectionIndex = iframe.dataset.sectionIndex != null
? parseInt(iframe.dataset.sectionIndex) : undefined
if (sectionIndex != null) {
const overlayer = this.#overlayers.get(sectionIndex)
if (overlayer) {
Object.assign(overlayer.element.style, {
position: 'absolute',
top: '0',
left: '0',
width: `${(width ?? blankWidth) * scale}px`,
height: `${(height ?? blankHeight) * scale}px`,
})
applyOverlayerViewBox({
onZoom,
width: width ?? blankWidth,
height: height ?? blankHeight,
}, overlayer)
overlayer.redraw()
}
}
const container= element.parentNode?.host
if (!container) return
const containerWidth = container.clientWidth
const containerHeight = container.clientHeight
const { scrollLeft, scrollTop } = computePaginatedScroll({
elementWidth: element.clientWidth,
containerWidth,
scrollTop: container.scrollTop,
pageTurn,
})
container.scrollLeft = scrollLeft
container.scrollTop = scrollTop
return {
width: element.clientWidth,
height: element.clientHeight,
containerWidth,
containerHeight,
}
}
if (this.#center) {
const dimensions = transform({frame: this.#center, styles: { marginInline: 'auto' }})
if (!dimensions) return renderPromises
const {width, height, containerWidth, containerHeight} = dimensions
this.#isOverflowX = width > containerWidth
this.#isOverflowY = height > containerHeight
} else {
// Hide the 1px white spine seam on a two-page spread by overlapping
// the right page onto the left by one device pixel (#4857). Always
// set `transform` (to 'none' when not overlapping) so a stale shift
// from a previous render is cleared when the layout changes.
const overlapX = computeSpreadSpineOverlap({
portrait,
leftBlank: Boolean(left.blank),
rightBlank: Boolean(right.blank),
devicePixelRatio: window.devicePixelRatio || 1,
})
// In portrait only the target page is shown; centre it instead of
// hugging the spine, which would strand it in one half of the
// viewport (#4984).
const margins = computeSpreadInlineMargins(portrait)
const leftDimensions = transform({frame: left, styles: margins.left})
const rightDimensions = transform({frame: right, styles: {
...margins.right,
transform: overlapX ? `translateX(${overlapX}px)` : 'none',
}})
if (!leftDimensions || !rightDimensions) return renderPromises
const {width: leftWidth, height: leftHeight, containerWidth, containerHeight} = leftDimensions
const {width: rightWidth, height: rightHeight} = rightDimensions
this.#isOverflowX = leftWidth + rightWidth > containerWidth
this.#isOverflowY = Math.max(leftHeight, rightHeight) > containerHeight
}
// A pinch commit overrides the default re-centring above: scroll the
// spread back to the on-screen rect it occupied in the live preview so
// the zoom doesn't jump (matters most when the page was scrolled within
// an overflowing zoom). See pinchEnd.
if (this.#pinchAnchor) {
const frame = this.#center ?? this.#left ?? this.#right
if (frame?.element) {
const b = frame.element.getBoundingClientRect()
const maxTop = Math.max(0, this.scrollHeight - this.clientHeight)
const maxLeft = Math.max(0, this.scrollWidth - this.clientWidth)
this.scrollTop = clamp(this.scrollTop + (b.top - this.#pinchAnchor.top), 0, maxTop)
this.scrollLeft = clamp(this.scrollLeft + (b.left - this.#pinchAnchor.left), 0, maxLeft)
}
this.#pinchAnchor = null
}
return renderPromises
}
async #showSpread({ left, right, center, side, spreadIndex }) {
this.#left = null
this.#right = null
this.#center = null
const cacheKey = spreadIndex !== undefined ? `spread-${spreadIndex}` : null
const prerendered = cacheKey ? this.#prerenderedSpreads.get(cacheKey) : null
if (prerendered) {
this.#spreadAccessTime.set(cacheKey, Date.now())
if (prerendered.center) {
this.#center = prerendered.center
} else {
this.#left = prerendered.left
this.#right = prerendered.right
}
} else {
if (center) {
this.#center = await this.#createFrame(center)
if (cacheKey) {
this.#prerenderedSpreads.set(cacheKey, { center: this.#center })
this.#spreadAccessTime.set(cacheKey, Date.now())
}
} else {
this.#left = await this.#createFrame(left)
this.#right = await this.#createFrame(right)
if (cacheKey) {
this.#prerenderedSpreads.set(cacheKey, { left: this.#left, right: this.#right })
this.#spreadAccessTime.set(cacheKey, Date.now())
}
}
}
this.#side = center ? 'center' : this.#left?.blank ? 'right'
: this.#right?.blank ? 'left' : side
const visibleFrames = center
? [this.#center?.element]
: [this.#left?.element, this.#right?.element]
Array.from(this.#root.children).forEach(child => {
const isVisible = visibleFrames.includes(child)
Object.assign(child.style, {
position: isVisible ? 'relative' : 'absolute',
visibility: isVisible ? 'visible' : 'hidden',
pointerEvents: isVisible ? 'auto' : 'none',
})
})
// Render layout and await any async onZoom callbacks (e.g. PDF text
// layer rendering) so the document is fully populated before overlayers
// try to resolve CFIs against it. Pass pageTurn so a tall fit-width page
// starts at the top instead of inheriting the previous page's scroll.
const renderPromises = this.#render(this.#side, true)
if (renderPromises.length) await Promise.all(renderPromises)
const showingFrames = center
? [this.#center]
: [this.#left, this.#right]
for (const frame of showingFrames) {
if (!frame?.iframe) continue
const index = frame.iframe.dataset.sectionIndex != null
? parseInt(frame.iframe.dataset.sectionIndex) : undefined
if (index != null && !this.#overlayers.has(index)) {
const doc = frame.iframe.contentDocument
if (doc) {
this.dispatchEvent(new CustomEvent('create-overlayer', {
detail: {
doc, index,
attach: overlayer => {
this.#overlayers.set(index, overlayer)
frame.element.append(overlayer.element)
applyOverlayerViewBox(frame, overlayer)
},
},
}))
}
}
}
}
#initScrollMode(targetIndex = 0) {
const currentIndex = targetIndex
// Hide all paginated content
for (const child of Array.from(this.#root.children)) {
child.style.display = 'none'
}
this.#scrollContainer = document.createElement('div')
this.#scrollContainer.className = 'scroll-container'
this.#root.append(this.#scrollContainer)
// RTL books read right to left: direction rtl on the host (the
// scrolling element itself) is what puts scrollLeft into the browser's
// negative-scrollLeft RTL convention — that convention is keyed off the
// scrolling box's own computed direction, not a descendant's. It also
// lays the flex row from the right edge and makes the leftward overflow
// reachable (overflow only grows toward the inline-end side). The
// container inherits this. Page content stays LTR via the per-frame
// dir attribute.
this.style.direction = this.#scrollHorizontal && this.rtl ? 'rtl' : ''
const sections = this.book.sections
const viewport = this.defaultViewport
const vw = viewport?.width ?? 1000
const vh = viewport?.height ?? 1400
this.#scrollPages = sections.map((section, i) => {
const el = document.createElement('div')
el.className = 'scroll-page'
el.dataset.index = i
this.#scrollContainer.append(el)
return { el, index: i, section, state: 'idle', visible: false, frame: null, vpWidth: vw, vpHeight: vh }
})
this.#renderScrollMode()
// Scroll to target position BEFORE setting up the observer
// so only pages near the target are observed as intersecting
if (currentIndex >= 0 && currentIndex < this.#scrollPages.length) {
this.#scrollPages[currentIndex].el.scrollIntoView(
this.#scrollHorizontal ? { inline: 'start', block: 'nearest' } : undefined)
this.#scrollCurrentIndex = currentIndex
}
this.addEventListener('scroll', this.#handleScrollEvent)
if (this.#scrollHorizontal) {
// passive: false because a translated tick must preventDefault so the
// (no-op) native vertical scroll cannot also fire elastic overscroll.
this.addEventListener('wheel', this.#handleScrollWheel, { passive: false })
}
// Set up IntersectionObserver after scroll position is established.
// rootMargin '200%' marks pages within ~2 viewport heights above/below as
// visible, giving the ~400 ms-per-page render enough lead time to finish
// before the page scrolls into view. The observer only flags visibility;
// #scheduleScrollPages decides what to actually load (nearest first,
// bounded concurrency) and evict.
this.#scrollObserver = new IntersectionObserver(entries => {
for (const entry of entries) {
const index = parseInt(entry.target.dataset.index)
const pageData = this.#scrollPages[index]
if (pageData) pageData.visible = entry.isIntersecting
}
this.#scheduleScrollPages()
}, { root: this, rootMargin: this.#scrollHorizontal ? '0px 200%' : '200% 0px' })
for (const page of this.#scrollPages) {
this.#scrollObserver.observe(page.el)
}
}
// Load the nearest visible idle pages and evict the farthest off-screen ones,
// honouring the concurrency and in-memory caps. Re-run whenever visibility or
// load state changes so a finished load immediately pulls in the next page.
#scheduleScrollPages() {
// While pinching, loading/evicting pages would resize placeholders and
// drift the scroll position, breaking the preview-to-commit alignment.
if (this.#pinching) return
const currentIndex = this.#getScrollIndex()
const { load, evict } = planScrollModePages({
pages: this.#scrollPages,
currentIndex,
maxLoaded: this.#scrollMaxLoaded,
maxConcurrent: this.#scrollMaxConcurrent,
loadingCount: this.#scrollLoadingCount,
})
for (const index of evict) this.#teardownScrollPage(this.#scrollPages[index])
for (const index of load) this.#loadScrollPage(this.#scrollPages[index])
}
#handleScrollEvent = () => {
// Drop iframe interaction while the host is actively scrolling so the
// scroll stays native-smooth (the iframe's own pointer handlers can't
// hijack it), then restore it on settle so text selection, taps, and
// same-page pinch work again. (Cross-page pinch is intentionally not
// supported in this mode: a gesture spanning two page iframes can't be
// owned by one document — keeping the iframes interactive is the
// trade-off for native selection.)
this.#scrolling = true
this.#setScrollIframeInteraction(false)
if (this.#scrollIdleTimer) clearTimeout(this.#scrollIdleTimer)
this.#scrollIdleTimer = setTimeout(() => {
this.#scrolling = false
this.#setScrollIframeInteraction(true)
// Report location only after scroll settles to avoid
// expensive React re-renders on every frame
this.#reportScrollLocation()
}, 150)
}
#handleScrollWheel = e => {
const delta = computeScrollWheelDelta({
deltaX: e.deltaX, deltaY: e.deltaY, ctrlKey: e.ctrlKey,
horizontal: this.#scrollHorizontal, rtl: this.rtl,
verticalOverflow: this.scrollHeight > this.clientHeight + 1,
})
if (!delta) return
e.preventDefault()
this.scrollBy({ left: delta.left, behavior: 'auto' })
}
#setScrollIframeInteraction(enabled) {
const value = enabled ? 'auto' : ''
for (const page of this.#scrollPages) {
if (page.frame?.iframe) {
page.frame.iframe.style.pointerEvents = value
}
}
}
#destroyScrollMode(navigate = true) {
// Use the cached scroll index because by the time attributeChangedCallback
// fires, the CSS has already switched from block/scroll to flex layout,
// making #getScrollIndex() return incorrect positions
const currentIndex = this.#scrollCurrentIndex >= 0
? this.#scrollCurrentIndex : this.#getScrollIndex()
this.removeEventListener('scroll', this.#handleScrollEvent)
this.removeEventListener('wheel', this.#handleScrollWheel)
if (this.#scrollObserver) {
this.#scrollObserver.disconnect()
this.#scrollObserver = null
}
if (this.#scrollIdleTimer) {
clearTimeout(this.#scrollIdleTimer)
this.#scrollIdleTimer = null
}
// Clean up all scroll page frames and overlayers
for (const page of this.#scrollPages) {
this.#teardownScrollPage(page)
}
this.#scrollPages = []
this.#scrollLoadGen.clear()
this.#scrollLoadingCount = 0
this.#scrollCurrentIndex = -1
if (this.#scrollContainer) {
this.#scrollContainer.remove()
this.#scrollContainer = null
}
// Reset scroll position left over from scroll mode
this.scrollTop = 0
this.scrollLeft = 0
// Must run even when navigate is false (axis rebuild): otherwise a
// horizontal-RTL -> vertical switch would leave the host direction
// rtl and the vertical re-init would inherit it.
this.style.removeProperty('direction')
if (navigate) {
// Restore paginated content
for (const child of Array.from(this.#root.children)) {
child.style.display = ''
}
// Navigate to the page we were on
if (currentIndex >= 0) {
const section = this.book.sections[currentIndex]
if (section) {
const spread = this.getSpreadOf(section)
if (spread) {
this.#index = -1
this.goToSpread(spread.index, spread.side, 'page')
}
}
}
}
}
// Create an iframe directly inside the page placeholder (no reparenting)
async #createScrollFrame(pageData, srcOption) {
const srcOptionIsString = typeof srcOption === 'string'
const src = srcOptionIsString ? srcOption : srcOption?.src
const data = srcOptionIsString ? null : srcOption?.data
const onZoom = srcOptionIsString ? null : srcOption?.onZoom
const element = document.createElement('div')
element.setAttribute('dir', 'ltr')
element.style.position = 'relative'
const iframe = document.createElement('iframe')
element.append(iframe)
Object.assign(iframe.style, {
border: '0',
display: 'none',
overflow: 'hidden',
})
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
iframe.setAttribute('scrolling', 'no')
iframe.setAttribute('part', 'filter')
// Place directly in the placeholder — no root append + reparent
pageData.el.append(element)
if (!src) return { blank: true, element, iframe }
return new Promise(resolve => {
iframe.addEventListener('load', () => {
const doc = iframe.contentDocument
iframe.dataset.sectionIndex = pageData.index
this.dispatchEvent(new CustomEvent('load', { detail: { doc, index: pageData.index } }))
const { width, height } = getViewport(doc, this.defaultViewport)
resolve({
element, iframe,
width: parseFloat(width),
height: parseFloat(height),
onZoom,