-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredact.html
More file actions
915 lines (794 loc) · 40.1 KB
/
redact.html
File metadata and controls
915 lines (794 loc) · 40.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redact PDF</title>
<script src="static/js/app.js"></script>
<script src="static/js/pdf.min.js"></script>
<link href="static/css/fonts_googleapis.css" rel="stylesheet">
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = 'static/js/pdf.worker.min.js';
</script>
<link rel="stylesheet" href="static/css/all.min.css">
<style>
body { font-family: 'Inter', sans-serif; -webkit-font-smoothing: antialiased; }
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; border: 2px solid transparent; background-clip: content-box; }
::-webkit-scrollbar-thumb:hover { background: #94a3b8; border-radius: 10px; border: 2px solid transparent; background-clip: content-box; }
.word-box {
position: absolute;
background-color: transparent;
cursor: pointer;
z-index: 10;
transition: all 0.15s ease;
border-radius: 2px;
}
.word-box:hover {
background-color: rgba(16, 185, 129, 0.15);
outline: 1px solid rgba(16, 185, 129, 0.4);
}
.word-box.redacted {
background-color: #000 !important;
opacity: 0.8 !important;
border-radius: 0;
}
.word-box.edited {
background-color: rgba(59, 130, 246, 0.1);
border-bottom: 2px solid #3b82f6;
}
.mode-group button {
padding: 0.375rem 1rem; /* px-4 py-1.5 */
font-size: 0.75rem; /* text-xs */
font-weight: 600; /* font-semibold */
transition-property: all;
transition-duration: 200ms;
border-right-width: 1px;
border-color: #334155; /* border-slate-700 */
box-sizing: border-box;
}
.mode-group button:last-child {
border-right-width: 0px;
}
.mode-group button.active {
background-color: #334155; /* bg-slate-700 */
color: #ffffff; /* text-white */
}
.quad-poly {
fill: black;
fill-opacity: 0.8;
stroke: none;
pointer-events: auto;
cursor: pointer;
}
.drawing-point { fill: red; }
.drawing-line { stroke: red; stroke-width: 2; }
.edit-input {
position: absolute;
border: none;
background: rgba(255, 255, 255, 0.9);
padding: 0;
margin: 0;
outline: 2px solid #3b82f6;
z-index: 20;
color: black;
font-family: sans-serif;
resize: none;
overflow: hidden;
white-space: nowrap;
}
.manual-box {
position: absolute;
border: 2px solid #ef4444;
background-color: rgba(239, 68, 68, 0.1);
z-index: 15;
}
.manual-box.finalized {
background-color: black;
border: none;
opacity: 0.8;
}
/* Tooltip Box Style */
.mode-tooltip {
visibility: hidden;
position: absolute;
top: 110%; /* Place it below the button */
left: 50%;
transform: translateX(-50%);
background-color: #1e293b; /* Slate-800 */
color: #ffffff;
padding: 6px 10px;
border-radius: 6px;
font-size: 11px;
font-weight: 500;
white-space: nowrap;
z-index: 60;
opacity: 0;
transition: opacity 0.2s, transform 0.2s;
pointer-events: none; /* Prevents flickering when mouse moves over it */
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
}
/* Arrow for the box */
.mode-tooltip::after {
content: "";
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent #1e293b transparent;
}
/* Show on hover */
.mode-group button:hover .mode-tooltip {
visibility: visible;
opacity: 1;
transform: translateX(-50%) translateY(4px);
}
#pdf-wrapper {
box-shadow: 0 0 0 1px rgba(0,0,0,0.05), 0 10px 30px -10px rgba(0,0,0,0.2);
}
</style>
</head>
<body class="bg-[#f8fafc] h-screen flex flex-col overflow-hidden text-slate-900">
<header class="h-14 bg-white border-b border-slate-200 flex items-center justify-between px-4 z-50 shrink-0">
<div class="flex items-center gap-3 w-1/4">
<div class="w-8 h-8 bg-emerald-500 rounded-lg flex items-center justify-center text-white shadow-sm shadow-emerald-200">
<i class="fa-solid fa-user-secret"></i>
</div>
<h1 class="text-sm font-bold tracking-tight text-slate-800">Redact<span class="text-emerald-600">PDF</span></h1>
<button onclick="pywebview.api.home_page()" class="ml-2 p-2 text-slate-400 hover:text-emerald-600 transition-colors" title="Home">
<i class="fa-solid fa-house text-lg"></i> Go to Home Page
</button>
</div>
<div id="tool-bar" class="hidden flex items-center bg-slate-100 border border-slate-200 rounded-lg p-0.5 mode-group">
<button onclick="setMode('select')" id="btn-mode-select" class="active text-slate-600 hover:bg-white rounded-md relative group">
<i class="fa-solid fa-mouse-pointer mr-2"></i>Select
<span class="mode-tooltip">Quickly select words to redact. No need to drag cursor over a word or draw boxes.</span>
</button>
<button onclick="setMode('draw')" id="btn-mode-draw" class="text-slate-600 hover:bg-white rounded-md relative group">
Rect
<span class="mode-tooltip">Draw a rectangle over any area or text.</span>
</button>
<button onclick="setMode('quad')" id="btn-mode-quad" class="text-slate-600 hover:bg-white rounded-md relative group">
Polygon
<span class="mode-tooltip">Draw a quadrilateral over any area or text.</span>
</button>
<button onclick="setMode('edit')" id="btn-mode-edit" class="text-slate-600 hover:bg-white rounded-md relative group">
<i class="fa-solid fa-pen-to-square mr-2"></i>Edit Text
<span class="mode-tooltip">Edit the actual text content inside the available boxes to redact instead of hiding it behind black bars.</span>
</button>
</div>
<div id="action-bar" class="hidden flex items-center justify-end gap-2 w-1/4">
<button onclick="location.reload()" class="text-slate-500 hover:text-slate-700 p-2 rounded-md transition hover:bg-slate-100">
<i class="fa-solid fa-arrow-up-from-bracket"></i> New Upload
</button>
<button onclick="submitRedaction()" id="submit-btn" class="bg-slate-900 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-xs font-bold transition-all flex items-center gap-2">
<i class="fa-solid fa-file-export"></i> Process PDF
</button>
</div>
</header>
<main class="flex-1 flex overflow-hidden">
<aside class="w-64 bg-slate-50 border-r border-slate-200 flex flex-col hidden" id="sidebar">
<div class="p-4 flex justify-between items-center shrink-0">
<span class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Page Navigator</span>
<span class="text-xs font-semibold bg-slate-200 px-2 py-0.5 rounded-full text-slate-600" id="sidebar-count">0</span>
</div>
<div class="flex-1 overflow-y-auto px-4 pb-4 space-y-3" id="thumbnail-container"></div>
</aside>
<section class="flex-1 bg-slate-200/50 relative overflow-auto flex justify-center p-12 scroll-smooth" id="viewer-stage">
<div id="upload-zone" class="m-auto text-center w-full max-w-md">
<div class="bg-white p-12 rounded-3xl shadow-sm border border-slate-200 hover:border-emerald-400 transition-all cursor-pointer group"
onclick="document.getElementById('file-input').click()"
ondragover="event.preventDefault()"
ondrop="handleDrop(event)">
<div class="w-20 h-20 bg-emerald-50 text-emerald-500 rounded-2xl flex items-center justify-center mx-auto mb-6 group-hover:scale-110 transition-transform duration-300">
<i class="fa-solid fa-plus text-3xl"></i>
</div>
<h3 class="text-lg font-bold text-slate-800 mb-1">Upload Document</h3>
<p class="text-sm text-slate-400 mb-8">Or Drag & drop your PDF here</p>
<input type="file" id="file-input" class="hidden" accept=".pdf" onchange="handleFileSelect(event)">
<span class="inline-block bg-slate-900 text-white px-8 py-2.5 rounded-full font-bold text-xs">Browse Files</span>
</div>
</div>
<div id="loader" class="hidden m-auto text-center">
<div class="relative w-12 h-12 mx-auto mb-4">
<div class="absolute inset-0 border-4 border-slate-200 rounded-full"></div>
<div class="absolute inset-0 border-4 border-emerald-500 rounded-full border-t-transparent animate-spin"></div>
</div>
<p class="text-sm text-slate-600 font-medium">Preparing Your Document...<br>May take some time for large size PDFs (~30 MB/sec).</p>
</div>
<div id="pdf-wrapper" class="hidden relative bg-white transition-all duration-300">
<canvas id="the-canvas" class="block"></canvas>
<svg id="svg-overlay" class="absolute inset-0 pointer-events-none z-20"></svg>
<div id="bbox-overlay" class="absolute inset-0 z-10"></div>
</div>
</section>
<div id="pagination-controls" class="hidden fixed bottom-8 left-1/2 -translate-x-1/2 bg-white/80 backdrop-blur-md border border-slate-200 text-slate-700 px-5 py-2.5 rounded-2xl shadow-xl flex items-center gap-6 z-40">
<button onclick="changePage(-1)" class="hover:text-emerald-600 transition disabled:opacity-30">
<i class="fa-solid fa-chevron-left text-sm"></i>
</button>
<div class="flex items-center gap-2 text-xs font-bold">
<input type="number" id="page-input" value="1" min="1" class="w-10 bg-slate-100 text-center py-1 rounded-md border-none focus:ring-2 focus:ring-emerald-500 transition" onchange="handlePageInput(this)">
<span class="text-slate-400 mx-1">/</span>
<span id="total-pages-display">--</span>
</div>
<button onclick="changePage(1)" class="hover:text-emerald-600 transition disabled:opacity-30">
<i class="fa-solid fa-chevron-right text-sm"></i>
</button>
</div>
<div id="file-output-container" class="hidden fixed inset-0 flex items-center justify-center z-[100] bg-slate-900/60 backdrop-blur-sm px-4">
</div>
</main>
<script>
// --- Global State ---
let currentFile = null;
let filename = "";
let pdfDoc = null;
let pageNum = 1;
let totalPages = 0;
let pdfScale = 1.5;
let bboxData = null;
let redactionSet = new Set(); // IDs of boxes marked for Black Box redaction
let editMap = new Map(); // Map<ID, {text: string}> for Text Edits
let manualRects = [];
let manualQuads = [];
let currentMode = 'select'; // 'select', 'draw', 'quad', 'edit'
// Drawing State
let isDrawing = false;
let startX, startY;
let activeDrawBox = null;
let activeQuadPoints = [];
// Scaling
let currentScaleX = 1;
let currentScaleY = 1;
// --- Mode Switching ---
function setMode(mode) {
currentMode = mode;
// UI Button Updates
const buttons = ['select', 'draw', 'quad', 'edit'];
buttons.forEach(m => {
const btn = document.getElementById(`btn-mode-${m}`);
btn.classList.remove('active', 'bg-slate-700', 'text-white');
btn.classList.add('text-slate-600');
});
const activeBtn = document.getElementById(`btn-mode-${mode}`);
activeBtn.classList.add('active', 'bg-slate-700', 'text-white');
activeBtn.classList.remove('text-slate-600');
const overlay = document.getElementById('bbox-overlay');
const cursorMap = { 'draw': 'crosshair', 'quad': 'cell', 'edit': 'text', 'select': 'pointer' };
overlay.style.cursor = cursorMap[mode] || 'default';
const boxes = document.querySelectorAll('.word-box');
boxes.forEach(box => {
box.style.pointerEvents = (mode === 'draw' || mode === 'quad') ? 'none' : 'auto';
});
}
// --- File Handling ---
function handleDrop(e) {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file && file.type === "application/pdf") processUpload(file);
}
function handleFileSelect(e) {
const file = e.target.files[0];
if (file) processUpload(file);
}
async function processUpload(file) {
currentFile = file;
document.getElementById('upload-zone').classList.add('hidden');
document.getElementById('loader').classList.remove('hidden');
try {
const base64File = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result.split(',')[1];
resolve(base64String);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
const data = await pywebview.api.get_bbox(file.name, base64File);
console.log(data)
bboxData = {
filename: data.filename,
total_pages: data.total_pages,
pages: new Array(data.total_pages).fill(null)
};
// Fill in the first page only
data.pages.forEach((p, i) => {
bboxData.pages[i] = p;
});
filename = data.filename;
totalPages = data.total_pages;
const fileReader = new FileReader();
fileReader.onload = function() {
const typedarray = new Uint8Array(this.result);
loadPDF(typedarray);
};
fileReader.readAsArrayBuffer(file);
} catch (error) {
alert('Error: ' + error.message);
location.reload();
}
}
async function loadPDF(data) {
pdfDoc = await pdfjsLib.getDocument(data).promise;
document.getElementById('loader').classList.add('hidden');
document.getElementById('pdf-wrapper').classList.remove('hidden');
document.getElementById('tool-bar').classList.remove('hidden');
document.getElementById('action-bar').classList.remove('hidden');
document.getElementById('pagination-controls').classList.remove('hidden');
document.getElementById('sidebar').classList.remove('hidden');
document.getElementById('sidebar-count').textContent = totalPages;
document.getElementById('total-pages-display').textContent = totalPages;
renderThumbnails();
renderPage(pageNum);
}
async function renderThumbnails() {
const container = document.getElementById('thumbnail-container');
container.innerHTML = '';
for (let i = 1; i <= totalPages; i++) {
const page = await pdfDoc.getPage(i);
const viewport = page.getViewport({ scale: 0.2 });
const wrapper = document.createElement('div');
wrapper.id = `thumb-${i}`;
wrapper.className = 'cursor-pointer hover:opacity-80 transition bg-slate-200 p-1 mb-2 rounded border-2 border-transparent';
wrapper.onclick = () => { pageNum = i; renderPage(i); };
const canvas = document.createElement('canvas');
canvas.height = viewport.height;
canvas.width = viewport.width;
canvas.className = 'bg-white block mx-auto';
wrapper.appendChild(canvas);
container.appendChild(wrapper);
await page.render({ canvasContext: canvas.getContext('2d'), viewport: viewport }).promise;
}
}
function syncSidebar(num) {
const container = document.getElementById('thumbnail-container');
const allThumbs = container.querySelectorAll('[id^="thumb-"]');
allThumbs.forEach(thumb => {
thumb.className = 'cursor-pointer hover:bg-slate-200 transition p-2 rounded-xl border-2 border-transparent';
});
const activeThumb = document.getElementById(`thumb-${num}`);
if (activeThumb) {
activeThumb.className = 'cursor-pointer bg-white shadow-sm border-emerald-500 p-2 rounded-xl border-2';
activeThumb.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
}
async function renderPage(num) {
const page = await pdfDoc.getPage(num);
const canvas = document.getElementById('the-canvas');
const wrapper = document.getElementById('pdf-wrapper');
const overlay = document.getElementById('bbox-overlay');
const svg = document.getElementById('svg-overlay');
const viewport = page.getViewport({ scale: pdfScale });
canvas.height = viewport.height;
canvas.width = viewport.width;
[wrapper, overlay, svg].forEach(el => {
el.style.width = `${viewport.width}px`;
el.style.height = `${viewport.height}px`;
});
await page.render({ canvasContext: canvas.getContext('2d'), viewport: viewport }).promise;
document.getElementById('page-input').value = num;
// Check if we already have data for this page (num-1 because 0-indexed)
if (!bboxData.pages[num - 1]) {
// Show a small subtle loader over the PDF
overlay.innerHTML = '<div class="absolute inset-0 flex items-center justify-center bg-white/50 z-50"><i class="fa-solid fa-spinner fa-spin text-2xl text-emerald-500"></i><span class="ml-2">Loading boxes...</span></div>';
try {
// Call the new backend API
const newPageData = await pywebview.api.get_single_page_bbox(filename, num - 1);
if(newPageData.error) throw new Error(newPageData.error);
// Store it in our global state
bboxData.pages[num - 1] = newPageData;
} catch (err) {
console.error("Failed to fetch page data", err);
overlay.innerHTML = '';
return;
}
}
// Coordinate Scaling
const pageData = bboxData.pages[num - 1];
if (pageData) {
currentScaleX = viewport.width / pageData.width;
currentScaleY = viewport.height / pageData.height;
drawWordBoxes(num, pageData);
restoreManualShapes(num);
}
syncSidebar(num);
}
function drawWordBoxes(pageIndex, pageData) {
const overlay = document.getElementById('bbox-overlay');
overlay.innerHTML = ''; // Clear
pageData.words.forEach((word, idx) => {
const div = document.createElement('div');
const boxId = `${pageIndex-1}-${idx}`;
div.className = 'word-box';
div.dataset.id = boxId;
// Set CSS styles based on stored state
if (redactionSet.has(boxId)) div.classList.add('redacted');
if (editMap.has(boxId)) {
div.classList.add('edited');
// Optional: Display edited text preview
// div.title = "Edited to: " + editMap.get(boxId).text;
}
const x = word.x0 * currentScaleX;
const y = word.top * currentScaleY;
const w = (word.x1 - word.x0) * currentScaleX;
const h = (word.bottom - word.top) * currentScaleY;
div.style.left = `${x}px`;
div.style.top = `${y}px`;
div.style.width = `${w}px`;
div.style.height = `${h}px`;
// Store Font data in dataset for easy access
div.dataset.fontName = word.font_name;
div.dataset.fontSize = word.font_size;
div.dataset.text = word.text;
div.onclick = (e) => handleBoxClick(e, div, boxId, word);
overlay.appendChild(div);
});
}
function handleBoxClick(e, div, boxId, wordData) {
e.stopPropagation();
if (currentMode === 'select') {
// Redaction Toggle
if (editMap.has(boxId)) {
if(!confirm("This will discard your text edit. Continue?")) return;
editMap.delete(boxId);
div.classList.remove('edited');
}
if (redactionSet.has(boxId)) {
redactionSet.delete(boxId);
div.classList.remove('redacted');
} else {
redactionSet.add(boxId);
div.classList.add('redacted');
}
}
else if (currentMode === 'edit') {
// Text Edit Mode
if (redactionSet.has(boxId)) {
alert("Unselect the redaction (black box) before editing text.");
return;
}
activateInlineEdit(div, boxId, wordData);
}
}
function activateInlineEdit(div, boxId, wordData) {
// 1. Setup the input element
const input = document.createElement('input');
input.type = 'text';
input.className = 'edit-input shadow-lg';
// 2. Get current value or original text
const existingEdit = editMap.get(boxId);
input.value = existingEdit ? existingEdit.text : wordData.text;
// 3. Position the input EXACTLY where the word box is
input.style.left = div.style.left;
input.style.top = div.style.top;
input.style.width = div.style.width;
input.style.height = div.style.height;
// 4. Match the font size from the PDF scaling
// We use a slight multiplier (e.g., 0.9) if the text feels too cramped
input.style.fontSize = (wordData.font_size * currentScaleY) + 'px';
// 5. Visual management
div.style.visibility = 'hidden'; // Hide the original box background
document.getElementById('bbox-overlay').appendChild(input);
input.focus();
input.select();
// 6. Logic to save the data
const finishEdit = () => {
const newVal = input.value;
if (newVal !== wordData.text && newVal.trim() !== "") {
editMap.set(boxId, {
text: newVal,
original: wordData
});
div.classList.add('edited');
} else if (newVal === wordData.text) {
editMap.delete(boxId);
div.classList.remove('edited');
}
div.style.visibility = 'visible';
input.remove();
};
// 7. Event Listeners
input.onblur = finishEdit;
input.onkeydown = (e) => {
if (e.key === 'Enter') {
input.blur(); // Triggers finishEdit
}
if (e.key === 'Escape') {
input.value = wordData.text; // Revert
input.blur();
}
};
}
// --- Manual Drawing Logic (Same as before, simplified for brevity) ---
const overlay = document.getElementById('bbox-overlay');
overlay.onmousedown = (e) => {
if(e.target.classList.contains('manual-box') || e.target.classList.contains('quad-poly')) return;
const rect = overlay.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if(currentMode === 'draw') {
isDrawing = true; startX = x; startY = y;
activeDrawBox = document.createElement('div');
activeDrawBox.className = 'manual-box';
activeDrawBox.style.left = x+'px'; activeDrawBox.style.top = y+'px';
overlay.appendChild(activeDrawBox);
} else if (currentMode === 'quad') {
activeQuadPoints.push({x, y});
renderActiveQuad();
if(activeQuadPoints.length === 4) finalizeQuad();
}
};
overlay.onmousemove = (e) => {
if(currentMode === 'draw' && isDrawing && activeDrawBox) {
const rect = overlay.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
activeDrawBox.style.width = Math.abs(x - startX) + 'px';
activeDrawBox.style.height = Math.abs(y - startY) + 'px';
activeDrawBox.style.left = Math.min(x, startX) + 'px';
activeDrawBox.style.top = Math.min(y, startY) + 'px';
}
};
overlay.onmouseup = () => {
if(currentMode === 'draw' && isDrawing && activeDrawBox) {
isDrawing = false;
const w = parseFloat(activeDrawBox.style.width);
const h = parseFloat(activeDrawBox.style.height);
if(w < 5 || h < 5) { activeDrawBox.remove(); return; }
activeDrawBox.classList.add('finalized');
const rectData = {
id: Date.now(),
pageIndex: pageNum - 1,
pdfX0: parseFloat(activeDrawBox.style.left) / currentScaleX,
pdfTop: parseFloat(activeDrawBox.style.top) / currentScaleY,
pdfW: w / currentScaleX,
pdfH: h / currentScaleY
};
manualRects.push(rectData);
const el = activeDrawBox;
const id = rectData.id;
el.onclick = (e) => {
e.stopPropagation();
if(currentMode !== 'select') {
manualRects = manualRects.filter(r => r.id !== id);
el.remove();
}
}
activeDrawBox = null;
}
};
function renderActiveQuad() {
const svg = document.getElementById('svg-overlay');
const temps = svg.querySelectorAll('.temp-draw');
temps.forEach(el => el.remove());
if(activeQuadPoints.length === 0) return;
activeQuadPoints.forEach((pt, i) => {
const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y); c.setAttribute("r", 4);
c.setAttribute("class", "drawing-point temp-draw");
svg.appendChild(c);
if(i > 0) {
const l = document.createElementNS("http://www.w3.org/2000/svg", "line");
l.setAttribute("x1", activeQuadPoints[i-1].x); l.setAttribute("y1", activeQuadPoints[i-1].y);
l.setAttribute("x2", pt.x); l.setAttribute("y2", pt.y);
l.setAttribute("class", "drawing-line temp-draw");
svg.appendChild(l);
}
});
}
function finalizeQuad() {
const pdfPoints = activeQuadPoints.map(p => ({x: p.x/currentScaleX, y: p.y/currentScaleY}));
const id = Date.now();
manualQuads.push({ id, pageIndex: pageNum-1, points: pdfPoints });
const poly = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
poly.setAttribute("points", activeQuadPoints.map(p => `${p.x},${p.y}`).join(" "));
poly.setAttribute("class", "quad-poly");
poly.onclick = (e) => {
e.stopPropagation();
if(currentMode !== 'select') {
manualQuads = manualQuads.filter(q => q.id !== id);
poly.remove();
}
};
document.getElementById('svg-overlay').appendChild(poly);
activeQuadPoints = [];
renderActiveQuad();
}
function restoreManualShapes(pNum) {
const overlay = document.getElementById('bbox-overlay');
const svg = document.getElementById('svg-overlay');
svg.innerHTML = '';
// 1. Rects
manualRects.filter(r => r.pageIndex === pNum - 1).forEach(r => {
const d = document.createElement('div');
d.className = 'manual-box finalized';
d.style.left = (r.pdfX0 * currentScaleX) + 'px';
d.style.top = (r.pdfTop * currentScaleY) + 'px';
d.style.width = (r.pdfW * currentScaleX) + 'px';
d.style.height = (r.pdfH * currentScaleY) + 'px';
d.onclick = (e) => {
e.stopPropagation();
if(currentMode !== 'select') {
manualRects = manualRects.filter(x => x.id !== r.id);
d.remove();
}
};
overlay.appendChild(d);
});
// 2. Quads
manualQuads.filter(q => q.pageIndex === pNum -1).forEach(q => {
const poly = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
const ptrStr = q.points.map(p => `${p.x * currentScaleX},${p.y * currentScaleY}`).join(" ");
poly.setAttribute("points", ptrStr);
poly.setAttribute("class", "quad-poly");
poly.onclick = (e) => {
e.stopPropagation();
if(currentMode !== 'select') {
manualQuads = manualQuads.filter(x => x.id !== q.id);
poly.remove();
}
};
svg.appendChild(poly);
});
}
function displayFilePathAndCopyButton(filePath) {
const container = document.getElementById('file-output-container');
container.className = "fixed inset-0 flex items-center justify-center z-[100] bg-slate-900/40 backdrop-blur-sm px-4";
container.innerHTML = `
<div class="bg-white rounded-3xl shadow-2xl p-8 max-w-lg w-full transform animate-in fade-in zoom-in duration-300">
<div class="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-4">
<i class="fa-solid fa-file-shield text-2xl"></i>
</div>
<h2 class="text-2xl font-bold text-slate-800 text-center mb-2">Redaction Complete</h2>
<p class="text-slate-500 text-center mb-6 text-sm">Your secure file has been generated and saved to the following location:</p>
<div class="bg-slate-50 border border-slate-200 rounded-xl p-4 mb-6 relative group">
<p id="path-text" class="text-xs font-mono text-slate-600 break-all leading-relaxed">${filePath}</p>
<button id="copy-btn"
class="mt-3 w-full bg-slate-900 hover:bg-emerald-600 text-white py-2 rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2">
<i class="fa-regular fa-copy"></i> <span>Copy File Path</span>
</button>
</div>
<button onclick="document.getElementById('file-output-container').classList.add('hidden')"
class="w-full text-slate-400 hover:text-slate-600 text-sm font-medium py-2 transition-colors">
Dismiss
</button>
</div>
`;
// Attach the event listener directly to the element
const copyBtn = document.getElementById('copy-btn');
copyBtn.addEventListener('click', () => copyToClipboard(filePath, copyBtn));
// Ensure container is visible (if it was hidden before)
container.classList.remove('hidden');
}
async function copyToClipboard(text, btn) {
try {
await navigator.clipboard.writeText(text);
const span = btn.querySelector('span');
const icon = btn.querySelector('i');
const originalText = span.textContent;
span.textContent = "Copied!";
btn.classList.replace('bg-slate-900', 'bg-emerald-600');
icon.className = "fa-solid fa-check";
setTimeout(() => {
span.textContent = originalText;
btn.classList.replace('bg-emerald-600', 'bg-slate-900');
icon.className = "fa-regular fa-copy";
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
// --- Submit ---
async function submitRedaction() {
if (redactionSet.size === 0 && manualRects.length === 0 && manualQuads.length === 0 && editMap.size === 0) {
alert("No changes marked.");
return;
}
const btn = document.getElementById('submit-btn');
const originalText = btn.innerHTML;
btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
btn.disabled = true;
const bboxesToProcess = [];
// 1. Redactions (Words)
redactionSet.forEach(id => {
const [p, w] = id.split('-').map(Number);
const wd = bboxData.pages[p].words[w];
bboxesToProcess.push({
redact_type: "word", page_index: p,
x0: wd.x0, top: wd.top, x1: wd.x1, bottom: wd.bottom
});
});
// 2. Edits (Text Replacement)
editMap.forEach((val, id) => {
const [p, w] = id.split('-').map(Number);
const wd = val.original; // Original data contains font info
bboxesToProcess.push({
redact_type: "text_edit",
page_index: p,
x0: wd.x0, top: wd.top, x1: wd.x1, bottom: wd.bottom,
text: val.text, // The new text
original_text: wd.text,
font_name: wd.font_name,
font_size: wd.font_size,
text_color: wd.text_color,
flags: wd.flags,
origin_y: wd.origin_y
});
});
// 3. Manual Rects
manualRects.forEach(r => {
const x0 = r.pdfX0;
const top = r.pdfTop;
const x1 = r.pdfX0 + r.pdfW;
const bottom = r.pdfTop + r.pdfH;
// Only push if all values are valid numbers
if (
!isNaN(x0) &&
!isNaN(top) &&
!isNaN(x1) &&
!isNaN(bottom)
) {
bboxesToProcess.push({
redact_type: "manual_rect",
page_index: r.pageIndex,
x0,
top,
x1,
bottom
});
}
});
// 4. Manual Quads
manualQuads.forEach(q => {
bboxesToProcess.push({
redact_type: "manual_quad", page_index: q.pageIndex,
x0: 1.1, top: 1.1, x1: 1.1, bottom: 1.1,
points: q.points.map(p => [p.x, p.y])
});
});
try {
const data = await pywebview.api.redact_pdf(filename, bboxesToProcess);
console.log('herejs1');
if (data.success && typeof pywebview.api !== 'undefined') {
if (data.filepath) {
displayFilePathAndCopyButton(data.file_data);
// alert('File is too large for direct download. Path displayed below.');
await pywebview.api.open_containing_folder(data.file_data);
} else {
const saveResult = await pywebview.api.save_file_dialog(data.filename, data.file_data);
if (saveResult) {
// alert('File saved successfully!');
console.log('file saved')
} else {
alert('File save was cancelled or failed.');
}
}
} else {
throw new Error(data.message || "Processing failed in Python API.");
}
} catch (e) {
alert(e.message);
} finally {
btn.innerHTML = originalText;
btn.disabled = false;
}
}
function changePage(offset) {
const next = pageNum + offset;
if(next > 0 && next <= totalPages) {
pageNum = next;
renderPage(pageNum);
}
}
function handlePageInput(el) {
let n = parseInt(el.value);
if(n < 1) n = 1; if(n > totalPages) n = totalPages;
pageNum = n; renderPage(n);
}
</script>
</body>
</html>