-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRollPDF.html
More file actions
1063 lines (944 loc) · 40.4 KB
/
Copy pathRollPDF.html
File metadata and controls
1063 lines (944 loc) · 40.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RollPDF</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90' fill='%23f5a623'>▣</text></svg>">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Syne:wght@700;800&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f0f11;
--surface: #18181c;
--surface2: #222228;
--border: #2e2e38;
--amber: #f5a623;
--amber-dim: #c4841b;
--amber-glow: rgba(245,166,35,0.12);
--text: #e8e6e0;
--text-dim: #7a7880;
--text-muted: #4a4852;
--radius: 3px;
--toolbar-h: 52px;
}
html, body {
width: 100%; height: 100%;
background: var(--bg);
color: var(--text);
font-family: 'DM Mono', monospace;
font-size: 13px;
overflow: hidden;
user-select: none;
}
/* ── TOOLBAR ─────────────────────────────── */
#toolbar {
position: fixed; top: 0; left: 0; right: 0;
height: var(--toolbar-h);
background: var(--surface);
border-bottom: 1px solid var(--border);
display: flex; align-items: center; gap: 6px;
padding: 0 16px;
z-index: 100;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
scrollbar-width: none; /* Firefox */
transition: transform 0.25s cubic-bezier(0.4,0,0.2,1), opacity 0.25s ease;
}
#toolbar::-webkit-scrollbar { display: none; } /* Chrome/Safari */
body.is-fullscreen #toolbar {
transform: translateY(-100%);
opacity: 0;
pointer-events: none;
background: rgba(24,24,28,0.92);
backdrop-filter: blur(12px);
border-bottom-color: rgba(46,46,56,0.6);
box-shadow: 0 4px 24px rgba(0,0,0,0.5);
}
body.is-fullscreen.toolbar-visible #toolbar {
transform: translateY(0);
opacity: 1;
pointer-events: all;
}
#toolbar-trigger {
display: none;
position: fixed; top: 0; left: 0; right: 0;
height: 20px; z-index: 99;
}
body.is-fullscreen #toolbar-trigger { display: block; }
body.is-fullscreen #viewer.visible { top: 0; }
body.is-fullscreen.cursor-hidden,
body.is-fullscreen.cursor-hidden * { cursor: none !important; }
.tb-logo {
font-family: 'Syne', sans-serif;
font-weight: 800; font-size: 16px;
color: var(--amber);
letter-spacing: -0.5px;
margin-right: 8px;
white-space: nowrap;
cursor: pointer;
transition: opacity 0.15s;
flex-shrink: 0;
}
.tb-logo:hover { opacity: 0.75; }
.tb-sep { width: 1px; height: 24px; background: var(--border); margin: 0 6px; flex-shrink: 0; }
.tb-info {
color: var(--text-dim); font-size: 11px;
white-space: nowrap; overflow: hidden;
text-overflow: ellipsis; max-width: 220px;
flex-shrink: 0;
}
.tb-info span { color: var(--text); }
.tb-spacer { flex-shrink: 0; min-width: 12px; }
#direction-label { display: none; }
.btn {
display: flex; align-items: center; gap: 5px;
padding: 5px 10px;
background: var(--surface2);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--text-dim);
font-family: 'DM Mono', monospace; font-size: 11px;
cursor: pointer; transition: all 0.15s; white-space: nowrap;
flex-shrink: 0;
}
.btn:hover { border-color: var(--amber-dim); color: var(--text); }
.btn.active { background: var(--amber-glow); border-color: var(--amber); color: var(--amber); }
.btn svg { width: 13px; height: 13px; flex-shrink: 0; }
.zoom-display {
padding: 5px 8px;
background: var(--surface2);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--amber); font-size: 11px;
min-width: 56px; text-align: center;
flex-shrink: 0;
}
/* ── DROP ZONE ───────────────────────────── */
#drop-zone {
position: fixed; inset: 0;
display: flex; flex-direction: column;
align-items: center; justify-content: center; gap: 16px;
background: var(--bg); z-index: 50;
transition: background 0.2s;
}
#drop-zone.drag-over { background: rgba(245,166,35,0.04); }
#drop-zone.hidden { display: none; }
.drop-icon {
width: 72px; height: 72px;
border: 2px solid var(--border); border-radius: 8px;
display: flex; align-items: center; justify-content: center;
transition: border-color 0.2s;
}
#drop-zone.drag-over .drop-icon { border-color: var(--amber); }
.drop-icon svg { width: 32px; height: 32px; color: var(--text-muted); }
#drop-zone.drag-over .drop-icon svg { color: var(--amber); }
.drop-title { font-family: 'Syne', sans-serif; font-weight: 800; font-size: 22px; color: var(--text); letter-spacing: -0.5px; }
.drop-sub { font-size: 11px; color: var(--text-muted); text-align: center; line-height: 1.7; }
.drop-btn {
margin-top: 4px; padding: 8px 20px;
background: transparent; border: 1px solid var(--border); border-radius: var(--radius);
color: var(--text-dim); font-family: 'DM Mono', monospace; font-size: 12px;
cursor: pointer; transition: all 0.15s;
}
.drop-btn:hover { border-color: var(--amber); color: var(--amber); }
#file-input { display: none; }
#drag-overlay {
position: fixed; inset: 0; margin: 12px;
border: 2px dashed var(--amber); border-radius: 6px;
pointer-events: none; opacity: 0; transition: opacity 0.15s; z-index: 200;
}
#drag-overlay.visible { opacity: 1; }
/* ── VIEWER ──────────────────────────────── */
#viewer {
position: fixed;
top: var(--toolbar-h); left: 0; right: 0; bottom: 0;
overflow-x: auto; overflow-y: auto;
display: none; background: var(--bg);
cursor: grab;
}
#viewer.visible { display: block; }
#viewer.dragging { cursor: grabbing; }
/* Disable native horizontal pan so JS controls horizontal scroll for both touch and mouse */
#viewer { touch-action: pan-y pinch-zoom; }
#viewer::-webkit-scrollbar { height: 4px; width: 4px; }
#viewer::-webkit-scrollbar-track { background: var(--surface); }
#viewer::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
#viewer::-webkit-scrollbar-thumb:hover { background: var(--amber-dim); }
/* No gap between pages */
#pages-container {
display: flex;
flex-direction: row;
align-items: center;
gap: 0;
padding: 0;
min-height: 100%;
width: max-content;
transform-origin: top left;
will-change: transform; /* GPU-composite the zoom preview */
}
.page-wrapper {
flex-shrink: 0;
display: block;
line-height: 0;
}
.page-wrapper canvas {
display: block; background: #fff;
image-rendering: high-quality;
/* contrast boost preserves thin font strokes when CSS-downscaled */
filter: contrast(1.1);
}
/* Page number overlay */
.page-wrapper .page-num {
position: absolute;
bottom: 6px; left: 50%;
transform: translateX(-50%);
font-size: 10px;
color: rgba(255,255,255,0.55);
background: rgba(0,0,0,0.45);
padding: 1px 6px;
border-radius: 8px;
pointer-events: none;
white-space: nowrap;
opacity: 0;
transition: opacity 0.4s ease;
}
body.overlays-visible .page-num { opacity: 1; }
.page-wrapper { position: relative; }
/* ── LOADING ─────────────────────────────── */
#loading {
position: fixed; inset: 0; background: var(--bg);
display: flex; align-items: center; justify-content: center;
flex-direction: column; gap: 16px;
z-index: 150; opacity: 0; pointer-events: none; transition: opacity 0.2s;
}
#loading.visible { opacity: 1; pointer-events: all; }
.spinner {
width: 32px; height: 32px;
border: 2px solid var(--border); border-top-color: var(--amber);
border-radius: 50%; animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.loading-text { font-size: 11px; color: var(--text-dim); }
#progress-bar {
position: fixed; bottom: 0; left: 0;
height: 2px; background: var(--amber); width: 0%;
z-index: 100; transition: width 0.1s;
box-shadow: 0 0 8px var(--amber);
}
#zoom-hint {
position: fixed; bottom: 20px; right: 20px;
background: var(--surface); border: 1px solid var(--border);
border-radius: var(--radius); padding: 6px 12px;
font-size: 10px; color: var(--text-dim);
opacity: 0; transition: opacity 0.3s; pointer-events: none; z-index: 101;
}
#zoom-hint.visible { opacity: 1; }
#page-indicator {
position: fixed; bottom: 14px; left: 50%; transform: translateX(-50%);
font-size: 10px; color: var(--text-muted); pointer-events: none; z-index: 101;
opacity: 0; transition: opacity 0.4s ease;
}
#page-indicator.visible { opacity: 1; }
/* Continuous scroll indicator */
#scroll-indicator {
position: fixed; bottom: 30px; right: 20px;
background: var(--surface); border: 1px solid var(--amber);
border-radius: var(--radius); padding: 5px 10px;
font-size: 10px; color: var(--amber);
opacity: 0; transition: opacity 0.3s; pointer-events: none; z-index: 101;
}
#scroll-indicator.visible { opacity: 1; }
/* Render progress badge */
#render-progress {
position: fixed;
top: calc(var(--toolbar-h) + 10px); right: 16px;
background: var(--surface); border: 1px solid var(--amber);
border-radius: var(--radius); padding: 4px 10px;
font-size: 10px; color: var(--amber);
z-index: 120; opacity: 0; transition: opacity 0.3s;
pointer-events: none;
display: flex; align-items: center; gap: 6px;
}
#render-progress.visible { opacity: 1; }
#render-progress .rp-spinner {
width: 10px; height: 10px;
border: 1.5px solid var(--border); border-top-color: var(--amber);
border-radius: 50%; animation: spin 0.7s linear infinite;
flex-shrink: 0;
}
</style>
</head>
<body>
<div id="drag-overlay"></div>
<div id="toolbar">
<div class="tb-logo" id="tb-logo" title="Open RollPDF on GitHub">▣ RollPDF</div>
<div class="tb-sep"></div>
<div class="tb-info" id="tb-info">Drop a PDF to open</div>
<div class="tb-spacer"></div>
<!-- Binding direction -->
<button class="btn" id="btn-direction" title="Toggle binding direction">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
<path id="dir-arrow" d="M2 8h12M10 4l4 4-4 4"/>
</svg>
<span id="direction-label">L-bind</span>
</button>
<div class="tb-sep"></div>
<!-- Zoom -->
<button class="btn" id="btn-zoom-out" title="Zoom out (Ctrl+-)">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
<circle cx="7" cy="7" r="5"/><path d="M13 13l-2.5-2.5M5 7h4"/>
</svg>
</button>
<div class="zoom-display" id="zoom-display">100%</div>
<button class="btn" id="btn-zoom-in" title="Zoom in (Ctrl++)">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
<circle cx="7" cy="7" r="5"/><path d="M13 13l-2.5-2.5M5 7h4M7 5v4"/>
</svg>
</button>
<!-- Fit height button (replaces 100% reset) -->
<button class="btn" id="btn-fit-height" title="Fit page height">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M8 2v12M5 4l3-3 3 3M5 12l3 3 3-3"/>
</svg>
</button>
<div class="tb-sep"></div>
<!-- Open file -->
<button class="btn" id="btn-open" title="Open file">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M2 4h5l2 2h5v8H2z"/>
</svg>
</button>
<div class="tb-sep"></div>
<!-- Fullscreen -->
<button class="btn" id="btn-fullscreen" title="Fullscreen (F)">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" id="fs-icon">
<path d="M2 5V2h3M11 2h3v3M14 11v3h-3M5 14H2v-3"/>
</svg>
</button>
</div>
<!-- Fullscreen hover trigger -->
<div id="toolbar-trigger"></div>
<!-- Drop zone -->
<div id="drop-zone">
<div class="drop-icon">
<svg viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M6 26h20M16 6v14M10 14l6-6 6 6"/>
</svg>
</div>
<div class="drop-title">Drop a PDF</div>
<div class="drop-sub">Drag & drop a PDF file here<br>or click the button below</div>
<button class="drop-btn" id="drop-open-btn">Choose file</button>
</div>
<!-- Loading -->
<div id="loading">
<div class="spinner"></div>
<div class="loading-text" id="loading-text">Loading PDF…</div>
</div>
<!-- Viewer -->
<div id="viewer">
<div id="pages-container"></div>
</div>
<div id="render-progress"><span class="rp-spinner"></span><span id="render-progress-text"></span></div>
<div id="progress-bar"></div>
<div id="zoom-hint">Ctrl+Wheel to zoom</div>
<div id="page-indicator"></div>
<div id="scroll-indicator">▶▶ Continuous scroll</div>
<input type="file" id="file-input" accept=".pdf,application/pdf">
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
// ── State ─────────────────────────────────────────────
let pdfDoc = null;
let isRTL = false;
let totalPages = 0;
let renderedPages = 0;
let zoomHintTimer = null;
// Zoom model:
// Initial render: fitScale × OVER_RENDER × dpr (high quality headroom)
// CSS zoom gives instant visual feedback on every zoom gesture.
// display resolution (fitScale × uiZoom × dpr) — no spinner, no flash.
// This is the only way to preserve font strokes at arbitrary zoom levels.
const OVER_RENDER = 3.0; // render at 3× fit height for thin-stroke preservation
let fitScale = 1.0; // logical scale so 1 page fills viewer height exactly
let uiZoom = 1.0; // user zoom multiplier (1.0 = fit)
let renderScale = 1.0; // actual PDF.js scale used in last canvas render
// ── Drag / inertia / continuous-scroll state ──────────
let isDragging = false;
let isRendering = false; // true while renderAllPages is running
let dragStartX = 0;
let dragStartY = 0;
let dragScrollLeft = 0;
let dragScrollTop = 0;
let inertiaRAF = null;
let isAutoScroll = false; // continuous scroll active
// Scroll-based velocity tracking (shared by mouse, touch, wheel)
let scrollSamples = []; // [{pos, t}] — scrollLeft samples
let scrollStopTimer = null; // fires when scrolling pauses
const FRICTION = 0.92;
const MIN_VEL = 0.5; // px/frame stop threshold
const VEL_WIN = 80; // ms window for instant velocity
const SCROLL_STOP_DELAY = 120; // ms quiet period → gesture ended
const CONTINUOUS_THRESHOLD = 1000; // ms: sustained scroll → continuous mode
// ── Overlay auto-hide ─────────────────────────────────
// Overlays: page numbers + page indicator + scroll indicator
// Shown on scroll/drag activity; auto-hide after 3s of inactivity
let overlayHideTimer = null;
const OVERLAY_TIMEOUT = 3000; // ms
function showOverlays() {
document.body.classList.add('overlays-visible');
pageIndicator.classList.add('visible');
clearTimeout(overlayHideTimer);
overlayHideTimer = setTimeout(hideOverlays, OVERLAY_TIMEOUT);
}
function hideOverlays() {
document.body.classList.remove('overlays-visible');
pageIndicator.classList.remove('visible');
// scroll-indicator is managed separately (stays while continuous scrolling)
}
// ── Elements ──────────────────────────────────────────
const dropZone = document.getElementById('drop-zone');
const viewer = document.getElementById('viewer');
const pagesContainer = document.getElementById('pages-container');
const loading = document.getElementById('loading');
const loadingText = document.getElementById('loading-text');
const progressBar = document.getElementById('progress-bar');
const zoomDisplay = document.getElementById('zoom-display');
const tbInfo = document.getElementById('tb-info');
const btnDirection = document.getElementById('btn-direction');
const directionLabel = document.getElementById('direction-label');
const dirArrow = document.getElementById('dir-arrow');
const btnZoomIn = document.getElementById('btn-zoom-in');
const btnZoomOut = document.getElementById('btn-zoom-out');
const btnFitHeight = document.getElementById('btn-fit-height');
const zoomHint = document.getElementById('zoom-hint');
const pageIndicator = document.getElementById('page-indicator');
const scrollIndicator = document.getElementById('scroll-indicator');
const renderProgress = document.getElementById('render-progress');
const renderProgressText = document.getElementById('render-progress-text');
const fileInput = document.getElementById('file-input');
const dragOverlay = document.getElementById('drag-overlay');
const btnFullscreen = document.getElementById('btn-fullscreen');
const fsIcon = document.getElementById('fs-icon');
const toolbarTrigger = document.getElementById('toolbar-trigger');
// ── Fullscreen ────────────────────────────────────────
function enterFullscreen() { document.documentElement.requestFullscreen().catch(() => {}); }
function exitFullscreen() { if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); }
let toolbarHideTimer = null;
function showToolbar() {
document.body.classList.add('toolbar-visible');
clearTimeout(toolbarHideTimer);
toolbarHideTimer = setTimeout(() => document.body.classList.remove('toolbar-visible'), 2200);
}
// ── Fullscreen cursor auto-hide (3s inactivity) ───────
let cursorHideTimer = null;
function resetCursorHide() {
if (!document.fullscreenElement) return;
document.body.classList.remove('cursor-hidden');
clearTimeout(cursorHideTimer);
cursorHideTimer = setTimeout(() => {
if (document.fullscreenElement) document.body.classList.add('cursor-hidden');
}, 3000);
}
document.addEventListener('mousemove', resetCursorHide);
document.addEventListener('mousedown', resetCursorHide);
document.addEventListener('fullscreenchange', () => {
const isFs = !!document.fullscreenElement;
document.body.classList.toggle('is-fullscreen', isFs);
fsIcon.innerHTML = isFs
? '<path d="M5 2H2v3M14 5V2h-3M11 14h3v-3M2 11v3h3"/>'
: '<path d="M2 5V2h3M11 2h3v3M14 11v3h-3M5 14H2v-3"/>';
if (!isFs) {
document.body.classList.remove('toolbar-visible');
document.body.classList.remove('cursor-hidden');
clearTimeout(cursorHideTimer);
clearTimeout(toolbarHideTimer);
} else {
// Entering fullscreen: viewer height changed, re-fit after layout settles
requestAnimationFrame(() => applyFitHeight());
resetCursorHide(); // start 3s inactivity timer immediately
}
});
btnFullscreen.addEventListener('click', () =>
document.fullscreenElement ? exitFullscreen() : enterFullscreen()
);
toolbarTrigger.addEventListener('mouseenter', showToolbar);
document.getElementById('toolbar').addEventListener('mouseenter', showToolbar);
document.getElementById('toolbar').addEventListener('mouseleave', () => {
if (!document.body.classList.contains('is-fullscreen')) return;
toolbarHideTimer = setTimeout(() => document.body.classList.remove('toolbar-visible'), 400);
});
// ── URL parameter parsing ─────────────────────────────
function getParams() {
const p = new URLSearchParams(window.location.search);
return {
pdfUrl: p.get('pdf') || p.get('url') || null,
page: parseInt(p.get('page')) || 1,
binding: (p.get('binding') || '').toUpperCase(), // 'R' | 'L'
autoscroll: (p.get('autoscroll') || '').toLowerCase(), // 'on' | 'off'
};
}
// ── File loading ──────────────────────────────────────
async function loadFile(file) {
if (!file) return;
stopScroll();
showLoading('Loading PDF…');
try {
const buf = await file.arrayBuffer();
const loadingTask = pdfjsLib.getDocument({ data: buf, cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/cmaps/', cMapPacked: true });
loadingTask.onProgress = (d) => {
if (d.total) progressBar.style.width = Math.round((d.loaded / d.total) * 50) + '%';
};
pdfDoc = await loadingTask.promise;
totalPages = pdfDoc.numPages;
const displayName = (() => { try { return decodeURIComponent(file.name); } catch(_) { return file.name; } })();
tbInfo.innerHTML = `<span>${displayName.replace(/\.pdf$/i, '')}</span>`;
await afterDocLoaded({ page: 1 });
} catch (e) {
showError('Failed to load PDF');
console.error(e);
}
}
async function loadUrl(url, params) {
stopScroll();
showLoading('Fetching PDF…');
try {
const loadingTask = pdfjsLib.getDocument({ url, withCredentials: false, cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/cmaps/', cMapPacked: true });
loadingTask.onProgress = (d) => {
if (d.total) progressBar.style.width = Math.round((d.loaded / d.total) * 50) + '%';
};
pdfDoc = await loadingTask.promise;
totalPages = pdfDoc.numPages;
const rawName = url.split('/').pop().replace(/\.pdf$/i, '') || 'document';
const name = (() => { try { return decodeURIComponent(rawName); } catch(_) { return rawName; } })();
tbInfo.innerHTML = `<span>${name}</span>`;
await afterDocLoaded(params);
} catch (e) {
showError('Failed to fetch PDF');
console.error(e);
}
}
// Shared post-load steps: detect binding, fit height, render, scroll to page
async function afterDocLoaded(params) {
// 1. Detect binding from ViewerPreferences (unless overridden by URL param)
if (params.binding === 'R') {
isRTL = true;
} else if (params.binding === 'L') {
isRTL = false;
} else {
try {
const prefs = await pdfDoc.getViewerPreferences();
isRTL = !!(prefs && prefs.Direction === 'R2L');
} catch (_) {}
}
updateDirectionUI();
// 2. Compute fit-height scale from first page before rendering
await applyFitHeight();
dropZone.classList.add('hidden');
viewer.classList.add('visible');
hideLoading(); // hide full-screen overlay so viewer is immediately visible
// 3. Render all pages
await renderAllPages(params.page);
// 4. Autoscroll from URL param
if (params.autoscroll === 'on') {
// start continuous scroll at a default gentle speed
startContinuous(2 * (isRTL ? -1 : 1));
}
}
// ── Fit height ────────────────────────────────────────
async function applyFitHeight() {
if (!pdfDoc) return;
try {
const page = await pdfDoc.getPage(1);
const vp1 = page.getViewport({ scale: 1.0 });
const viewerH = viewer.clientHeight || window.innerHeight;
fitScale = viewerH / vp1.height;
uiZoom = 1.0;
zoomDisplay.textContent = '100%';
if (pagesContainer.children.length > 0) {
// Instant CSS feedback
if (renderScale > 0) {
// Save current scroll ratio before the zoom change alters scrollWidth
// (same approach as setScale — without this, changing zoom shifts what
// is visible: harmless for L-bind, where page 1 sits at scrollLeft 0,
// but for R-bind, where page 1 is pinned to the *right* edge via an
// absolute scrollLeft, that value goes stale and a different page ends
// up on screen).
const prevMax = viewer.scrollWidth - viewer.clientWidth;
const ratio = prevMax > 0 ? viewer.scrollLeft / prevMax : 0;
pagesContainer.style.zoom = String(fitScale / renderScale);
// Restore scroll position after layout updates
requestAnimationFrame(() => {
const newMax = viewer.scrollWidth - viewer.clientWidth;
viewer.scrollLeft = ratio * newMax;
});
}
// Then re-render at exact fit resolution
}
} catch (e) { console.error('fitHeight:', e); }
}
// ── Render all pages ──────────────────────────────────
async function renderAllPages(targetPage) {
if (!pdfDoc) return;
// Show small render-progress badge (non-blocking) instead of full loading overlay
pagesContainer.innerHTML = '';
renderedPages = 0;
const dpr = window.devicePixelRatio || 1;
renderScale = fitScale * OVER_RENDER; // render at 2× fit height (no re-render on zoom)
const physScale = renderScale * dpr; // physical px per PDF point
pagesContainer.style.zoom = String(uiZoom / OVER_RENDER); // CSS zoom so fit = 100%
// R-bind: reverse flex layout so page 1 is at the visual right end
pagesContainer.style.flexDirection = isRTL ? 'row-reverse' : '';
renderProgressText.textContent = `0 / ${totalPages}`;
renderProgress.classList.add('visible');
isRendering = true;
// Track whether user has scrolled/dragged during loading
let userScrolledDuringLoad = false;
const onUserScroll = () => { userScrolledDuringLoad = true; };
viewer.addEventListener('scroll', onUserScroll, { passive: true });
const nums = Array.from({ length: totalPages }, (_, i) => i + 1);
for (const pageNum of nums) {
try {
const page = await pdfDoc.getPage(pageNum);
const viewport = page.getViewport({ scale: physScale });
const wrapper = document.createElement('div');
wrapper.className = 'page-wrapper';
wrapper.dataset.page = pageNum;
const canvas = document.createElement('canvas');
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
// CSS size = logical pixels (physical ÷ dpr)
canvas.style.width = Math.floor(viewport.width / dpr) + 'px';
canvas.style.height = Math.floor(viewport.height / dpr) + 'px';
const ctx = canvas.getContext('2d');
await page.render({ canvasContext: ctx, viewport }).promise;
wrapper.appendChild(canvas);
// Page number overlay
const numEl = document.createElement('div');
numEl.className = 'page-num';
numEl.textContent = pageNum;
wrapper.appendChild(numEl);
// Always append in page order 1→N regardless of binding direction.
// row-reverse layout places page 1 at the visual right end.
if (isRTL) {
const prevScrollWidth = viewer.scrollWidth;
pagesContainer.appendChild(wrapper);
const addedWidth = viewer.scrollWidth - prevScrollWidth;
if (isDragging) {
// During drag: don't touch scrollLeft (drag formula owns it).
// Instead shift the drag anchor so the formula stays coherent.
dragScrollLeft += addedWidth;
} else if (userScrolledDuringLoad) {
// Compensate: new page added to visual left shifts existing content right
viewer.scrollLeft += addedWidth;
} else {
// User hasn't scrolled yet: pin to right end so page 1 stays visible
viewer.scrollLeft = viewer.scrollWidth - viewer.clientWidth;
}
} else {
pagesContainer.appendChild(wrapper);
}
renderedPages++;
progressBar.style.width = (50 + Math.round((renderedPages / totalPages) * 50)) + '%';
renderProgressText.textContent = `${renderedPages} / ${totalPages}`;
} catch (e) {
console.error(`Page ${pageNum}:`, e);
}
}
viewer.removeEventListener('scroll', onUserScroll);
isRendering = false;
renderProgress.classList.remove('visible');
progressBar.style.width = '100%';
setTimeout(() => { progressBar.style.width = '0%'; }, 800);
// Only scroll when an explicit non-default page was requested (e.g. ?page=5)
if (targetPage && targetPage > 1) {
requestAnimationFrame(() => {
scrollToPage(targetPage);
updatePageIndicator();
});
} else {
requestAnimationFrame(updatePageIndicator);
}
if (!localStorage.getItem('zoomHintSeen')) {
showZoomHint();
localStorage.setItem('zoomHintSeen', '1');
}
}
// ── Get currently visible page number ────────────────
function getCurrentPage() {
if (!pdfDoc) return 1;
const max = viewer.scrollWidth - viewer.clientWidth;
const pct = max > 0 ? viewer.scrollLeft / max : 0;
// RTL: row-reverse layout; page 1 is rightmost (pct=1), page N is leftmost (pct=0)
return isRTL
? Math.max(1, totalPages - Math.floor(pct * totalPages))
: Math.max(1, Math.ceil(pct * totalPages) || 1);
}
// ── Scroll to page number ─────────────────────────────
function scrollToPage(pageNum) {
if (!pdfDoc) return;
const clampedPage = Math.max(1, Math.min(totalPages, pageNum));
// DOM is always 1→N; offsetLeft already reflects row-reverse positioning for RTL
const wrappers = pagesContainer.querySelectorAll('.page-wrapper');
const wrapper = wrappers[clampedPage - 1];
viewer.scrollLeft = wrapper ? wrapper.offsetLeft : (isRTL ? viewer.scrollWidth : 0);
}
// ── Logo click → GitHub ───────────────────────────────
document.getElementById('tb-logo').addEventListener('click', () => {
window.open('https://github.com/covao/RollPDF', '_blank', 'noopener');
});
// ── Direction toggle ──────────────────────────────────
function updateDirectionUI() {
directionLabel.textContent = isRTL ? 'R-bind' : 'L-bind';
dirArrow.setAttribute('d', isRTL
? 'M14 8H2M6 4L2 8l4 4'
: 'M2 8h12M10 4l4 4-4 4');
}
btnDirection.addEventListener('click', () => {
isRTL = !isRTL;
updateDirectionUI();
if (pdfDoc) renderAllPages(1);
});
// ── Zoom (CSS-only — no re-render) ────────────────────
const SCALE_STEP = 0.1; // 10% per step relative to fit
const SCALE_MIN = 0.1; // 10% of fit height
const SCALE_MAX = 5.0; // 500% of fit height
function setScale(v) {
uiZoom = Math.min(SCALE_MAX, Math.max(SCALE_MIN, v));
zoomDisplay.textContent = Math.round(uiZoom * 100) + '%';
if (renderScale > 0) {
// Save current scroll ratio before zoom changes scrollWidth
const prevMax = viewer.scrollWidth - viewer.clientWidth;
const ratio = prevMax > 0 ? viewer.scrollLeft / prevMax : 0;
pagesContainer.style.zoom = String((fitScale * uiZoom) / renderScale);
// Restore scroll position after layout updates
requestAnimationFrame(() => {
const newMax = viewer.scrollWidth - viewer.clientWidth;
viewer.scrollLeft = ratio * newMax;
});
}
}
btnZoomIn.addEventListener('click', () => setScale(uiZoom + SCALE_STEP));
btnZoomOut.addEventListener('click', () => setScale(uiZoom - SCALE_STEP));
btnFitHeight.addEventListener('click', () => applyFitHeight());
// ── Wheel: zoom or scroll ─────────────────────────────
viewer.addEventListener('wheel', (e) => {
e.preventDefault();
if (e.ctrlKey || e.metaKey) {
setScale(uiZoom + (e.deltaY > 0 ? -SCALE_STEP : SCALE_STEP));
showZoomHint();
return;
}
stopActiveScroll(); // stop rAF animation but keep scroll samples accumulating
const raw = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
const dir = isRTL ? -1 : 1;
viewer.scrollLeft += raw * dir * 1.5;
// showOverlays() and updatePageIndicator() handled by scroll event listener
}, { passive: false });
// ── Mouse drag ────────────────────────────────────────
viewer.addEventListener('mousedown', (e) => {
if (e.button !== 0) return;
if (isRendering && isRTL) return;
stopScroll(); // new gesture: clear samples + stop animation
showOverlays();
isDragging = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
dragScrollLeft = viewer.scrollLeft;
dragScrollTop = viewer.scrollTop;
viewer.classList.add('dragging');
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
viewer.scrollLeft = dragScrollLeft + (dragStartX - e.clientX);
viewer.scrollTop = dragScrollTop + (dragStartY - e.clientY);
// scroll event fires automatically → scrollSamples updated
});
document.addEventListener('mouseup', () => {
if (!isDragging) return;
isDragging = false;
viewer.classList.remove('dragging');
// onScrollStopped() fires via scrollStopTimer after SCROLL_STOP_DELAY
});
// ── Touch drag ────────────────────────────────────────
let touchStartX = 0;
let touchStartY = 0;
let touchScrollLeft = 0;
let touchScrollTop = 0;
viewer.addEventListener('touchstart', (e) => {
if (e.touches.length !== 1) return;
stopScroll(); // new gesture
showOverlays();
isDragging = true;
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
touchScrollLeft = viewer.scrollLeft;
touchScrollTop = viewer.scrollTop;
}, { passive: true });
viewer.addEventListener('touchmove', (e) => {
if (!isDragging || e.touches.length !== 1) return;
const dx = touchStartX - e.touches[0].clientX;
const dy = touchStartY - e.touches[0].clientY;
if (Math.abs(dx) > Math.abs(dy)) e.preventDefault(); // block native horizontal scroll
viewer.scrollLeft = touchScrollLeft + dx;
viewer.scrollTop = touchScrollTop + dy;
}, { passive: false });
viewer.addEventListener('touchend', () => { if (isDragging) isDragging = false; });
viewer.addEventListener('touchcancel', () => { isDragging = false; });
// ── Scroll-based velocity tracker (mouse / touch / wheel unified) ─────────
viewer.addEventListener('scroll', () => {
if (isAutoScroll) return; // ignore rAF-driven scroll events
showOverlays();
updatePageIndicator();
const now = performance.now();
scrollSamples.push({ pos: viewer.scrollLeft, t: now });
// Trim samples older than 1.5 s
while (scrollSamples.length > 1 && now - scrollSamples[0].t > 1500) scrollSamples.shift();
clearTimeout(scrollStopTimer);
scrollStopTimer = setTimeout(onScrollStopped, SCROLL_STOP_DELAY);
}, { passive: true });
function onScrollStopped() {
if (isAutoScroll || isDragging || scrollSamples.length < 2) {
scrollSamples = [];
return;
}
const now = performance.now();
// Instantaneous velocity from the most recent samples
const horizon = VEL_WIN + SCROLL_STOP_DELAY + 20;
const recent = scrollSamples.filter(s => now - s.t <= horizon);
let instVel = 0;
if (recent.length >= 2) {
const a = recent[0], b = recent[recent.length - 1];
const dt = b.t - a.t;
if (dt > 0) instVel = ((b.pos - a.pos) / dt) * (1000 / 60);
}
const duration = scrollSamples[scrollSamples.length - 1].t - scrollSamples[0].t;
scrollSamples = [];
if (Math.abs(instVel) < MIN_VEL) return;
if (duration >= CONTINUOUS_THRESHOLD) {
startContinuous(instVel);
} else {
startInertia(instVel);
}
}
// ── Inertia (friction decay) ──────────────────────────
function startInertia(vel) {
stopActiveScroll();
isAutoScroll = false;
showOverlays();
function tick() {
if (Math.abs(vel) < MIN_VEL) { inertiaRAF = null; return; }
viewer.scrollLeft += vel;
vel *= FRICTION;
updatePageIndicator();
inertiaRAF = requestAnimationFrame(tick);
}
inertiaRAF = requestAnimationFrame(tick);
}
// ── Continuous scroll (constant speed) ───────────────
let scrollIndicatorTimer = null;
function startContinuous(vel) {
stopActiveScroll();
isAutoScroll = true;
showOverlays();
scrollIndicator.classList.add('visible');
clearTimeout(scrollIndicatorTimer);
scrollIndicatorTimer = setTimeout(() => scrollIndicator.classList.remove('visible'), OVERLAY_TIMEOUT);
function tick() {
const maxScroll = viewer.scrollWidth - viewer.clientWidth;
const atEnd = vel > 0 ? viewer.scrollLeft >= maxScroll - 1 : viewer.scrollLeft <= 1;
if (atEnd) { inertiaRAF = null; isAutoScroll = false; scrollIndicator.classList.remove('visible'); return; }
viewer.scrollLeft += vel;
updatePageIndicator();
inertiaRAF = requestAnimationFrame(tick);
}
inertiaRAF = requestAnimationFrame(tick);
}
function stopActiveScroll() {
if (inertiaRAF) { cancelAnimationFrame(inertiaRAF); inertiaRAF = null; }
if (isAutoScroll) { isAutoScroll = false; scrollIndicator.classList.remove('visible'); clearTimeout(scrollIndicatorTimer); }
}
function stopScroll() {
stopActiveScroll();
clearTimeout(scrollStopTimer);
scrollSamples = [];
}
function updatePageIndicator() {
if (!pdfDoc) return;
const max = viewer.scrollWidth - viewer.clientWidth;
const pct = max > 0 ? viewer.scrollLeft / max : 0;
// RTL: row-reverse layout; page 1 is rightmost (pct=1), page N is leftmost (pct=0)
const approxPage = isRTL
? Math.max(1, totalPages - Math.floor(pct * totalPages))
: Math.max(1, Math.ceil(pct * totalPages) || 1);
pageIndicator.textContent = `${approxPage} / ${totalPages}`;
}
// Note: updatePageIndicator is called from the unified scroll event listener above
// ── File drag & drop ──────────────────────────────────
let dragCounter = 0;
document.addEventListener('dragenter', (e) => {
e.preventDefault(); dragCounter++;
dragOverlay.classList.add('visible');
dropZone.classList.add('drag-over');