-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
717 lines (645 loc) · 37.6 KB
/
index.html
File metadata and controls
717 lines (645 loc) · 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Tool Suite | Created by Vishal Kumar Basson</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- PDF-Lib for PDF manipulation -->
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
<!-- JSZip for zipping split files -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<!-- FileSaver.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<!-- Lucide Icons -->
<script src="https://unpkg.com/lucide@latest"></script>
<style>
.drag-active {
border-color: #3b82f6;
background-color: #eff6ff;
transform: scale(1.01);
}
.file-list {
overflow: visible;
}
.dragging {
opacity: 0.4;
transform: scale(0.95);
}
.tab-btn.active {
color: #2563eb;
border-bottom-color: #2563eb;
background-color: #eff6ff;
}
@keyframes sparkle {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.1); opacity: 0.8; }
}
.sparkle-icon {
animation: sparkle 2s infinite;
}
.creator-badge {
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
color: white;
padding: 0.2rem 0.75rem;
border-radius: 9999px;
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 0.25rem;
}
.file-item-hover:hover {
border-color: #3b82f6;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
}
/* Page Grid Styles */
.page-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 1.5rem;
}
.page-card {
transition: all 0.2s ease;
position: relative;
}
.page-card:hover .delete-page-btn {
opacity: 1;
}
.delete-page-btn {
opacity: 0;
transition: opacity 0.2s;
}
</style>
</head>
<body class="bg-slate-50 min-h-screen font-sans text-slate-800 pb-12">
<div class="max-w-5xl mx-auto px-4 py-8">
<!-- Header -->
<header class="text-center mb-6">
<h1 class="text-3xl font-bold text-slate-900 mb-2 flex items-center justify-center gap-3">
<i data-lucide="layers" class="w-8 h-8 text-blue-600"></i>
PDF Master Tool
</h1>
<div class="flex flex-col items-center gap-2">
<p class="text-slate-500 text-sm">Easy to use, Secure and Open Source.</p>
<div class="creator-badge text-xs">
<i data-lucide="user" class="w-3.5 h-3.5"></i>
Created by Vishal Kumar Basson
</div>
</div>
</header>
<!-- Navigation Tabs -->
<nav class="flex justify-center mb-6 border-b border-slate-200">
<button onclick="switchTab('merge')" id="tab-merge" class="tab-btn active px-6 py-2.5 font-semibold text-slate-500 border-b-2 border-transparent hover:text-blue-500 transition-all flex items-center gap-2">
<i data-lucide="combine" class="w-4 h-4"></i> Merge
</button>
<button onclick="switchTab('organize')" id="tab-organize" class="tab-btn px-6 py-2.5 font-semibold text-slate-500 border-b-2 border-transparent hover:text-blue-500 transition-all flex items-center gap-2">
<i data-lucide="layout-grid" class="w-4 h-4"></i> Organize <span class="text-[10px] bg-blue-100 text-blue-600 px-1.5 rounded uppercase font-bold">New</span>
</button>
<button onclick="switchTab('split')" id="tab-split" class="tab-btn px-6 py-2.5 font-semibold text-slate-500 border-b-2 border-transparent hover:text-blue-500 transition-all flex items-center gap-2">
<i data-lucide="scissors" class="w-4 h-4"></i> Split
</button>
</nav>
<!-- MERGE SECTION (Existing) -->
<section id="view-merge" class="bg-white rounded-2xl shadow-xl border border-slate-200 mb-6">
<div class="p-6">
<div id="drop-zone-merge" class="border-2 border-dashed border-slate-300 rounded-xl p-8 text-center transition-all duration-200 hover:border-blue-400 hover:bg-slate-50 cursor-pointer group relative">
<input type="file" id="file-input-merge" multiple accept=".pdf" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
<div class="pointer-events-none">
<div class="w-12 h-12 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-3 group-hover:scale-110 transition-transform">
<i data-lucide="upload-cloud" class="w-6 h-6"></i>
</div>
<h3 class="text-lg font-bold text-slate-700">Drop PDF files here</h3>
<p class="text-slate-400 text-sm mt-1">or click to browse your computer</p>
</div>
</div>
</div>
<div id="merge-toolbar" class="hidden px-6 py-3 bg-slate-50 border-y border-slate-200 flex flex-wrap gap-2 justify-between items-center">
<div class="flex items-center gap-2">
<span class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Sort:</span>
<button onclick="sortFiles('num')" class="px-3 py-2 bg-white border border-slate-200 rounded-md text-sm hover:bg-slate-50 text-slate-700 flex items-center gap-1.5 shadow-sm font-bold transition-all">
<i data-lucide="list-ordered" class="w-4 h-4"></i> 1 2 3
</button>
<button onclick="sortMinima()" class="px-3 py-2 bg-blue-600 border border-blue-700 rounded-md text-sm hover:bg-blue-700 text-white flex items-center gap-1.5 shadow-sm font-bold transition-all">
<i data-lucide="list-checks" class="w-4 h-4"></i> Minima Sequence
</button>
<button onclick="sortFiles('asc')" class="px-3 py-2 bg-white border border-slate-200 rounded-md text-sm hover:bg-slate-50 text-slate-700 flex items-center gap-1.5 shadow-sm transition-all">
<i data-lucide="arrow-down-a-z" class="w-4 h-4"></i> A-Z
</button>
<button onclick="sortFiles('desc')" class="px-3 py-2 bg-white border border-slate-200 rounded-md text-sm hover:bg-slate-50 text-slate-700 flex items-center gap-1.5 shadow-sm transition-all">
<i data-lucide="arrow-up-a-z" class="w-4 h-4"></i> Z-A
</button>
<button id="ai-rename-btn" onclick="suggestMergedName()" class="px-3 py-2 bg-blue-50 border border-blue-200 rounded-md text-sm hover:bg-blue-100 text-blue-700 flex items-center gap-1.5 ml-2 shadow-sm transition-all">
<i data-lucide="sparkles" class="w-4 h-4 sparkle-icon"></i> ✨ AI Rename
</button>
</div>
<button onclick="clearMergeFiles()" class="text-sm text-red-500 hover:text-red-700 font-bold px-2 py-1">Clear All</button>
</div>
<ul id="file-list-merge" class="file-list hidden p-4 space-y-3 bg-slate-50/50"></ul>
<div class="p-6 bg-white border-t border-slate-200">
<div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
<div id="status-msg-merge" class="text-sm font-medium text-blue-600 hidden flex items-center gap-2">
<div class="animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"></div>
Merging your files...
</div>
<div class="flex items-center gap-2 w-full sm:w-auto">
<input type="text" id="custom-filename" placeholder="Output filename" class="px-4 py-3 border border-slate-300 rounded-xl text-sm w-full sm:w-64 focus:ring-2 focus:ring-blue-500 focus:outline-none font-medium">
<button id="merge-btn" onclick="mergePDFs()" disabled class="px-8 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-slate-300 text-white rounded-xl font-bold shadow-lg transition-all flex items-center justify-center gap-2 whitespace-nowrap text-base">
<i data-lucide="merge" class="w-5 h-5"></i> Merge PDFs
</button>
</div>
</div>
</div>
</section>
<!-- ORGANIZE SECTION (New Add-on) -->
<section id="view-organize" class="hidden bg-white rounded-2xl shadow-xl border border-slate-200 mb-6 overflow-hidden">
<div class="p-6 bg-blue-600 text-white flex items-center justify-between">
<div>
<h2 class="text-xl font-bold flex items-center gap-2">
<i data-lucide="layout-grid" class="w-6 h-6"></i> Organize PDF Pages
</h2>
<p class="text-blue-100 text-xs mt-1">Drag and drop pages to rearrange. Click 'X' to remove.</p>
</div>
<div class="flex items-center gap-3">
<div id="organize-count-badge" class="hidden px-3 py-1 bg-blue-500/50 rounded-full text-xs font-bold">
<span id="total-page-count">0</span> Pages Total
</div>
<button onclick="clearOrganize()" class="text-xs font-bold hover:text-blue-200">Reset</button>
</div>
</div>
<div class="p-6">
<!-- Multi-file Upload for Organize -->
<div id="organize-drop-zone" class="border-2 border-dashed border-blue-200 rounded-xl p-8 text-center transition-all hover:bg-blue-50 cursor-pointer group relative mb-6">
<input type="file" id="organize-file-input" multiple accept=".pdf" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
<div class="pointer-events-none">
<div class="w-10 h-10 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-2">
<i data-lucide="plus" class="w-5 h-5"></i>
</div>
<h3 class="text-base font-bold text-slate-700">Add PDF Files to Organize</h3>
<p class="text-slate-400 text-xs">Mix pages from different documents together</p>
</div>
</div>
<!-- Page Grid -->
<div id="organize-grid" class="page-grid min-h-[200px] border-t border-slate-100 pt-6 hidden">
<!-- Pages will appear here as thumbnails -->
</div>
<!-- Placeholder when empty -->
<div id="organize-empty" class="py-12 text-center text-slate-400">
<i data-lucide="image" class="w-12 h-12 mx-auto mb-2 opacity-20"></i>
<p class="text-sm">Upload files to start arranging pages</p>
</div>
</div>
<!-- Footer Controls for Organize -->
<div id="organize-footer" class="hidden p-6 bg-slate-50 border-t border-slate-200">
<div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
<p class="text-xs text-slate-500 font-medium">Final PDF will follow the sequence above.</p>
<div class="flex items-center gap-3 w-full sm:w-auto">
<input type="text" id="organize-filename" placeholder="Organized Output" class="px-4 py-2.5 border border-slate-300 rounded-xl text-sm w-full sm:w-64 focus:ring-2 focus:ring-blue-500 focus:outline-none font-medium">
<button id="organize-save-btn" onclick="saveOrganizedPDF()" class="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold shadow-lg flex items-center gap-2 whitespace-nowrap">
<i data-lucide="file-check" class="w-4 h-4"></i> Generate PDF
</button>
</div>
</div>
</div>
</section>
<!-- SPLIT SECTION (Existing) -->
<section id="view-split" class="hidden bg-white rounded-2xl shadow-xl border border-slate-200 mb-6">
<div class="p-8">
<div id="drop-zone-split" class="border-2 border-dashed border-slate-300 rounded-xl p-10 text-center transition-all duration-200 hover:border-purple-400 hover:bg-slate-50 cursor-pointer group relative">
<input type="file" id="file-input-split" accept=".pdf" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
<div class="pointer-events-none">
<div class="w-14 h-14 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center mx-auto mb-4 group-hover:scale-110 transition-transform">
<i data-lucide="file-minus" class="w-8 h-8"></i>
</div>
<h3 class="text-lg font-bold text-slate-700">Drop 1 PDF to Split</h3>
<p class="text-slate-400 text-sm mt-1">Extracts all pages into a ZIP archive</p>
</div>
</div>
<div id="split-file-info" class="hidden mt-4 p-6 bg-purple-50 border border-purple-100 rounded-xl shadow-inner">
<div class="flex items-center justify-between mb-4">
<div class="flex items-center gap-4 overflow-hidden">
<div class="p-3 bg-purple-600 text-white rounded-lg">
<i data-lucide="file-text" class="w-6 h-6"></i>
</div>
<span id="split-filename" class="font-bold text-slate-800 truncate text-lg">filename.pdf</span>
</div>
<button onclick="clearSplitFile()" class="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-full transition-colors">
<i data-lucide="x" class="w-6 h-6"></i>
</button>
</div>
<div class="pt-4 border-t border-purple-200">
<button onclick="summarizePdf()" id="ai-summary-btn" class="flex items-center gap-2 text-sm font-bold text-purple-700 bg-white border border-purple-200 px-4 py-2.5 rounded-lg hover:bg-purple-100 transition-all shadow-sm">
<i data-lucide="sparkles" class="w-4 h-4 sparkle-icon"></i> ✨ AI Generate Summary
</button>
<div id="summary-content" class="hidden mt-3 p-4 bg-white rounded-lg border border-purple-100 text-sm text-slate-700 italic leading-relaxed shadow-sm"></div>
</div>
</div>
</div>
<div class="p-6 bg-white border-t border-slate-200 flex flex-col sm:flex-row justify-between items-center gap-4">
<div id="status-msg-split" class="text-sm font-medium text-purple-600 hidden flex items-center gap-2">
<div class="animate-spin rounded-full h-4 w-4 border-2 border-purple-600 border-t-transparent"></div>
Processing...
</div>
<button id="split-btn" onclick="splitPDF()" disabled class="w-full sm:w-auto px-8 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-slate-300 text-white rounded-xl font-bold shadow-lg transition-all flex items-center justify-center gap-2 ml-auto text-base">
<i data-lucide="package" class="w-5 h-5"></i> Split & Download ZIP
</button>
</div>
</section>
<!-- Global Footer -->
<footer class="mt-8 py-6 text-center border-t border-slate-200">
<p class="text-slate-500 text-sm flex items-center justify-center gap-1 font-medium">
Made with <i data-lucide="heart" class="w-3.5 h-3.5 text-red-500 fill-current"></i> by <span class="text-slate-900 font-bold">Vishal Kumar Basson</span>
</p>
<p class="text-slate-400 text-[10px] mt-1 uppercase tracking-widest font-bold">
© <span id="year"></span> PDF Master Tool
</p>
</footer>
</div>
<a id="download-link" class="hidden"></a>
<script>
const apiKey = "";
const appId = typeof __app_id !== 'undefined' ? __app_id : 'pdf-master-suite';
// --- Core Helpers ---
async function callGemini(prompt, systemPrompt = "You are a helpful PDF assistant.") {
try {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
systemInstruction: { parts: [{ text: systemPrompt }] }
})
});
if (response.ok) {
const data = await response.json();
return data.candidates?.[0]?.content?.parts?.[0]?.text || "No response.";
}
return null;
} catch (err) { return null; }
}
lucide.createIcons();
document.getElementById('year').textContent = new Date().getFullYear();
// --- Global State ---
let mergeFiles = [];
let splitFile = null;
let organizePages = []; // Array of objects { fileIndex, pageIndex, fileName }
let organizeFileReferences = []; // Actual PDFDocument objects
let dragSrcEl = null;
const views = {
merge: document.getElementById('view-merge'),
split: document.getElementById('view-split'),
organize: document.getElementById('view-organize')
};
const tabs = {
merge: document.getElementById('tab-merge'),
split: document.getElementById('tab-split'),
organize: document.getElementById('tab-organize')
};
function switchTab(tabName) {
Object.values(views).forEach(el => el.classList.add('hidden'));
views[tabName].classList.remove('hidden');
Object.values(tabs).forEach(el => {
el.classList.remove('active');
el.classList.add('text-slate-500');
});
tabs[tabName].classList.add('active');
tabs[tabName].classList.remove('text-slate-500');
lucide.createIcons();
}
// --- ORGANIZE LOGIC (NEW) ---
const organizeGrid = document.getElementById('organize-grid');
const organizeFooter = document.getElementById('organize-footer');
const organizeEmpty = document.getElementById('organize-empty');
const organizeCountBadge = document.getElementById('organize-count-badge');
const totalPageSpan = document.getElementById('total-page-count');
const organizeInput = document.getElementById('organize-file-input');
document.getElementById('organize-drop-zone').addEventListener('dragover', (e) => e.preventDefault());
document.getElementById('organize-drop-zone').addEventListener('drop', (e) => {
e.preventDefault();
handleOrganizeFiles(e.dataTransfer.files);
});
organizeInput.addEventListener('change', (e) => {
handleOrganizeFiles(e.target.files);
organizeInput.value = '';
});
async function handleOrganizeFiles(files) {
const { PDFDocument } = PDFLib;
const validFiles = Array.from(files).filter(f => f.type === 'application/pdf');
for (const file of validFiles) {
try {
const arrayBuffer = await file.arrayBuffer();
const pdfDoc = await PDFDocument.load(arrayBuffer);
const fileIndex = organizeFileReferences.length;
organizeFileReferences.push(pdfDoc);
const pageCount = pdfDoc.getPageCount();
for (let i = 0; i < pageCount; i++) {
organizePages.push({
fileIndex: fileIndex,
pageIndex: i,
fileName: file.name,
id: Math.random().toString(36).substr(2, 9)
});
}
} catch (e) { console.error("Error loading PDF for organize", e); }
}
renderOrganizeGrid();
}
function renderOrganizeGrid() {
organizeGrid.innerHTML = '';
if (organizePages.length === 0) {
organizeGrid.classList.add('hidden');
organizeFooter.classList.add('hidden');
organizeEmpty.classList.remove('hidden');
organizeCountBadge.classList.add('hidden');
return;
}
organizeGrid.classList.remove('hidden');
organizeFooter.classList.remove('hidden');
organizeEmpty.classList.add('hidden');
organizeCountBadge.classList.remove('hidden');
totalPageSpan.textContent = organizePages.length;
organizePages.forEach((page, index) => {
const card = document.createElement('div');
card.className = 'page-card bg-slate-50 border border-slate-200 rounded-lg p-2 shadow-sm cursor-move relative flex flex-col items-center';
card.setAttribute('draggable', true);
card.dataset.id = page.id;
// Thumbnail Placeholder (PDF-Lib thumbnailing is complex in browser, using visual cards)
card.innerHTML = `
<div class="w-full aspect-[3/4] bg-white border border-slate-100 rounded shadow-inner flex flex-col items-center justify-center p-2 text-center">
<i data-lucide="file-text" class="w-8 h-8 text-blue-300 mb-1"></i>
<span class="text-[10px] text-slate-400 font-bold uppercase truncate w-full px-1">${page.fileName}</span>
</div>
<div class="mt-2 text-xs font-bold text-slate-600">Page ${page.pageIndex + 1}</div>
<div class="absolute -top-2 -left-2 w-6 h-6 bg-slate-800 text-white rounded-full flex items-center justify-center text-[10px] font-bold shadow-md">
${index + 1}
</div>
<button onclick="removePage('${page.id}')" class="delete-page-btn absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center shadow-md hover:bg-red-600 transition-colors">
<i data-lucide="x" class="w-3.5 h-3.5"></i>
</button>
`;
card.addEventListener('dragstart', handleDragStart);
card.addEventListener('dragover', handleDragOver);
card.addEventListener('drop', handleDrop);
card.addEventListener('dragend', handleDragEnd);
organizeGrid.appendChild(card);
});
lucide.createIcons();
}
function removePage(id) {
organizePages = organizePages.filter(p => p.id !== id);
renderOrganizeGrid();
}
function clearOrganize() {
organizePages = [];
organizeFileReferences = [];
renderOrganizeGrid();
}
// Drag & Drop for Page Cards
function handleDragStart(e) {
this.classList.add('dragging');
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
}
function handleDragOver(e) {
if (e.preventDefault) e.preventDefault();
return false;
}
function handleDrop(e) {
if (e.stopPropagation) e.stopPropagation();
if (dragSrcEl !== this) {
const srcId = dragSrcEl.dataset.id;
const targetId = this.dataset.id;
const srcIdx = organizePages.findIndex(p => p.id === srcId);
const targetIdx = organizePages.findIndex(p => p.id === targetId);
const [movedItem] = organizePages.splice(srcIdx, 1);
organizePages.splice(targetIdx, 0, movedItem);
renderOrganizeGrid();
}
return false;
}
function handleDragEnd() {
this.classList.remove('dragging');
}
async function saveOrganizedPDF() {
if (organizePages.length === 0) return;
const saveBtn = document.getElementById('organize-save-btn');
const originalHtml = saveBtn.innerHTML;
saveBtn.disabled = true;
saveBtn.innerHTML = '<div class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div> Working...';
try {
const { PDFDocument } = PDFLib;
const newPdf = await PDFDocument.create();
for (const pageInfo of organizePages) {
const sourceDoc = organizeFileReferences[pageInfo.fileIndex];
const [copiedPage] = await newPdf.copyPages(sourceDoc, [pageInfo.pageIndex]);
newPdf.addPage(copiedPage);
}
const pdfBytes = await newPdf.save();
const filename = document.getElementById('organize-filename').value.trim() || 'organized_document';
downloadFile(pdfBytes, `${filename}.pdf`, 'application/pdf');
} catch (err) {
alert("Error creating organized PDF.");
} finally {
saveBtn.disabled = false;
saveBtn.innerHTML = originalHtml;
lucide.createIcons();
}
}
// --- MERGE LOGIC (Existing) ---
const dropZoneMerge = document.getElementById('drop-zone-merge');
const fileInputMerge = document.getElementById('file-input-merge');
const fileListMerge = document.getElementById('file-list-merge');
const mergeBtn = document.getElementById('merge-btn');
const mergeToolbar = document.getElementById('merge-toolbar');
const customFilenameInput = document.getElementById('custom-filename');
setupDragVisuals(dropZoneMerge);
dropZoneMerge.addEventListener('drop', (e) => handleMergeFiles(e.dataTransfer.files));
fileInputMerge.addEventListener('change', (e) => { handleMergeFiles(e.target.files); fileInputMerge.value = ''; });
function handleMergeFiles(files) {
const newFiles = Array.from(files).filter(f => f.type === 'application/pdf');
mergeFiles = [...mergeFiles, ...newFiles];
renderMergeList();
}
function clearMergeFiles() { mergeFiles = []; renderMergeList(); customFilenameInput.value = ''; }
function removeMergeFile(index) { mergeFiles.splice(index, 1); renderMergeList(); }
function sortMinima() {
const takeoffVersions = ["aip0", "aipt", "aorg", "aorgt"];
const iacVersions = ["aip00", "aip0t", "aidu0", "aidut", "aia00", "aia0t", "aipk0", "aipkt", "nvr00", "nvr0t", "srr00", "srr0t"];
const minimaVersions = ["maorg0", "maorgt", "maip00", "maip0t", "maia00", "maia0t", "maipk0", "maipkt"];
const getSortValue = (file) => {
const name = file.name.toLowerCase();
const part = name.substring(4);
if (name.includes("haorg")) return { cat: 4, num: 0, ver: 0 };
const match = part.match(/(\d+)([lim])(.+)/);
if (!match) return { cat: 5, num: 0, ver: 0 };
const num = parseInt(match[1]);
const type = match[2];
const version = match[3].replace(".pdf", "");
if (type === 'l') return { cat: 1, num, ver: takeoffVersions.indexOf(version) };
if (type === 'i') return { cat: 2, num, ver: iacVersions.indexOf(version) };
if (type === 'm') return { cat: 3, num, ver: minimaVersions.indexOf(version) };
return { cat: 6, num: 0, ver: 0 };
};
mergeFiles.sort((a, b) => {
const valA = getSortValue(a), valB = getSortValue(b);
if (valA.cat !== valB.cat) return valA.cat - valB.cat;
if (valA.num !== valB.num) return valA.num - valB.num;
return valA.ver - valB.ver;
});
renderMergeList();
}
function sortFiles(type) {
if (type === 'num') {
const collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
mergeFiles.sort((a, b) => collator.compare(a.name, b.name));
} else {
mergeFiles.sort((a, b) => {
const nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase();
return type === 'asc' ? (nameA < nameB ? -1 : 1) : (nameA > nameB ? -1 : 1);
});
}
renderMergeList();
}
async function suggestMergedName() {
if (mergeFiles.length < 1) return;
const btn = document.getElementById('ai-rename-btn');
btn.innerHTML = '✨ Thinking...';
btn.disabled = true;
const filenames = mergeFiles.map(f => f.name).join(', ');
const suggestion = await callGemini(`Suggest a slugified filename for: ${filenames}`, "Concise naming assistant.");
if (suggestion) customFilenameInput.value = suggestion.trim().replace(/\s+/g, '_').toLowerCase();
btn.innerHTML = '<i data-lucide="sparkles" class="w-4 h-4 sparkle-icon"></i> ✨ AI Rename';
btn.disabled = false;
lucide.createIcons();
}
function renderMergeList() {
fileListMerge.innerHTML = '';
if (mergeFiles.length > 0) {
fileListMerge.classList.remove('hidden');
mergeToolbar.classList.remove('hidden');
mergeBtn.disabled = false;
} else {
fileListMerge.classList.add('hidden');
mergeToolbar.classList.add('hidden');
mergeBtn.disabled = true;
}
mergeFiles.forEach((file, index) => {
const li = document.createElement('li');
li.setAttribute('draggable', true);
li.dataset.index = index;
li.className = 'file-item-hover bg-white border border-slate-200 rounded-xl p-4 flex items-center justify-between shadow-sm cursor-grab active:cursor-grabbing transition-all';
li.innerHTML = `
<div class="flex items-center gap-4 overflow-hidden pointer-events-none w-full">
<div class="shrink-0 w-8 h-8 flex items-center justify-center bg-slate-100 rounded text-slate-400">
<i data-lucide="grip-vertical" class="w-5 h-5"></i>
</div>
<div class="shrink-0 w-8 h-8 bg-blue-50 text-blue-600 rounded flex items-center justify-center font-bold text-xs">
${index + 1}
</div>
<div class="min-w-0 flex-1">
<p class="text-sm font-bold text-slate-800 truncate">${file.name}</p>
<p class="text-[10px] font-semibold text-slate-400">${formatSize(file.size)}</p>
</div>
</div>
<button onclick="removeMergeFile(${index})" class="p-2 text-slate-300 hover:text-red-500 rounded-lg"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
`;
li.addEventListener('dragstart', function(e) { this.classList.add('dragging'); dragSrcEl = this; e.dataTransfer.effectAllowed = 'move'; });
li.addEventListener('dragover', e => e.preventDefault());
li.addEventListener('drop', function(e) {
if (dragSrcEl !== this) {
const sIdx = parseInt(dragSrcEl.dataset.index), tIdx = parseInt(this.dataset.index);
const [item] = mergeFiles.splice(sIdx, 1);
mergeFiles.splice(tIdx, 0, item);
renderMergeList();
}
});
li.addEventListener('dragend', function() { this.classList.remove('dragging'); });
fileListMerge.appendChild(li);
});
lucide.createIcons();
}
async function mergePDFs() {
if (mergeFiles.length === 0) return;
setLoading('merge', true);
try {
const { PDFDocument } = PDFLib;
const mergedPdf = await PDFDocument.create();
for (const file of mergeFiles) {
const pdf = await PDFDocument.load(await file.arrayBuffer());
(await mergedPdf.copyPages(pdf, pdf.getPageIndices())).forEach(p => mergedPdf.addPage(p));
}
const name = customFilenameInput.value.trim() || `merged-${Date.now()}`;
downloadFile(await mergedPdf.save(), `${name}.pdf`, 'application/pdf');
} catch (err) { alert("Error merging."); }
finally { setLoading('merge', false); }
}
// --- SPLIT LOGIC (Existing) ---
const dropZoneSplit = document.getElementById('drop-zone-split');
const splitBtn = document.getElementById('split-btn');
const splitInfo = document.getElementById('split-file-info');
const summaryContent = document.getElementById('summary-content');
setupDragVisuals(dropZoneSplit);
dropZoneSplit.addEventListener('drop', (e) => {
const f = e.dataTransfer.files[0];
if(f && f.type === "application/pdf") setSplitFile(f);
});
document.getElementById('file-input-split').addEventListener('change', (e) => { if(e.target.files[0]) setSplitFile(e.target.files[0]); });
function setSplitFile(file) {
splitFile = file;
document.getElementById('split-filename').textContent = file.name;
dropZoneSplit.classList.add('hidden');
splitInfo.classList.remove('hidden');
splitBtn.disabled = false;
}
function clearSplitFile() { splitFile = null; dropZoneSplit.classList.remove('hidden'); splitInfo.classList.add('hidden'); splitBtn.disabled = true; }
async function summarizePdf() {
if (!splitFile) return;
const btn = document.getElementById('ai-summary-btn');
btn.innerHTML = '✨ Summarizing...';
summaryContent.classList.remove('hidden');
summaryContent.textContent = "Analyzing...";
const summary = await callGemini(`Summarize PDF: ${splitFile.name}`, "Concise analyst.");
summaryContent.textContent = summary || "Done.";
btn.innerHTML = '✨ AI Generate Summary';
}
async function splitPDF() {
setLoading('split', true);
try {
const { PDFDocument } = PDFLib;
const sourcePdf = await PDFDocument.load(await splitFile.arrayBuffer());
const zip = new JSZip(), folder = zip.folder("split_pages");
for (let i = 0; i < sourcePdf.getPageCount(); i++) {
const newPdf = await PDFDocument.create();
const [p] = await newPdf.copyPages(sourcePdf, [i]);
newPdf.addPage(p);
folder.file(`page_${(i+1).toString().padStart(3,'0')}.pdf`, await newPdf.save());
}
saveAs(await zip.generateAsync({type:"blob"}), `split-${splitFile.name.replace('.pdf','')}.zip`);
} catch (err) { alert("Error splitting."); }
finally { setLoading('split', false); }
}
function setupDragVisuals(el) {
['dragenter', 'dragover'].forEach(evt => el.addEventListener(evt, (e) => { e.preventDefault(); el.classList.add('drag-active'); }));
['dragleave', 'drop'].forEach(evt => el.addEventListener(evt, (e) => { e.preventDefault(); el.classList.remove('drag-active'); }));
}
function formatSize(bytes) {
if (bytes === 0) return '0 B';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + ['B', 'KB', 'MB', 'GB'][i];
}
function downloadFile(data, filename, type) {
const blob = new Blob([data], { type });
const link = document.getElementById('download-link');
link.href = URL.createObjectURL(blob); link.download = filename; link.click();
}
function setLoading(type, isLoading) {
const btn = type === 'merge' ? mergeBtn : splitBtn;
const msg = document.getElementById(`status-msg-${type}`);
btn.disabled = isLoading;
btn.innerHTML = isLoading ? 'Processing...' : (type === 'merge' ? 'Merge PDFs' : 'Split & Download ZIP');
msg.classList.toggle('hidden', !isLoading);
if (!isLoading) lucide.createIcons();
}
</script>
</body>
</html>