@farisabid/foliokit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +151 -2
  3. package/bin/foliokit.js +476 -0
  4. package/package.json +46 -4
  5. package/public/css/main.css +915 -0
  6. package/public/css/tokens.css +29 -0
  7. package/public/favicon.svg +17 -0
  8. package/public/index.html +747 -0
  9. package/public/js/core/pdf-engine.js +69 -0
  10. package/public/js/core/state.js +365 -0
  11. package/public/js/tools/dev-tools.js +1508 -0
  12. package/public/js/tools/edit-pdf.js +1618 -0
  13. package/public/js/tools/office-tools.js +221 -0
  14. package/public/js/tools/pdf-ops.js +949 -0
  15. package/public/js/tools/sign-pdf.js +198 -0
  16. package/public/manifest.json +26 -0
  17. package/public/sw.js +88 -0
  18. package/public/vendor/fonts/inter-1.woff2 +0 -0
  19. package/public/vendor/fonts/inter-2.woff2 +0 -0
  20. package/public/vendor/fonts/inter-3.woff2 +0 -0
  21. package/public/vendor/fonts/inter-4.woff2 +0 -0
  22. package/public/vendor/fonts/inter-5.woff2 +0 -0
  23. package/public/vendor/fonts/inter-6.woff2 +0 -0
  24. package/public/vendor/fonts/inter-7.woff2 +0 -0
  25. package/public/vendor/fonts/inter.css +316 -0
  26. package/public/vendor/fonts/jbmono-1.woff2 +0 -0
  27. package/public/vendor/fonts/jbmono-2.woff2 +0 -0
  28. package/public/vendor/fonts/jbmono-3.woff2 +0 -0
  29. package/public/vendor/fonts/jbmono-4.woff2 +0 -0
  30. package/public/vendor/fonts/jbmono-5.woff2 +0 -0
  31. package/public/vendor/fonts/jbmono-6.woff2 +0 -0
  32. package/public/vendor/fonts/jbmono.css +109 -0
  33. package/public/vendor/jszip.min.js +13 -0
  34. package/public/vendor/pdf-lib.min.js +16 -0
  35. package/public/vendor/pdf.min.js +22 -0
  36. package/public/vendor/pdf.worker.min.js +22 -0
  37. package/public/vendor/qrcode.min.js +1 -0
  38. package/server.js +125 -0
  39. package/start.bat +19 -0
  40. package/start.sh +12 -0
@@ -0,0 +1,1618 @@
1
+ /**
2
+ * Foliokit — Edit PDF Studio (v2.0)
3
+ * 100% client-side. Menggambar anotasi di overlay canvas dengan koordinat
4
+ * ternormalisasi (0..1) agar stabil terhadap zoom & resize, lalu mengekspor
5
+ * lewat pdf-lib (vector) atau composite raster (secure flatten).
6
+ *
7
+ * Dimuat setelah app.js. Semua fungsi publik memakai awalan editPdf* agar
8
+ * tidak bentrok dengan registry app.js.
9
+ */
10
+ 'use strict';
11
+
12
+ const editPdfState = {
13
+ bytes: null,
14
+ name: '',
15
+ fileSize: 0,
16
+ pdfDoc: null,
17
+ pageCount: 0,
18
+ currentPage: 1,
19
+ zoom: 1.0,
20
+ activeTool: 'select',
21
+ selectedId: null,
22
+ annotations: [],
23
+ history: [],
24
+ historyIndex: -1,
25
+ flattenOnExport: true,
26
+ stampIncludeDate: true,
27
+ dirty: false,
28
+ initialized: false,
29
+ pageInfo: {},
30
+ imgCache: {}, // dataUrl -> HTMLImageElement
31
+ viewW: 0,
32
+ viewH: 0,
33
+ defaults: {
34
+ fontFamily: 'Helvetica',
35
+ fontSize: 14,
36
+ bold: false,
37
+ italic: false,
38
+ align: 'left',
39
+ color: '#1E1B4B',
40
+ whiteout: false,
41
+ highlightColor: '#FDE047',
42
+ highlightOpacity: 0.5,
43
+ strokeColor: '#2563EB',
44
+ strokeWidth: 2.5,
45
+ shapeType: 'rect',
46
+ shapeFill: 'transparent',
47
+ },
48
+ };
49
+
50
+ const EDIT_TEXT_COLORS = ['#1E1B4B', '#0F172A', '#DC2626', '#2563EB', '#059669', '#B45309'];
51
+ const EDIT_HIGHLIGHT_COLORS = ['#FDE047', '#86EFAC', '#FBCFE8', '#BAE6FD'];
52
+ const EDIT_STROKE_COLORS = ['#2563EB', '#0F172A', '#DC2626', '#059669', '#D97706'];
53
+ const EDIT_STAMP_PRESETS = {
54
+ DISETUJUI: { color: '#059669', bg: '#ECFDF5' },
55
+ LUNAS: { color: '#2563EB', bg: '#EFF6FF' },
56
+ RAHASIA: { color: '#DC2626', bg: '#FEF2F2' },
57
+ DRAFT: { color: '#D97706', bg: '#FFFBEB' },
58
+ SALINAN: { color: '#475569', bg: '#F1F5F9' },
59
+ };
60
+
61
+ // ============================================================
62
+ // HELPERS
63
+ // ============================================================
64
+ const epEl = id => document.getElementById(id);
65
+ const epClamp = (v, a, b) => Math.max(a, Math.min(b, v));
66
+ let epUidN = 1;
67
+ const epUid = () => 'a' + (epUidN++) + '_' + Date.now().toString(36).slice(-4);
68
+ const epFmt = (b) => (typeof fmtSize === 'function' ? fmtSize(b) : b + ' B');
69
+
70
+ function epPageInfo() {
71
+ return editPdfState.pageInfo[editPdfState.currentPage] || { w: 595, h: 842, rotation: 0 };
72
+ }
73
+ function epViewSize() {
74
+ return { W: editPdfState.viewW || 1, H: editPdfState.viewH || 1 };
75
+ }
76
+ function epGetSelected() {
77
+ return editPdfState.annotations.find(a => a.id === editPdfState.selectedId) || null;
78
+ }
79
+ function epAnnBBox(a) {
80
+ if (a.type === 'draw' && a.points && a.points.length) {
81
+ const xs = a.points.map(p => p.x), ys = a.points.map(p => p.y);
82
+ const x = Math.min(...xs), y = Math.min(...ys);
83
+ return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };
84
+ }
85
+ if (a.type === 'shape' && (a.shapeType === 'line' || a.shapeType === 'arrow')) {
86
+ return {
87
+ x: Math.min(a.x, a.x + a.w), y: Math.min(a.y, a.y + a.h),
88
+ w: Math.abs(a.w), h: Math.abs(a.h),
89
+ };
90
+ }
91
+ return { x: a.x, y: a.y, w: a.w, h: a.h };
92
+ }
93
+ function epTypeLabel(a) {
94
+ const map = { text: 'Teks', highlight: 'Stabilo', redact: 'Sensor', draw: 'Coretan', shape: 'Bentuk', image: 'Gambar', stamp: 'Stempel' };
95
+ let s = map[a.type] || a.type;
96
+ if (a.type === 'text' && a.text) s += ' · ' + a.text.slice(0, 16);
97
+ if (a.type === 'stamp') s += ' · ' + a.presetText;
98
+ return s;
99
+ }
100
+
101
+ function hexToRgb01(hex) {
102
+ hex = String(hex || '#000000').replace('#', '');
103
+ if (hex.length === 3) hex = hex.split('').map(c => c + c).join('');
104
+ const n = parseInt(hex, 16);
105
+ return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255 };
106
+ }
107
+
108
+ function wrapLines(ctx, text, maxW) {
109
+ const out = [];
110
+ String(text == null ? '' : text).split('\n').forEach(para => {
111
+ if (!para) { out.push(''); return; }
112
+ const words = para.split(/\s+/);
113
+ let line = '';
114
+ words.forEach(w => {
115
+ const test = line ? line + ' ' + w : w;
116
+ if (ctx.measureText(test).width > maxW && line) { out.push(line); line = w; }
117
+ else line = test;
118
+ });
119
+ out.push(line);
120
+ });
121
+ return out;
122
+ }
123
+
124
+ function wrapForPdf(font, text, size, maxW) {
125
+ const out = [];
126
+ String(text == null ? '' : text).split('\n').forEach(para => {
127
+ if (!para) { out.push(''); return; }
128
+ const words = para.split(/\s+/);
129
+ let line = '';
130
+ words.forEach(w => {
131
+ const test = line ? line + ' ' + w : w;
132
+ if (font.widthOfTextAtSize(test, size) > maxW && line) { out.push(line); line = w; }
133
+ else line = test;
134
+ });
135
+ out.push(line);
136
+ });
137
+ return out;
138
+ }
139
+
140
+ // ============================================================
141
+ // INIT
142
+ // ============================================================
143
+ function initEditPdfStudio() {
144
+ const wrap = epEl('edit-stage-wrap');
145
+ if (wrap) wrap.classList.add('tool-' + editPdfState.activeTool);
146
+
147
+ if (!editPdfState.initialized) {
148
+ editPdfState.initialized = true;
149
+
150
+ document.querySelectorAll('#edit-toolbar .edit-tool').forEach(btn => {
151
+ btn.addEventListener('click', () => editPdfSetTool(btn.dataset.tool));
152
+ });
153
+
154
+ const overlay = epEl('edit-annot-canvas');
155
+ overlay.addEventListener('pointerdown', epOnPointerDown);
156
+ overlay.addEventListener('pointermove', epOnPointerMove);
157
+ overlay.addEventListener('pointerup', epOnPointerUp);
158
+ overlay.addEventListener('pointercancel', epOnPointerUp);
159
+ overlay.addEventListener('dblclick', epOnDoubleClick);
160
+
161
+ const ta = epEl('edit-text-inline');
162
+ ta.addEventListener('blur', epCommitInlineText);
163
+ ta.addEventListener('keydown', e => {
164
+ if (e.key === 'Escape') { e.preventDefault(); epCommitInlineText(); }
165
+ else if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); epCommitInlineText(); }
166
+ });
167
+
168
+ const fl = epEl('edit-flatten');
169
+ if (fl) fl.checked = editPdfState.flattenOnExport;
170
+
171
+ document.addEventListener('keydown', epHandleKey);
172
+ }
173
+
174
+ editPdfSetTool(editPdfState.activeTool, true);
175
+ epUpdateUndoRedo();
176
+ epRenderInspector();
177
+ epRenderLayers();
178
+ epUpdateZoomLabel();
179
+
180
+ if (editPdfState.pdfDoc) {
181
+ epShowStage(true);
182
+ epRenderPage();
183
+ epRenderThumbs();
184
+ } else {
185
+ epShowStage(false);
186
+ }
187
+ }
188
+
189
+ function epShowStage(hasDoc) {
190
+ epEl('edit-empty').classList.toggle('hidden', hasDoc);
191
+ epEl('edit-stage-scroll').classList.toggle('hidden', !hasDoc);
192
+ epEl('edit-pager').classList.toggle('hidden', !hasDoc);
193
+ epEl('edit-file-name').textContent = hasDoc ? (editPdfState.name || 'Dokumen') : 'Belum ada berkas';
194
+ epEl('edit-file-meta').innerHTML = hasDoc
195
+ ? `<span class="m">${epFmt(editPdfState.fileSize)}</span><span class="m">${editPdfState.pageCount} halaman</span>`
196
+ : '';
197
+ }
198
+
199
+ // ============================================================
200
+ // LOAD PDF
201
+ // ============================================================
202
+ async function loadEditPdfFile(file) {
203
+ if (!file) return;
204
+ const okPdf = file.type === 'application/pdf' || /\.pdf$/i.test(file.name || '');
205
+ if (!okPdf) return showToast('Berkas harus PDF.', false);
206
+ if (editPdfState.dirty && editPdfState.annotations.length) {
207
+ if (!confirm('Ada anotasi yang belum diunduh. Ganti berkas dan buang perubahan?')) return;
208
+ }
209
+ try {
210
+ if (window.pdfjsLib && !pdfjsLib.GlobalWorkerOptions.workerSrc) {
211
+ pdfjsLib.GlobalWorkerOptions.workerSrc = './vendor/pdf.worker.min.js';
212
+ }
213
+ const bytes = await file.arrayBuffer();
214
+ const doc = await pdfjsLib.getDocument({ data: bytes.slice(0) }).promise;
215
+
216
+ editPdfState.bytes = bytes;
217
+ editPdfState.name = file.name;
218
+ editPdfState.fileSize = file.size;
219
+ editPdfState.pdfDoc = doc;
220
+ editPdfState.pageCount = doc.numPages;
221
+ editPdfState.currentPage = 1;
222
+ editPdfState.zoom = 1.0;
223
+ editPdfState.annotations = [];
224
+ editPdfState.selectedId = null;
225
+ editPdfState.pageInfo = {};
226
+ editPdfState.imgCache = {};
227
+ editPdfState.dirty = false;
228
+ editPdfState.activeTool = 'select';
229
+ editPdfState.history = [];
230
+ editPdfState.historyIndex = -1;
231
+
232
+ epResetHistory();
233
+ epShowStage(true);
234
+ epUpdateZoomLabel();
235
+ epUpdateUndoRedo();
236
+ await epRenderPage();
237
+ await epRenderThumbs();
238
+ epRenderInspector();
239
+ epRenderLayers();
240
+ showToast('PDF dimuat. Pilih alat anotasi untuk mulai.');
241
+ } catch (err) {
242
+ console.error(err);
243
+ showToast('Gagal membaca PDF: ' + err.message, false);
244
+ }
245
+ }
246
+
247
+ // ============================================================
248
+ // HISTORY
249
+ // ============================================================
250
+ function epSnapshot() { return JSON.stringify(editPdfState.annotations); }
251
+ function epResetHistory() {
252
+ editPdfState.history = [epSnapshot()];
253
+ editPdfState.historyIndex = 0;
254
+ epUpdateUndoRedo();
255
+ }
256
+ let epHistTimer = null;
257
+ function epMarkDirty() {
258
+ editPdfState.dirty = true;
259
+ clearTimeout(epHistTimer);
260
+ epHistTimer = setTimeout(() => epPushHistory(), 350);
261
+ }
262
+ function epPushHistory() {
263
+ clearTimeout(epHistTimer);
264
+ const snap = epSnapshot();
265
+ if (editPdfState.history[editPdfState.historyIndex] === snap) return;
266
+ editPdfState.history.splice(editPdfState.historyIndex + 1);
267
+ editPdfState.history.push(snap);
268
+ if (editPdfState.history.length > 50) editPdfState.history.shift();
269
+ editPdfState.historyIndex = editPdfState.history.length - 1;
270
+ editPdfState.dirty = true;
271
+ epUpdateUndoRedo();
272
+ }
273
+ function epUpdateUndoRedo() {
274
+ const u = epEl('edit-undo'), r = epEl('edit-redo');
275
+ if (u) u.disabled = editPdfState.historyIndex <= 0;
276
+ if (r) r.disabled = editPdfState.historyIndex >= editPdfState.history.length - 1;
277
+ }
278
+ function editPdfUndo() {
279
+ if (editPdfState.historyIndex <= 0) return;
280
+ epCommitInlineText();
281
+ editPdfState.historyIndex--;
282
+ editPdfState.annotations = JSON.parse(editPdfState.history[editPdfState.historyIndex]);
283
+ editPdfState.selectedId = null;
284
+ epUpdateUndoRedo();
285
+ epRedrawOverlay();
286
+ epRenderInspector();
287
+ epRenderLayers();
288
+ epUpdateThumbCounts();
289
+ epMarkDirty();
290
+ }
291
+ function editPdfRedo() {
292
+ if (editPdfState.historyIndex >= editPdfState.history.length - 1) return;
293
+ epCommitInlineText();
294
+ editPdfState.historyIndex++;
295
+ editPdfState.annotations = JSON.parse(editPdfState.history[editPdfState.historyIndex]);
296
+ editPdfState.selectedId = null;
297
+ epUpdateUndoRedo();
298
+ epRedrawOverlay();
299
+ epRenderInspector();
300
+ epRenderLayers();
301
+ epUpdateThumbCounts();
302
+ epMarkDirty();
303
+ }
304
+
305
+ // ============================================================
306
+ // RENDER PAGE
307
+ // ============================================================
308
+ async function epRenderPage() {
309
+ const doc = editPdfState.pdfDoc;
310
+ if (!doc) return;
311
+ const page = await doc.getPage(editPdfState.currentPage);
312
+ const vp1 = page.getViewport({ scale: 1 });
313
+ editPdfState.pageInfo[editPdfState.currentPage] = { w: vp1.width, h: vp1.height, rotation: page.rotate || 0 };
314
+
315
+ const zoom = editPdfState.zoom;
316
+ const vp = page.getViewport({ scale: zoom });
317
+ const dpr = window.devicePixelRatio || 1;
318
+ const c = epEl('edit-pdf-canvas');
319
+ c.width = Math.floor(vp.width * dpr);
320
+ c.height = Math.floor(vp.height * dpr);
321
+ c.style.width = Math.round(vp.width) + 'px';
322
+ c.style.height = Math.round(vp.height) + 'px';
323
+ const ctx = c.getContext('2d');
324
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
325
+ ctx.clearRect(0, 0, vp.width, vp.height);
326
+ await page.render({ canvasContext: ctx, viewport: vp }).promise;
327
+
328
+ const o = epEl('edit-annot-canvas');
329
+ o.width = c.width; o.height = c.height;
330
+ o.style.width = c.style.width; o.style.height = c.style.height;
331
+ editPdfState.viewW = vp.width;
332
+ editPdfState.viewH = vp.height;
333
+
334
+ const wrap = epEl('edit-stage-wrap');
335
+ wrap.style.width = c.style.width;
336
+ wrap.style.height = c.style.height;
337
+
338
+ epRedrawOverlay();
339
+ epUpdatePager();
340
+ }
341
+
342
+ function epUpdatePager() {
343
+ const p = editPdfState.currentPage, n = editPdfState.pageCount || 1;
344
+ const label = epEl('edit-pager-label');
345
+ if (label) label.textContent = `Hal ${p} / ${n}`;
346
+ const prev = epEl('edit-prev'), next = epEl('edit-next');
347
+ if (prev) prev.disabled = p <= 1;
348
+ if (next) next.disabled = p >= n;
349
+ epUpdateZoomLabel();
350
+ }
351
+
352
+ function epUpdateZoomLabel() {
353
+ const z = epEl('edit-zoom-label');
354
+ if (z) z.textContent = Math.round(editPdfState.zoom * 100) + '%';
355
+ }
356
+
357
+ function editPdfPage(delta) {
358
+ const n = editPdfState.pageCount;
359
+ if (!n) return;
360
+ const p = epClamp(editPdfState.currentPage + delta, 1, n);
361
+ if (p === editPdfState.currentPage) return;
362
+ epCommitInlineText();
363
+ editPdfState.currentPage = p;
364
+ editPdfState.selectedId = null;
365
+ epUpdateThumbsActive();
366
+ epRenderPage();
367
+ epRenderInspector();
368
+ epRenderLayers();
369
+ }
370
+ function editPdfGoto(p) {
371
+ if (!editPdfState.pdfDoc) return;
372
+ epCommitInlineText();
373
+ editPdfState.currentPage = epClamp(p, 1, editPdfState.pageCount);
374
+ editPdfState.selectedId = null;
375
+ epUpdateThumbsActive();
376
+ epRenderPage();
377
+ epRenderInspector();
378
+ epRenderLayers();
379
+ }
380
+ function epUpdateThumbsActive() {
381
+ document.querySelectorAll('#edit-thumbs .edit-thumb').forEach(el => {
382
+ el.classList.toggle('active', Number(el.dataset.page) === editPdfState.currentPage);
383
+ });
384
+ }
385
+
386
+ function editPdfZoom(delta) {
387
+ if (!editPdfState.pdfDoc) return;
388
+ editPdfState.zoom = epClamp(Math.round((editPdfState.zoom + delta) * 10) / 10, 0.4, 2.5);
389
+ epUpdateZoomLabel();
390
+ epRenderPage();
391
+ }
392
+ function editPdfFit() {
393
+ if (!editPdfState.pdfDoc) return;
394
+ const info = epPageInfo();
395
+ const stage = epEl('edit-stage');
396
+ const avail = Math.max(200, (stage ? stage.clientWidth : 800) - 70);
397
+ editPdfState.zoom = epClamp(avail / info.w, 0.4, 2.5);
398
+ epUpdateZoomLabel();
399
+ epRenderPage();
400
+ }
401
+
402
+ // ============================================================
403
+ // THUMBNAILS
404
+ // ============================================================
405
+ async function epRenderThumbs() {
406
+ const wrap = epEl('edit-thumbs');
407
+ if (!wrap) return;
408
+ wrap.innerHTML = '';
409
+ const doc = editPdfState.pdfDoc;
410
+ if (!doc) return;
411
+ const cnt = epEl('edit-page-count');
412
+ if (cnt) cnt.textContent = editPdfState.pageCount + ' hal';
413
+
414
+ for (let i = 1; i <= editPdfState.pageCount; i++) {
415
+ const btn = document.createElement('button');
416
+ btn.type = 'button';
417
+ btn.className = 'edit-thumb' + (i === editPdfState.currentPage ? ' active' : '');
418
+ btn.dataset.page = i;
419
+ btn.onclick = () => editPdfGoto(i);
420
+ const canvas = document.createElement('canvas');
421
+ const label = document.createElement('div');
422
+ label.className = 'edit-thumb-label';
423
+ label.innerHTML = `<span>Hal ${i}</span><span class="edit-count" data-count="${i}"></span>`;
424
+ btn.appendChild(canvas);
425
+ btn.appendChild(label);
426
+ wrap.appendChild(btn);
427
+ try {
428
+ const page = await doc.getPage(i);
429
+ const vp1 = page.getViewport({ scale: 1 });
430
+ const scale = 138 / vp1.width;
431
+ const vp = page.getViewport({ scale });
432
+ canvas.width = Math.floor(vp.width);
433
+ canvas.height = Math.floor(vp.height);
434
+ await page.render({ canvasContext: canvas.getContext('2d'), viewport: vp }).promise;
435
+ } catch (e) { /* ignore thumb error */ }
436
+ }
437
+ epUpdateThumbCounts();
438
+ }
439
+ function epUpdateThumbCounts() {
440
+ const counts = {};
441
+ editPdfState.annotations.forEach(a => { counts[a.page] = (counts[a.page] || 0) + 1; });
442
+ document.querySelectorAll('#edit-thumbs [data-count]').forEach(el => {
443
+ const n = counts[el.dataset.count] || 0;
444
+ el.textContent = n ? `${n} edit` : '';
445
+ });
446
+ }
447
+
448
+ // ============================================================
449
+ // DRAWING (preview + export composite)
450
+ // ============================================================
451
+ function epDrawAnnotation(ctx, a, W, H, preview, info) {
452
+ info = info || epPageInfo();
453
+ const scale = W / (info.w || W || 1);
454
+ const x = a.x * W, y = a.y * H, w = a.w * W, h = a.h * H;
455
+
456
+ if (a.type === 'highlight') {
457
+ ctx.save();
458
+ ctx.globalAlpha = a.opacity != null ? a.opacity : 0.5;
459
+ ctx.fillStyle = a.color || '#FDE047';
460
+ ctx.fillRect(x, y, w, h);
461
+ ctx.restore();
462
+ return;
463
+ }
464
+
465
+ if (a.type === 'redact') {
466
+ ctx.save();
467
+ ctx.fillStyle = '#0F172A';
468
+ ctx.fillRect(x, y, w, h);
469
+ if (preview) {
470
+ ctx.strokeStyle = '#F43F5E';
471
+ ctx.lineWidth = 1.5;
472
+ ctx.setLineDash([5, 4]);
473
+ ctx.strokeRect(x + 0.75, y + 0.75, Math.max(0, w - 1.5), Math.max(0, h - 1.5));
474
+ ctx.setLineDash([]);
475
+ ctx.fillStyle = 'rgba(255,255,255,0.9)';
476
+ ctx.font = '600 9px Inter, Arial, sans-serif';
477
+ ctx.textBaseline = 'middle';
478
+ ctx.fillText('SENSOR', x + 5, y + h / 2);
479
+ }
480
+ ctx.restore();
481
+ return;
482
+ }
483
+
484
+ if (a.type === 'text') {
485
+ const fontPx = Math.max(4, (a.fontSize || 13) * scale);
486
+ const padX = Math.max(1, fontPx * 0.12);
487
+ const padY = Math.max(1, fontPx * 0.1);
488
+ if (a.whiteout) {
489
+ ctx.save();
490
+ ctx.fillStyle = '#FFFFFF';
491
+ ctx.fillRect(x, y, w, h);
492
+ ctx.restore();
493
+ }
494
+ ctx.save();
495
+ ctx.beginPath();
496
+ ctx.rect(x, y, w, h);
497
+ ctx.clip();
498
+ ctx.fillStyle = a.color || '#1E1B4B';
499
+ ctx.textBaseline = 'top';
500
+ ctx.textAlign = 'left';
501
+ ctx.font = `${a.italic ? 'italic ' : ''}${a.bold ? '600' : '400'} ${fontPx}px Helvetica, Arial, sans-serif`;
502
+ const lines = wrapLines(ctx, a.text || '', Math.max(10, w - padX * 2));
503
+ const lh = fontPx * 1.25;
504
+ lines.forEach((ln, i) => {
505
+ ctx.fillText(ln, x + padX, y + padY + i * lh);
506
+ });
507
+ ctx.restore();
508
+ return;
509
+ }
510
+
511
+ if (a.type === 'draw') {
512
+ if (!a.points || !a.points.length) return;
513
+ ctx.save();
514
+ ctx.strokeStyle = a.color || '#2563EB';
515
+ ctx.lineWidth = Math.max(1, (a.strokeWidth || 2.5) * scale * 0.75);
516
+ ctx.lineCap = 'round';
517
+ ctx.lineJoin = 'round';
518
+ ctx.beginPath();
519
+ a.points.forEach((p, i) => {
520
+ const px = p.x * W, py = p.y * H;
521
+ if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
522
+ });
523
+ ctx.stroke();
524
+ ctx.restore();
525
+ return;
526
+ }
527
+
528
+ if (a.type === 'shape') {
529
+ const sw = Math.max(1, (a.strokeWidth || 2.5) * scale * 0.75);
530
+ ctx.save();
531
+ ctx.strokeStyle = a.strokeColor || '#2563EB';
532
+ ctx.lineWidth = sw;
533
+ ctx.lineCap = 'round';
534
+ ctx.lineJoin = 'round';
535
+ if (a.shapeType === 'line' || a.shapeType === 'arrow') {
536
+ const x1 = a.x * W, y1 = a.y * H, x2 = (a.x + a.w) * W, y2 = (a.y + a.h) * H;
537
+ ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
538
+ if (a.shapeType === 'arrow') {
539
+ const ang = Math.atan2(y2 - y1, x2 - x1);
540
+ const len = Math.max(8, sw * 3.2);
541
+ ctx.beginPath();
542
+ ctx.moveTo(x2, y2);
543
+ ctx.lineTo(x2 - len * Math.cos(ang - Math.PI / 6), y2 - len * Math.sin(ang - Math.PI / 6));
544
+ ctx.moveTo(x2, y2);
545
+ ctx.lineTo(x2 - len * Math.cos(ang + Math.PI / 6), y2 - len * Math.sin(ang + Math.PI / 6));
546
+ ctx.stroke();
547
+ }
548
+ } else {
549
+ if (a.fillColor && a.fillColor !== 'transparent') {
550
+ ctx.fillStyle = a.fillColor;
551
+ ctx.fillRect(x, y, w, h);
552
+ }
553
+ ctx.strokeRect(x + sw / 2, y + sw / 2, Math.max(0, w - sw), Math.max(0, h - sw));
554
+ }
555
+ ctx.restore();
556
+ return;
557
+ }
558
+
559
+ if (a.type === 'image') {
560
+ const img = editPdfState.imgCache[a.dataUrl];
561
+ if (img && img.complete && img.naturalWidth) {
562
+ try { ctx.drawImage(img, x, y, w, h); } catch (e) { /* ignore */ }
563
+ } else {
564
+ ctx.save();
565
+ ctx.fillStyle = 'rgba(99,102,241,0.12)';
566
+ ctx.fillRect(x, y, w, h);
567
+ ctx.strokeStyle = '#6366F1';
568
+ ctx.setLineDash([4, 3]);
569
+ ctx.strokeRect(x, y, w, h);
570
+ ctx.restore();
571
+ }
572
+ return;
573
+ }
574
+
575
+ if (a.type === 'stamp') {
576
+ epDrawStamp(ctx, a, x, y, w, h, scale);
577
+ return;
578
+ }
579
+ }
580
+
581
+ function epDrawStamp(ctx, a, x, y, w, h, scale) {
582
+ const colors = EDIT_STAMP_PRESETS[a.presetText] || { color: '#059669', bg: '#ECFDF5' };
583
+ const color = a.color || colors.color;
584
+ const bg = a.bgColor || colors.bg;
585
+ ctx.save();
586
+ ctx.translate(x + w / 2, y + h / 2);
587
+ ctx.rotate(-6 * Math.PI / 180);
588
+ const bw = w, bh = h;
589
+ ctx.fillStyle = bg;
590
+ ctx.fillRect(-bw / 2, -bh / 2, bw, bh);
591
+ ctx.strokeStyle = color;
592
+ ctx.lineWidth = Math.max(1.5, Math.min(bw, bh) * 0.045);
593
+ ctx.strokeRect(-bw / 2 + 2, -bh / 2 + 2, bw - 4, bh - 4);
594
+ ctx.fillStyle = color;
595
+ ctx.textAlign = 'center';
596
+ ctx.textBaseline = 'middle';
597
+ const fs = Math.max(8, Math.min(bh * 0.42, bw * 0.16));
598
+ ctx.font = `800 ${fs}px Helvetica, Arial, sans-serif`;
599
+ ctx.fillText(a.presetText || 'STEMPEL', 0, -fs * 0.28);
600
+ if (a.subText) {
601
+ ctx.font = `500 ${Math.max(6, fs * 0.42)}px Helvetica, Arial, sans-serif`;
602
+ ctx.fillText(a.subText, 0, fs * 0.62);
603
+ }
604
+ ctx.restore();
605
+ }
606
+
607
+ function epRedrawOverlay() {
608
+ const o = epEl('edit-annot-canvas');
609
+ if (!o) return;
610
+ const dpr = window.devicePixelRatio || 1;
611
+ const W = editPdfState.viewW || (o.width / dpr) || 1;
612
+ const H = editPdfState.viewH || (o.height / dpr) || 1;
613
+ const ctx = o.getContext('2d');
614
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
615
+ ctx.clearRect(0, 0, W, H);
616
+ const info = epPageInfo();
617
+
618
+ editPdfState.annotations
619
+ .filter(a => a.page === editPdfState.currentPage && !a.hidden)
620
+ .forEach(a => epDrawAnnotation(ctx, a, W, H, true, info));
621
+
622
+ const sel = epGetSelected();
623
+ if (sel && sel.page === editPdfState.currentPage && !sel.hidden) {
624
+ const b = epAnnBBox(sel);
625
+ const x = b.x * W, y = b.y * H, w = b.w * W, h = b.h * H;
626
+ ctx.save();
627
+ ctx.strokeStyle = '#4F46E5';
628
+ ctx.lineWidth = 1.5;
629
+ ctx.setLineDash([4, 3]);
630
+ ctx.strokeRect(x, y, w, h);
631
+ ctx.setLineDash([]);
632
+ if (sel.type !== 'draw' && !(sel.type === 'shape' && (sel.shapeType === 'line' || sel.shapeType === 'arrow'))) {
633
+ const hs = 7;
634
+ [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].forEach(([hx, hy]) => {
635
+ ctx.fillStyle = '#fff';
636
+ ctx.fillRect(hx - hs / 2, hy - hs / 2, hs, hs);
637
+ ctx.strokeStyle = '#4F46E5';
638
+ ctx.strokeRect(hx - hs / 2, hy - hs / 2, hs, hs);
639
+ });
640
+ }
641
+ ctx.restore();
642
+ }
643
+ }
644
+
645
+ // ============================================================
646
+ // POINTER INTERACTION
647
+ // ============================================================
648
+ const epDrag = { mode: null, startX: 0, startY: 0, ann: null, handle: null, startAnn: null };
649
+
650
+ function epEventPoint(e) {
651
+ const o = epEl('edit-annot-canvas');
652
+ const r = o.getBoundingClientRect();
653
+ const W = editPdfState.viewW || r.width || 1;
654
+ const H = editPdfState.viewH || r.height || 1;
655
+ return {
656
+ x: (e.clientX - r.left) * (W / (r.width || W)),
657
+ y: (e.clientY - r.top) * (H / (r.height || H)),
658
+ nx: (e.clientX - r.left) / (r.width || W),
659
+ ny: (e.clientY - r.top) / (r.height || H),
660
+ };
661
+ }
662
+
663
+ function epHandleHit(mx, my) {
664
+ const sel = epGetSelected();
665
+ if (!sel) return null;
666
+ const b = epAnnBBox(sel);
667
+ const hs = 10;
668
+ const pts = {
669
+ nw: [b.x * editPdfState.viewW, b.y * editPdfState.viewH],
670
+ ne: [(b.x + b.w) * editPdfState.viewW, b.y * editPdfState.viewH],
671
+ sw: [b.x * editPdfState.viewW, (b.y + b.h) * editPdfState.viewH],
672
+ se: [(b.x + b.w) * editPdfState.viewW, (b.y + b.h) * editPdfState.viewH],
673
+ };
674
+ for (const k of Object.keys(pts)) {
675
+ if (Math.abs(mx - pts[k][0]) <= hs && Math.abs(my - pts[k][1]) <= hs) return k;
676
+ }
677
+ return null;
678
+ }
679
+
680
+ function epHitTest(nx, ny) {
681
+ const list = editPdfState.annotations.filter(a => a.page === editPdfState.currentPage && !a.hidden);
682
+ for (let i = list.length - 1; i >= 0; i--) {
683
+ const b = epAnnBBox(list[i]);
684
+ if (nx >= b.x && nx <= b.x + b.w && ny >= b.y && ny <= b.y + b.h) return list[i];
685
+ }
686
+ return null;
687
+ }
688
+
689
+ function epOnPointerDown(e) {
690
+ if (!editPdfState.pdfDoc) return;
691
+ if (epEl('edit-text-inline') && !epEl('edit-text-inline').classList.contains('hidden')) return;
692
+ const p = epEventPoint(e);
693
+ const tool = editPdfState.activeTool;
694
+ e.preventDefault();
695
+ try { epEl('edit-annot-canvas').setPointerCapture?.(e.pointerId); } catch (_) {}
696
+
697
+ if (tool === 'select') {
698
+ const handle = epHandleHit(p.x, p.y);
699
+ if (handle) {
700
+ const sel = epGetSelected();
701
+ epDrag.mode = 'resize';
702
+ epDrag.handle = handle;
703
+ epDrag.startAnn = JSON.parse(JSON.stringify(sel));
704
+ epDrag.startX = p.nx; epDrag.startY = p.ny;
705
+ return;
706
+ }
707
+ const hit = epHitTest(p.nx, p.ny);
708
+ if (hit) {
709
+ editPdfState.selectedId = hit.id;
710
+ epDrag.mode = 'move';
711
+ epDrag.ann = hit;
712
+ epDrag.startAnn = JSON.parse(JSON.stringify(hit));
713
+ epDrag.startX = p.nx; epDrag.startY = p.ny;
714
+ epRenderInspector();
715
+ epRenderLayers();
716
+ epRedrawOverlay();
717
+ } else {
718
+ editPdfState.selectedId = null;
719
+ epRenderInspector();
720
+ epRenderLayers();
721
+ epRedrawOverlay();
722
+ }
723
+ return;
724
+ }
725
+
726
+ if (tool === 'image') { editPdfPickImage(); return; }
727
+ if (tool === 'stamp') { showToast('Pilih preset stempel di panel kanan.', false); return; }
728
+
729
+ const base = {
730
+ id: epUid(), page: editPdfState.currentPage, x: p.nx, y: p.ny, w: 0, h: 0,
731
+ rotation: 0, opacity: 1, hidden: false,
732
+ };
733
+
734
+ if (tool === 'text') {
735
+ const a = Object.assign(base, {
736
+ type: 'text', w: 0.34, h: 0.055,
737
+ text: 'Teks baru', fontFamily: editPdfState.defaults.fontFamily,
738
+ fontSize: editPdfState.defaults.fontSize, bold: editPdfState.defaults.bold,
739
+ italic: editPdfState.defaults.italic, align: editPdfState.defaults.align,
740
+ color: editPdfState.defaults.color, whiteout: editPdfState.defaults.whiteout,
741
+ });
742
+ if (a.x + a.w > 1) a.x = Math.max(0, 1 - a.w);
743
+ if (a.y + a.h > 1) a.y = Math.max(0, 1 - a.h);
744
+ editPdfState.annotations.push(a);
745
+ editPdfState.selectedId = a.id;
746
+ editPdfState.activeTool = 'select';
747
+ epUpdateToolbar();
748
+ epMarkDirty();
749
+ epRedrawOverlay();
750
+ epRenderLayers();
751
+ epStartInlineEdit(a);
752
+ return;
753
+ }
754
+
755
+ if (tool === 'draw') {
756
+ const a = Object.assign(base, {
757
+ type: 'draw', points: [{ x: p.nx, y: p.ny }],
758
+ color: editPdfState.defaults.strokeColor,
759
+ strokeWidth: editPdfState.defaults.strokeWidth,
760
+ });
761
+ editPdfState.annotations.push(a);
762
+ editPdfState.selectedId = a.id;
763
+ epDrag.mode = 'draw';
764
+ epDrag.ann = a;
765
+ epRedrawOverlay();
766
+ return;
767
+ }
768
+
769
+ if (tool === 'highlight' || tool === 'redact' || tool === 'shape') {
770
+ const a = Object.assign(base, {});
771
+ if (tool === 'highlight') {
772
+ a.type = 'highlight';
773
+ a.color = editPdfState.defaults.highlightColor;
774
+ a.opacity = editPdfState.defaults.highlightOpacity;
775
+ } else if (tool === 'redact') {
776
+ a.type = 'redact'; a.label = 'SENSOR';
777
+ } else {
778
+ a.type = 'shape';
779
+ a.shapeType = editPdfState.defaults.shapeType;
780
+ a.strokeColor = editPdfState.defaults.strokeColor;
781
+ a.strokeWidth = editPdfState.defaults.strokeWidth;
782
+ a.fillColor = editPdfState.defaults.shapeFill;
783
+ }
784
+ editPdfState.annotations.push(a);
785
+ editPdfState.selectedId = a.id;
786
+ epDrag.mode = 'create';
787
+ epDrag.ann = a;
788
+ epDrag.startX = p.nx; epDrag.startY = p.ny;
789
+ epRedrawOverlay();
790
+ return;
791
+ }
792
+ }
793
+
794
+ function epOnPointerMove(e) {
795
+ if (!epDrag.mode) return;
796
+ const p = epEventPoint(e);
797
+ const a = epDrag.ann;
798
+
799
+ if (epDrag.mode === 'draw' && a) {
800
+ const last = a.points[a.points.length - 1];
801
+ const dx = (p.nx - last.x) * editPdfState.viewW;
802
+ const dy = (p.ny - last.y) * editPdfState.viewH;
803
+ if (Math.hypot(dx, dy) > 2) a.points.push({ x: p.nx, y: p.ny });
804
+ epRedrawOverlay();
805
+ return;
806
+ }
807
+
808
+ if (epDrag.mode === 'create' && a) {
809
+ a.x = epDrag.startX; a.y = epDrag.startY;
810
+ a.w = p.nx - epDrag.startX;
811
+ a.h = p.ny - epDrag.startY;
812
+ epRedrawOverlay();
813
+ return;
814
+ }
815
+
816
+ if (epDrag.mode === 'move' && a && epDrag.startAnn) {
817
+ const dx = p.nx - epDrag.startX, dy = p.ny - epDrag.startY;
818
+ a.x = epDrag.startAnn.x + dx;
819
+ a.y = epDrag.startAnn.y + dy;
820
+ if (a.type === 'draw' && epDrag.startAnn.points) {
821
+ a.points = epDrag.startAnn.points.map(pt => ({ x: pt.x + dx, y: pt.y + dy }));
822
+ }
823
+ epRedrawOverlay();
824
+ return;
825
+ }
826
+
827
+ if (epDrag.mode === 'resize' && a && epDrag.startAnn) {
828
+ const s = epDrag.startAnn;
829
+ const dx = p.nx - epDrag.startX, dy = p.ny - epDrag.startY;
830
+ let x1 = s.x, y1 = s.y, x2 = s.x + s.w, y2 = s.y + s.h;
831
+ if (epDrag.handle.includes('w')) x1 = s.x + dx;
832
+ if (epDrag.handle.includes('e')) x2 = s.x + s.w + dx;
833
+ if (epDrag.handle.includes('n')) y1 = s.y + dy;
834
+ if (epDrag.handle.includes('s')) y2 = s.y + s.h + dy;
835
+ a.x = Math.min(x1, x2); a.y = Math.min(y1, y2);
836
+ a.w = Math.abs(x2 - x1); a.h = Math.abs(y2 - y1);
837
+ epRedrawOverlay();
838
+ }
839
+ }
840
+
841
+ function epOnPointerUp() {
842
+ if (!epDrag.mode) return;
843
+ const mode = epDrag.mode;
844
+ const a = epDrag.ann;
845
+ if (a) {
846
+ if (mode === 'create') {
847
+ if (a.type === 'highlight' || a.type === 'redact' || (a.type === 'shape' && a.shapeType === 'rect')) {
848
+ if (a.w < 0) { a.x += a.w; a.w = -a.w; }
849
+ if (a.h < 0) { a.y += a.h; a.h = -a.h; }
850
+ if (a.w < 0.012 || a.h < 0.006) { a.w = Math.max(a.w, 0.15); a.h = Math.max(a.h, 0.05); }
851
+ }
852
+ }
853
+ if (a.type === 'draw') {
854
+ const xs = a.points.map(p => p.x), ys = a.points.map(p => p.y);
855
+ const x = Math.min(...xs), y = Math.min(...ys);
856
+ a.x = x; a.y = y;
857
+ a.w = Math.max(0.001, Math.max(...xs) - x);
858
+ a.h = Math.max(0.001, Math.max(...ys) - y);
859
+ }
860
+ // clamp to page
861
+ a.x = epClamp(a.x, 0, 1);
862
+ a.y = epClamp(a.y, 0, 1);
863
+ a.w = Math.min(a.w, 1 - a.x);
864
+ a.h = Math.min(a.h, 1 - a.y);
865
+ }
866
+ epDrag.mode = null; epDrag.ann = null; epDrag.handle = null; epDrag.startAnn = null;
867
+ epPushHistory();
868
+ epRedrawOverlay();
869
+ epRenderLayers();
870
+ epUpdateThumbCounts();
871
+ epRenderInspector();
872
+ }
873
+
874
+ function epOnDoubleClick(e) {
875
+ const p = epEventPoint(e);
876
+ const hit = epHitTest(p.nx, p.ny);
877
+ if (hit && hit.type === 'text') {
878
+ editPdfState.selectedId = hit.id;
879
+ editPdfState.activeTool = 'select';
880
+ epUpdateToolbar();
881
+ epStartInlineEdit(hit);
882
+ }
883
+ }
884
+
885
+ // ============================================================
886
+ // INLINE TEXT EDIT
887
+ // ============================================================
888
+ let epEditingId = null;
889
+
890
+ function epStartInlineEdit(a) {
891
+ const ta = epEl('edit-text-inline');
892
+ const info = epPageInfo();
893
+ const { W, H } = epViewSize();
894
+ const scale = W / (info.w || W || 1);
895
+ ta.dataset.annId = a.id;
896
+ ta.value = a.text || '';
897
+ ta.style.left = (a.x * W) + 'px';
898
+ ta.style.top = (a.y * H) + 'px';
899
+ ta.style.width = Math.max(70, a.w * W) + 'px';
900
+ ta.style.height = Math.max(26, a.h * H) + 'px';
901
+ ta.style.fontSize = Math.max(8, a.fontSize * scale) + 'px';
902
+ ta.style.fontWeight = a.bold ? '600' : '400';
903
+ ta.style.fontStyle = a.italic ? 'italic' : 'normal';
904
+ ta.style.color = a.color || '#1E1B4B';
905
+ ta.style.textAlign = a.align || 'left';
906
+ ta.classList.remove('hidden');
907
+ epEditingId = a.id;
908
+ setTimeout(() => { ta.focus(); ta.select(); }, 0);
909
+ }
910
+
911
+ function epCommitInlineText() {
912
+ const ta = epEl('edit-text-inline');
913
+ if (!ta || ta.classList.contains('hidden')) return;
914
+ const id = epEditingId || ta.dataset.annId;
915
+ const a = editPdfState.annotations.find(x => x.id === id);
916
+ ta.classList.add('hidden');
917
+ epEditingId = null;
918
+ if (!a) return;
919
+ const val = ta.value;
920
+ if (!val.trim()) {
921
+ editPdfState.annotations = editPdfState.annotations.filter(x => x.id !== id);
922
+ editPdfState.selectedId = null;
923
+ } else {
924
+ a.text = val;
925
+ epAutoSizeText(a);
926
+ }
927
+ editPdfState.dirty = true;
928
+ epPushHistory();
929
+ epRedrawOverlay();
930
+ epRenderLayers();
931
+ epRenderInspector();
932
+ epUpdateThumbCounts();
933
+ }
934
+
935
+ function epAutoSizeText(a) {
936
+ const info = epPageInfo();
937
+ const { W, H } = epViewSize();
938
+ if (!W || !H) return;
939
+ const scale = W / (info.w || W);
940
+ const fontPx = Math.max(4, a.fontSize * scale);
941
+ const c = epEl('edit-annot-canvas');
942
+ const ctx = c.getContext('2d');
943
+ ctx.font = `${a.italic ? 'italic ' : ''}${a.bold ? '600' : '400'} ${fontPx}px Helvetica, Arial, sans-serif`;
944
+ const lines = wrapLines(ctx, a.text || '', Math.max(10, a.w * W - fontPx * 0.24));
945
+ a.h = epClamp((lines.length * fontPx * 1.25 + fontPx * 0.4) / H, 0.02, 0.6);
946
+ }
947
+
948
+ // ============================================================
949
+ // TOOLBAR / TOOLS
950
+ // ============================================================
951
+ const EP_TOOL_TITLES = {
952
+ select: 'Pilih & Geser', text: 'Tambah Teks', highlight: 'Stabilo',
953
+ draw: 'Coret Bebas', shape: 'Bentuk', redact: 'Sensor Data',
954
+ image: 'Sisip Gambar', stamp: 'Stempel Kantor',
955
+ };
956
+
957
+ function epUpdateToolbar() {
958
+ document.querySelectorAll('#edit-toolbar .edit-tool').forEach(b => {
959
+ b.classList.toggle('active', b.dataset.tool === editPdfState.activeTool);
960
+ });
961
+ const wrap = epEl('edit-stage-wrap');
962
+ if (wrap) wrap.className = 'edit-stage-wrap tool-' + editPdfState.activeTool;
963
+ }
964
+
965
+ function editPdfSetTool(tool, silent) {
966
+ if (!tool) return;
967
+ editPdfState.activeTool = tool;
968
+ if (tool !== 'select') editPdfState.selectedId = null;
969
+ if (tool === 'image') {
970
+ epUpdateToolbar();
971
+ epRenderInspector();
972
+ return;
973
+ }
974
+ epUpdateToolbar();
975
+ epRenderInspector();
976
+ if (!silent) {
977
+ if (tool === 'stamp') showToast('Pilih preset stempel pada panel kanan.');
978
+ else if (tool === 'text') showToast('Klik pada halaman untuk menambah teks.');
979
+ }
980
+ }
981
+
982
+ // ============================================================
983
+ // INSPECTOR
984
+ // ============================================================
985
+ function epSwatches(key, colors, cur) {
986
+ const c0 = String(cur || '').toLowerCase();
987
+ return `<div class="edit-swatches">${colors.map(c =>
988
+ `<button type="button" class="edit-swatch${c.toLowerCase() === c0 ? ' active' : ''}" style="background:${c}" title="${c}" onclick="editPdfSetColor('${key}','${c}')"></button>`
989
+ ).join('')}</div>`;
990
+ }
991
+
992
+ function epRenderInspector() {
993
+ const panel = epEl('edit-props-panel');
994
+ if (!panel) return;
995
+ const sel = epGetSelected();
996
+ const type = sel ? sel.type : (editPdfState.activeTool === 'select' ? 'none' : editPdfState.activeTool);
997
+ const d = editPdfState.defaults;
998
+ let h = '';
999
+
1000
+ const title = sel ? epTypeLabel(sel) : (EP_TOOL_TITLES[editPdfState.activeTool] || 'Properti');
1001
+ h += `<div class="edit-sec-title">${sel ? 'Objek Terpilih' : title}</div>`;
1002
+
1003
+ if (sel) {
1004
+ h += `<div class="edit-row">
1005
+ <button class="edit-btn" style="flex:1" onclick="editPdfDuplicateSelected()">Duplikat</button>
1006
+ <button class="edit-btn" style="color:#E11D48;border-color:#FECDD3;background:#FFF1F2;" onclick="editPdfDeleteSelected()">Hapus</button>
1007
+ </div>`;
1008
+ }
1009
+ if (sel && sel.page !== editPdfState.currentPage) {
1010
+ h += `<div class="edit-note">Objek berada di halaman ${sel.page}. <button class="btn-ghost" onclick="editPdfGoto(${sel.page})">Buka halaman</button></div>`;
1011
+ }
1012
+
1013
+ if (type === 'none') {
1014
+ h += `<div class="edit-note">Pilih alat di toolbar untuk menambah anotasi, atau klik objek pada halaman untuk mengatur propertinya.</div>
1015
+ <div class="edit-note">Pintasan: <b>V</b> pilih · <b>T</b> teks · <b>H</b> stabilo · <b>D</b> coret · <b>R</b> bentuk · <b>X</b> sensor · <b>I</b> gambar · <b>S</b> stempel.</div>`;
1016
+ panel.innerHTML = h;
1017
+ return;
1018
+ }
1019
+
1020
+ if (type === 'text') {
1021
+ const cur = sel || d;
1022
+ if (sel) {
1023
+ h += `<div class="edit-field"><label>Teks</label>
1024
+ <textarea class="edit-input" rows="2" oninput="editPdfLiveText(this.value)" onchange="editPdfCommit()">${(cur.text || '').replace(/</g, '&lt;')}</textarea></div>`;
1025
+ }
1026
+ h += `<div class="edit-row">
1027
+ <div class="edit-field"><label>Font</label>
1028
+ <select class="edit-input" onchange="editPdfSetProp('fontFamily',this.value);editPdfCommit()">
1029
+ ${['Helvetica', 'TimesRoman', 'Courier'].map(f => `<option value="${f}"${cur.fontFamily === f ? ' selected' : ''}>${f}</option>`).join('')}
1030
+ </select>
1031
+ </div>
1032
+ <div class="edit-field" style="max-width:82px;"><label>Ukuran</label>
1033
+ <input type="number" class="edit-input" min="8" max="48" value="${cur.fontSize || 13}" oninput="editPdfSetProp('fontSize',this.value,1);editPdfCommit()">
1034
+ </div>
1035
+ </div>`;
1036
+ h += `<div class="edit-row">
1037
+ <button class="edit-btn" style="font-weight:800;${cur.bold ? 'border-color:#4F46E5;color:#4F46E5;' : ''}" onclick="editPdfToggleStyle('bold')">B</button>
1038
+ <button class="edit-btn" style="font-style:italic;${cur.italic ? 'border-color:#4F46E5;color:#4F46E5;' : ''}" onclick="editPdfToggleStyle('italic')">I</button>
1039
+ <div class="edit-seg" style="flex:1;">
1040
+ ${['left', 'center', 'right'].map(al => `<button class="${cur.align === al ? 'active' : ''}" onclick="editPdfSetProp('align','${al}');editPdfCommit()">${al === 'left' ? 'Kiri' : al === 'center' ? 'Tengah' : 'Kanan'}</button>`).join('')}
1041
+ </div>
1042
+ </div>`;
1043
+ h += `<div class="edit-field"><span class="lbl">Warna Teks</span>${epSwatches('color', EDIT_TEXT_COLORS, cur.color)}</div>`;
1044
+ h += `<label class="edit-check"><input type="checkbox"${cur.whiteout ? ' checked' : ''} onchange="editPdfSetProp('whiteout', this.checked);editPdfCommit()"><span><b>Latar Putih (Whiteout)</b> — menutup teks lama di belakangnya.</span></label>`;
1045
+ }
1046
+
1047
+ if (type === 'highlight') {
1048
+ const cur = sel || d;
1049
+ h += `<div class="edit-field"><span class="lbl">Warna Stabilo</span>${epSwatches('highlightColor', EDIT_HIGHLIGHT_COLORS, cur.highlightColor)}</div>`;
1050
+ h += `<div class="edit-field"><label>Opasitas ${Math.round((cur.highlightOpacity || 0.5) * 100)}%</label>
1051
+ <input type="range" min="0.25" max="0.7" step="0.05" value="${cur.highlightOpacity || 0.5}" oninput="editPdfSetProp('highlightOpacity',this.value,1);editPdfCommit()"></div>`;
1052
+ }
1053
+
1054
+ if (type === 'redact') {
1055
+ h += `<div class="edit-warn">Area ini akan dicetak hitam pekat. Aktifkan <b>Flatten</b> saat export agar teks di bawahnya benar-benar hilang dan tidak bisa disalin.</div>`;
1056
+ if (!editPdfState.flattenOnExport) {
1057
+ h += `<div class="edit-warn">Flatten sedang NONAKTIF. Dokumen dengan sensor wajib di-flatten — sistem akan otomatis mem-flatten halaman sensor saat export.</div>`;
1058
+ }
1059
+ }
1060
+
1061
+ if (type === 'draw') {
1062
+ const cur = sel || d;
1063
+ h += `<div class="edit-field"><span class="lbl">Warna Coretan</span>${epSwatches('strokeColor', EDIT_STROKE_COLORS, cur.strokeColor)}</div>`;
1064
+ h += `<div class="edit-field"><label>Tebal ${cur.strokeWidth || 2.5}px</label>
1065
+ <input type="range" min="1" max="12" step="0.5" value="${cur.strokeWidth || 2.5}" oninput="editPdfSetProp('strokeWidth',this.value,1);editPdfCommit()"></div>`;
1066
+ }
1067
+
1068
+ if (type === 'shape') {
1069
+ const cur = sel || d;
1070
+ const st = cur.shapeType || 'rect';
1071
+ h += `<div class="edit-field"><span class="lbl">Jenis Bentuk</span>
1072
+ <div class="edit-seg">
1073
+ ${[['rect', 'Kotak'], ['line', 'Garis'], ['arrow', 'Panah']].map(([k, v]) => `<button class="${st === k ? 'active' : ''}" onclick="editPdfSetProp('shapeType','${k}');editPdfCommit()">${v}</button>`).join('')}
1074
+ </div></div>`;
1075
+ h += `<div class="edit-field"><span class="lbl">Warna Garis</span>${epSwatches('strokeColor', EDIT_STROKE_COLORS, cur.strokeColor)}</div>`;
1076
+ h += `<div class="edit-field"><label>Tebal ${cur.strokeWidth || 2.5}px</label>
1077
+ <input type="range" min="1" max="12" step="0.5" value="${cur.strokeWidth || 2.5}" oninput="editPdfSetProp('strokeWidth',this.value,1);editPdfCommit()"></div>`;
1078
+ if (st === 'rect') {
1079
+ h += `<div class="edit-field"><label>Warna Isi</label>
1080
+ <select class="edit-input" onchange="editPdfSetProp('shapeFill',this.value);editPdfCommit()">
1081
+ ${[['transparent', 'Tanpa isi'], ['#FFFFFF', 'Putih'], ['#F1F5F9', 'Abu muda'], ['#FEF3C7', 'Krem']].map(([v, l]) => `<option value="${v}"${cur.shapeFill === v ? ' selected' : ''}>${l}</option>`).join('')}
1082
+ </select></div>`;
1083
+ }
1084
+ }
1085
+
1086
+ if (type === 'image') {
1087
+ h += `<button class="edit-btn" style="width:100%;justify-content:center;" onclick="editPdfPickImage()">Pilih Gambar (PNG/JPG)</button>
1088
+ <div class="edit-note">Gambar disisipkan di tengah halaman dengan rasio aspek terjaga. Setelah itu pilih alat <b>Pilih</b> untuk menggeser.</div>`;
1089
+ }
1090
+
1091
+ if (type === 'stamp') {
1092
+ h += `<div class="edit-field"><span class="lbl">Preset Stempel</span>
1093
+ <div class="edit-stamp-grid">
1094
+ ${Object.keys(EDIT_STAMP_PRESETS).map(k => `<button class="edit-stamp-btn" style="color:${EDIT_STAMP_PRESETS[k].color};background:${EDIT_STAMP_PRESETS[k].bg};border-color:${EDIT_STAMP_PRESETS[k].color}33;" onclick="editPdfInsertStamp('${k}')">${k}</button>`).join('')}
1095
+ </div></div>
1096
+ <label class="edit-check"><input type="checkbox"${editPdfState.stampIncludeDate ? ' checked' : ''} onchange="editPdfState.stampIncludeDate=this.checked"><span>Sertakan tanggal hari ini.</span></label>
1097
+ <div class="edit-note">Stempel ditempatkan di tengah halaman. Geser & atur ukurannya dengan alat Pilih.</div>`;
1098
+ }
1099
+
1100
+ panel.innerHTML = h;
1101
+ }
1102
+
1103
+ function editPdfSetProp(key, val, numeric) {
1104
+ const sel = epGetSelected();
1105
+ const t = sel || editPdfState.defaults;
1106
+ t[key] = numeric ? Number(val) : val;
1107
+ if (sel) epMarkDirty();
1108
+ if (sel && sel.type === 'text') { /* autosize handled on commit */ }
1109
+ epRedrawOverlay();
1110
+ }
1111
+ function editPdfSetColor(key, val) {
1112
+ const sel = epGetSelected();
1113
+ (sel || editPdfState.defaults)[key] = val;
1114
+ if (sel) epMarkDirty();
1115
+ epRedrawOverlay();
1116
+ epRenderInspector();
1117
+ epPushHistory();
1118
+ }
1119
+ function editPdfToggleStyle(key) {
1120
+ const sel = epGetSelected();
1121
+ const t = sel || editPdfState.defaults;
1122
+ t[key] = !t[key];
1123
+ if (sel) {
1124
+ epAutoSizeText(sel);
1125
+ epMarkDirty();
1126
+ }
1127
+ epRedrawOverlay();
1128
+ epRenderInspector();
1129
+ epPushHistory();
1130
+ }
1131
+ function editPdfLiveText(v) {
1132
+ const a = epGetSelected();
1133
+ if (!a || a.type !== 'text') return;
1134
+ a.text = v;
1135
+ epMarkDirty();
1136
+ epRedrawOverlay();
1137
+ }
1138
+ function editPdfCommit() {
1139
+ const a = epGetSelected();
1140
+ if (a && a.type === 'text') epAutoSizeText(a);
1141
+ epPushHistory();
1142
+ epRedrawOverlay();
1143
+ epRenderLayers();
1144
+ epUpdateThumbCounts();
1145
+ }
1146
+ function editPdfDeleteSelected() {
1147
+ const a = epGetSelected();
1148
+ if (!a) return;
1149
+ editPdfState.annotations = editPdfState.annotations.filter(x => x.id !== a.id);
1150
+ editPdfState.selectedId = null;
1151
+ epPushHistory();
1152
+ epRedrawOverlay();
1153
+ epRenderInspector();
1154
+ epRenderLayers();
1155
+ epUpdateThumbCounts();
1156
+ showToast('Objek dihapus.');
1157
+ }
1158
+ function editPdfDuplicateSelected() {
1159
+ const a = epGetSelected();
1160
+ if (!a) return;
1161
+ const c = JSON.parse(JSON.stringify(a));
1162
+ c.id = epUid();
1163
+ c.x = epClamp(c.x + 0.02, 0, 1); c.y = epClamp(c.y + 0.02, 0, 1);
1164
+ editPdfState.annotations.push(c);
1165
+ editPdfState.selectedId = c.id;
1166
+ epPushHistory();
1167
+ epRedrawOverlay();
1168
+ epRenderInspector();
1169
+ epRenderLayers();
1170
+ epUpdateThumbCounts();
1171
+ }
1172
+
1173
+ // ============================================================
1174
+ // LAYERS
1175
+ // ============================================================
1176
+ function epRenderLayers() {
1177
+ const list = epEl('edit-layers-list');
1178
+ if (!list) return;
1179
+ const anns = editPdfState.annotations
1180
+ .filter(a => a.page === editPdfState.currentPage)
1181
+ .slice().reverse();
1182
+ if (!anns.length) {
1183
+ list.innerHTML = `<div class="edit-note">Belum ada anotasi di halaman ini.</div>`;
1184
+ return;
1185
+ }
1186
+ list.innerHTML = anns.map(a => `
1187
+ <div class="edit-layer${a.id === editPdfState.selectedId ? ' active' : ''}" onclick="editPdfSelectLayer('${a.id}')">
1188
+ <span class="ly-name" style="${a.hidden ? 'opacity:.45;text-decoration:line-through;' : ''}">${epTypeLabel(a).replace(/</g, '&lt;')}</span>
1189
+ <button class="ly-btn" title="${a.hidden ? 'Tampilkan' : 'Sembunyikan'}" onclick="event.stopPropagation();editPdfToggleHidden('${a.id}')">
1190
+ ${a.hidden
1191
+ ? '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3l18 18M10.6 10.6a2 2 0 002.8 2.8M9.9 5.2A9.8 9.8 0 0112 5c5 0 9 4.5 9 7a11 11 0 01-3 4M6.2 6.2C4.2 7.8 3 9.6 3 12c0 2.5 4 7 9 7a10 10 0 004.1-.9"/></svg>'
1192
+ : '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.6"/></svg>'}
1193
+ </button>
1194
+ <button class="ly-btn" title="Hapus" onclick="event.stopPropagation();editPdfDeleteLayer('${a.id}')">
1195
+ <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M6 7h12M9 7V5h6v2m-8 0l1 12h8l1-12"/></svg>
1196
+ </button>
1197
+ </div>`).join('');
1198
+ }
1199
+ function editPdfSelectLayer(id) {
1200
+ const a = editPdfState.annotations.find(x => x.id === id);
1201
+ if (!a) return;
1202
+ if (a.page !== editPdfState.currentPage) editPdfGoto(a.page);
1203
+ editPdfState.selectedId = id;
1204
+ if (editPdfState.activeTool !== 'select') editPdfSetTool('select');
1205
+ epRedrawOverlay();
1206
+ epRenderInspector();
1207
+ epRenderLayers();
1208
+ }
1209
+ function editPdfToggleHidden(id) {
1210
+ const a = editPdfState.annotations.find(x => x.id === id);
1211
+ if (!a) return;
1212
+ a.hidden = !a.hidden;
1213
+ epPushHistory();
1214
+ epRedrawOverlay();
1215
+ epRenderLayers();
1216
+ epUpdateThumbCounts();
1217
+ }
1218
+ function editPdfDeleteLayer(id) {
1219
+ editPdfState.annotations = editPdfState.annotations.filter(x => x.id !== id);
1220
+ if (editPdfState.selectedId === id) editPdfState.selectedId = null;
1221
+ epPushHistory();
1222
+ epRedrawOverlay();
1223
+ epRenderInspector();
1224
+ epRenderLayers();
1225
+ epUpdateThumbCounts();
1226
+ }
1227
+
1228
+ // ============================================================
1229
+ // IMAGE & STAMP
1230
+ // ============================================================
1231
+ let epImgInput = null;
1232
+ function editPdfPickImage() {
1233
+ if (!epImgInput) {
1234
+ epImgInput = document.createElement('input');
1235
+ epImgInput.type = 'file';
1236
+ epImgInput.accept = 'image/png,image/jpeg,image/webp';
1237
+ epImgInput.className = 'hidden';
1238
+ epImgInput.addEventListener('change', () => {
1239
+ const f = epImgInput.files[0];
1240
+ if (f) epInsertImageFile(f);
1241
+ epImgInput.value = '';
1242
+ });
1243
+ document.body.appendChild(epImgInput);
1244
+ }
1245
+ epImgInput.click();
1246
+ }
1247
+
1248
+ function epInsertImageFile(file) {
1249
+ if (!editPdfState.pdfDoc) return showToast('Muat PDF terlebih dahulu.', false);
1250
+ const reader = new FileReader();
1251
+ reader.onload = () => {
1252
+ const dataUrl = reader.result;
1253
+ const img = new Image();
1254
+ img.onload = () => {
1255
+ editPdfState.imgCache[dataUrl] = img;
1256
+ const info = epPageInfo();
1257
+ const wN = 0.32;
1258
+ const hN = epClamp((wN * info.w * (img.naturalHeight / (img.naturalWidth || 1))) / info.h, 0.03, 0.9);
1259
+ const a = {
1260
+ id: epUid(), page: editPdfState.currentPage, type: 'image',
1261
+ x: (1 - wN) / 2, y: (1 - hN) / 2, w: wN, h: hN,
1262
+ rotation: 0, opacity: 1, hidden: false, dataUrl,
1263
+ naturalW: img.naturalWidth, naturalH: img.naturalHeight,
1264
+ };
1265
+ editPdfState.annotations.push(a);
1266
+ editPdfState.selectedId = a.id;
1267
+ editPdfSetTool('select');
1268
+ epPushHistory();
1269
+ epRedrawOverlay();
1270
+ epRenderInspector();
1271
+ epRenderLayers();
1272
+ epUpdateThumbCounts();
1273
+ showToast('Gambar disisipkan.');
1274
+ };
1275
+ img.onerror = () => showToast('Gagal membaca gambar.', false);
1276
+ img.src = dataUrl;
1277
+ };
1278
+ reader.onerror = () => showToast('Gagal membaca berkas gambar.', false);
1279
+ reader.readAsDataURL(file);
1280
+ }
1281
+
1282
+ function editPdfInsertStamp(preset) {
1283
+ if (!editPdfState.pdfDoc) return showToast('Muat PDF terlebih dahulu.', false);
1284
+ const cfg = EDIT_STAMP_PRESETS[preset] || EDIT_STAMP_PRESETS.DISETUJUI;
1285
+ const d = new Date();
1286
+ const sub = editPdfState.stampIncludeDate
1287
+ ? d.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }).toUpperCase()
1288
+ : '';
1289
+ const a = {
1290
+ id: epUid(), page: editPdfState.currentPage, type: 'stamp',
1291
+ x: 0.35, y: 0.44, w: 0.3, h: 0.12, rotation: 0, opacity: 1, hidden: false,
1292
+ presetText: preset, subText: sub, color: cfg.color, bgColor: cfg.bg,
1293
+ };
1294
+ editPdfState.annotations.push(a);
1295
+ editPdfState.selectedId = a.id;
1296
+ editPdfSetTool('select');
1297
+ epPushHistory();
1298
+ epRedrawOverlay();
1299
+ epRenderInspector();
1300
+ epRenderLayers();
1301
+ epUpdateThumbCounts();
1302
+ showToast('Stempel ' + preset + ' ditambahkan.');
1303
+ }
1304
+
1305
+ // ============================================================
1306
+ // BLANK PAGE
1307
+ // ============================================================
1308
+ async function editPdfAddBlankPage() {
1309
+ if (!editPdfState.pdfDoc) return showToast('Muat PDF terlebih dahulu.', false);
1310
+ try {
1311
+ const { PDFDocument } = PDFLib;
1312
+ const doc = await PDFDocument.load(editPdfState.bytes.slice(0), { ignoreEncryption: true });
1313
+ const info = epPageInfo();
1314
+ const insertAt = editPdfState.currentPage; // after current (0-based index = current)
1315
+ doc.insertPage(insertAt, [info.w, info.h]);
1316
+ const bytes = await doc.save();
1317
+ editPdfState.bytes = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1318
+ editPdfState.pageCount = doc.getPageCount();
1319
+ editPdfState.annotations.forEach(a => { if (a.page > editPdfState.currentPage) a.page += 1; });
1320
+ const reloaded = await pdfjsLib.getDocument({ data: editPdfState.bytes.slice(0) }).promise;
1321
+ editPdfState.pdfDoc = reloaded;
1322
+ epPushHistory();
1323
+ await epRenderThumbs();
1324
+ await epRenderPage();
1325
+ epRenderLayers();
1326
+ showToast('Halaman kosong disisipkan.');
1327
+ } catch (err) {
1328
+ console.error(err);
1329
+ showToast('Gagal menambah halaman: ' + err.message, false);
1330
+ }
1331
+ }
1332
+
1333
+ // ============================================================
1334
+ // VIEW CONTROLS
1335
+ // ============================================================
1336
+ function editPdfGoHome() {
1337
+ editPdfState.dirty = editPdfState.annotations.length > 0;
1338
+ if (editPdfState.dirty && !confirm('Ada anotasi yang belum diunduh. Kembali ke beranda dan buang perubahan?')) return;
1339
+ switchView('dashboard');
1340
+ }
1341
+ function editPdfToggleFlatten(v) {
1342
+ editPdfState.flattenOnExport = !!v;
1343
+ if (!v && editPdfState.annotations.some(a => a.type === 'redact')) {
1344
+ showToast('Sensor tetap akan di-flatten otomatis demi keamanan.', false);
1345
+ }
1346
+ epRenderInspector();
1347
+ }
1348
+ function editPdfDrop(e) {
1349
+ e.preventDefault();
1350
+ const el = epEl('edit-empty');
1351
+ if (el) el.classList.remove('drag-over');
1352
+ const f = e.dataTransfer.files[0];
1353
+ if (f) loadEditPdfFile(f);
1354
+ }
1355
+
1356
+ // ============================================================
1357
+ // KEYBOARD
1358
+ // ============================================================
1359
+ function epHandleKey(e) {
1360
+ if (typeof state === 'undefined' || state.activeView !== 'edit-pdf') return;
1361
+ const t = e.target;
1362
+ const tag = (t && t.tagName ? t.tagName : '').toLowerCase();
1363
+ const typing = tag === 'input' || tag === 'textarea' || tag === 'select' || (t && t.isContentEditable);
1364
+
1365
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {
1366
+ if (typing) return;
1367
+ e.preventDefault();
1368
+ if (e.shiftKey) editPdfRedo(); else editPdfUndo();
1369
+ return;
1370
+ }
1371
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'y') {
1372
+ if (typing) return;
1373
+ e.preventDefault(); editPdfRedo(); return;
1374
+ }
1375
+ if (typing) return;
1376
+
1377
+ if (e.key === 'Escape') {
1378
+ if (!epEl('edit-text-inline').classList.contains('hidden')) { epCommitInlineText(); return; }
1379
+ if (editPdfState.selectedId) { editPdfState.selectedId = null; epRedrawOverlay(); epRenderInspector(); epRenderLayers(); return; }
1380
+ if (editPdfState.activeTool !== 'select') { editPdfSetTool('select'); return; }
1381
+ editPdfGoHome();
1382
+ return;
1383
+ }
1384
+
1385
+ if (e.key === 'Delete' || e.key === 'Backspace') {
1386
+ if (editPdfState.selectedId) { e.preventDefault(); editPdfDeleteSelected(); }
1387
+ return;
1388
+ }
1389
+
1390
+ if (e.key.startsWith('Arrow') && editPdfState.selectedId) {
1391
+ e.preventDefault();
1392
+ const a = epGetSelected();
1393
+ if (!a) return;
1394
+ const step = e.shiftKey ? 10 : 1;
1395
+ const dx = step / (editPdfState.viewW || 1);
1396
+ const dy = step / (editPdfState.viewH || 1);
1397
+ if (e.key === 'ArrowLeft') a.x -= dx;
1398
+ if (e.key === 'ArrowRight') a.x += dx;
1399
+ if (e.key === 'ArrowUp') a.y -= dy;
1400
+ if (e.key === 'ArrowDown') a.y += dy;
1401
+ if (a.type === 'draw' && a.points) {
1402
+ const ox = e.key === 'ArrowLeft' ? -dx : e.key === 'ArrowRight' ? dx : 0;
1403
+ const oy = e.key === 'ArrowUp' ? -dy : e.key === 'ArrowDown' ? dy : 0;
1404
+ a.points.forEach(p => { p.x += ox; p.y += oy; });
1405
+ }
1406
+ epMarkDirty();
1407
+ epRedrawOverlay();
1408
+ return;
1409
+ }
1410
+
1411
+ const k = e.key.toLowerCase();
1412
+ if (['v', 't', 'h', 'd', 'r', 'x', 'i', 's'].includes(k)) {
1413
+ const map = { v: 'select', t: 'text', h: 'highlight', d: 'draw', r: 'shape', x: 'redact', i: 'image', s: 'stamp' };
1414
+ e.preventDefault();
1415
+ editPdfSetTool(map[k]);
1416
+ return;
1417
+ }
1418
+ if (e.key === '+' || e.key === '=') { e.preventDefault(); editPdfZoom(0.1); }
1419
+ if (e.key === '-' || e.key === '_') { e.preventDefault(); editPdfZoom(-0.1); }
1420
+ if (e.key === '0') { e.preventDefault(); editPdfState.zoom = 1; epUpdateZoomLabel(); epRenderPage(); }
1421
+ }
1422
+
1423
+ // ============================================================
1424
+ // EXPORT
1425
+ // ============================================================
1426
+ async function epEnsureImages() {
1427
+ const imgs = editPdfState.annotations.filter(a => a.type === 'image' && a.dataUrl);
1428
+ await Promise.all(imgs.map(a => new Promise(resolve => {
1429
+ if (editPdfState.imgCache[a.dataUrl]) return resolve();
1430
+ const im = new Image();
1431
+ im.onload = () => { editPdfState.imgCache[a.dataUrl] = im; resolve(); };
1432
+ im.onerror = () => resolve();
1433
+ im.src = a.dataUrl;
1434
+ })));
1435
+ }
1436
+
1437
+ function epFontKey(a) {
1438
+ return `${a.fontFamily}|${a.bold ? 1 : 0}|${a.italic ? 1 : 0}`;
1439
+ }
1440
+ async function epGetPdfFont(doc, a, cache, StandardFonts) {
1441
+ const key = epFontKey(a);
1442
+ if (cache[key]) return cache[key];
1443
+ const fam = a.fontFamily || 'Helvetica';
1444
+ let name;
1445
+ if (fam === 'TimesRoman') {
1446
+ name = a.bold && a.italic ? StandardFonts.TimesRomanBoldItalic
1447
+ : a.bold ? StandardFonts.TimesRomanBold
1448
+ : a.italic ? StandardFonts.TimesRomanItalic : StandardFonts.TimesRoman;
1449
+ } else if (fam === 'Courier') {
1450
+ name = a.bold && a.italic ? StandardFonts.CourierBoldOblique
1451
+ : a.bold ? StandardFonts.CourierBold
1452
+ : a.italic ? StandardFonts.CourierOblique : StandardFonts.Courier;
1453
+ } else {
1454
+ name = a.bold && a.italic ? StandardFonts.HelveticaBoldOblique
1455
+ : a.bold ? StandardFonts.HelveticaBold
1456
+ : a.italic ? StandardFonts.HelveticaOblique : StandardFonts.Helvetica;
1457
+ }
1458
+ const f = await doc.embedFont(name);
1459
+ cache[key] = f;
1460
+ return f;
1461
+ }
1462
+
1463
+ function epStampDataUrl(a) {
1464
+ const ratio = a.h / a.w;
1465
+ const c = document.createElement('canvas');
1466
+ c.width = 640;
1467
+ c.height = Math.max(120, Math.round(640 * ratio));
1468
+ const ctx = c.getContext('2d');
1469
+ epDrawStamp(ctx, a, 0, 0, c.width, c.height, 1);
1470
+ return c.toDataURL('image/png');
1471
+ }
1472
+
1473
+ async function epDrawVectorAnnotation(outDoc, page, a, fontCache, PL) {
1474
+ const { rgb, degrees, StandardFonts } = PL;
1475
+ const { width: pw, height: ph } = page.getSize();
1476
+ const x = a.x * pw, w = a.w * pw, h = a.h * ph;
1477
+ const y = ph - (a.y * ph) - h; // flip Y
1478
+
1479
+ if (a.type === 'highlight') {
1480
+ page.drawRectangle({ x, y, width: w, height: h, color: rgb(hexToRgb01(a.color).r, hexToRgb01(a.color).g, hexToRgb01(a.color).b), opacity: a.opacity != null ? a.opacity : 0.5 });
1481
+ return;
1482
+ }
1483
+ if (a.type === 'redact') {
1484
+ page.drawRectangle({ x, y, width: w, height: h, color: rgb(0.06, 0.09, 0.16) });
1485
+ return;
1486
+ }
1487
+ if (a.type === 'text') {
1488
+ if (a.whiteout) page.drawRectangle({ x, y, width: w, height: h, color: rgb(1, 1, 1) });
1489
+ const font = await epGetPdfFont(outDoc, a, fontCache, StandardFonts);
1490
+ const size = a.fontSize || 13;
1491
+ const c = hexToRgb01(a.color || '#1E1B4B');
1492
+ const lines = wrapForPdf(font, a.text || '', size, Math.max(5, w - 2));
1493
+ const lh = size * 1.25;
1494
+ const topY = ph - a.y * ph;
1495
+ lines.forEach((ln, i) => {
1496
+ const tw = font.widthOfTextAtSize(ln, size);
1497
+ let tx = x;
1498
+ if (a.align === 'center') tx = x + (w - tw) / 2;
1499
+ if (a.align === 'right') tx = x + w - tw;
1500
+ page.drawText(ln, { x: tx, y: topY - size * 0.95 - i * lh, size, font, color: rgb(c.r, c.g, c.b) });
1501
+ });
1502
+ return;
1503
+ }
1504
+ if (a.type === 'draw' && a.points && a.points.length) {
1505
+ const c = hexToRgb01(a.color || '#2563EB');
1506
+ const th = Math.max(0.6, (a.strokeWidth || 2.5) * 0.75);
1507
+ const pts = a.points.map(p => ({ x: p.x * pw, y: ph - p.y * ph }));
1508
+ for (let i = 1; i < pts.length; i++) {
1509
+ page.drawLine({ start: pts[i - 1], end: pts[i], thickness: th, color: rgb(c.r, c.g, c.b), lineCap: 1 });
1510
+ }
1511
+ return;
1512
+ }
1513
+ if (a.type === 'shape') {
1514
+ const c = hexToRgb01(a.strokeColor || '#2563EB');
1515
+ const sw = Math.max(0.6, (a.strokeWidth || 2.5) * 0.75);
1516
+ if (a.shapeType === 'line' || a.shapeType === 'arrow') {
1517
+ const p1 = { x: a.x * pw, y: ph - a.y * ph };
1518
+ const p2 = { x: (a.x + a.w) * pw, y: ph - (a.y + a.h) * ph };
1519
+ page.drawLine({ start: p1, end: p2, thickness: sw, color: rgb(c.r, c.g, c.b), lineCap: 1 });
1520
+ if (a.shapeType === 'arrow') {
1521
+ const ang = Math.atan2(p2.y - p1.y, p2.x - p1.x);
1522
+ const len = Math.max(6, sw * 3.4);
1523
+ page.drawLine({ start: p2, end: { x: p2.x - len * Math.cos(ang - Math.PI / 6), y: p2.y - len * Math.sin(ang - Math.PI / 6) }, thickness: sw, color: rgb(c.r, c.g, c.b) });
1524
+ page.drawLine({ start: p2, end: { x: p2.x - len * Math.cos(ang + Math.PI / 6), y: p2.y - len * Math.sin(ang + Math.PI / 6) }, thickness: sw, color: rgb(c.r, c.g, c.b) });
1525
+ }
1526
+ } else {
1527
+ const fill = a.fillColor && a.fillColor !== 'transparent' ? hexToRgb01(a.fillColor) : null;
1528
+ page.drawRectangle({
1529
+ x, y, width: w, height: h,
1530
+ borderColor: rgb(c.r, c.g, c.b), borderWidth: sw,
1531
+ color: fill ? rgb(fill.r, fill.g, fill.b) : undefined,
1532
+ });
1533
+ }
1534
+ return;
1535
+ }
1536
+ if (a.type === 'image' && a.dataUrl) {
1537
+ const png = await outDoc.embedPng(a.dataUrl);
1538
+ page.drawImage(png, { x, y, width: w, height: h });
1539
+ return;
1540
+ }
1541
+ if (a.type === 'stamp') {
1542
+ const png = await outDoc.embedPng(epStampDataUrl(a));
1543
+ page.drawImage(png, { x, y, width: w, height: h });
1544
+ return;
1545
+ }
1546
+ }
1547
+
1548
+ async function epCompositePage(outDoc, pageIndex, anns, PL) {
1549
+ const page = await editPdfState.pdfDoc.getPage(pageIndex);
1550
+ const vp = page.getViewport({ scale: 2 });
1551
+ const canvas = document.createElement('canvas');
1552
+ canvas.width = Math.floor(vp.width);
1553
+ canvas.height = Math.floor(vp.height);
1554
+ const ctx = canvas.getContext('2d');
1555
+ await page.render({ canvasContext: ctx, viewport: vp }).promise;
1556
+ const info = editPdfState.pageInfo[pageIndex] || { w: vp.width / 2, h: vp.height / 2, rotation: page.rotate || 0 };
1557
+ anns.forEach(a => epDrawAnnotation(ctx, a, canvas.width, canvas.height, false, info));
1558
+ const dataUrl = canvas.toDataURL('image/jpeg', 0.92);
1559
+ const jpg = await outDoc.embedJpg(dataUrl);
1560
+ const p = outDoc.addPage([canvas.width, canvas.height]);
1561
+ p.drawImage(jpg, { x: 0, y: 0, width: canvas.width, height: canvas.height });
1562
+ }
1563
+
1564
+ async function exportEditedPdf() {
1565
+ if (!editPdfState.pdfDoc) return showToast('Muat PDF terlebih dahulu.', false);
1566
+ const visible = editPdfState.annotations.filter(a => !a.hidden);
1567
+ if (!visible.length) return showToast('Belum ada anotasi untuk diekspor.', false);
1568
+ epCommitInlineText();
1569
+
1570
+ const btn = epEl('edit-btn-export');
1571
+ const old = btn ? btn.innerHTML : '';
1572
+ if (btn) { btn.disabled = true; btn.textContent = 'Memproses…'; }
1573
+ showToast('Menyiapkan PDF…');
1574
+
1575
+ try {
1576
+ await epEnsureImages();
1577
+ const PL = PDFLib;
1578
+ const { PDFDocument } = PL;
1579
+ const src = await PDFDocument.load(editPdfState.bytes.slice(0), { ignoreEncryption: true });
1580
+ const out = await PDFDocument.create();
1581
+ const fontCache = {};
1582
+
1583
+ for (let i = 1; i <= editPdfState.pageCount; i++) {
1584
+ const pageAnns = visible.filter(a => a.page === i);
1585
+ const srcPage = src.getPage(i - 1);
1586
+ const rot = (srcPage.getRotation && srcPage.getRotation().angle) || 0;
1587
+ const hasRedact = pageAnns.some(a => a.type === 'redact');
1588
+
1589
+ if (!pageAnns.length) {
1590
+ const [cp] = await out.copyPages(src, [i - 1]);
1591
+ out.addPage(cp);
1592
+ continue;
1593
+ }
1594
+
1595
+ const mustFlatten = editPdfState.flattenOnExport || hasRedact || (rot % 360 !== 0);
1596
+ if (mustFlatten) {
1597
+ await epCompositePage(out, i, pageAnns, PL);
1598
+ } else {
1599
+ const [cp] = await out.copyPages(src, [i - 1]);
1600
+ const added = out.addPage(cp);
1601
+ for (const a of pageAnns) {
1602
+ try { await epDrawVectorAnnotation(out, added, a, fontCache, PL); }
1603
+ catch (e) { console.warn('vector annot skip', a.type, e); }
1604
+ }
1605
+ }
1606
+ }
1607
+
1608
+ const bytes = await out.save();
1609
+ downloadBlob(new Blob([bytes], { type: 'application/pdf' }), tsName('Edit_PDF', 'pdf'));
1610
+ editPdfState.dirty = false;
1611
+ showToast('PDF berhasil disimpan & diunduh.');
1612
+ } catch (err) {
1613
+ console.error(err);
1614
+ showToast('Gagal mengekspor: ' + err.message, false);
1615
+ } finally {
1616
+ if (btn) { btn.disabled = false; btn.innerHTML = old; }
1617
+ }
1618
+ }