-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf.html
More file actions
1020 lines (843 loc) · 49.8 KB
/
Copy pathpdf.html
File metadata and controls
1020 lines (843 loc) · 49.8 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" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Power Engine Pro</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- PDF.js for rendering and text extraction -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<!-- PDF-lib for editing and generating PDFs -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"></script>
<!-- SortableJS for Drag & Drop Organizing -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<!-- Phosphor Icons -->
<script src="https://unpkg.com/@phosphor-icons/web"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
body { font-family: 'Inter', system-ui, sans-serif; background-color: #020617; color: #f8fafc; overflow: hidden; }
/* Professional Scrollbars */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #475569; }
.page-wrapper {
box-shadow: 0 20px 40px -10px rgba(0, 0, 0, 0.7), 0 0 0 1px rgba(255,255,255,0.05);
transition: opacity 0.3s ease, transform 0.3s ease, margin 0.3s ease, height 0.3s ease, box-shadow 0.2s ease;
transform-origin: center center;
}
.page-wrapper.deleting {
opacity: 0;
transform: scale(0.8);
margin: 0 !important;
height: 0 !important;
overflow: hidden;
}
.canvas-container {
transition: transform 0.3s ease;
}
/* Organize Mode Grid System */
.organize-mode {
flex-direction: row !important;
flex-wrap: wrap !important;
justify-content: center !important;
align-content: flex-start;
padding: 3rem !important;
gap: 2rem !important;
}
.page-wrapper.thumbnail {
width: 200px !important;
height: auto !important;
cursor: grab;
border-radius: 8px;
overflow: visible;
}
.page-wrapper.thumbnail:active {
cursor: grabbing;
transform: scale(1.05);
box-shadow: 0 30px 60px -15px rgba(0, 0, 0, 0.9), 0 0 0 2px #3b82f6;
z-index: 50;
}
.page-wrapper.thumbnail canvas {
border-radius: 8px;
}
.page-wrapper.thumbnail .page-label {
font-size: 14px;
padding: 4px 8px;
background-color: #3b82f6 !important;
color: #ffffff !important;
border-radius: 4px;
}
.page-wrapper.thumbnail .canvas-container {
pointer-events: none; /* Prevents text selection inside canvas while dragging */
}
/* Grid Background for Viewer */
.viewer-bg {
background-size: 40px 40px;
background-image: linear-gradient(to right, rgba(255, 255, 255, 0.02) 1px, transparent 1px),
linear-gradient(to bottom, rgba(255, 255, 255, 0.02) 1px, transparent 1px);
}
/* Spinners */
.loader-ring {
border: 3px solid rgba(59, 130, 246, 0.2);
border-top: 3px solid #3b82f6;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
/* Color Picker Reset */
input[type="color"] {
-webkit-appearance: none;
border: none;
width: 28px;
height: 28px;
border-radius: 6px;
padding: 0;
overflow: hidden;
cursor: pointer;
box-shadow: 0 0 0 1px rgba(255,255,255,0.1);
}
input[type="color"]::-webkit-color-swatch-wrapper { padding: 0; }
input[type="color"]::-webkit-color-swatch { border: none; border-radius: 6px; }
/* Toast Notifications */
#toastContainer {
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s;
}
</style>
</head>
<body class="h-screen w-screen flex flex-col text-sm antialiased">
<!-- Drag & Drop Overlay -->
<div id="dragOverlay" class="fixed inset-0 bg-blue-900/60 z-[200] hidden flex-col items-center justify-center backdrop-blur-sm border-8 border-blue-500 transition-all pointer-events-none">
<div class="bg-slate-900 p-10 rounded-3xl shadow-2xl flex flex-col items-center border border-slate-700 pointer-events-none transform scale-105">
<i class="ph-fill ph-file-arrow-down text-7xl text-blue-400 mb-6 animate-bounce"></i>
<h2 class="text-3xl font-bold text-white tracking-tight">Drop PDF here</h2>
<p class="text-slate-400 mt-2 font-medium">Release to open document in Engine</p>
</div>
</div>
<!-- Non-Blocking Toast Notification -->
<div id="toastContainer" class="fixed bottom-6 left-1/2 -translate-x-1/2 translate-y-20 opacity-0 z-[150] bg-slate-800 text-white px-5 py-3 rounded-full shadow-2xl border border-slate-700 flex items-center gap-3 pointer-events-none">
<i id="toastIcon" class="ph-fill ph-info text-blue-400 text-lg"></i>
<span id="toastMessage" class="font-medium text-sm">Action completed</span>
</div>
<!-- Full Screen Blocking Loader -->
<div id="loadingOverlay" class="fixed inset-0 bg-slate-950/90 z-[100] hidden flex-col items-center justify-center backdrop-blur-md transition-opacity">
<div class="loader-ring mb-5"></div>
<h2 id="loadingText" class="text-xl font-bold text-white tracking-tight">Processing Engine...</h2>
<p id="loadingSubtext" class="text-slate-400 mt-2 text-xs font-medium">Running high-performance PDF operations</p>
<div id="renderProgressContainer" class="w-64 h-1.5 bg-slate-800 rounded-full mt-6 hidden overflow-hidden">
<div id="renderProgressBar" class="h-full bg-blue-500 transition-all duration-200" style="width: 0%"></div>
</div>
</div>
<!-- Header Navigation -->
<header class="bg-slate-900 border-b border-slate-800 h-16 px-6 flex justify-between items-center shrink-0 z-30 shadow-sm relative">
<div class="flex items-center gap-4">
<div class="bg-gradient-to-br from-blue-600 to-indigo-600 p-2 rounded-xl shadow-lg shadow-blue-900/20">
<i class="ph-fill ph-file-pdf text-white text-xl"></i>
</div>
<div>
<h1 class="text-base font-bold tracking-wide text-slate-100 flex items-center gap-2">
Power Engine
<span class="text-[10px] font-black bg-blue-500/20 text-blue-400 px-2 py-0.5 rounded-full uppercase tracking-wider border border-blue-500/20">Pro</span>
</h1>
</div>
</div>
<!-- Central Toolbar: Undo / Redo -->
<div class="absolute left-1/2 -translate-x-1/2 flex items-center bg-slate-950 rounded-lg p-1 border border-slate-800 shadow-inner">
<button id="undoBtn" class="flex items-center gap-1.5 px-3 py-1.5 rounded-md text-slate-400 hover:text-white hover:bg-slate-800 transition-colors disabled:opacity-30 disabled:cursor-not-allowed" disabled title="Undo (Ctrl+Z)">
<i class="ph-bold ph-arrow-u-up-left"></i>
<span class="text-xs font-semibold">Undo</span>
</button>
<div class="w-px h-4 bg-slate-700 mx-1"></div>
<button id="redoBtn" class="flex items-center gap-1.5 px-3 py-1.5 rounded-md text-slate-400 hover:text-white hover:bg-slate-800 transition-colors disabled:opacity-30 disabled:cursor-not-allowed" disabled title="Redo (Ctrl+Y)">
<span class="text-xs font-semibold">Redo</span>
<i class="ph-bold ph-arrow-u-up-right"></i>
</button>
</div>
<div class="flex items-center gap-5">
<div id="docInfo" class="hidden items-center gap-4 text-xs font-medium text-slate-400 border-r border-slate-800 pr-5">
<span class="flex items-center gap-1.5"><i class="ph-fill ph-files text-slate-500"></i> <span id="infoPages">0 Pages</span></span>
<span class="flex items-center gap-1.5"><i class="ph-fill ph-hard-drives text-slate-500"></i> <span id="infoSize">0 MB</span></span>
</div>
<button id="downloadBtn" class="hidden bg-white text-slate-900 hover:bg-slate-200 px-4 py-2 rounded-lg font-bold transition-all shadow-lg flex items-center gap-2 transform active:scale-95 text-xs">
<i class="ph-bold ph-download-simple text-base"></i>
Export PDF
</button>
</div>
</header>
<!-- Main Workspace -->
<main class="flex-1 flex overflow-hidden bg-slate-950 relative">
<!-- Left Sidebar - Tools -->
<aside class="w-[320px] bg-slate-900/50 backdrop-blur-md border-r border-slate-800 flex flex-col shrink-0 z-20 shadow-2xl relative">
<div class="flex-1 overflow-y-auto p-5 custom-scrollbar space-y-8">
<!-- 1. Source -->
<div class="bg-slate-900 rounded-xl p-4 border border-slate-800 shadow-sm">
<div class="flex items-center gap-2 mb-4">
<div class="w-6 h-6 rounded bg-blue-500/20 flex items-center justify-center"><i class="ph-bold ph-upload-simple text-blue-400"></i></div>
<h3 class="font-semibold text-slate-200 text-xs uppercase tracking-wider">Source Document</h3>
</div>
<label class="flex flex-col items-center justify-center w-full h-24 border border-slate-700 border-dashed rounded-lg cursor-pointer bg-slate-950 hover:bg-slate-800 hover:border-blue-500/50 transition-all group">
<div class="flex flex-col items-center justify-center pt-4 pb-4">
<i class="ph ph-plus-circle text-2xl text-slate-500 group-hover:text-blue-400 mb-1 transition-colors"></i>
<p class="text-[11px] text-slate-400 font-medium">Click to upload or Drag & Drop</p>
</div>
<input id="fileInput" type="file" class="hidden" accept="application/pdf" />
</label>
<div id="fileMeta" class="hidden mt-3 p-2.5 bg-slate-950 rounded border border-slate-800 flex items-center justify-between group">
<span id="fileNameDisplay" class="text-[11px] text-slate-300 truncate font-medium max-w-[200px]"></span>
<button id="clearFileBtn" class="text-slate-500 hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"><i class="ph-bold ph-trash"></i></button>
</div>
</div>
<!-- 2. Highlight Engine -->
<div class="bg-slate-900 rounded-xl p-4 border border-slate-800 shadow-sm relative">
<div class="flex items-center justify-between mb-4">
<div class="flex items-center gap-2">
<div class="w-6 h-6 rounded bg-indigo-500/20 flex items-center justify-center"><i class="ph-bold ph-highlighter text-indigo-400"></i></div>
<h3 class="font-semibold text-slate-200 text-xs uppercase tracking-wider">Smart Highlight</h3>
</div>
<div class="relative group" title="Choose highlight color">
<input type="color" id="highlightColor" value="#facc15">
</div>
</div>
<p class="text-[10px] text-slate-400 mb-3 leading-relaxed">Paste bulk numbers to find and permanently highlight in structure.</p>
<!-- NEW: Live Search inside the Bulk Query -->
<div class="relative mb-2 flex items-center gap-2">
<input type="text" id="querySearchInput" placeholder="Verify specific number in query..." class="w-full bg-slate-950 border border-slate-700/50 rounded-lg p-2 pl-7 text-[11px] text-slate-300 placeholder-slate-600 focus:outline-none focus:border-indigo-500 transition-all font-mono">
<i class="ph-bold ph-magnifying-glass absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-500 text-xs"></i>
<div id="querySearchResult" class="hidden absolute right-2 top-1/2 -translate-y-1/2 text-[10px] font-bold px-1.5 py-0.5 rounded transition-colors"></div>
</div>
<div class="relative mb-3">
<textarea id="searchQueries" rows="6" class="w-full bg-slate-950 border border-slate-700/50 rounded-lg p-3 pb-8 text-xs text-slate-300 placeholder-slate-600 focus:outline-none focus:border-indigo-500 transition-all font-mono resize-none shadow-inner custom-scrollbar" placeholder="4181 3538..."></textarea>
<div class="absolute bottom-2 right-2 flex items-center gap-1 text-[10px] font-bold text-slate-500 bg-slate-900 px-2 py-0.5 rounded border border-slate-800">
<span id="queryCount">0</span> queries
</div>
</div>
<button id="highlightBtn" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white py-2 rounded-lg font-semibold transition-all flex justify-center items-center gap-2 disabled:opacity-30 disabled:cursor-not-allowed shadow-lg shadow-indigo-900/20 text-xs" disabled>
<i class="ph-bold ph-magic-wand"></i>
Execute Highlights
</button>
<div id="searchStats" class="mt-3 p-2 bg-emerald-500/10 rounded border border-emerald-500/20 hidden flex items-center gap-2">
<i class="ph-fill ph-check-circle text-emerald-400 text-lg"></i>
<div>
<p class="text-[11px] text-emerald-400 font-bold"><span id="matchCount">0</span> matches baked structurally.</p>
</div>
</div>
</div>
<!-- 3. Tool Guide -->
<div class="bg-slate-900 rounded-xl p-4 border border-slate-800 shadow-sm">
<div class="flex items-center gap-2 mb-3">
<div class="w-6 h-6 rounded bg-orange-500/20 flex items-center justify-center"><i class="ph-bold ph-wrench text-orange-400"></i></div>
<h3 class="font-semibold text-slate-200 text-xs uppercase tracking-wider">Pro Tools</h3>
</div>
<p class="text-[10px] text-slate-400 leading-relaxed mb-3">
Hover over any document page in the viewer to access instant structural modifiers. Use the <strong>Organize Mode</strong> to drag, drop, and rearrange pages structurally.
</p>
</div>
</div>
</aside>
<!-- Center Workspace - Viewer -->
<section class="flex-1 flex flex-col relative overflow-hidden viewer-bg">
<!-- Sticky Navigation Bar -->
<div id="viewerNav" class="absolute top-0 left-0 right-0 h-12 bg-slate-900/80 backdrop-blur-md border-b border-slate-800 z-20 hidden items-center justify-between px-6 shadow-sm">
<div class="flex items-center gap-3">
<span class="text-xs font-semibold text-slate-400 uppercase tracking-wider">Navigate</span>
<div class="flex items-center bg-slate-950 border border-slate-700 rounded overflow-hidden shadow-inner">
<div class="px-2 py-1 bg-slate-800 border-r border-slate-700 text-slate-400 text-xs"><i class="ph-bold ph-magnifying-glass"></i></div>
<input type="number" id="pageJumpInput" class="w-14 bg-transparent text-center text-xs text-white focus:outline-none focus:bg-slate-800 transition-colors py-1 appearance-none" min="1" placeholder="Pg">
<div class="px-2 py-1 bg-slate-800 border-l border-slate-700 text-slate-400 text-xs font-medium">/ <span id="totalJumpPages">0</span></div>
</div>
</div>
<div class="flex items-center gap-4">
<!-- NEW: Organize Toggle -->
<button id="organizeBtn" class="flex items-center gap-1.5 px-3 py-1.5 bg-slate-950 border border-slate-700 hover:border-blue-500 text-slate-400 hover:text-white rounded shadow-inner transition-colors text-xs font-semibold">
<i class="ph-bold ph-squares-four text-sm"></i>
<span>Organize Mode</span>
</button>
<!-- Quick Zoom -->
<div id="zoomControls" class="flex bg-slate-950 rounded border border-slate-700 shadow-inner items-center transition-opacity">
<button id="zoomOutBtn" class="px-2 py-1 text-slate-400 hover:text-white transition-colors"><i class="ph-bold ph-minus"></i></button>
<div class="px-2 text-[11px] font-bold text-slate-300 border-x border-slate-700 w-12 text-center" id="zoomDisplay">120%</div>
<button id="zoomInBtn" class="px-2 py-1 text-slate-400 hover:text-white transition-colors"><i class="ph-bold ph-plus"></i></button>
</div>
</div>
</div>
<!-- Continuous / Grid Scroll Container -->
<div id="viewerContainer" class="flex-1 overflow-y-auto w-full flex flex-col items-center pt-20 pb-20 gap-10 scroll-smooth custom-scrollbar relative z-10 transition-all">
<!-- Empty State -->
<div id="emptyState" class="m-auto flex flex-col items-center justify-center text-slate-600">
<div class="w-20 h-20 bg-slate-900 rounded-2xl flex items-center justify-center mb-5 shadow-inner border border-slate-800">
<i class="ph-fill ph-file-dashed text-4xl text-slate-500"></i>
</div>
<h2 class="text-lg font-bold text-slate-300 mb-1">Engine Offline</h2>
<p class="text-xs font-medium text-slate-500">Upload or Drag & Drop a PDF to activate the workspace.</p>
</div>
</div>
</section>
</main>
<script>
// Setup Workers
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
// --- Core State & History (Undo/Redo Engine) ---
let stateHistory = [];
let historyIndex = -1;
let currentPdfBytes = null;
let pdfjsDoc = null;
let pdfLibDoc = null;
let totalPages = 0;
let currentScale = 1.2;
// --- Organize Mode State ---
let isOrganizeMode = false;
let sortableInstance = null;
// --- DOM Elements ---
const ui = {
dragOverlay: document.getElementById('dragOverlay'),
fileInput: document.getElementById('fileInput'),
fileNameDisplay: document.getElementById('fileNameDisplay'),
fileMeta: document.getElementById('fileMeta'),
clearFileBtn: document.getElementById('clearFileBtn'),
searchQueries: document.getElementById('searchQueries'),
querySearchInput: document.getElementById('querySearchInput'),
querySearchResult: document.getElementById('querySearchResult'),
queryCount: document.getElementById('queryCount'),
highlightColor: document.getElementById('highlightColor'),
highlightBtn: document.getElementById('highlightBtn'),
searchStats: document.getElementById('searchStats'),
matchCount: document.getElementById('matchCount'),
downloadBtn: document.getElementById('downloadBtn'),
undoBtn: document.getElementById('undoBtn'),
redoBtn: document.getElementById('redoBtn'),
organizeBtn: document.getElementById('organizeBtn'),
viewerContainer: document.getElementById('viewerContainer'),
emptyState: document.getElementById('emptyState'),
viewerNav: document.getElementById('viewerNav'),
pageJumpInput: document.getElementById('pageJumpInput'),
totalJumpPages: document.getElementById('totalJumpPages'),
zoomControls: document.getElementById('zoomControls'),
zoomInBtn: document.getElementById('zoomInBtn'),
zoomOutBtn: document.getElementById('zoomOutBtn'),
zoomDisplay: document.getElementById('zoomDisplay'),
docInfo: document.getElementById('docInfo'),
infoPages: document.getElementById('infoPages'),
infoSize: document.getElementById('infoSize'),
toastContainer: document.getElementById('toastContainer'),
toastMessage: document.getElementById('toastMessage'),
toastIcon: document.getElementById('toastIcon')
};
// --- Utilities ---
function showLoader(title, subtitle, showProgress = false) {
document.getElementById('loadingText').textContent = title;
document.getElementById('loadingSubtext').textContent = subtitle || "";
document.getElementById('loadingOverlay').classList.remove('hidden');
document.getElementById('loadingOverlay').classList.add('flex');
if (showProgress) {
document.getElementById('renderProgressContainer').classList.remove('hidden');
updateLoaderProgress(0);
} else {
document.getElementById('renderProgressContainer').classList.add('hidden');
}
}
function updateLoaderProgress(percent) {
document.getElementById('renderProgressBar').style.width = `${percent}%`;
}
function hideLoader() {
document.getElementById('loadingOverlay').classList.add('hidden');
document.getElementById('loadingOverlay').classList.remove('flex');
}
let toastTimeout;
function showToast(message, type = 'success') {
clearTimeout(toastTimeout);
ui.toastMessage.textContent = message;
if(type === 'success') {
ui.toastIcon.className = 'ph-fill ph-check-circle text-emerald-400 text-lg';
} else if (type === 'info') {
ui.toastIcon.className = 'ph-fill ph-info text-blue-400 text-lg';
} else if (type === 'error') {
ui.toastIcon.className = 'ph-fill ph-warning text-red-400 text-lg';
}
ui.toastContainer.style.transform = 'translate(-50%, 0)';
ui.toastContainer.style.opacity = '1';
toastTimeout = setTimeout(() => {
ui.toastContainer.style.transform = 'translate(-50%, 20px)';
ui.toastContainer.style.opacity = '0';
}, 3000);
}
// --- Keyboard Shortcuts ---
window.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
if (e.key === 'z') { e.preventDefault(); handleUndo(); }
if (e.key === 'y') { e.preventDefault(); handleRedo(); }
}
});
// --- Live Query Search (Sidebar) ---
ui.querySearchInput.addEventListener('input', (e) => {
const term = e.target.value.toLowerCase().trim();
const text = ui.searchQueries.value.toLowerCase();
if (!term) {
ui.querySearchResult.classList.add('hidden');
ui.querySearchInput.classList.remove('border-emerald-500', 'border-red-500', 'text-emerald-400', 'text-red-400');
return;
}
ui.querySearchResult.classList.remove('hidden');
// Count occurrences correctly (handling special regex characters safely)
const escapedTerm = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(escapedTerm, 'g');
const count = (text.match(regex) || []).length;
if (count > 0) {
ui.querySearchResult.textContent = `${count} Found`;
ui.querySearchResult.className = 'absolute right-2 top-1/2 -translate-y-1/2 text-[10px] font-bold px-1.5 py-0.5 rounded transition-colors bg-emerald-500/20 text-emerald-400';
ui.querySearchInput.classList.add('border-emerald-500', 'text-emerald-400');
ui.querySearchInput.classList.remove('border-red-500', 'text-red-400');
} else {
ui.querySearchResult.textContent = '0 Found';
ui.querySearchResult.className = 'absolute right-2 top-1/2 -translate-y-1/2 text-[10px] font-bold px-1.5 py-0.5 rounded transition-colors bg-red-500/20 text-red-400';
ui.querySearchInput.classList.add('border-red-500', 'text-red-400');
ui.querySearchInput.classList.remove('border-emerald-500', 'text-emerald-400');
}
});
// --- Drag & Drop Engine (File Upload) ---
let dragCounter = 0;
window.addEventListener('dragenter', (e) => {
e.preventDefault();
dragCounter++;
ui.dragOverlay.classList.remove('hidden');
ui.dragOverlay.classList.add('flex');
});
window.addEventListener('dragleave', (e) => {
e.preventDefault();
dragCounter--;
if (dragCounter === 0) {
ui.dragOverlay.classList.add('hidden');
ui.dragOverlay.classList.remove('flex');
}
});
window.addEventListener('dragover', (e) => { e.preventDefault(); });
window.addEventListener('drop', async (e) => {
e.preventDefault();
dragCounter = 0;
ui.dragOverlay.classList.add('hidden');
ui.dragOverlay.classList.remove('flex');
const file = e.dataTransfer.files[0];
if (file) {
if (file.type === "application/pdf" || file.name.toLowerCase().endsWith('.pdf')) {
await processFileUpload(file);
} else {
showToast("Only PDF documents are supported", "error");
}
}
});
// --- Organize Mode Engine (Drag & Drop Reordering) ---
ui.organizeBtn.addEventListener('click', toggleOrganizeMode);
function toggleOrganizeMode() {
if (!pdfjsDoc) return;
isOrganizeMode = !isOrganizeMode;
if (isOrganizeMode) {
// UI Activations
ui.organizeBtn.classList.add('bg-blue-600/20', 'text-blue-400', 'border-blue-500/50');
ui.organizeBtn.classList.remove('text-slate-400', 'border-slate-700');
ui.viewerContainer.classList.add('organize-mode');
ui.zoomControls.classList.add('opacity-30', 'pointer-events-none');
// Add thumbnail class to all existing pages
document.querySelectorAll('.page-wrapper').forEach(w => w.classList.add('thumbnail'));
// Initialize Sortable Grid
if (!sortableInstance) {
sortableInstance = new Sortable(ui.viewerContainer, {
animation: 200,
ghostClass: 'opacity-40',
onEnd: handleReorderStructure
});
} else {
sortableInstance.options.disabled = false;
}
showToast("Organize Mode: Drag pages to reorder.", "info");
} else {
// Deactivations
ui.organizeBtn.classList.remove('bg-blue-600/20', 'text-blue-400', 'border-blue-500/50');
ui.organizeBtn.classList.add('text-slate-400', 'border-slate-700');
ui.viewerContainer.classList.remove('organize-mode');
ui.zoomControls.classList.remove('opacity-30', 'pointer-events-none');
// Remove thumbnail class
document.querySelectorAll('.page-wrapper').forEach(w => w.classList.remove('thumbnail'));
if (sortableInstance) {
sortableInstance.options.disabled = true;
}
}
}
async function handleReorderStructure(evt) {
// If dragging didn't change position, ignore
if (evt.oldIndex === evt.newIndex) return;
showLoader("Reorganizing Document...", "Committing new structure to memory");
try {
// Extract the new 0-based index order from the DOM dataset elements
const pageElements = Array.from(ui.viewerContainer.querySelectorAll('.page-wrapper'));
const newIndices = pageElements.map(el => parseInt(el.dataset.pageNum) - 1);
// Re-build PDF structurally
const newDoc = await PDFLib.PDFDocument.create();
const sourceDoc = await PDFLib.PDFDocument.load(currentPdfBytes, { ignoreEncryption: true });
// Copy pages in exactly the new arranged sequence
const copiedPages = await newDoc.copyPages(sourceDoc, newIndices);
copiedPages.forEach(p => newDoc.addPage(p));
const newBytes = await newDoc.save();
// Save to history & reload context
await pushState(newBytes);
currentPdfBytes = new Uint8Array(newBytes);
const viewerBytes = new Uint8Array(currentPdfBytes);
pdfjsDoc = await pdfjsLib.getDocument({ data: viewerBytes }).promise;
// Render will clear the DOM and recreate wrappers with correct page numbers (1,2,3..)
await renderAllPages();
showToast("Pages reorganized successfully", "success");
} catch (error) {
console.error(error);
showToast("Failed to reorder document", "error");
} finally {
hideLoader();
}
}
// --- State Management Engine ---
async function pushState(bytes) {
stateHistory = stateHistory.slice(0, historyIndex + 1);
const clonedBytes = new Uint8Array(bytes);
stateHistory.push(clonedBytes);
historyIndex++;
updateHistoryUI();
}
function updateHistoryUI() {
ui.undoBtn.disabled = historyIndex <= 0;
ui.redoBtn.disabled = historyIndex >= stateHistory.length - 1;
}
async function handleUndo() {
if (historyIndex > 0) {
showLoader("Reverting State...", "Restoring previous document structure");
historyIndex--;
await loadPdfFromBytes(stateHistory[historyIndex], false);
updateHistoryUI();
showToast("Action reverted", "info");
}
}
async function handleRedo() {
if (historyIndex < stateHistory.length - 1) {
showLoader("Restoring State...", "Reapplying modifications");
historyIndex++;
await loadPdfFromBytes(stateHistory[historyIndex], false);
updateHistoryUI();
showToast("Action restored", "info");
}
}
ui.undoBtn.addEventListener('click', handleUndo);
ui.redoBtn.addEventListener('click', handleRedo);
// --- Initialization / Upload Processing ---
ui.searchQueries.addEventListener('input', (e) => {
const lines = e.target.value.split(/\r?\n|,/).filter(q => q.trim().length > 0);
ui.queryCount.textContent = lines.length;
// Re-trigger live search update if query block changes
ui.querySearchInput.dispatchEvent(new Event('input'));
});
ui.fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
await processFileUpload(file);
});
async function processFileUpload(file) {
if (!file) return;
ui.fileNameDisplay.textContent = file.name;
ui.infoSize.textContent = (file.size / (1024*1024)).toFixed(2) + ' MB';
ui.fileMeta.classList.remove('hidden');
// Remove empty state explicitly from the container
if (ui.emptyState.parentNode) {
ui.emptyState.parentNode.removeChild(ui.emptyState);
}
ui.docInfo.classList.remove('hidden');
ui.docInfo.classList.add('flex');
ui.viewerNav.classList.remove('hidden');
ui.viewerNav.classList.add('flex');
ui.downloadBtn.classList.remove('hidden');
ui.highlightBtn.disabled = false;
showLoader("Initializing Engine...", "Parsing document layout");
try {
const arrayBuffer = await file.arrayBuffer();
const bytes = new Uint8Array(arrayBuffer);
if (bytes.length < 4 || bytes[0] !== 0x25 || bytes[1] !== 0x50 || bytes[2] !== 0x44 || bytes[3] !== 0x46) {
throw new Error("Invalid Format. Selected file is not a valid PDF.");
}
stateHistory = [];
historyIndex = -1;
// If Organize mode was left open from a previous file, reset it
if (isOrganizeMode) toggleOrganizeMode();
await loadPdfFromBytes(bytes, true);
showToast("Document Loaded");
} catch (error) {
alert("Engine Error: " + error.message);
resetWorkspace();
} finally {
ui.fileInput.value = '';
}
}
ui.clearFileBtn.addEventListener('click', resetWorkspace);
function resetWorkspace() {
ui.fileInput.value = '';
ui.fileMeta.classList.add('hidden');
ui.viewerContainer.innerHTML = '';
ui.viewerContainer.appendChild(ui.emptyState);
ui.docInfo.classList.add('hidden');
ui.docInfo.classList.remove('flex');
ui.viewerNav.classList.add('hidden');
ui.viewerNav.classList.remove('flex');
ui.downloadBtn.classList.add('hidden');
ui.highlightBtn.disabled = true;
ui.searchStats.classList.add('hidden');
if (isOrganizeMode) toggleOrganizeMode();
stateHistory = [];
historyIndex = -1;
updateHistoryUI();
}
// --- Core Load & Render Engine ---
async function loadPdfFromBytes(bytes, isNewUpload = false) {
currentPdfBytes = new Uint8Array(bytes);
pdfLibDoc = await PDFLib.PDFDocument.load(currentPdfBytes, { ignoreEncryption: true });
const viewerBytes = new Uint8Array(currentPdfBytes);
pdfjsDoc = await pdfjsLib.getDocument({ data: viewerBytes }).promise;
totalPages = pdfjsDoc.numPages;
ui.infoPages.textContent = `${totalPages} Pages`;
ui.totalJumpPages.textContent = totalPages;
ui.pageJumpInput.max = totalPages;
if (isNewUpload) {
await pushState(currentPdfBytes);
}
await renderAllPages();
hideLoader();
}
async function renderAllPages() {
ui.viewerContainer.innerHTML = ''; // Clear container
for (let i = 1; i <= totalPages; i++) {
const page = await pdfjsDoc.getPage(i);
const viewport = page.getViewport({ scale: currentScale });
// Page Wrapper
const wrapper = document.createElement('div');
wrapper.className = 'page-wrapper relative bg-white group flex-shrink-0';
if (isOrganizeMode) wrapper.classList.add('thumbnail'); // Persist mode class
wrapper.style.width = `${viewport.width}px`;
wrapper.style.height = `${viewport.height}px`;
wrapper.id = `page-container-${i}`;
wrapper.dataset.pageNum = i;
// Professional Action Toolbar
const toolbar = document.createElement('div');
toolbar.className = 'absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity bg-slate-900/95 backdrop-blur rounded p-1 flex gap-1 shadow-2xl border border-slate-700 z-10';
toolbar.innerHTML = `
<div class="px-2 py-1 text-[10px] font-bold text-slate-400 border-r border-slate-700 mr-1 flex items-center page-label">PG ${i}</div>
<button class="rotate-left p-1.5 bg-slate-800 text-slate-300 hover:bg-blue-600 hover:text-white rounded transition-colors" title="Rotate Left"><i class="ph-bold ph-arrow-u-up-left"></i></button>
<button class="rotate-right p-1.5 bg-slate-800 text-slate-300 hover:bg-blue-600 hover:text-white rounded transition-colors" title="Rotate Right"><i class="ph-bold ph-arrow-u-up-right"></i></button>
<div class="w-px bg-slate-700 mx-0.5"></div>
<button class="delete-page p-1.5 bg-slate-800 text-red-400 hover:bg-red-600 hover:text-white rounded transition-colors" title="Delete Page"><i class="ph-bold ph-trash"></i></button>
`;
// Attach Events
toolbar.querySelector('.rotate-left').addEventListener('click', () => handleInstantRotate(wrapper, -90));
toolbar.querySelector('.rotate-right').addEventListener('click', () => handleInstantRotate(wrapper, 90));
toolbar.querySelector('.delete-page').addEventListener('click', () => handleInstantDelete(wrapper));
// Canvas Layer
const canvasContainer = document.createElement('div');
canvasContainer.className = 'canvas-container w-full h-full';
const canvas = document.createElement('canvas');
canvas.className = 'block w-full h-full';
canvas.width = viewport.width;
canvas.height = viewport.height;
const ctx = canvas.getContext('2d');
canvasContainer.appendChild(canvas);
wrapper.appendChild(toolbar);
wrapper.appendChild(canvasContainer);
ui.viewerContainer.appendChild(wrapper);
const renderContext = { canvasContext: ctx, viewport: viewport };
page.render(renderContext);
}
}
// --- Instant Manipulation Engine ---
async function handleInstantRotate(wrapper, degrees) {
const pageNum = parseInt(wrapper.dataset.pageNum);
const container = wrapper.querySelector('.canvas-container');
let currentRot = parseInt(container.dataset.rot || 0);
currentRot += degrees;
container.dataset.rot = currentRot;
container.style.transform = `rotate(${currentRot}deg)`;
showToast(`Page rotated`, 'success');
const pdfPage = pdfLibDoc.getPage(pageNum - 1);
const structureRot = pdfPage.getRotation().angle;
pdfPage.setRotation(PDFLib.degrees(structureRot + degrees));
const newBytes = await pdfLibDoc.save();
await pushState(newBytes);
currentPdfBytes = new Uint8Array(newBytes);
const viewerBytes = new Uint8Array(currentPdfBytes);
pdfjsDoc = await pdfjsLib.getDocument({ data: viewerBytes }).promise;
}
async function handleInstantDelete(wrapper) {
if (totalPages <= 1) return showToast("Cannot delete last page", "error");
const pageNum = parseInt(wrapper.dataset.pageNum);
wrapper.classList.add('deleting');
showToast("Page removed", "success");
setTimeout(async () => {
wrapper.remove();
const remainingWrappers = ui.viewerContainer.querySelectorAll('.page-wrapper');
remainingWrappers.forEach((w, idx) => {
const newIndex = idx + 1;
w.id = `page-container-${newIndex}`;
w.dataset.pageNum = newIndex;
w.querySelector('.page-label').textContent = `PG ${newIndex}`;
});
totalPages = remainingWrappers.length;
ui.infoPages.textContent = `${totalPages} Pages`;
ui.totalJumpPages.textContent = totalPages;
ui.pageJumpInput.max = totalPages;
pdfLibDoc.removePage(pageNum - 1);
const newBytes = await pdfLibDoc.save();
await pushState(newBytes);
currentPdfBytes = new Uint8Array(newBytes);
const viewerBytes = new Uint8Array(currentPdfBytes);
pdfjsDoc = await pdfjsLib.getDocument({ data: viewerBytes }).promise;
}, 300);
}
// --- Smart Highlight Engine ---
ui.highlightBtn.addEventListener('click', async () => {
const textRaw = ui.searchQueries.value;
if (!textRaw.trim()) return;
const queries = textRaw.split(/\r?\n|,/).map(q => q.trim()).filter(q => q.length > 0);
if (queries.length === 0) return;
showLoader("Executing Smart Highlight...", "Scanning layout and writing coordinates", true);
let totalMatchesFound = 0;
try {
const pages = pdfLibDoc.getPages();
const hex = ui.highlightColor.value;
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
const selectedColor = PDFLib.rgb(r, g, b);
for (let pageIndex = 1; pageIndex <= pdfjsDoc.numPages; pageIndex++) {
updateLoaderProgress(Math.round((pageIndex / pdfjsDoc.numPages) * 100));
const page = await pdfjsDoc.getPage(pageIndex);
const textContent = await page.getTextContent();
const pdfLibPage = pages[pageIndex - 1];
let originalStr = "";
let itemMap = [];
const items = textContent.items;
for (let i = 0; i < items.length; i++) {
const item = items[i];
for (let c = 0; c < item.str.length; c++) {
originalStr += item.str[c];
itemMap.push(item);
}
}
let normalizedStr = "";
let normToOrigMap = [];
for (let i = 0; i < originalStr.length; i++) {
const char = originalStr[i];
if (/[a-zA-Z0-9]/.test(char)) {
normalizedStr += char.toLowerCase();
normToOrigMap.push(i);
}
}
for (const q of queries) {
const cleanQuery = q.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
if (!cleanQuery) continue;
let startIdx = 0;
while ((startIdx = normalizedStr.indexOf(cleanQuery, startIdx)) !== -1) {
totalMatchesFound++;
const endIdx = startIdx + cleanQuery.length - 1;
const origStart = normToOrigMap[startIdx];
const origEnd = normToOrigMap[endIdx];
const itemsToHighlight = new Set();
for (let k = origStart; k <= origEnd; k++) {
if (itemMap[k] && itemMap[k].str.trim().length > 0) {
itemsToHighlight.add(itemMap[k]);
}
}
itemsToHighlight.forEach(item => {
const tx = item.transform[4];
const ty = item.transform[5];
const fontHeight = Math.abs(item.transform[3]) || 10;
const width = item.width || (fontHeight * 0.5 * item.str.length);
pdfLibPage.drawRectangle({
x: tx,
y: ty - (fontHeight * 0.15),
width: width,
height: fontHeight * 1.15,
color: selectedColor,
opacity: 0.5,
blendMode: PDFLib.BlendMode.Multiply
});
});
startIdx += cleanQuery.length;
}
}
}
if (totalMatchesFound > 0) {
const newBytes = await pdfLibDoc.save();
await pushState(newBytes);
await loadPdfFromBytes(newBytes, false);
ui.searchStats.classList.remove('hidden');
ui.matchCount.textContent = totalMatchesFound;
showToast(`Highlighted ${totalMatchesFound} matches`);
} else {
showToast("No matches found", "info");
}
} catch (error) {
console.error(error);
alert("Algorithm Error during highlight.");
} finally {
hideLoader();
}
});
// --- Navigation: Jump to Page ---
ui.pageJumpInput.addEventListener('keydown', (e) => {
if(e.key === 'Enter') {
const p = parseInt(ui.pageJumpInput.value);
if(p >= 1 && p <= totalPages) {
const target = document.getElementById(`page-container-${p}`);
if(target) {
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
target.style.outline = '4px solid #3b82f6';
setTimeout(() => target.style.outline = 'none', 1000);
ui.pageJumpInput.blur();
}
} else {
showToast("Invalid page number", "error");
}
}
});
// --- Quick Zoom ---
function applyZoom() {
ui.zoomDisplay.textContent = `${Math.round(currentScale * 100)}%`;
if (pdfjsDoc) renderAllPages();
}
ui.zoomInBtn.addEventListener('click', () => {
if (currentScale >= 3.0) return;
currentScale += 0.2;
applyZoom();
});
ui.zoomOutBtn.addEventListener('click', () => {
if (currentScale <= 0.6) return;
currentScale -= 0.2;
applyZoom();
});
// --- Export & Download ---
ui.downloadBtn.addEventListener('click', async () => {
if (!pdfLibDoc) return;
showLoader("Packaging Payload...", "Generating highly optimized PDF");
try {
const finalBytes = await pdfLibDoc.save();
const blob = new Blob([finalBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);