privacy-redact 0.1.0 → 1.0.2

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.
@@ -0,0 +1,840 @@
1
+ /**
2
+ * Review screen controller. Looks up its nodes inside the element root so a host
3
+ * page can mount the same flow without owning the document.
4
+ */
5
+ import { CATEGORIES, TEXT_TYPES } from '../detect/patterns.js';
6
+ import { regionsFromLines, maskHint, documentTranscript } from '../detect/textRegions.js';
7
+ import { renderRedactions } from '../render/effects.js';
8
+ import {
9
+ SCAN_TYPES, PICTURE_SCAN_TYPES, loadScanPrefs, saveScanPrefs, defaultScanPrefs,
10
+ normalizeScanPrefs, enabledTextTypes, enabledSteps, emailPhonePrefs, scanScopeText,
11
+ } from '../prefs/scan.js';
12
+
13
+ const TAGS = {
14
+ card: 'Credit card', ssn: 'SSN / ID', email: 'Email', phone: 'Phone', address: 'Address', account: 'Account no.',
15
+ dob: 'Birth date', secret: 'Secret / key', face: 'Face', barcode: 'Barcode / QR', manual: 'Manual',
16
+ };
17
+ const CAT_ORDER = [...SCAN_TYPES, 'manual'];
18
+ const STYLES = ['blur', 'pixelate', 'blackout'];
19
+ const DROP_TITLE = 'Drop a screenshot, photo, or PDF here';
20
+
21
+ /**
22
+ * Bind the review flow to one element. Queries stay in its shadow tree. Page paste
23
+ * is ignored while the person is typing in the host.
24
+ * @param {HTMLElement} host
25
+ * @param {{ style?: string, strength?: number }} [initial]
26
+ */
27
+ export function attachController(host, initial = {}) {
28
+ const root = host.shadowRoot;
29
+ const $ = (id) => root.querySelector(`#${id}`);
30
+ /** Events cross the shadow boundary so a host can listen on the element. */
31
+ const emit = (name, detail) => {
32
+ host.dispatchEvent(new CustomEvent(name, { bubbles: true, composed: true, detail }));
33
+ };
34
+ /** Scan progress lives on the element, not on the host document. */
35
+ const setScan = (value) => {
36
+ if (value) host.dataset.scan = value;
37
+ else delete host.dataset.scan;
38
+ };
39
+ /** A span with a class, so the markup strings do not look like JSX to the dev server. */
40
+ const span = (className, text) => {
41
+ const el = document.createElement('span');
42
+ el.className = className;
43
+ if (text) el.textContent = text;
44
+ return el;
45
+ };
46
+
47
+ const state = { doc: null, page: 0, style: 'blur', strength: 0.65, catOn: {}, scan: loadScanPrefs(), scanning: false, run: 0, transcriptRedacted: true };
48
+ let nextId = 1;
49
+
50
+ const isActive = (r) => state.catOn[r.type] !== false && r.on;
51
+ const cur = () => state.doc.pages[state.page];
52
+ const activeRegions = (p) => p.regions.filter(isActive);
53
+ const preview = $('preview');
54
+ let rafId = 0;
55
+ const schedule = () => { cancelAnimationFrame(rafId); rafId = requestAnimationFrame(renderNow); };
56
+
57
+ function toast(msg, ms = 3200) {
58
+ const t = $('toast');
59
+ t.textContent = msg; t.hidden = false;
60
+ clearTimeout(toast.t);
61
+ toast.t = setTimeout(() => (t.hidden = true), ms);
62
+ }
63
+ function showError(msg) {
64
+ const e = $('landing-error');
65
+ e.textContent = msg; e.hidden = !msg;
66
+ }
67
+
68
+ /** Tell the host which screen is showing so it can hide its own marketing. */
69
+ function setScreen(screen) {
70
+ $('review-drop').hidden = screen !== 'drop';
71
+ $('settings').hidden = screen !== 'settings';
72
+ $('workspace').hidden = screen !== 'review';
73
+ host.dataset.screen = screen;
74
+ emit('mode', { screen, hasDoc: !!state.doc });
75
+ }
76
+
77
+ function renderNow() {
78
+ if (!state.doc) return;
79
+ const p = cur();
80
+ renderRedactions(preview, p.canvas, activeRegions(p), state.style, state.strength);
81
+ }
82
+
83
+ function drawOverlay() {
84
+ const ov = $('overlay');
85
+ ov.replaceChildren();
86
+ if (!state.doc) return;
87
+ const p = cur();
88
+ const W = p.canvas.width, H = p.canvas.height;
89
+ for (const r of p.regions) {
90
+ const el = document.createElement('div');
91
+ el.className = `box ${isActive(r) ? 'on' : 'off'} ${r.type === 'face' ? 'face' : ''} ${r.manual ? 'manual' : ''}`;
92
+ const padX = r.type === 'face' ? r.w * 0.18 : Math.max(3, r.h * 0.18);
93
+ const padY = r.type === 'face' ? r.h * 0.28 : Math.max(2, r.h * 0.14);
94
+ el.style.left = `${((r.x - padX) / W) * 100}%`;
95
+ el.style.top = `${((r.y - padY) / H) * 100}%`;
96
+ el.style.width = `${((r.w + padX * 2) / W) * 100}%`;
97
+ el.style.height = `${((r.h + padY * 2) / H) * 100}%`;
98
+ el.dataset.id = r.id;
99
+ const tag = document.createElement('span');
100
+ tag.className = 'tag';
101
+ tag.textContent = `${TAGS[r.type]}${r.hint ? ' · ' + r.hint : ''}${isActive(r) ? '' : ' · NOT hidden'}`;
102
+ el.append(tag);
103
+ if (r.manual) {
104
+ const x = document.createElement('span');
105
+ x.className = 'x'; x.textContent = '×'; x.title = 'Remove';
106
+ x.dataset.remove = r.id;
107
+ el.append(x);
108
+ }
109
+ ov.append(el);
110
+ }
111
+ }
112
+
113
+ function drawCategories() {
114
+ const ul = $('cats');
115
+ ul.replaceChildren();
116
+ const counts = {};
117
+ let total = 0;
118
+ if (state.doc) for (const p of state.doc.pages) for (const r of p.regions) counts[r.type] = (counts[r.type] || 0) + 1;
119
+ const order = CAT_ORDER.filter((t) => (t === 'manual' ? counts.manual : state.scan[t] !== false || counts[t]));
120
+ order.sort((a, b) => (counts[b] ? 1 : 0) - (counts[a] ? 1 : 0) || CAT_ORDER.indexOf(a) - CAT_ORDER.indexOf(b));
121
+ for (const t of order) {
122
+ const n = counts[t] || 0;
123
+ if (state.catOn[t] !== false) total += n;
124
+ const li = document.createElement('li');
125
+ li.className = `cat ${n ? 'has' : 'none'} ${state.catOn[t] !== false ? 'enabled' : ''}`;
126
+ li.dataset.type = t;
127
+ li.setAttribute('role', 'switch');
128
+ li.setAttribute('aria-checked', String(state.catOn[t] !== false));
129
+ li.tabIndex = 0;
130
+ const meta = t === 'manual' ? { icon: '✏️', label: 'Drawn by you' } : CATEGORIES[t];
131
+ li.append(span('ic'), span('lbl'), span('n'), span('switch'));
132
+ li.children[0].textContent = meta.icon;
133
+ li.children[1].textContent = meta.label;
134
+ li.children[2].textContent = n;
135
+ ul.append(li);
136
+ }
137
+ $('scan-count').textContent = total ? `${total} hidden` : '';
138
+ if (!state.scanning && state.doc) $('scan-title').textContent = scanTitle(total);
139
+ }
140
+
141
+ /** Title after a scan. An empty field list is not the same as a scan that found nothing. */
142
+ function scanTitle(total) {
143
+ if (!enabledSteps(state.scan).length) return 'Nothing selected to scan';
144
+ return total ? `Shielded ${total} item${total === 1 ? '' : 's'}` : 'Nothing sensitive found';
145
+ }
146
+
147
+ function drawMeta() {
148
+ const ul = $('meta');
149
+ ul.replaceChildren();
150
+ const { fields } = state.doc.meta;
151
+ const tag = root.querySelector('#meta-card .tag');
152
+ if (!fields.length) {
153
+ const li = document.createElement('li');
154
+ li.className = 'empty';
155
+ li.textContent = state.doc.kind === 'pdf'
156
+ ? 'No document info found. Pages are flattened, so any hidden text layer is discarded too.'
157
+ : 'No EXIF, GPS or camera data found. The export is metadata-free either way.';
158
+ ul.append(li);
159
+ tag.textContent = 'clean'; tag.className = 'tag ok';
160
+ return;
161
+ }
162
+ tag.textContent = `${fields.length} field${fields.length === 1 ? '' : 's'} will be stripped`;
163
+ tag.className = 'tag warn';
164
+ for (const f of fields) {
165
+ const li = document.createElement('li');
166
+ const k = document.createElement('span'); k.className = 'k'; k.textContent = `${f.icon} ${f.label}`;
167
+ const v = document.createElement('span'); v.className = `v ${f.risk}`; v.textContent = f.value;
168
+ li.append(k, v);
169
+ ul.append(li);
170
+ }
171
+ }
172
+
173
+ function drawPageNav() {
174
+ const n = state.doc.pages.length;
175
+ $('pagenav').hidden = n <= 1;
176
+ $('pg-label').textContent = `Page ${state.page + 1} / ${n}`;
177
+ $('pg-prev').disabled = state.page === 0;
178
+ $('pg-next').disabled = state.page === n - 1;
179
+ }
180
+
181
+ /** Fold or open the scanner reading without touching the text already filled in. */
182
+ function setTranscriptOpen(open) {
183
+ $('transcript-panel').hidden = !open;
184
+ $('transcript-toggle').setAttribute('aria-expanded', String(open));
185
+ $('transcript-card').classList.toggle('open', open);
186
+ }
187
+
188
+ /** Text fields still hidden in the preview. The transcript redaction follows these. */
189
+ function activeTranscriptTypes() {
190
+ return enabledTextTypes(state.scan).filter((id) => state.catOn[id] !== false);
191
+ }
192
+
193
+ /** Keep the Redacted switch in step with the reading that will be copied. */
194
+ function syncTranscriptRedact() {
195
+ const on = state.transcriptRedacted !== false;
196
+ const btn = $('transcript-redact');
197
+ btn.setAttribute('aria-checked', String(on));
198
+ btn.classList.toggle('on', on);
199
+ btn.title = on
200
+ ? 'Showing redacted text. Click for the original words.'
201
+ : 'Showing the original words. Click to redact.';
202
+ }
203
+
204
+ /**
205
+ * The whole document, redacted or original.
206
+ * Copy stays off until every page has been read, so a paste is never a partial file.
207
+ */
208
+ function transcriptView() {
209
+ const pages = state.doc.pages;
210
+ const textOn = enabledSteps(state.scan).includes('ocr');
211
+ if (!textOn && pages.every((p) => !p.ocr)) {
212
+ return { text: '', empty: 'Text reading is off. Choose fields in Settings, then rescan.', pending: false };
213
+ }
214
+ const pending = textOn && pages.some((p) => !p.ocr);
215
+ const failed = pages.some((p) => p.ocr === 'fail');
216
+ const text = documentTranscript(
217
+ pages.map((p) => (p.ocr === 'done' ? p.lines : [])),
218
+ { redact: state.transcriptRedacted !== false, types: activeTranscriptTypes() },
219
+ );
220
+ if (pending && !text) return { text: '', empty: 'Reading the document…', pending: true };
221
+ if (!text && failed) return { text: '', empty: 'Text reading failed.', pending: false };
222
+ if (!text) return { text: '', empty: 'The scanner did not read any words.', pending: false };
223
+ if (pending) return { text, empty: 'Copy waits until every page has been read.', pending: true };
224
+ return { text, empty: '', pending: false };
225
+ }
226
+
227
+ /** Redacted reading for the host. Follows the boxes still on, not the on-screen original switch. */
228
+ function redactedTranscript() {
229
+ return documentTranscript(
230
+ state.doc.pages.map((p) => (p.ocr === 'done' ? p.lines : [])),
231
+ { redact: true, types: activeTranscriptTypes() },
232
+ );
233
+ }
234
+
235
+ /** Counts of boxes still turned on, one entry per category that has any. */
236
+ function activeFindings() {
237
+ const counts = {};
238
+ for (const page of state.doc.pages) {
239
+ for (const region of activeRegions(page)) counts[region.type] = (counts[region.type] || 0) + 1;
240
+ }
241
+ return CAT_ORDER.filter((type) => counts[type]).map((type) => ({
242
+ type,
243
+ label: type === 'manual' ? 'Manual' : (CATEGORIES[type]?.label || TAGS[type] || type),
244
+ count: counts[type],
245
+ }));
246
+ }
247
+
248
+ /** Fill the folded transcript. Stays closed until the user opens it. */
249
+ function drawTranscript() {
250
+ const pre = $('transcript-text');
251
+ const empty = $('transcript-empty');
252
+ const copy = $('btn-transcript-copy');
253
+ if (!state.doc) {
254
+ pre.textContent = '';
255
+ empty.hidden = true;
256
+ copy.disabled = true;
257
+ copy.textContent = 'Copy text';
258
+ $('transcript-count').textContent = '';
259
+ return;
260
+ }
261
+ const n = state.doc.pages.length;
262
+ $('transcript-label').textContent = 'What the scanner read';
263
+ const view = transcriptView();
264
+ pre.textContent = view.text;
265
+ pre.hidden = !view.text;
266
+ empty.textContent = view.empty;
267
+ empty.hidden = !view.empty;
268
+ copy.disabled = !view.text || view.pending;
269
+ copy.textContent = n > 1 ? 'Copy all' : 'Copy text';
270
+ const lines = view.text ? view.text.split('\n').length : 0;
271
+ const bits = [];
272
+ if (n > 1) bits.push(`${n} pages`);
273
+ if (lines) bits.push(`${lines} line${lines === 1 ? '' : 's'}`);
274
+ $('transcript-count').textContent = bits.join(' · ');
275
+ }
276
+
277
+ function refreshAll() { drawOverlay(); drawCategories(); drawTranscript(); schedule(); }
278
+
279
+ const STEPS = [
280
+ ['ocr', 'Reading text'],
281
+ ['barcode', 'Barcodes & QR codes'],
282
+ ['face', 'Faces'],
283
+ ];
284
+ /** Detector rows for this preference set, in the same order as STEPS. */
285
+ function stepsFor(prefs) {
286
+ const ids = new Set(enabledSteps(prefs));
287
+ return STEPS.filter(([id]) => ids.has(id));
288
+ }
289
+ function initSteps(steps) {
290
+ const ul = $('steps');
291
+ ul.replaceChildren();
292
+ for (const [id, label] of steps) {
293
+ const li = document.createElement('li');
294
+ li.id = `step-${id}`;
295
+ li.append(span('ic', '○'), span('l'), span('r'));
296
+ li.children[1].textContent = label;
297
+ ul.append(li);
298
+ }
299
+ }
300
+ function setStep(id, status, right = '') {
301
+ const li = $(`step-${id}`);
302
+ if (!li) return;
303
+ li.className = status;
304
+ li.children[0].textContent = status === 'done' ? '✓' : status === 'fail' ? '!' : status === 'run' ? '' : '○';
305
+ li.children[2].textContent = right;
306
+ }
307
+
308
+ function finishScan() {
309
+ $('scan-bar').style.width = '100%';
310
+ state.scanning = false;
311
+ $('scan-card').classList.add('done');
312
+ $('scanfx').hidden = true;
313
+ $('btn-save').disabled = false;
314
+ $('btn-copy').disabled = false;
315
+ refreshAll();
316
+ setScan('done');
317
+ }
318
+
319
+ async function scanDocument(runId) {
320
+ const doc = state.doc;
321
+ const prefs = normalizeScanPrefs(state.scan);
322
+ const textTypes = enabledTextTypes(prefs);
323
+ const steps = stepsFor(prefs);
324
+ state.scanning = true;
325
+ drawTranscript();
326
+ setScan('running');
327
+ $('scan-card').classList.remove('done');
328
+ $('scan-title').textContent = steps.length ? 'Scanning…' : 'Nothing selected to scan';
329
+ $('scanfx').hidden = !steps.length;
330
+ $('btn-save').disabled = true; $('btn-copy').disabled = true;
331
+ initSteps(steps);
332
+ const scope = scanScopeText(prefs);
333
+ const scopeEl = $('scan-scope');
334
+ scopeEl.textContent = scope;
335
+ scopeEl.hidden = !scope;
336
+ const nPages = doc.pages.length;
337
+ const bar = $('scan-bar');
338
+ const totals = { ocr: 0, barcode: 0, face: 0 };
339
+ const fails = new Set();
340
+ const stale = () => runId !== state.run;
341
+ if (!steps.length) {
342
+ if (!stale()) finishScan();
343
+ return;
344
+ }
345
+
346
+ const load = (p) => p.catch((err) => { console.error('[privacy-redact] could not load detector', err); return null; });
347
+ const ids = new Set(steps.map(([id]) => id));
348
+ const [ocrMod, barMod, faceMod] = await Promise.all([
349
+ ids.has('ocr') ? load(import('../detect/ocr.js')) : null,
350
+ ids.has('barcode') ? load(import('../detect/barcodes.js')) : null,
351
+ ids.has('face') ? load(import('../detect/faces.js')) : null,
352
+ ]);
353
+ if (stale()) return;
354
+
355
+ const nSteps = steps.length;
356
+ for (let pi = 0; nPages > pi; pi++) {
357
+ const page = doc.pages[pi];
358
+ const suffix = nPages > 1 ? ` · p${pi + 1}/${nPages}` : '';
359
+ const progress = (si, f) => { bar.style.width = `${(((pi * nSteps + si + f) / (nPages * nSteps)) * 100).toFixed(1)}%`; };
360
+
361
+ for (let si = 0; nSteps > si; si++) {
362
+ const id = steps[si][0];
363
+ if (fails.has(id)) {
364
+ if (id === 'ocr') page.ocr = 'fail';
365
+ progress(si, 1);
366
+ continue;
367
+ }
368
+ setStep(id, 'run', suffix.replace(' · ', ''));
369
+ progress(si, 0);
370
+ try {
371
+ let found = [];
372
+ if (!{ ocr: ocrMod, barcode: barMod, face: faceMod }[id]) throw new Error('detector not loaded');
373
+ if (id === 'ocr') {
374
+ const lines = await ocrMod.recognizeLines(page.canvas, (f) => !stale() && progress(si, f));
375
+ page.lines = lines;
376
+ page.ocr = 'done';
377
+ found = regionsFromLines(lines, textTypes).map((r) => ({ ...r, hint: maskHint(r.text) }));
378
+ } else if (id === 'barcode') {
379
+ found = (await barMod.detectBarcodes(page.canvas)).map((r) => ({ ...r, type: 'barcode' }));
380
+ } else {
381
+ found = (await faceMod.detectFaces(page.canvas, (f) => !stale() && progress(si, f))).map((r) => ({ ...r, type: 'face' }));
382
+ }
383
+ if (stale()) return;
384
+ for (const r of found) page.regions.push({ id: nextId++, on: true, manual: false, type: r.type, x: r.x, y: r.y, w: r.w, h: r.h, hint: r.hint || '' });
385
+ totals[id] += found.length;
386
+ setStep(id, 'done', `${totals[id]} found`);
387
+ if (pi === state.page) refreshAll(); else drawCategories();
388
+ } catch (err) {
389
+ console.error(`[privacy-redact] ${id} failed`, err);
390
+ fails.add(id);
391
+ if (id === 'ocr') page.ocr = 'fail';
392
+ setStep(id, 'fail', 'unavailable');
393
+ toast(`Couldn’t run ${STEPS.find((s) => s[0] === id)[1].toLowerCase()} detection – you can still draw boxes by hand.`, 5000);
394
+ }
395
+ }
396
+ }
397
+ if (stale()) return;
398
+ finishScan();
399
+ }
400
+
401
+ /** Apply a host style before the person edits, and keep the style buttons in step. */
402
+ function setStyle(name) {
403
+ if (!STYLES.includes(name)) return;
404
+ state.style = name;
405
+ for (const button of $('styles').children) {
406
+ const on = button.dataset.style === name;
407
+ button.classList.toggle('on', on);
408
+ button.setAttribute('aria-checked', String(on));
409
+ }
410
+ schedule();
411
+ }
412
+
413
+ /** Apply a host strength from 0 to 1 and move the slider to match. */
414
+ function setStrength(value) {
415
+ const n = Number(value);
416
+ if (!Number.isFinite(n)) return;
417
+ state.strength = Math.min(1, Math.max(0, n));
418
+ $('strength').value = String(Math.round(state.strength * 100));
419
+ schedule();
420
+ }
421
+
422
+ async function openFile(file) {
423
+ if (!file) return;
424
+ showError('');
425
+ const runId = ++state.run;
426
+ $('dropzone').style.opacity = .6;
427
+ try {
428
+ const { loadFile } = await import('../io/loader.js');
429
+ const doc = await loadFile(file, (m) => ($('dropzone').querySelector('.dz-title').textContent = m));
430
+ if (runId !== state.run) return;
431
+ doc.pages = doc.pages.map((canvas) => ({ canvas, regions: [], lines: [], ocr: null }));
432
+ setTranscriptOpen(false);
433
+ state.transcriptRedacted = true;
434
+ syncTranscriptRedact();
435
+ state.doc = doc;
436
+ state.page = 0;
437
+ state.catOn = {};
438
+ if (doc.truncated) toast('Only the first 60 pages were loaded.', 5000);
439
+ setScreen('review');
440
+
441
+ const fmt = $('format');
442
+ fmt.replaceChildren();
443
+ const opts = doc.kind === 'pdf'
444
+ ? [['pdf', 'PDF (pages flattened)']]
445
+ : [['png', 'PNG (lossless)'], ['jpeg', 'JPG (smaller)']];
446
+ for (const [v, l] of opts) fmt.append(new Option(l, v));
447
+ fmt.value = doc.kind === 'pdf' ? 'pdf' : (/\.jpe?g$/i.test(doc.name) ? 'jpeg' : 'png');
448
+ $('btn-copy').hidden = doc.kind === 'pdf';
449
+ $('save-note').hidden = true;
450
+
451
+ drawMeta();
452
+ drawPageNav();
453
+ preview.width = doc.pages[0].canvas.width;
454
+ preview.height = doc.pages[0].canvas.height;
455
+ refreshAll();
456
+ $('workspace').focus({ preventScroll: true });
457
+ scanDocument(runId);
458
+ } catch (err) {
459
+ console.error(err);
460
+ showError(err.message || 'Could not open that file.');
461
+ $('dropzone').querySelector('.dz-title').textContent = DROP_TITLE;
462
+ } finally {
463
+ $('dropzone').style.opacity = 1;
464
+ }
465
+ }
466
+
467
+ function reset() {
468
+ state.run++;
469
+ state.doc = null;
470
+ state.scanning = false;
471
+ setScan('');
472
+ setScreen('drop');
473
+ $('file').value = '';
474
+ $('dropzone').querySelector('.dz-title').textContent = DROP_TITLE;
475
+ $('scanfx').hidden = true;
476
+ setTranscriptOpen(false);
477
+ showError('');
478
+ import('../detect/ocr.js').then((m) => m.disposeOcr()).catch(() => {});
479
+ }
480
+
481
+ const fileInput = $('file');
482
+ fileInput.addEventListener('change', () => fileInput.files[0] && openFile(fileInput.files[0]));
483
+ $('dropzone').addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); fileInput.click(); } });
484
+
485
+ /** Add a non-interactive group label to the field list. */
486
+ function appendPrefGroup(ul, label) {
487
+ const li = document.createElement('li');
488
+ li.className = 'prefs-group';
489
+ li.textContent = label;
490
+ ul.append(li);
491
+ }
492
+
493
+ /** One on/off row for a scannable field. */
494
+ function appendPrefSwitch(ul, id) {
495
+ const on = state.scan[id] !== false;
496
+ const li = document.createElement('li');
497
+ li.className = `cat ${on ? 'enabled' : ''}`;
498
+ li.dataset.type = id;
499
+ li.setAttribute('role', 'switch');
500
+ li.setAttribute('aria-checked', String(on));
501
+ li.tabIndex = 0;
502
+ li.append(span('ic'), span('lbl'), span('switch'));
503
+ li.children[0].textContent = CATEGORIES[id].icon;
504
+ li.children[1].textContent = CATEGORIES[id].label;
505
+ ul.append(li);
506
+ }
507
+
508
+ /** Rebuild the settings switches from the saved field set. */
509
+ function drawPrefs() {
510
+ const ul = $('prefs');
511
+ ul.replaceChildren();
512
+ appendPrefGroup(ul, 'Text');
513
+ for (const id of TEXT_TYPES) appendPrefSwitch(ul, id);
514
+ appendPrefGroup(ul, 'Picture');
515
+ for (const id of PICTURE_SCAN_TYPES) appendPrefSwitch(ul, id);
516
+ }
517
+
518
+ /** Show rescan only while a file is open, and keep a single primary button. */
519
+ function syncSettingsActions() {
520
+ const hasDoc = !!state.doc;
521
+ $('prefs-rescan').hidden = !hasDoc;
522
+ $('prefs-done').classList.toggle('primary', !hasDoc);
523
+ $('prefs-done').classList.toggle('ghost', hasDoc);
524
+ }
525
+
526
+ /** Close settings and return to the open file, or the drop screen. */
527
+ function closeSettings() {
528
+ setScreen(state.doc ? 'review' : 'drop');
529
+ }
530
+
531
+ /** Open the field picker. The current file stays in memory. */
532
+ function showSettings() {
533
+ setScreen('settings');
534
+ syncSettingsActions();
535
+ drawPrefs();
536
+ $('settings-title').focus();
537
+ }
538
+
539
+ /** Save a new field set and refresh the switches. */
540
+ function applyScanPrefs(next) {
541
+ state.scan = saveScanPrefs(next);
542
+ drawPrefs();
543
+ }
544
+
545
+ /** Drop automatic boxes and scan the open file again with the current fields. */
546
+ function rescanCurrent() {
547
+ if (!state.doc) return;
548
+ const runId = ++state.run;
549
+ state.catOn = {};
550
+ for (const page of state.doc.pages) {
551
+ page.regions = page.regions.filter((r) => r.manual);
552
+ page.lines = [];
553
+ page.ocr = null;
554
+ if (page.regions.length) state.catOn.manual = true;
555
+ }
556
+ setScreen('review');
557
+ refreshAll();
558
+ scanDocument(runId);
559
+ }
560
+
561
+ function toggleSettings() {
562
+ if ($('settings').hidden) showSettings();
563
+ else closeSettings();
564
+ }
565
+
566
+ /** Brand control: leave the open file, or leave settings for the drop screen. */
567
+ function home() {
568
+ if (state.doc) reset();
569
+ else closeSettings();
570
+ }
571
+
572
+ $('btn-settings-landing').addEventListener('click', showSettings);
573
+ $('prefs-all').addEventListener('click', () => applyScanPrefs(defaultScanPrefs()));
574
+ $('prefs-email-phone').addEventListener('click', () => applyScanPrefs(emailPhonePrefs()));
575
+ $('prefs-done').addEventListener('click', closeSettings);
576
+ $('prefs-rescan').addEventListener('click', rescanCurrent);
577
+ $('prefs').addEventListener('click', (e) => {
578
+ const li = e.target.closest('.cat');
579
+ if (!li) return;
580
+ const id = li.dataset.type;
581
+ applyScanPrefs({ ...state.scan, [id]: state.scan[id] === false });
582
+ });
583
+ $('prefs').addEventListener('keydown', (e) => {
584
+ if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('cat')) { e.preventDefault(); e.target.click(); }
585
+ });
586
+
587
+ let dragDepth = 0;
588
+ /** True when a file drag is aimed at this element, not at another control on the page. */
589
+ const dragHasFile = (e) => e.dataTransfer?.types?.includes('Files');
590
+ const onDragEnter = (e) => { if (dragHasFile(e)) { dragDepth++; $('dragveil').hidden = false; } };
591
+ const onDragLeave = () => { dragDepth = Math.max(0, dragDepth - 1); if (!dragDepth) $('dragveil').hidden = true; };
592
+ const onDragOver = (e) => { if (dragHasFile(e)) e.preventDefault(); };
593
+ const onDrop = (e) => {
594
+ if (!dragHasFile(e)) return;
595
+ e.preventDefault(); dragDepth = 0; $('dragveil').hidden = true;
596
+ const files = [...(e.dataTransfer?.files || [])];
597
+ if (!files.length) return;
598
+ if (files.length > 1) toast('Opened the first file. One document at a time.');
599
+ openFile(files[0]);
600
+ };
601
+ host.addEventListener('dragenter', onDragEnter);
602
+ host.addEventListener('dragleave', onDragLeave);
603
+ host.addEventListener('dragover', onDragOver);
604
+ host.addEventListener('drop', onDrop);
605
+
606
+ /** True for a text field. File and range inputs still accept a pasted screenshot. */
607
+ const blocksPaste = (node) => {
608
+ if (!(node instanceof Element)) return false;
609
+ if (node.closest('textarea, select, [contenteditable="true"]')) return true;
610
+ const input = node.closest('input');
611
+ if (!input) return false;
612
+ const type = (input.getAttribute('type') || 'text').toLowerCase();
613
+ return !['file', 'range', 'button', 'checkbox', 'radio', 'hidden'].includes(type);
614
+ };
615
+ /** Paste an image into this screen, and leave text fields on the host page alone. */
616
+ const onPaste = (e) => {
617
+ const node = e.composedPath()[0];
618
+ if (blocksPaste(node)) return;
619
+ const inside = e.composedPath().includes(host);
620
+ if (!inside) {
621
+ const activeHost = document.activeElement?.closest?.('privacy-redact-review');
622
+ if (activeHost && activeHost !== host) return;
623
+ if (!activeHost && document.querySelector('privacy-redact-review') !== host) return;
624
+ }
625
+ const item = [...(e.clipboardData?.items || [])].find((i) => i.kind === 'file' && /^image\//.test(i.type));
626
+ if (!item) return;
627
+ const f = item.getAsFile();
628
+ if (!f) return;
629
+ e.preventDefault();
630
+ openFile(new File([f], `pasted-screenshot.${(f.type.split('/')[1] || 'png').replace('jpeg', 'jpg')}`, { type: f.type }));
631
+ };
632
+ window.addEventListener('paste', onPaste);
633
+
634
+ $('cats').addEventListener('click', (e) => {
635
+ const li = e.target.closest('.cat');
636
+ if (!li) return;
637
+ const t = li.dataset.type;
638
+ state.catOn[t] = state.catOn[t] === false;
639
+ refreshAll();
640
+ });
641
+ $('cats').addEventListener('keydown', (e) => {
642
+ if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('cat')) { e.preventDefault(); e.target.click(); }
643
+ });
644
+
645
+ $('styles').addEventListener('click', (e) => {
646
+ const b = e.target.closest('button[data-style]');
647
+ if (!b) return;
648
+ setStyle(b.dataset.style);
649
+ });
650
+ $('strength').addEventListener('input', (e) => { state.strength = e.target.value / 100; schedule(); });
651
+
652
+ $('pg-prev').addEventListener('click', () => gotoPage(state.page - 1));
653
+ $('pg-next').addEventListener('click', () => gotoPage(state.page + 1));
654
+ function gotoPage(i) {
655
+ if (!state.doc || 0 > i || i >= state.doc.pages.length) return;
656
+ state.page = i;
657
+ drawPageNav();
658
+ refreshAll();
659
+ }
660
+ const onKey = (e) => {
661
+ const target = e.composedPath()[0];
662
+ if (e.key === 'Escape' && !$('settings').hidden) { e.stopPropagation(); closeSettings(); return; }
663
+ if (!$('settings').hidden) return;
664
+ if (!state.doc) return;
665
+ if (target instanceof Element && /^(INPUT|SELECT|TEXTAREA)$/.test(target.tagName)) return;
666
+ if (e.key === 'ArrowRight') gotoPage(state.page + 1);
667
+ if (e.key === 'ArrowLeft') gotoPage(state.page - 1);
668
+ };
669
+ host.addEventListener('keydown', onKey);
670
+ $('stage').addEventListener('pointerdown', () => { $('workspace').focus({ preventScroll: true }); });
671
+
672
+ const peekOn = () => { if (!state.doc) return; $('frame').classList.add('peeking'); preview.getContext('2d').drawImage(cur().canvas, 0, 0); };
673
+ const peekOff = () => { $('frame').classList.remove('peeking'); schedule(); };
674
+ const peek = $('btn-peek');
675
+ peek.addEventListener('pointerdown', (e) => { peek.setPointerCapture(e.pointerId); peekOn(); });
676
+ peek.addEventListener('pointerup', peekOff);
677
+ peek.addEventListener('pointercancel', peekOff);
678
+ peek.addEventListener('keydown', (e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); peekOn(); } });
679
+ peek.addEventListener('keyup', (e) => { if (e.key === ' ' || e.key === 'Enter') peekOff(); });
680
+
681
+ const overlay = $('overlay');
682
+ overlay.addEventListener('click', (e) => {
683
+ if (!state.doc) return;
684
+ const rm = e.target.closest('[data-remove]');
685
+ const box = e.target.closest('.box');
686
+ if (rm) {
687
+ const p = cur();
688
+ p.regions = p.regions.filter((r) => String(r.id) !== rm.dataset.remove);
689
+ refreshAll();
690
+ } else if (box) {
691
+ const r = cur().regions.find((x) => String(x.id) === box.dataset.id);
692
+ if (r) {
693
+ if (state.catOn[r.type] === false) { state.catOn[r.type] = true; r.on = true; } else r.on = !r.on;
694
+ refreshAll();
695
+ }
696
+ }
697
+ });
698
+ let drag = null;
699
+ overlay.addEventListener('pointerdown', (e) => {
700
+ if (!state.doc || e.target !== overlay || e.button !== 0) return;
701
+ const rect = overlay.getBoundingClientRect();
702
+ drag = { rect, x0: e.clientX - rect.left, y0: e.clientY - rect.top, el: document.createElement('div') };
703
+ drag.el.className = 'box draft';
704
+ overlay.append(drag.el);
705
+ overlay.setPointerCapture(e.pointerId);
706
+ });
707
+ overlay.addEventListener('pointermove', (e) => {
708
+ if (!drag) return;
709
+ const x = Math.max(0, Math.min(drag.rect.width, e.clientX - drag.rect.left));
710
+ const y = Math.max(0, Math.min(drag.rect.height, e.clientY - drag.rect.top));
711
+ Object.assign(drag.el.style, {
712
+ left: `${Math.min(x, drag.x0)}px`, top: `${Math.min(y, drag.y0)}px`,
713
+ width: `${Math.abs(x - drag.x0)}px`, height: `${Math.abs(y - drag.y0)}px`,
714
+ });
715
+ });
716
+ const endDrag = (e) => {
717
+ if (!drag) return;
718
+ const { rect, el } = drag;
719
+ drag = null;
720
+ const w = parseFloat(el.style.width) || 0, h = parseFloat(el.style.height) || 0;
721
+ const l = parseFloat(el.style.left) || 0, t = parseFloat(el.style.top) || 0;
722
+ el.remove();
723
+ if (8 > w || 8 > h || e.type === 'pointercancel') return;
724
+ const p = cur();
725
+ const sx = p.canvas.width / rect.width, sy = p.canvas.height / rect.height;
726
+ p.regions.push({ id: nextId++, type: 'manual', manual: true, on: true, hint: '', x: l * sx, y: t * sy, w: w * sx, h: h * sy });
727
+ state.catOn.manual = true;
728
+ refreshAll();
729
+ };
730
+ overlay.addEventListener('pointerup', endDrag);
731
+ overlay.addEventListener('pointercancel', endDrag);
732
+
733
+ $('btn-save').addEventListener('click', async () => {
734
+ if (!state.doc || state.scanning) return;
735
+ const btn = $('btn-save');
736
+ const label = btn.textContent;
737
+ btn.disabled = true; btn.textContent = 'Sanitizing…';
738
+ const note = $('save-note');
739
+ try {
740
+ const ex = await import('../io/exporter.js');
741
+ const opts = { style: state.style, strength: state.strength };
742
+ const pagesIn = state.doc.pages.map((p) => ({ canvas: p.canvas, regions: activeRegions(p) }));
743
+ let res;
744
+ if (state.doc.kind === 'pdf') res = await ex.exportPdf(pagesIn, opts);
745
+ else res = await ex.exportImage(pagesIn[0], { ...opts, format: $('format').value });
746
+ const name = ex.outputName(state.doc.name, res.ext);
747
+ ex.download(res.blob, name);
748
+ const hidden = pagesIn.reduce((n, p) => n + p.regions.length, 0);
749
+ const stripped = state.doc.meta.fields.length;
750
+ note.className = `save-note ${res.clean ? '' : 'bad'}`;
751
+ note.textContent = res.clean
752
+ ? `✓ Saved ${name} · ${hidden} region${hidden === 1 ? '' : 's'} hidden · ${stripped ? stripped + ' metadata field' + (stripped === 1 ? '' : 's') + ' removed · ' : ''}re-checked: 0 metadata fields in the output`
753
+ : `Saved ${name}, but a metadata check still found data. Please report this bug.`;
754
+ note.hidden = false;
755
+ emit('result', {
756
+ file: res.blob,
757
+ filename: name,
758
+ findings: activeFindings(),
759
+ clean: res.clean,
760
+ truncated: !!state.doc.truncated,
761
+ transcript: redactedTranscript(),
762
+ });
763
+ } catch (err) {
764
+ console.error(err);
765
+ note.className = 'save-note bad'; note.textContent = `Export failed: ${err.message}`; note.hidden = false;
766
+ } finally {
767
+ btn.disabled = false; btn.textContent = label;
768
+ }
769
+ });
770
+ $('transcript-toggle').addEventListener('click', () => {
771
+ setTranscriptOpen($('transcript-panel').hidden);
772
+ });
773
+
774
+ /** Switch the reading between redacted (default) and the original words. */
775
+ $('transcript-redact').addEventListener('click', () => {
776
+ state.transcriptRedacted = !state.transcriptRedacted;
777
+ syncTranscriptRedact();
778
+ drawTranscript();
779
+ });
780
+
781
+ /** Copy every page. Works while the panel is still folded, in whichever mode is showing. */
782
+ $('btn-transcript-copy').addEventListener('click', async () => {
783
+ if (!state.doc) return;
784
+ const view = transcriptView();
785
+ if (!view.text || view.pending) return;
786
+ const kind = state.transcriptRedacted !== false ? 'Redacted' : 'Original';
787
+ try {
788
+ await navigator.clipboard.writeText(view.text);
789
+ toast(`${kind} transcript copied.`);
790
+ } catch (err) {
791
+ console.error(err);
792
+ toast('Your browser blocked clipboard access. Expand the transcript and select the text.', 4500);
793
+ }
794
+ });
795
+
796
+ $('btn-copy').addEventListener('click', async () => {
797
+ if (!state.doc || state.scanning) return;
798
+ try {
799
+ const ex = await import('../io/exporter.js');
800
+ const res = await ex.exportImage({ canvas: cur().canvas, regions: activeRegions(cur()) }, { style: state.style, strength: state.strength, format: 'png' });
801
+ await ex.copyImage(res.blob);
802
+ toast('Copied. Paste it into the destination.');
803
+ } catch (err) {
804
+ console.error(err);
805
+ toast('Your browser blocked clipboard access – use Save instead.', 4500);
806
+ }
807
+ });
808
+
809
+ if (new URLSearchParams(location.search).has('debug')) window.__privacyRedact = {
810
+ state,
811
+ detectFaces: async (...a) => (await import('../detect/faces.js')).detectFaces(...a),
812
+ detectBarcodes: async (...a) => (await import('../detect/barcodes.js')).detectBarcodes(...a),
813
+ };
814
+
815
+ if (initial.style) setStyle(initial.style);
816
+ if (initial.strength != null) setStrength(initial.strength);
817
+ setScreen('drop');
818
+
819
+ return {
820
+ open: openFile,
821
+ reset,
822
+ toggleSettings,
823
+ home,
824
+ setStyle,
825
+ setStrength,
826
+ getStyle: () => state.style,
827
+ getStrength: () => state.strength,
828
+ /** Release page listeners. The element calls this when it leaves the document. */
829
+ dispose() {
830
+ cancelAnimationFrame(rafId);
831
+ clearTimeout(toast.t);
832
+ window.removeEventListener('paste', onPaste);
833
+ host.removeEventListener('dragenter', onDragEnter);
834
+ host.removeEventListener('dragleave', onDragLeave);
835
+ host.removeEventListener('dragover', onDragOver);
836
+ host.removeEventListener('drop', onDrop);
837
+ host.removeEventListener('keydown', onKey);
838
+ },
839
+ };
840
+ }