forked from johnfactotum/foliate-js
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathpaginator.js
More file actions
2528 lines (2436 loc) · 112 KB
/
paginator.js
File metadata and controls
2528 lines (2436 loc) · 112 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
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
const debounce = (f, wait, immediate) => {
let timeout
return (...args) => {
const later = () => {
timeout = null
if (!immediate) f(...args)
}
const callNow = immediate && !timeout
if (timeout) clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) f(...args)
}
}
// Transforms ALL children of the container so multi-view layouts
// animate as a unified whole. Extra elements (e.g. background) are
// also transformed so they slide in sync with the content.
const animateScroll = (element, scrollProp, startValue, endValue, duration, extraElements = []) => new Promise(resolve => {
if (document.hidden) {
element[scrollProp] = endValue
return resolve()
}
const children = [...element.children]
if (!children.length) {
element[scrollProp] = endValue
return resolve()
}
const allElements = [...children, ...extraElements]
const isHorizontal = scrollProp === 'scrollLeft'
const delta = endValue - startValue
const transformProp = isHorizontal ? 'translateX' : 'translateY'
// Prepare all elements for animation
for (const el of allElements) {
el.style.willChange = 'transform'
el.style.transform = `${transformProp}(0px)`
el.style.transition = 'none'
}
// Force reflow to apply initial state
element.getBoundingClientRect()
// Start animation on all elements
for (const el of allElements) {
el.style.transition = `transform ${duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`
el.style.transform = `${transformProp}(${-delta}px)`
}
let resolved = false
const cleanup = () => {
if (resolved) return
resolved = true
for (const el of allElements) {
el.style.willChange = ''
el.style.transform = ''
el.style.transition = ''
}
// Apply final scroll position
element[scrollProp] = endValue
resolve()
}
// Listen for transition end on the first child
const first = children[0]
const onTransitionEnd = (e) => {
if (e.target === first && e.propertyName === 'transform') {
first.removeEventListener('transitionend', onTransitionEnd)
cleanup()
}
}
first.addEventListener('transitionend', onTransitionEnd)
// Fallback timeout in case transitionend doesn't fire
setTimeout(cleanup, duration + 50)
})
// collapsed range doesn't return client rects sometimes (or always?)
// try make get a non-collapsed range or element
const uncollapse = range => {
if (!range?.collapsed) return range
const { endOffset, endContainer } = range
if (endContainer.nodeType === 1) {
const node = endContainer.childNodes[endOffset]
if (node?.nodeType === 1) return node
return endContainer
}
if (endOffset + 1 < endContainer.length) range.setEnd(endContainer, endOffset + 1)
else if (endOffset > 1) range.setStart(endContainer, endOffset - 1)
else return endContainer.parentNode
return range
}
const makeRange = (doc, node, start, end = start) => {
const range = doc.createRange()
range.setStart(node, start)
range.setEnd(node, end)
return range
}
// use binary search to find an offset value in a text node
const bisectNode = (doc, node, cb, start = 0, end = node.nodeValue.length) => {
if (end - start === 1) {
const result = cb(makeRange(doc, node, start), makeRange(doc, node, end))
return result < 0 ? start : end
}
const mid = Math.floor(start + (end - start) / 2)
const result = cb(makeRange(doc, node, start, mid), makeRange(doc, node, mid, end))
return result < 0 ? bisectNode(doc, node, cb, start, mid)
: result > 0 ? bisectNode(doc, node, cb, mid, end) : mid
}
const { SHOW_ELEMENT, SHOW_TEXT, SHOW_CDATA_SECTION,
FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP } = NodeFilter
const filter = SHOW_ELEMENT | SHOW_TEXT | SHOW_CDATA_SECTION
// needed cause there seems to be a bug in `getBoundingClientRect()` in Firefox
// where it fails to include rects that have zero width and non-zero height
// (CSSOM spec says "rectangles [...] of which the height or width is not zero")
// which makes the visible range include an extra space at column boundaries
const getBoundingClientRect = target => {
let top = Infinity, right = -Infinity, left = Infinity, bottom = -Infinity
for (const rect of target.getClientRects()) {
left = Math.min(left, rect.left)
top = Math.min(top, rect.top)
right = Math.max(right, rect.right)
bottom = Math.max(bottom, rect.bottom)
}
return new DOMRect(left, top, right - left, bottom - top)
}
const getVisibleRange = (doc, start, end, mapRect) => {
// A resize/scroll callback can fire after the view's document has been
// torn down (e.g. during teardown, or while an async section load is still
// settling); there is nothing to measure without a body.
if (!doc?.body) return
// first get all visible nodes
const acceptNode = node => {
const name = node.localName?.toLowerCase()
// ignore all scripts, styles, and their children
if (name === 'script' || name === 'style') return FILTER_REJECT
// ignore cfi-inert nodes (e.g. injected a11y skip-links) and their
// subtree: they are invisible to CFI, so anchoring the visible range on
// one yields a degenerate CFI and can crash `fromRange` when such a node
// is the only child of its parent (content-less background sections).
if (node.nodeType === 1 && node.hasAttribute?.('cfi-inert')) return FILTER_REJECT
if (node.nodeType === 1) {
const { left, right } = mapRect(node.getBoundingClientRect())
if (left === 0 && right === 0) return FILTER_REJECT
// no need to check child nodes if it's completely out of view
if (right < start || left > end) return FILTER_REJECT
// elements must be completely in view to be considered visible
// because you can't specify offsets for elements
if (left >= start && right <= end) return FILTER_ACCEPT
// TODO: it should probably allow elements that do not contain text
// because they can exceed the whole viewport in both directions
// especially in scrolled mode
} else {
// ignore empty text nodes
if (!node.nodeValue?.trim()) return FILTER_SKIP
// create range to get rect
const range = doc.createRange()
range.selectNodeContents(node)
const { left, right } = mapRect(range.getBoundingClientRect())
// it's visible if any part of it is in view
if (left === 0 && right === 0) return FILTER_REJECT
if (right >= start && left <= end) return FILTER_ACCEPT
}
return FILTER_SKIP
}
const walker = doc.createTreeWalker(doc.body, filter, { acceptNode })
const nodes = []
for (let node = walker.nextNode(); node; node = walker.nextNode())
nodes.push(node)
// we're only interested in the first and last visible nodes
const from = nodes[0] ?? doc.body
const to = nodes[nodes.length - 1] ?? from
// find the offset at which visibility changes
const startOffset = from.nodeType === 1 ? 0
: bisectNode(doc, from, (a, b) => {
const p = mapRect(getBoundingClientRect(a))
const q = mapRect(getBoundingClientRect(b))
if (p.right < start && q.left > start) return 0
return q.left > start ? -1 : 1
})
const endOffset = to.nodeType === 1 ? 0
: bisectNode(doc, to, (a, b) => {
const p = mapRect(getBoundingClientRect(a))
const q = mapRect(getBoundingClientRect(b))
if (p.right < end && q.left > end) return 0
return q.left > end ? -1 : 1
})
const range = doc.createRange()
range.setStart(from, startOffset)
range.setEnd(to, endOffset)
return range
}
const selectionIsBackward = sel => {
const range = document.createRange()
range.setStart(sel.anchorNode, sel.anchorOffset)
range.setEnd(sel.focusNode, sel.focusOffset)
return range.collapsed
}
const setSelectionTo = (target, collapse) => {
let range
if (target.startContainer) range = target.cloneRange()
else if (target.nodeType) {
range = document.createRange()
range.selectNode(target)
}
if (range) {
const sel = range.startContainer.ownerDocument?.defaultView.getSelection()
if (sel) {
sel.removeAllRanges()
if (collapse === -1) range.collapse(true)
else if (collapse === 1) range.collapse()
sel.addRange(range)
}
}
}
// Whether a view's bounding rect overlaps the visible region of its container.
// Used by #syncA11y to mark only the pre-loaded views that lie outside the
// viewport as `aria-hidden`. Views still visible to sighted users (e.g. the
// right column in a dual-page spread that belongs to a different section
// than the left column) stay exposed to assistive tech.
// See readest/readest#4243 and readest/readest#4259.
export const isViewVisibleInContainer = (viewRect, containerRect) =>
viewRect.right > containerRect.left
&& viewRect.left < containerRect.right
&& viewRect.bottom > containerRect.top
&& viewRect.top < containerRect.bottom
export const getDirection = doc => {
const { defaultView } = doc
let { writingMode, direction } = defaultView.getComputedStyle(doc.body)
// Some EPUBs set writing-mode on the first child of body instead of body itself
if (!writingMode || writingMode === 'horizontal-tb') {
const firstChild = doc.body.querySelector(':scope > :not([cfi-inert])')
if (firstChild) {
const childStyle = defaultView.getComputedStyle(firstChild)
if (childStyle.writingMode === 'vertical-rl'
|| childStyle.writingMode === 'vertical-lr') {
writingMode = childStyle.writingMode
}
}
}
const vertical = writingMode === 'vertical-rl'
|| writingMode === 'vertical-lr'
const rtl = doc.body.dir === 'rtl'
|| direction === 'rtl'
|| doc.documentElement.dir === 'rtl'
return { vertical, rtl }
}
const getBackground = doc => {
const bodyStyle = doc.defaultView.getComputedStyle(doc.body)
return bodyStyle.backgroundColor === 'rgba(0, 0, 0, 0)'
&& bodyStyle.backgroundImage === 'none'
? doc.defaultView.getComputedStyle(doc.documentElement).background
: bodyStyle.background
}
// Compute the full-bleed background segments for paginated mode. Each rendered
// view yields one segment positioned so it tracks its content on screen
// (segStart = inset + viewOffset - scrollPos). Because the paginator rebuilds
// these on every scroll, the backgrounds stay glued to the content while the
// user drags a swipe; when two sections with different backgrounds are both on
// screen the seam falls on the real content boundary instead of one flat colour
// spanning the viewport. A segment that meets a content edge is stretched out
// into the full-bleed gutter (outside #container) so a coloured page fills the
// screen edge to edge, matching its content area. `views` is the sorted list of
// { size, bg } with bg already resolved ('' = transparent → no segment).
export const computeBackgroundSegments = (views, scrollPos, bgSize, inset, containerSize) => {
const containerStart = inset
const containerEnd = inset + containerSize
const segments = []
let offset = 0
for (const view of views) {
const segStart = inset + offset - scrollPos
const segEnd = segStart + view.size
offset += view.size
if (segEnd <= 0 || segStart >= bgSize) continue // off screen
if (!view.bg) continue // transparent → let the host/theme show through
let start = segStart
let end = segEnd
if (start <= containerStart && end > containerStart) start = 0
if (start < containerEnd && end >= containerEnd) end = bgSize
segments.push({ start, size: end - start, bg: view.bg })
}
return segments
}
const makeMarginals = (length, part) => Array.from({ length }, () => {
const div = document.createElement('div')
const child = document.createElement('div')
div.append(child)
child.setAttribute('part', part)
return div
})
const setStyles = (el, styles) => {
const { style } = el
for (const [k, v] of Object.entries(styles)) style.setProperty(k, v)
}
const setStylesImportant = (el, styles) => {
const { style } = el
for (const [k, v] of Object.entries(styles)) style.setProperty(k, v, 'important')
}
class View {
#observer = new ResizeObserver(() => this.expand())
#element = document.createElement('div')
#iframe = document.createElement('iframe')
#contentRange = document.createRange()
#overlayer
#vertical = false
#rtl = false
#column = true
#size
#columnCount = 1
#layout = {}
#contentPages = 0
#bgImageSize = null
fontReady = Promise.resolve()
constructor({ container, onExpand }) {
this.container = container
this.onExpand = onExpand
this.#iframe.setAttribute('part', 'filter')
this.#element.append(this.#iframe)
Object.assign(this.#element.style, {
boxSizing: 'content-box',
position: 'relative',
overflow: 'hidden',
flex: '0 0 auto',
width: '100%', height: '100%',
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
})
Object.assign(this.#iframe.style, {
overflow: 'hidden',
border: '0',
display: 'none',
width: '100%', height: '100%',
})
// `allow-scripts` is needed for events because of WebKit bug
// https://bugs.webkit.org/show_bug.cgi?id=218086
this.#iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
this.#iframe.setAttribute('scrolling', 'no')
}
get element() {
return this.#element
}
get document() {
return this.#iframe.contentDocument
}
get contentPages() {
return this.#contentPages
}
async load(src, data, afterLoad, beforeRender) {
if (typeof src !== 'string') throw new Error(`${src} is not string`)
return new Promise(resolve => {
this.#iframe.addEventListener('load', async () => {
const doc = this.document
afterLoad?.(doc)
this.#iframe.setAttribute('aria-label', doc.title)
// it needs to be visible for Firefox to get computed style
this.#iframe.style.display = 'block'
const { vertical, rtl } = getDirection(doc)
this.docBackground = getBackground(doc)
doc.body.style.background = 'none'
// Resolve the body background image's natural size BEFORE the
// first render so the scrolled-mode view is sized to fit it
// from the start. Sizing it lazily — expanding only once the
// image loads — grows the view *after* navigation has already
// scrolled to it. On reopen that growth lands above the saved
// position (e.g. a preloaded previous section's full-page
// illustration) and, with no reliable cross-iframe scroll
// anchoring on WebKit, drifts the viewport to the chapter
// start. Awaiting a local EPUB resource here is near-instant.
let bgRendered = false
const bgUrl = this.docBackground
?.match(/url\(["']?([^"')]+)["']?\)/)?.[1]
if (bgUrl && !this.container.noBackground) {
const img = new Image()
let resolveWait
const waited = new Promise(res => { resolveWait = res })
img.onload = () => {
this.#bgImageSize = {
width: img.naturalWidth,
height: img.naturalHeight,
}
// If the image only resolves after this view has
// already rendered (slower than the bounded wait
// below), grow to fit it now — the original lazy path,
// kept as a fallback rather than the norm.
if (bgRendered && !this.#column) this.expand()
resolveWait()
}
// A missing or broken image just renders without the
// background, exactly as before.
img.onerror = () => resolveWait()
img.src = bgUrl
// Bound the wait so a missing, broken, or hung image (one
// that fires neither load nor error) can never block the
// section from rendering.
let timer
await Promise.race([
waited,
new Promise(res => { timer = setTimeout(res, 3000) }),
])
clearTimeout(timer)
}
// Awaiting the background image yields control, so the view may
// have been torn down or reloaded meanwhile — don't render into
// a stale document.
if (this.document !== doc) return resolve()
this.#iframe.style.display = 'none'
this.#vertical = vertical
this.#rtl = rtl
this.#contentRange.selectNodeContents(doc.body)
const layout = beforeRender?.({ vertical, rtl })
this.#iframe.style.display = 'block'
this.render(layout)
bgRendered = true
this.#observer.observe(doc.body)
// the resize observer above doesn't work in Firefox
// (see https://bugzilla.mozilla.org/show_bug.cgi?id=1832939)
// until the bug is fixed we can at least account for font load
this.fontReady = doc.fonts.ready.then(() => this.expand())
resolve()
}, { once: true })
if (data) {
this.#iframe.srcdoc = data
} else {
this.#iframe.src = src
}
})
}
render(layout) {
if (!layout || !this.document?.documentElement) return
this.#column = layout.flow !== 'scrolled'
this.#layout = layout
if (this.#column) this.columnize(layout)
else this.scrolled(layout)
}
scrolled({ width, height, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }) {
const vertical = this.#vertical
const doc = this.document
setStylesImportant(doc.documentElement, {
'box-sizing': 'border-box',
'column-width': 'auto',
'height': 'auto',
'width': 'auto',
})
const availableWidth = Math.trunc(width - marginLeft - marginRight)
const availableHeight = Math.trunc(height - marginTop - marginBottom)
const sidePaddingLeft = marginLeft / 2 + gap / 2
const sidePaddingRight = marginRight / 2 + gap / 2
setStyles(doc.documentElement, {
'padding': vertical
? `${marginTop * 1.5}px 0px ${marginBottom * 1.5}px 0px`
: `0px ${sidePaddingRight}px 0px ${sidePaddingLeft}px`,
'--page-margin-top': `${vertical ? marginTop * 1.5 : marginTop}px`,
'--page-margin-right': `${vertical ? marginRight : sidePaddingRight}px`,
'--page-margin-bottom': `${vertical ? marginBottom * 1.5 : marginBottom}px`,
'--page-margin-left': `${vertical ? marginLeft : sidePaddingLeft}px`,
'--full-width': `${Math.trunc(width)}`,
'--full-height': `${Math.trunc(height)}`,
'--available-width': `${availableWidth}`,
'--available-height': `${availableHeight}`,
})
setStylesImportant(doc.body, {
[vertical ? 'max-height' : 'max-width']: `${columnWidth}px`,
'margin': 'auto',
// Prevent position:absolute/fixed on body from coupling its
// size to the iframe, which causes diverging expand() loops
'position': 'static',
})
this.setImageSize(availableWidth, availableHeight)
this.expand()
}
columnize({ width, height, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth, columnCount }) {
const vertical = this.#vertical
this.#size = vertical ? height : width
this.#columnCount = columnCount || 1
const doc = this.document
const horizontalColumnGap = columnCount > 1 ? (marginLeft + marginRight) / 4 + gap / 2 : (marginLeft + marginRight) / 2 + gap
const sidePaddingLeft = columnCount > 1 ? marginLeft / 4 + gap / 4 : marginLeft / 2 + gap / 2
const sidePaddingRight = columnCount > 1 ? marginRight / 4 + gap / 4 : marginRight / 2 + gap / 2
setStylesImportant(doc.documentElement, {
'box-sizing': 'border-box',
'column-width': `${Math.trunc(columnWidth)}px`,
'column-gap': vertical ? `${(marginTop + marginBottom) * 1.5}px` : `${horizontalColumnGap}px`,
'column-fill': 'auto',
...(vertical
? { 'width': `${width}px` }
: { 'height': `${height}px` }),
'overflow': 'hidden',
// force wrap long words
'overflow-wrap': 'break-word',
// reset some potentially problematic props
'position': 'static', 'border': '0', 'margin': '0',
'max-height': 'none', 'max-width': 'none',
'min-height': 'none', 'min-width': 'none',
// fix glyph clipping in WebKit
'-webkit-line-box-contain': 'block glyphs replaced',
})
const availableWidth = vertical
? Math.trunc(width - marginLeft / 2 - marginRight / 2 - gap)
: Math.trunc(width / this.#columnCount)
const availableHeight = vertical
? Math.trunc(height / this.#columnCount)
: Math.trunc(height - marginTop - marginBottom)
setStyles(doc.documentElement, {
'padding': vertical
? `${marginTop * 1.5}px ${marginRight}px ${marginBottom * 1.5}px ${marginLeft}px`
: `${marginTop}px ${sidePaddingRight}px ${marginBottom}px ${sidePaddingLeft}px`,
'--page-margin-top': `${vertical ? marginTop * 1.5 : marginTop}px`,
'--page-margin-right': `${vertical ? marginRight : sidePaddingRight}px`,
'--page-margin-bottom': `${vertical ? marginBottom * 1.5 : marginBottom}px`,
'--page-margin-left': `${vertical ? marginLeft : sidePaddingLeft}px`,
'--full-width': `${Math.trunc(availableWidth)}`,
'--full-height': `${Math.trunc(availableHeight)}`,
'--available-width': `${availableWidth}`,
'--available-height': `${availableHeight}`,
})
setStylesImportant(doc.body, {
'max-height': 'none',
'max-width': 'none',
'margin': '0',
// Prevent position:absolute/fixed on body from coupling its
// size to the iframe, which causes diverging expand() loops
'position': 'static',
})
this.setImageSize(availableWidth, availableHeight)
this.expand()
}
setImageSize(availableWidth, availableHeight) {
const { width, height, marginTop, marginRight, marginBottom, marginLeft } = this.#layout
const vertical = this.#vertical
const doc = this.document
const pageFullscreen = doc.documentElement.hasAttribute('data-duokan-page-fullscreen')
// The fullscreen treatment pins the image with position:absolute and
// height:100% so it fills the fixed-height page. That only works in
// paginated (columnized) mode; in scrolled mode the container height is
// `auto`, so height:100% resolves to 0 and the cover collapses out of
// sight (#4379). Apply it only when columnized.
const applyFullscreen = pageFullscreen && this.#column
for (const el of doc.body.querySelectorAll('img, svg, video')) {
// clear previous inline constraints so we read CSS-authored values,
// not stale pixel values from a previous resize (#3634)
el.style.removeProperty('max-width')
el.style.removeProperty('max-height')
// preserve max size if they are already set in CSS
let { maxHeight, maxWidth } = doc.defaultView.getComputedStyle(el)
if (parseInt(maxWidth) > availableWidth) {
maxWidth = `${availableWidth}px`
}
if (parseInt(maxHeight) > availableHeight) {
maxHeight = `${availableHeight}px`
}
setStylesImportant(el, {
'max-height': vertical
? (maxHeight !== 'none' && maxHeight !== '0px' ? maxHeight : '100%')
: `${height - (applyFullscreen ? 0 : (marginTop + marginBottom))}px`,
'max-width': vertical
? `${width - (applyFullscreen ? 0 : (marginLeft + marginRight))}px`
: (maxWidth !== 'none' && maxWidth !== '0px' ? maxWidth : '100%'),
'object-fit': 'contain',
'page-break-inside': 'avoid',
'break-inside': 'avoid',
'box-sizing': 'border-box',
})
if (applyFullscreen) {
setStylesImportant(doc.documentElement, {
position: 'relative',
})
setStylesImportant(el, {
position: 'absolute',
inset: '0',
width: '100%',
height: '100%',
margin: '0',
})
let ancestor = el.parentElement
while (ancestor && ancestor !== doc.body) {
setStylesImportant(ancestor, {
width: '100%',
height: '100%',
margin: '0',
padding: '0',
})
ancestor = ancestor.parentElement
}
if (el.localName === 'svg') {
el.setAttribute('preserveAspectRatio', 'xMidYMid meet')
}
} else if (pageFullscreen) {
// Scrolled mode for a fullscreen-cover doc: undo any absolute
// pinning left over from a previous paginated render so the
// image flows normally, bounded by the max-height set above
// (#4379). Without this, toggling paginated -> scrolled keeps
// the stale position:absolute/height:100% and the cover stays
// collapsed.
doc.documentElement.style.removeProperty('position')
for (const prop of ['position', 'inset', 'width', 'height', 'margin']) {
el.style.removeProperty(prop)
}
let ancestor = el.parentElement
while (ancestor && ancestor !== doc.body) {
for (const prop of ['width', 'height', 'margin', 'padding']) {
ancestor.style.removeProperty(prop)
}
ancestor = ancestor.parentElement
}
}
}
}
get #zoom() {
// Safari does not zoom the client rects, while Chrome, Edge and Firefox does
if (/^((?!chrome|android).)*AppleWebKit/i.test(navigator.userAgent) && !window.chrome) {
return window.getComputedStyle(this.document.body).zoom || 1.0
}
return 1.0
}
expand() {
if (!this.document?.documentElement) return
const { documentElement } = this.document
if (this.#column) {
const side = this.#vertical ? 'height' : 'width'
const otherSide = this.#vertical ? 'width' : 'height'
const contentRect = this.#contentRange.getBoundingClientRect()
const rootRect = documentElement.getBoundingClientRect()
// offset caused by column break at the start of the page
// which seem to be supported only by WebKit and only for horizontal writing
const contentStart = this.#vertical ? 0
: this.#rtl ? rootRect.right - contentRect.right : contentRect.left - rootRect.left
const contentSize = (contentStart + contentRect[side]) * this.#zoom
// Size content by individual columns, not full spreads.
// This allows adjacent sections to share a spread when a
// section doesn't fill all available columns.
const columnSize = this.#size / this.#columnCount
const pageCount = Math.ceil(contentSize / columnSize)
this.#contentPages = pageCount
const expandedSize = pageCount * columnSize
this.#element.style.padding = '0'
this.#iframe.style[side] = `${expandedSize}px`
this.#element.style[side] = `${expandedSize}px`
this.#iframe.style[otherSide] = '100%'
this.#element.style[otherSide] = '100%'
// One column per "page" — overflow columns extend into adjacent pages
documentElement.style[side] = `${columnSize}px`
if (this.#overlayer) {
this.#overlayer.element.style.margin = '0'
this.#overlayer.element.style.left = '0'
this.#overlayer.element.style.top = '0'
this.#overlayer.element.style[side] = `${expandedSize}px`
this.#overlayer.redraw()
}
} else {
const side = this.#vertical ? 'width' : 'height'
const otherSide = this.#vertical ? 'height' : 'width'
const contentSize = documentElement.getBoundingClientRect()[side]
let expandedSize = contentSize
// If the section has a background image, ensure the view is
// at least as large as the image scaled to fit the cross axis
if (this.#bgImageSize) {
const crossSize = this.#element.getBoundingClientRect()[otherSide]
if (crossSize > 0) {
const { width: imgW, height: imgH } = this.#bgImageSize
const scaledSize = this.#vertical
? imgW * crossSize / imgH
: imgH * crossSize / imgW
expandedSize = Math.max(expandedSize, scaledSize)
}
}
this.#element.style.padding = '0'
this.#iframe.style[side] = `${expandedSize}px`
this.#element.style[side] = `${expandedSize}px`
this.#iframe.style[otherSide] = '100%'
this.#element.style[otherSide] = '100%'
if (this.#overlayer) {
this.#overlayer.element.style.margin = '0'
this.#overlayer.element.style.left = '0'
this.#overlayer.element.style.top = '0'
this.#overlayer.element.style[side] = `${expandedSize}px`
this.#overlayer.redraw()
}
}
this.onExpand()
}
set overlayer(overlayer) {
this.#overlayer = overlayer
this.#element.append(overlayer.element)
}
get overlayer() {
return this.#overlayer
}
#loupeEl = null
#loupeScaler = null
#loupeCursor = null
// Show a magnifier loupe inside the iframe document.
// winX/winY are in main-window (screen) coordinates.
showLoupe(winX, winY, { isVertical, color, gap, margin, radius, magnification }) {
const doc = this.document
if (!doc) return
const frameRect = this.#iframe.getBoundingClientRect()
// Cursor in iframe-viewport coordinates.
const vpX = winX - frameRect.left
const vpY = winY - frameRect.top
// Cursor in document coordinates (accounts for scroll).
const scrollX = doc.scrollingElement?.scrollLeft ?? 0
const scrollY = doc.scrollingElement?.scrollTop ?? 0
const docX = vpX + scrollX
const docY = vpY + scrollY
const MAGNIFICATION = magnification
const MARGIN = margin
// Capsule dimensions: elongated along the reading direction.
// For horizontal text the capsule is wider; for vertical it is taller.
const shortSide = radius * 2
const longSide = Math.round(radius * 3.6)
const loupeW = isVertical ? shortSide : longSide
const loupeH = isVertical ? longSide : shortSide
const halfW = loupeW / 2
const halfH = loupeH / 2
const borderRadius = shortSide / 2 // fully rounded ends
// Position loupe above the cursor (or to the left for vertical text).
const GAP = gap
let loupeLeft = isVertical ? vpX - loupeW - GAP : vpX - halfW
let loupeTop = isVertical ? vpY - halfH : vpY - loupeH - GAP
loupeLeft = Math.max(MARGIN, Math.min(loupeLeft, frameRect.width - loupeW - MARGIN))
loupeTop = Math.max(MARGIN, Math.min(loupeTop, frameRect.height - loupeH - MARGIN))
// CSS-transform math: map document point (docX, docY) to loupe centre.
// visual_pos = offset + coord × MAGNIFICATION = halfW (or halfH)
// ⟹ offset = half − coord × MAGNIFICATION
const offsetX = halfW - docX * MAGNIFICATION
const offsetY = halfH - docY * MAGNIFICATION
// Build loupe DOM structure once; cache it across hide/show cycles so
// the expensive body clone is not repeated on every drag start.
if (!this.#loupeEl || !this.#loupeEl.isConnected) {
this.#loupeEl = doc.createElement('div')
// Clone the live body once — inside the iframe the epub's CSS
// variables, @font-face fonts, and styles apply automatically.
const bodyClone = doc.body.cloneNode(true)
// Wrap the clone in a div that replicates documentElement's inline
// styles (column-width, column-gap, padding, height, etc.) so text
// flows with the same column layout as the original document.
const htmlWrapper = doc.createElement('div')
htmlWrapper.style.cssText = doc.documentElement.style.cssText
// expand() constrains documentElement's page-axis dimension to one
// page size (width for horizontal, height for vertical). Override
// with the full scroll dimension so all columns are rendered.
if (this.#vertical)
htmlWrapper.style.height = `${doc.documentElement.scrollHeight}px`
else
htmlWrapper.style.width = `${doc.documentElement.scrollWidth}px`
htmlWrapper.appendChild(bodyClone)
this.#loupeScaler = doc.createElement('div')
this.#loupeScaler.appendChild(htmlWrapper)
const cursorLen = Math.round(shortSide * 0.44)
this.#loupeCursor = doc.createElement('div')
this.#loupeCursor.style.cssText = isVertical
? `position:absolute;left:calc(50% - ${cursorLen / 2}px);top:50%;`
+ `margin-top:-1px;width:${cursorLen}px;height:2px;background:${color};pointer-events:none;z-index:1;box-sizing:border-box;`
: `position:absolute;left:50%;top:calc(50% - ${cursorLen / 2}px);`
+ `margin-left:-1px;width:2px;height:${cursorLen}px;background:${color};pointer-events:none;z-index:1;box-sizing:border-box;`
this.#loupeEl.appendChild(this.#loupeScaler)
this.#loupeEl.appendChild(this.#loupeCursor)
doc.documentElement.appendChild(this.#loupeEl)
// Static loupe shell styles (set once).
this.#loupeEl.style.cssText = `
position: absolute;
width: ${loupeW}px;
height: ${loupeH}px;
border-radius: ${borderRadius}px;
overflow: hidden;
border: 2.5px solid ${color};
box-shadow: 0 6px 24px rgba(0,0,0,0.28);
background-color: var(--theme-bg-color);
z-index: 9999;
pointer-events: none;
user-select: none;
box-sizing: border-box;
contain: strict;
`
// Static scaler styles (set once; only left/top change per move).
this.#loupeScaler.style.cssText = `
position: absolute;
transform: scale(${MAGNIFICATION});
transform-origin: 0 0;
pointer-events: none;
`
}
// Ensure visible (hideLoupe hides via CSS instead of removing).
this.#loupeEl.style.display = ''
// Update only the dynamic position values (fast path on every move).
this.#loupeScaler.style.left = `${offsetX}px`
this.#loupeScaler.style.top = `${offsetY}px`
this.#loupeScaler.style.width = `${doc.documentElement.scrollWidth}px`
this.#loupeScaler.style.height = `${doc.documentElement.scrollHeight}px`
this.#loupeEl.style.left = `${loupeLeft + scrollX}px`
this.#loupeEl.style.top = `${loupeTop + scrollY}px`
// Cut a capsule-shaped hole in the overlayer so highlights don't paint
// over the loupe.
if (this.#overlayer) {
const overlayerRect = this.#overlayer.element.getBoundingClientRect()
const dx = frameRect.left - overlayerRect.left
const dy = frameRect.top - overlayerRect.top
const pad = 3
const cx = loupeLeft + halfW + dx
const cy = loupeTop + halfH + dy
this.#overlayer.setHole(cx, cy, loupeW + pad * 2, loupeH + pad * 2, borderRadius + pad)
}
}
hideLoupe() {
// Hide via CSS instead of removing — keeps the cached body clone so
// the next showLoupe call skips the expensive cloneNode(true).
if (this.#loupeEl) {
this.#loupeEl.style.display = 'none'
}
if (this.#overlayer)
this.#overlayer.clearHole()
}
destroyLoupe() {
if (this.#loupeEl) {
this.#loupeEl.remove()
this.#loupeEl = null
this.#loupeScaler = null
this.#loupeCursor = null
}
if (this.#overlayer)
this.#overlayer.clearHole()
}
destroy() {
if (this.document?.body) this.#observer.unobserve(this.document.body)
this.destroyLoupe()
}
}
// NOTE: everything here assumes the so-called "negative scroll type" for RTL
export class Paginator extends HTMLElement {
static observedAttributes = [
'flow', 'gap', 'margin-top', 'margin-bottom', 'margin-left', 'margin-right',
'max-inline-size', 'max-block-size', 'max-column-count',
'no-preload', 'no-background', 'no-continuous-scroll',
]
#root = this.attachShadow({ mode: 'open' })
#observer = new ResizeObserver(() => this.render())
#top
#background
#container
#header
#footer
#views = new Map() // Map<sectionIndex, View>
#primaryIndex = -1
#vertical = false
#rtl = false
#marginTop = 0
#marginBottom = 0
#anchor = 0 // anchor view to a fraction (0-1), Range, or Element
#justAnchored = false
#locked = false // while true, prevent any further navigation
#styles
#styleMap = new WeakMap()
#mediaQuery = matchMedia('(prefers-color-scheme: dark)')
#mediaQueryListener
#scrollBounds
#touchState
#touchScrolled
#lastVisibleRange
#scrollLocked = false
#isAnimating = false
#filling = false // true while #fillVisibleArea is running
#fillPromise = null // tracks in-progress #fillVisibleArea for awaiting
#stabilizing = false // true while #display is stabilizing layout
#rendered = false // true after first #display completes
#lastLayout = null // cached layout from the last #beforeRender call
// Cache of section index → vertical (boolean). Populated as views
// are loaded so we can check direction *before* loading a section.
#directionCache = new Map()
constructor() {
super()
this.#root.innerHTML = `<style>
:host {
display: block;
container-type: size;
}
:host, #top {
box-sizing: border-box;
position: relative;
overflow: hidden;
width: 100%;
height: 100%;
}
#top {
--_gap: 7%;
--_margin-top: 48px;
--_margin-right: 48px;
--_margin-bottom: 48px;
--_margin-left: 48px;
--_max-inline-size: 720px;
--_max-block-size: 1440px;
--_max-column-count: 2;
--_max-column-count-portrait: var(--_max-column-count);
--_max-column-count-spread: var(--_max-column-count);
--_half-gap: calc(var(--_gap) / 2);
--_half-margin-left: calc(var(--_margin-left) / 2);
--_half-margin-right: calc(var(--_margin-right) / 2);
--_max-width: calc(var(--_max-inline-size) * var(--_max-column-count-spread));
--_max-height: var(--_max-block-size);
--_column-count: 1;
--_outer-min-left: calc((var(--_column-count) - 1) * (var(--_margin-left) / 4 + var(--_gap) / 4));
--_outer-min-right: calc((var(--_column-count) - 1) * (var(--_margin-right) / 4 + var(--_gap) / 4));
display: grid;
grid-template-columns:
minmax(var(--_outer-min-left), 1fr)
var(--_margin-left)
minmax(0, calc(var(--_max-width) - var(--_gap)))
var(--_margin-right)
minmax(var(--_outer-min-right), 1fr);
grid-template-rows:
minmax(var(--_margin-top), 1fr)
minmax(0, var(--_max-height))
minmax(var(--_margin-bottom), 1fr);
&.vertical {
--_max-column-count-spread: var(--_max-column-count-portrait);
--_max-width: var(--_max-block-size);
--_max-height: calc(var(--_max-inline-size) * var(--_max-column-count-spread));
}
@container (orientation: portrait) {
& {
--_max-column-count-spread: var(--_max-column-count-portrait);
}
&.vertical {
--_max-column-count-spread: var(--_max-column-count);
}
}
}
#background {
grid-column: 1 / -1;
grid-row: 1 / -1;
position: relative;
overflow: hidden;
}
#container {
grid-column: 2 / 5;
grid-row: 1 / -1;
overflow: hidden;
display: flex;
flex-direction: row;
/* GPU acceleration hints for smoother scrolling on high refresh rate displays */
transform: translateZ(0);
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
perspective: 1000px;
-webkit-perspective: 1000px;
transition: opacity 50ms ease-in;
}
#container.vertical {
flex-direction: column;
}