forked from johnfactotum/foliate-js
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathfixed-layout.js
More file actions
1325 lines (1255 loc) · 51.6 KB
/
fixed-layout.js
File metadata and controls
1325 lines (1255 loc) · 51.6 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()))
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) return Object.fromEntries(meta)
// 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, scrollTop, fallbackIndex = -1) => {
const fallbackPage = pages.find(page => page.index === fallbackIndex)
const currentPage = pages.find(page =>
page.height > 0
&& scrollTop >= page.top
&& scrollTop < page.top + page.height)
?? fallbackPage
?? pages.find(page => page.height > 0)
if (!currentPage) return null
return {
index: currentPage.index,
fraction: currentPage.height > 0
? clamp((scrollTop - currentPage.top) / currentPage.height, 0, 1)
: 0,
scrollTop,
}
}
export const restoreScrollModeAnchor = (pages, anchor, maxScrollTop) => {
if (!anchor) return 0
const page = pages.find(candidate => candidate.index === anchor.index)
if (!page || page.height <= 0) return clamp(anchor.scrollTop, 0, maxScrollTop)
return clamp(page.top + page.height * anchor.fraction, 0, maxScrollTop)
}
// 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']
#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
#scrollPages = []
#scrollObserver = null
#scrollContainer = null
#scrollLoadGen = new Map()
#scrollMaxLoaded = 8
#scrollIdleTimer = null
#scrollCurrentIndex = -1
#getScrollModePageMetrics() {
return this.#scrollPages.map(page => ({
index: page.index,
top: page.el.offsetTop,
height: page.el.offsetHeight,
}))
}
#captureScrollModeAnchor() {
if (!this.#scrollPages.length) return null
const fallbackIndex = this.#scrollCurrentIndex >= 0
? this.#scrollCurrentIndex : this.#getScrollIndex()
return captureScrollModeAnchor(
this.#getScrollModePageMetrics(),
this.scrollTop,
fallbackIndex,
)
}
#restoreScrollModeAnchor(anchor) {
if (!anchor || !this.#scrollPages.length) return
const maxScrollTop = Math.max(0, this.scrollHeight - this.clientHeight)
this.scrollTop = restoreScrollModeAnchor(
this.#getScrollModePageMetrics(),
anchor,
maxScrollTop,
)
this.#scrollCurrentIndex = anchor.index
}
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;
overflow-x: hidden;
}
:host([flow="scrolled"]) .scroll-container {
display: flex;
flex-direction: column;
align-items: center;
min-height: 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;
margin: 4px 0;
}
:host([flow="scrolled"]) .scroll-page iframe {
pointer-events: none;
}`)
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
}
}
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) {
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
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: zoomedOut ? 'flex' : 'block',
marginBlock: zoomedOut ? undefined : 'auto',
alignItems: zoomedOut ? 'center' : undefined,
justifyContent: zoomedOut ? '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
container.scrollLeft = (element.clientWidth - containerWidth) / 2
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 {
const leftDimensions = transform({frame: left, styles: { marginInlineStart: 'auto' }})
const rightDimensions = transform({frame: right, styles: { marginInlineEnd: 'auto' }})
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
}
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.
const renderPromises = this.#render()
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)
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', 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.#scrollCurrentIndex = currentIndex
}
this.addEventListener('scroll', this.#handleScrollEvent)
// Set up IntersectionObserver after scroll position is established.
// rootMargin '50%' loads ~1 page buffer above/below the viewport.
this.#scrollObserver = new IntersectionObserver(entries => {
for (const entry of entries) {
if (!entry.isIntersecting) continue
const index = parseInt(entry.target.dataset.index)
const pageData = this.#scrollPages[index]
if (pageData && pageData.state === 'idle') {
this.#loadScrollPage(pageData)
}
}
this.#evictScrollPages()
}, { root: this, rootMargin: '50% 0px' })
for (const page of this.#scrollPages) {
this.#scrollObserver.observe(page.el)
}
}
#handleScrollEvent = () => {
// Disable iframe interaction during scroll for native smooth scrolling
this.#setScrollIframeInteraction(false)
if (this.#scrollIdleTimer) clearTimeout(this.#scrollIdleTimer)
this.#scrollIdleTimer = setTimeout(() => {
this.#setScrollIframeInteraction(true)
// Report location only after scroll settles to avoid
// expensive React re-renders on every frame
this.#reportScrollLocation()
}, 150)
}
#setScrollIframeInteraction(enabled) {
const value = enabled ? 'auto' : ''
for (const page of this.#scrollPages) {
if (page.frame?.iframe) {
page.frame.iframe.style.pointerEvents = value
}
}
}
#destroyScrollMode() {
// 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)
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.#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
// 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,
})
}, { once: true })
if (data) {
iframe.srcdoc = data
} else {
iframe.src = src
}
})
}
async #loadScrollPage(pageData) {
if (pageData.state !== 'idle') return
pageData.state = 'loading'
// Generation counter to detect stale loads
const gen = (this.#scrollLoadGen.get(pageData.index) || 0) + 1
this.#scrollLoadGen.set(pageData.index, gen)
try {
const src = await pageData.section.load?.()
// Bail if cancelled or mode changed
if (this.#scrollLoadGen.get(pageData.index) !== gen || !this.#scrollMode) {
pageData.state = 'idle'
return
}
if (!src) { pageData.state = 'idle'; return }
const frame = await this.#createScrollFrame(pageData, src)
// Bail if cancelled during frame creation
if (this.#scrollLoadGen.get(pageData.index) !== gen || !this.#scrollMode) {
frame.element?.remove()
pageData.state = 'idle'
return
}
pageData.frame = frame
pageData.state = 'loaded'
const scrollAnchor = this.#captureScrollModeAnchor()
// Update dimensions from actual page viewport
if (frame.width && frame.height) {
pageData.vpWidth = frame.width
pageData.vpHeight = frame.height
}
this.#renderScrollPage(pageData)
this.#restoreScrollModeAnchor(scrollAnchor)
// Create overlayer
const doc = frame.iframe.contentDocument
if (doc) {
this.dispatchEvent(new CustomEvent('create-overlayer', {
detail: {
doc, index: pageData.index,
attach: overlayer => {
this.#overlayers.set(pageData.index, overlayer)
frame.element.append(overlayer.element)
applyOverlayerViewBox(frame, overlayer)
},
},
}))
// Forward wheel events to host when iframe has pointer-events
// (fallback for the brief window after scroll settles)
doc.addEventListener('wheel', e => {
// Disable pointer-events immediately so subsequent
// wheel ticks use native scroll
this.#setScrollIframeInteraction(false)
this.scrollBy({ top: e.deltaY, left: e.deltaX, behavior: 'instant' })
}, { passive: true })
}
} catch (e) {
console.warn('Failed to load scroll page', pageData.index, e)
pageData.state = 'idle'
}
}
// Remove a loaded scroll page's frame and overlayer
#teardownScrollPage(pageData) {
// Bump generation to cancel any in-progress load
const gen = (this.#scrollLoadGen.get(pageData.index) || 0) + 1
this.#scrollLoadGen.set(pageData.index, gen)
if (pageData.frame) {
const idx = pageData.index
this.#overlayers.delete(idx)
pageData.frame.element?.remove()
}
pageData.frame = null
pageData.state = 'idle'
}
// Evict the farthest loaded pages when over limit
#evictScrollPages() {
const loaded = this.#scrollPages.filter(p => p.state === 'loaded')
if (loaded.length <= this.#scrollMaxLoaded) return
const currentIndex = this.#getScrollIndex()
loaded.sort((a, b) =>
Math.abs(a.index - currentIndex) - Math.abs(b.index - currentIndex))
for (const page of loaded.slice(this.#scrollMaxLoaded)) {
this.#teardownScrollPage(page)
}
}
#renderScrollMode() {
const { width: hostWidth } = this.getBoundingClientRect()
if (!hostWidth) return
const scrollAnchor = this.#captureScrollModeAnchor()
for (const page of this.#scrollPages) {
const scale = (hostWidth / page.vpWidth) * this.#scaleFactor
page.el.style.width = `${page.vpWidth * scale}px`
page.el.style.height = `${page.vpHeight * scale}px`
if (page.state === 'loaded' && page.frame) {
this.#renderScrollPage(page)
}
}
this.#restoreScrollModeAnchor(scrollAnchor)
}
#renderScrollPage(pageData) {
const { width: hostWidth } = this.getBoundingClientRect()
if (!hostWidth || !pageData.frame) return
const { vpWidth: vw, vpHeight: vh, frame } = pageData
const scale = (hostWidth / vw) * this.#scaleFactor
if (frame.onZoom) {
frame.onZoom({ doc: frame.iframe.contentDocument, scale, pageColors: this.#pageColors })
Object.assign(frame.iframe.style, {
width: `${vw * scale}px`,
height: `${vh * scale}px`,
transform: 'none',
display: 'block',
})
} else {
Object.assign(frame.iframe.style, {
width: `${vw}px`,
height: `${vh}px`,
transform: `scale(${scale})`,
transformOrigin: 'top left',
display: 'block',
})
}
Object.assign(frame.element.style, {
width: `${vw * scale}px`,
height: `${vh * scale}px`,
})
// Update placeholder to match actual page dimensions
pageData.el.style.width = `${vw * scale}px`
pageData.el.style.height = `${vh * scale}px`
const overlayer = this.#overlayers.get(pageData.index)
if (overlayer) {
Object.assign(overlayer.element.style, {
position: 'absolute',
top: '0',
left: '0',
width: `${vw * scale}px`,
height: `${vh * scale}px`,
})
applyOverlayerViewBox(frame, overlayer)
overlayer.redraw()
}
}
#getScrollIndex() {
if (!this.#scrollPages.length) return -1
const hostRect = this.getBoundingClientRect()
const midY = hostRect.top + hostRect.height / 2
for (const page of this.#scrollPages) {
const rect = page.el.getBoundingClientRect()
if (rect.top <= midY && rect.bottom >= midY) return page.index
}
let closest = 0, minDist = Infinity
for (const page of this.#scrollPages) {
const rect = page.el.getBoundingClientRect()
const dist = Math.abs(rect.top + rect.height / 2 - midY)
if (dist < minDist) { minDist = dist; closest = page.index }
}
return closest
}
#reportScrollLocation() {
const index = this.#getScrollIndex()
if (index < 0) return
this.#scrollCurrentIndex = index
this.dispatchEvent(new CustomEvent('relocate', { detail:
{ reason: 'scroll', range: null, index, fraction: 0, size: 1 } }))
}
#goLeft() {
if (this.#center || this.#left?.blank) return
if (this.#portrait && this.#left?.element?.style?.display === 'none') {
this.#side = 'left'
this.#render()
this.#reportLocation('page')
return true
}
}
#goRight() {
if (this.#center || this.#right?.blank) return
if (this.#portrait && this.#right?.element?.style?.display === 'none') {
this.#side = 'right'
this.#render()
this.#reportLocation('page')
return true
}
}
open(book) {
this.book = book
this.defaultViewport = book.rendition?.viewport
this.rtl = book.dir === 'rtl'
this.#spread()
if (this.#scrollMode) this.#initScrollMode()
}
#spread(mode) {
const book = this.book
const { rendition } = book
const rtl = this.rtl
const ltr = !rtl
this.spread = mode || rendition?.spread
if (this.spread === 'none')
this.#spreads = book.sections.map(section => ({ center: section }))
else this.#spreads = book.sections.reduce((arr, section, i) => {
const last = arr[arr.length - 1]
const { pageSpread } = section
const newSpread = () => {
const spread = {}
arr.push(spread)
return spread
}
if (pageSpread === 'center') {
const spread = last.left || last.right ? newSpread() : last
spread.center = section
}
else if (pageSpread === 'left') {
const spread = last.center || last.left || ltr && i ? newSpread() : last
spread.left = section
}
else if (pageSpread === 'right') {
const spread = last.center || last.right || rtl && i ? newSpread() : last
spread.right = section
}
else if (ltr) {
if (last.center || last.right) newSpread().left = section
else if (last.left || !i) last.right = section
else last.left = section
}
else {
if (last.center || last.left) newSpread().right = section
else if (last.right || !i) last.left = section
else last.right = section
}
return arr
}, [{}])
}
#respread(spreadMode) {
if (this.#index === -1) return
const section = this.book.sections[this.index]
this.#spread(spreadMode)
const { index } = this.getSpreadOf(section)
this.#index = -1
this.#preloadCache.clear()
for (const frames of this.#prerenderedSpreads.values()) {
if (frames.center) {
frames.center.element?.remove()
} else {
frames.left?.element?.remove()
frames.right?.element?.remove()
}
}
this.#prerenderedSpreads.clear()
this.#spreadAccessTime.clear()
this.#overlayers.clear()
this.goToSpread(index, this.rtl ? 'right' : 'left', 'page')
}
get index() {
if (this.#scrollMode) return this.#scrollCurrentIndex >= 0
? this.#scrollCurrentIndex : this.#getScrollIndex()
if (this.#index < 0 || !this.#spreads) return -1
const spread = this.#spreads[this.#index]
if (!spread) return -1
const section = spread.center ?? (this.#side === 'left'
? spread.left ?? spread.right : spread.right ?? spread.left)
return this.book.sections.indexOf(section)
}
get pageColors() {
return this.#pageColors
}
set pageColors(value) {
this.#pageColors = value
this.#render()
}
get scrolled() {
return this.#scrollMode
}
get scrollLocked() {
return this.#scrollLocked
}
set scrollLocked(value) {
this.#scrollLocked = value
}
get isOverflowX() {
return this.#isOverflowX
}
get isOverflowY() {
return this.#isOverflowY
}
get atStart() {
if (this.#scrollMode) return this.scrollTop <= 0
return this.#index <= 0
}
get atEnd() {
if (this.#scrollMode) return this.scrollTop + this.clientHeight >= this.scrollHeight - 2
return this.#index >= this.#spreads.length - 1
}
#reportLocation(reason) {
this.dispatchEvent(new CustomEvent('relocate', { detail:
{ reason, range: null, index: this.index, fraction: 0, size: 1 } }))
}
getSpreadOf(section) {
const spreads = this.#spreads
for (let index = 0; index < spreads.length; index++) {
const { left, right, center } = spreads[index]
if (left === section) return { index, side: 'left' }
if (right === section) return { index, side: 'right' }
if (center === section) return { index, side: 'center' }
}
}
async goToSpread(index, side, reason) {
if (index < 0 || index > this.#spreads.length - 1) return
if (index === this.#index) {
this.#render(side)
return
}
this.#index = index
const spread = this.#spreads[index]
const cacheKey = `spread-${index}`
const cached = this.#preloadCache.get(cacheKey)
if (cached && cached !== 'loading') {
if (cached.center) {
const sectionIndex = this.book.sections.indexOf(spread.center)
await this.#showSpread({ center: { index: sectionIndex, src: cached.center }, spreadIndex: index, side })
} else {
const indexL = this.book.sections.indexOf(spread.left)
const indexR = this.book.sections.indexOf(spread.right)
const left = { index: indexL, src: cached.left }
const right = { index: indexR, src: cached.right }
await this.#showSpread({ left, right, side, spreadIndex: index })
}
} else {
if (spread.center) {
const sectionIndex = this.book.sections.indexOf(spread.center)
const src = await spread.center?.load?.()
await this.#showSpread({ center: { index: sectionIndex, src }, spreadIndex: index, side })
} else {
const indexL = this.book.sections.indexOf(spread.left)
const indexR = this.book.sections.indexOf(spread.right)
const srcL = await spread.left?.load?.()
const srcR = await spread.right?.load?.()
const left = { index: indexL, src: srcL }
const right = { index: indexR, src: srcR }
await this.#showSpread({ left, right, side, spreadIndex: index })
}
}
this.#reportLocation(reason)
this.#preloadNextSpreads()
}
#preloadNextSpreads() {
this.#cleanupPreloadCache()
if (this.#numPrerenderedSpreads <= 0) return
const toPreload = []
const forwardPreloadCount = Math.max(1, this.#numPrerenderedSpreads - 1)
const backwardPreloadCount = Math.max(0, this.#numPrerenderedSpreads - forwardPreloadCount)
for (let distance = 1; distance <= forwardPreloadCount; distance++) {
const forwardIndex = this.#index + distance