privacy-redact 1.0.3 → 1.2.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.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Review actions: the release buttons a host can set on the review screen. These are pure rules
3
+ * with no DOM, so the controller and the Node tests share one check.
4
+ */
5
+
6
+ const OUTPUTS = ['file', 'text'];
7
+ const VARIANTS = ['primary', 'secondary', 'ghost'];
8
+ const FORMATS = ['png', 'jpeg'];
9
+ const ID_PATTERN = /^[a-z0-9-]+$/;
10
+ const LABEL_MAX = 40;
11
+
12
+ /** Input for the built-in name "download", which keeps today's Save button. */
13
+ const BUILTIN_DOWNLOAD = {
14
+ id: 'download', label: 'Save sanitized file', outputs: ['file', 'text'], download: true, busyLabel: 'Sanitizing...',
15
+ };
16
+
17
+ /**
18
+ * Check a host action list and fill in the defaults. Throws a TypeError that names the entry and
19
+ * the field, so the caller can keep the list it had before.
20
+ * @param {unknown} list an array of "download" and/or action objects, or null for the default
21
+ * @returns {object[]} normalized actions, in the order given
22
+ */
23
+ export function normalizeActions(list) {
24
+ if (list == null) return [normalizeAction('download', 0)];
25
+ if (!Array.isArray(list)) throw new TypeError('actions must be an array of "download" and/or action objects');
26
+ const seen = new Set();
27
+ let primaries = 0;
28
+ return list.map((entry, i) => {
29
+ const action = normalizeAction(entry, i, seen);
30
+ if (action.variant === 'primary') primaries += 1;
31
+ if (primaries > 1) throw new TypeError(`actions[${i}].variant: only one action can be "primary"`);
32
+ return action;
33
+ });
34
+ }
35
+
36
+ /**
37
+ * Check one entry and return it with defaults filled in.
38
+ * @param {unknown} entry the built-in name "download", or an action object
39
+ * @param {number} i position in the list, used for the default variant and error messages
40
+ * @param {Set<string>} [seen] ids already used in this list
41
+ */
42
+ function normalizeAction(entry, i, seen = new Set()) {
43
+ const at = `actions[${i}]`;
44
+ const builtin = entry === 'download';
45
+ if (typeof entry === 'string' && !builtin) {
46
+ throw new TypeError(`${at}: unknown built-in "${entry}". The only built-in is "download".`);
47
+ }
48
+ if (!builtin && (!entry || typeof entry !== 'object' || Array.isArray(entry))) {
49
+ throw new TypeError(`${at}: expected "download" or an action object`);
50
+ }
51
+ const src = builtin ? BUILTIN_DOWNLOAD : entry;
52
+ if (!builtin && src.id === 'download') {
53
+ throw new TypeError(`${at}.id: "download" is reserved for the built-in. Use the string "download" instead.`);
54
+ }
55
+ if (typeof src.id !== 'string' || !ID_PATTERN.test(src.id)) {
56
+ throw new TypeError(`${at}.id must use lowercase letters, digits, and "-"`);
57
+ }
58
+ if (seen.has(src.id)) throw new TypeError(`${at}.id "${src.id}" is already used by another action`);
59
+ seen.add(src.id);
60
+
61
+ const label = typeof src.label === 'string' ? src.label.trim() : '';
62
+ if (!label || label.length > LABEL_MAX) throw new TypeError(`${at}.label must be 1 to ${LABEL_MAX} characters`);
63
+
64
+ const outputs = src.outputs;
65
+ if (!Array.isArray(outputs) || outputs.some((o) => !OUTPUTS.includes(o)) || new Set(outputs).size !== outputs.length) {
66
+ throw new TypeError(`${at}.outputs must list "file" and/or "text", each at most once`);
67
+ }
68
+
69
+ const choose = src.choose ?? false;
70
+ if (typeof choose !== 'boolean') throw new TypeError(`${at}.choose must be true or false`);
71
+ if (choose && outputs.length !== 2) throw new TypeError(`${at}.choose needs outputs ["file", "text"]`);
72
+
73
+ const variant = src.variant ?? (i === 0 ? 'primary' : 'secondary');
74
+ if (!VARIANTS.includes(variant)) throw new TypeError(`${at}.variant must be "primary", "secondary", or "ghost"`);
75
+
76
+ const format = src.format;
77
+ if (format !== undefined && !FORMATS.includes(format)) throw new TypeError(`${at}.format must be "png" or "jpeg"`);
78
+ if (format !== undefined && !outputs.includes('file')) throw new TypeError(`${at}.format needs "file" in outputs`);
79
+
80
+ const download = src.download ?? false;
81
+ if (typeof download !== 'boolean') throw new TypeError(`${at}.download must be true or false`);
82
+ if (download && !outputs.includes('file')) throw new TypeError(`${at}.download needs "file" in outputs`);
83
+
84
+ const busyLabel = src.busyLabel ?? 'Preparing...';
85
+ if (typeof busyLabel !== 'string' || !busyLabel.trim()) throw new TypeError(`${at}.busyLabel must be text`);
86
+
87
+ return { id: src.id, label, outputs: [...outputs], choose, variant, format, busyLabel, download, builtin };
88
+ }
89
+
90
+ /** The built-in Save action, used when the list leaves it out or the screen needs its defaults. */
91
+ export function downloadAction() {
92
+ return normalizeAction('download', 0);
93
+ }
@@ -2,13 +2,18 @@
2
2
  * Review screen controller. Looks up its nodes inside the element root so a host
3
3
  * page can mount the same flow without owning the document.
4
4
  */
5
- import { CATEGORIES, TEXT_TYPES } from '../detect/patterns.js';
5
+ import { CATEGORIES, TEXT_TYPES, createDetector, defaultDetector } from '../detect/patterns.js';
6
6
  import { regionsFromLines, maskHint, documentTranscript } from '../detect/textRegions.js';
7
7
  import { renderRedactions } from '../render/effects.js';
8
+ import { normalizeActions, downloadAction } from './actions.js';
8
9
  import {
9
10
  SCAN_TYPES, PICTURE_SCAN_TYPES, loadScanPrefs, saveScanPrefs, defaultScanPrefs,
10
11
  normalizeScanPrefs, enabledTextTypes, enabledSteps, emailPhonePrefs, scanScopeText,
11
12
  } from '../prefs/scan.js';
13
+ import {
14
+ OPTIONAL_LANGUAGES, loadLanguagePrefs, saveLanguagePrefs,
15
+ languagesFromPrefs, prefsFromLanguages,
16
+ } from '../prefs/languages.js';
12
17
 
13
18
  const TAGS = {
14
19
  card: 'Credit card', ssn: 'SSN / ID', aadhaar: 'Aadhaar', pan: 'PAN', email: 'Email', phone: 'Phone', address: 'Address', account: 'Account no.',
@@ -22,7 +27,7 @@ const DROP_TITLE = 'Drop a screenshot, photo, or PDF here';
22
27
  * Bind the review flow to one element. Queries stay in its shadow tree. Page paste
23
28
  * is ignored while the person is typing in the host.
24
29
  * @param {HTMLElement} host
25
- * @param {{ style?: string, strength?: number }} [initial]
30
+ * @param {{ style?: string, strength?: number, actions?: unknown, languages?: unknown, regions?: unknown }} [initial]
26
31
  */
27
32
  export function attachController(host, initial = {}) {
28
33
  const root = host.shadowRoot;
@@ -44,13 +49,52 @@ export function attachController(host, initial = {}) {
44
49
  return el;
45
50
  };
46
51
 
47
- const state = { doc: null, page: 0, style: 'blur', strength: 0.65, catOn: {}, scan: loadScanPrefs(), scanning: false, run: 0, transcriptRedacted: true };
52
+ const state = {
53
+ doc: null, page: 0, style: 'blur', strength: 0.65, catOn: {}, scan: loadScanPrefs(), scanning: false, run: 0, transcriptRedacted: true,
54
+ actions: normalizeActions(undefined), sendAs: 'both',
55
+ detector: defaultDetector,
56
+ languages: loadLanguagePrefs(),
57
+ regions: ['US', 'CA', 'GB', 'IN'],
58
+ };
48
59
  let nextId = 1;
49
60
 
61
+ /** Compile the detector from the current language prefs and regions. */
62
+ function applyDetectorScope() {
63
+ state.detector = createDetector({
64
+ languages: languagesFromPrefs(state.languages),
65
+ regions: state.regions,
66
+ });
67
+ import('../detect/ocr.js').then((m) => m.setOcrScope(state.detector)).catch(() => {});
68
+ }
69
+
70
+ /**
71
+ * Host override for languages/regions. A languages list also updates the
72
+ * Settings toggles and the local save so the screen matches the host.
73
+ */
74
+ function setScope({ languages, regions } = {}) {
75
+ if (regions != null) {
76
+ if (!Array.isArray(regions)) throw new TypeError('regions must be an array of region ids');
77
+ state.regions = regions;
78
+ }
79
+ if (languages != null) {
80
+ state.languages = saveLanguagePrefs(prefsFromLanguages(languages));
81
+ drawLangPrefs();
82
+ }
83
+ applyDetectorScope();
84
+ }
85
+
50
86
  const isActive = (r) => state.catOn[r.type] !== false && r.on;
51
87
  const cur = () => state.doc.pages[state.page];
52
88
  const activeRegions = (p) => p.regions.filter(isActive);
53
89
  const preview = $('preview');
90
+ /** Safety net: keep the preview inside its column even when the stylesheet did not load. */
91
+ function fitPreviewToColumn(canvas) {
92
+ if (!canvas) return;
93
+ canvas.style.display = 'block';
94
+ canvas.style.maxWidth = '100%';
95
+ canvas.style.height = 'auto';
96
+ }
97
+ fitPreviewToColumn(preview);
54
98
  let rafId = 0;
55
99
  const schedule = () => { cancelAnimationFrame(rafId); rafId = requestAnimationFrame(renderNow); };
56
100
 
@@ -178,16 +222,9 @@ export function attachController(host, initial = {}) {
178
222
  $('pg-next').disabled = state.page === n - 1;
179
223
  }
180
224
 
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);
225
+ /** Boxes still on, one list per page. The transcript mask follows these, so the text matches the image. */
226
+ function activeBoxesByPage() {
227
+ return state.doc.pages.map((p) => activeRegions(p));
191
228
  }
192
229
 
193
230
  /** Keep the Redacted switch in step with the reading that will be copied. */
@@ -215,7 +252,7 @@ export function attachController(host, initial = {}) {
215
252
  const failed = pages.some((p) => p.ocr === 'fail');
216
253
  const text = documentTranscript(
217
254
  pages.map((p) => (p.ocr === 'done' ? p.lines : [])),
218
- { redact: state.transcriptRedacted !== false, types: activeTranscriptTypes() },
255
+ { redact: state.transcriptRedacted !== false, boxes: activeBoxesByPage() },
219
256
  );
220
257
  if (pending && !text) return { text: '', empty: 'Reading the document…', pending: true };
221
258
  if (!text && failed) return { text: '', empty: 'Text reading failed.', pending: false };
@@ -228,10 +265,152 @@ export function attachController(host, initial = {}) {
228
265
  function redactedTranscript() {
229
266
  return documentTranscript(
230
267
  state.doc.pages.map((p) => (p.ocr === 'done' ? p.lines : [])),
231
- { redact: true, types: activeTranscriptTypes() },
268
+ { redact: true, boxes: activeBoxesByPage() },
232
269
  );
233
270
  }
234
271
 
272
+ /** Text is still being read on at least one page, so the transcript cannot be released yet. */
273
+ function textPending() {
274
+ if (!state.doc) return false;
275
+ return enabledSteps(state.scan).includes('ocr') && state.doc.pages.some((p) => !p.ocr);
276
+ }
277
+
278
+ /** Give a release button its look, part names, and label from its action. */
279
+ function styleButton(node, action) {
280
+ node.className = action.variant === 'primary' ? 'btn primary big' : `btn ${action.variant} wide`;
281
+ node.dataset.actionId = action.id;
282
+ node.setAttribute('part', `action action-${action.variant} action-${action.id}`);
283
+ node.textContent = action.label;
284
+ return node;
285
+ }
286
+
287
+ /** A release button for a host action. Its label is plain text, never parsed as HTML. */
288
+ function hostButton(action) {
289
+ const node = document.createElement('button');
290
+ node.type = 'button';
291
+ node.addEventListener('click', () => runAction(action, node));
292
+ return styleButton(node, action);
293
+ }
294
+
295
+ /** Put the release buttons in list order. The Save node stays in the DOM when the list leaves it out, so its listener still works. */
296
+ function renderActions() {
297
+ const save = $('btn-save');
298
+ const nodes = state.actions.map((action) => (action.builtin ? styleButton(save, action) : hostButton(action)));
299
+ const saveListed = nodes.includes(save);
300
+ save.hidden = !saveListed;
301
+ if (!saveListed) nodes.push(save);
302
+ nodes.push($('btn-copy'));
303
+ $('actions').replaceChildren(...nodes);
304
+ const fileActions = state.actions.filter((a) => a.outputs.includes('file'));
305
+ $('fmt-wrap').hidden = fileActions.length > 0 && fileActions.every((a) => a.format);
306
+ $('send-as').hidden = !state.actions.some((a) => a.choose);
307
+ syncActionButtons();
308
+ }
309
+
310
+ /** Apply a host action list. A list that fails the rules throws, and the previous list stays. */
311
+ function setActions(list) {
312
+ state.actions = normalizeActions(list);
313
+ renderActions();
314
+ }
315
+
316
+ /** Outputs an action releases right now. A "choose" action follows the person's Send as pick. */
317
+ function outputsFor(action) {
318
+ let outs = action.outputs;
319
+ if (action.choose) outs = state.sendAs === 'both' ? ['file', 'text'] : [state.sendAs];
320
+ if (outs.includes('text') && textPending()) outs = outs.filter((o) => o !== 'text');
321
+ return (outs.length || !action.choose) ? outs : ['file'];
322
+ }
323
+
324
+ /** True when a button must stay disabled: its outputs are not ready, or no document is open. */
325
+ function actionBlocked(action) {
326
+ if (!action.outputs.length) return false;
327
+ if (!state.doc || state.scanning) return true;
328
+ return !action.choose && action.outputs.includes('text') && textPending();
329
+ }
330
+
331
+ /** Enable or disable the release buttons, Copy, and the Send as choice from the current scan state. */
332
+ function syncActionButtons() {
333
+ for (const action of state.actions) {
334
+ const node = root.querySelector(`[data-action-id="${action.id}"]`);
335
+ if (node) node.disabled = actionBlocked(action);
336
+ }
337
+ $('btn-copy').disabled = !state.doc || state.scanning;
338
+ $('send-as-file').textContent = state.doc?.kind === 'pdf' ? 'PDF' : 'Image';
339
+ const pending = textPending();
340
+ for (const btn of root.querySelectorAll('#send-as [data-send]')) {
341
+ const pick = btn.dataset.send;
342
+ btn.disabled = !state.doc || state.scanning || (pick !== 'file' && pending);
343
+ btn.classList.toggle('on', pick === state.sendAs);
344
+ btn.setAttribute('aria-checked', String(pick === state.sendAs));
345
+ }
346
+ }
347
+
348
+ // Send as: the person picks what a "choose" action releases.
349
+ for (const btn of root.querySelectorAll('#send-as [data-send]')) {
350
+ btn.addEventListener('click', () => {
351
+ state.sendAs = btn.dataset.send;
352
+ syncActionButtons();
353
+ });
354
+ }
355
+
356
+ /** The save note under the export card: the file name, what was hidden, and the metadata re-check. */
357
+ function showSaveNote(name, clean, pagesIn) {
358
+ const note = $('save-note');
359
+ const hidden = pagesIn.reduce((n, p) => n + p.regions.length, 0);
360
+ const stripped = state.doc.meta.fields.length;
361
+ note.className = `save-note ${clean ? '' : 'bad'}`;
362
+ note.textContent = clean
363
+ ? `✓ Saved ${name} · ${hidden} region${hidden === 1 ? '' : 's'} hidden · ${stripped ? stripped + ' metadata field' + (stripped === 1 ? '' : 's') + ' removed · ' : ''}re-checked: 0 metadata fields in the output`
364
+ : `Saved ${name}, but a metadata check still found data. Please report this bug.`;
365
+ note.hidden = false;
366
+ }
367
+
368
+ /** Release what an action names, then fire `result` with exactly that. Runs only from a click on its button. */
369
+ async function runAction(action, btn) {
370
+ if (actionBlocked(action)) return;
371
+ const outputs = outputsFor(action);
372
+ const detail = {
373
+ action: action.id,
374
+ outputs,
375
+ findings: state.doc ? activeFindings() : [],
376
+ truncated: !!state.doc?.truncated,
377
+ scope: { ...state.detector.scope },
378
+ warnings: [],
379
+ };
380
+ // An action that releases nothing only reports the click. No document data leaves.
381
+ if (!outputs.length) {
382
+ emit('result', detail);
383
+ return;
384
+ }
385
+ const idle = action.label;
386
+ btn.disabled = true; btn.textContent = action.busyLabel;
387
+ try {
388
+ const ex = await import('../io/exporter.js');
389
+ const opts = { style: state.style, strength: state.strength };
390
+ const pagesIn = state.doc.pages.map((p) => ({ canvas: p.canvas, regions: activeRegions(p) }));
391
+ if (outputs.includes('file')) {
392
+ const format = action.format || $('format').value;
393
+ const res = state.doc.kind === 'pdf'
394
+ ? await ex.exportPdf(pagesIn, opts)
395
+ : await ex.exportImage(pagesIn[0], { ...opts, format });
396
+ const name = ex.outputName(state.doc.name, res.ext);
397
+ if (action.download) ex.download(res.blob, name);
398
+ Object.assign(detail, { file: res.blob, filename: name, clean: res.clean });
399
+ if (action.download) showSaveNote(name, res.clean, pagesIn);
400
+ }
401
+ if (outputs.includes('text')) detail.transcript = redactedTranscript();
402
+ emit('result', detail);
403
+ if (!action.download) toast(`Released ${outputs.map((o) => (o === 'file' ? 'the file' : 'the text')).join(' and ')}.`);
404
+ } catch (err) {
405
+ console.error(err);
406
+ const note = $('save-note');
407
+ note.className = 'save-note bad'; note.textContent = `Export failed: ${err.message}`; note.hidden = false;
408
+ } finally {
409
+ btn.textContent = idle;
410
+ syncActionButtons();
411
+ }
412
+ }
413
+
235
414
  /** Counts of boxes still turned on, one entry per category that has any. */
236
415
  function activeFindings() {
237
416
  const counts = {};
@@ -245,21 +424,35 @@ export function attachController(host, initial = {}) {
245
424
  }));
246
425
  }
247
426
 
248
- /** Fill the folded transcript. Stays closed until the user opens it. */
427
+ /** Word/character counts for the reading shown below the text. */
428
+ function transcriptStats(text) {
429
+ const chars = [...text].length;
430
+ const words = text.trim() ? text.trim().split(/\s+/).length : 0;
431
+ const bits = [
432
+ `${words} word${words === 1 ? '' : 's'}`,
433
+ `${chars} character${chars === 1 ? '' : 's'}`,
434
+ ];
435
+ if (state.doc?.pages.length > 1) bits.push(`${state.doc.pages.length} pages`);
436
+ return bits.join(' · ');
437
+ }
438
+
439
+ /** Fill the scrollable scanner reading and the stats under it. */
249
440
  function drawTranscript() {
250
441
  const pre = $('transcript-text');
251
442
  const empty = $('transcript-empty');
443
+ const stats = $('transcript-stats');
252
444
  const copy = $('btn-transcript-copy');
253
445
  if (!state.doc) {
254
446
  pre.textContent = '';
447
+ pre.hidden = true;
255
448
  empty.hidden = true;
449
+ stats.hidden = true;
450
+ stats.textContent = '';
256
451
  copy.disabled = true;
257
452
  copy.textContent = 'Copy text';
258
- $('transcript-count').textContent = '';
259
453
  return;
260
454
  }
261
455
  const n = state.doc.pages.length;
262
- $('transcript-label').textContent = 'What the scanner read';
263
456
  const view = transcriptView();
264
457
  pre.textContent = view.text;
265
458
  pre.hidden = !view.text;
@@ -267,14 +460,16 @@ export function attachController(host, initial = {}) {
267
460
  empty.hidden = !view.empty;
268
461
  copy.disabled = !view.text || view.pending;
269
462
  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(' · ');
463
+ if (view.text) {
464
+ stats.textContent = transcriptStats(view.text);
465
+ stats.hidden = false;
466
+ } else {
467
+ stats.textContent = '';
468
+ stats.hidden = true;
469
+ }
275
470
  }
276
471
 
277
- function refreshAll() { drawOverlay(); drawCategories(); drawTranscript(); schedule(); }
472
+ function refreshAll() { drawOverlay(); drawCategories(); drawTranscript(); syncActionButtons(); schedule(); }
278
473
 
279
474
  const STEPS = [
280
475
  ['ocr', 'Reading text'],
@@ -310,8 +505,6 @@ export function attachController(host, initial = {}) {
310
505
  state.scanning = false;
311
506
  $('scan-card').classList.add('done');
312
507
  $('scanfx').hidden = true;
313
- $('btn-save').disabled = false;
314
- $('btn-copy').disabled = false;
315
508
  refreshAll();
316
509
  setScan('done');
317
510
  }
@@ -327,7 +520,7 @@ export function attachController(host, initial = {}) {
327
520
  $('scan-card').classList.remove('done');
328
521
  $('scan-title').textContent = steps.length ? 'Scanning…' : 'Nothing selected to scan';
329
522
  $('scanfx').hidden = !steps.length;
330
- $('btn-save').disabled = true; $('btn-copy').disabled = true;
523
+ syncActionButtons();
331
524
  initSteps(steps);
332
525
  const scope = scanScopeText(prefs);
333
526
  const scopeEl = $('scan-scope');
@@ -371,10 +564,12 @@ export function attachController(host, initial = {}) {
371
564
  let found = [];
372
565
  if (!{ ocr: ocrMod, barcode: barMod, face: faceMod }[id]) throw new Error('detector not loaded');
373
566
  if (id === 'ocr') {
567
+ if (ocrMod.setOcrScope) ocrMod.setOcrScope(state.detector);
374
568
  const lines = await ocrMod.recognizeLines(page.canvas, (f) => !stale() && progress(si, f));
375
569
  page.lines = lines;
376
570
  page.ocr = 'done';
377
- found = regionsFromLines(lines, textTypes).map((r) => ({ ...r, hint: maskHint(r.text) }));
571
+ found = regionsFromLines(lines, textTypes, state.detector.findSensitive)
572
+ .map((r) => ({ ...r, hint: maskHint(r.text) }));
378
573
  } else if (id === 'barcode') {
379
574
  found = (await barMod.detectBarcodes(page.canvas)).map((r) => ({ ...r, type: 'barcode' }));
380
575
  } else {
@@ -390,7 +585,10 @@ export function attachController(host, initial = {}) {
390
585
  fails.add(id);
391
586
  if (id === 'ocr') page.ocr = 'fail';
392
587
  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);
588
+ const msg = String(err?.message || '');
589
+ toast(msg.startsWith('Text reading failed:')
590
+ ? msg
591
+ : `Couldn’t run ${STEPS.find((s) => s[0] === id)[1].toLowerCase()} detection – you can still draw boxes by hand.`, 5000);
394
592
  }
395
593
  }
396
594
  }
@@ -429,7 +627,6 @@ export function attachController(host, initial = {}) {
429
627
  const doc = await loadFile(file, (m) => ($('dropzone').querySelector('.dz-title').textContent = m));
430
628
  if (runId !== state.run) return;
431
629
  doc.pages = doc.pages.map((canvas) => ({ canvas, regions: [], lines: [], ocr: null }));
432
- setTranscriptOpen(false);
433
630
  state.transcriptRedacted = true;
434
631
  syncTranscriptRedact();
435
632
  state.doc = doc;
@@ -468,12 +665,12 @@ export function attachController(host, initial = {}) {
468
665
  state.run++;
469
666
  state.doc = null;
470
667
  state.scanning = false;
668
+ syncActionButtons();
471
669
  setScan('');
472
670
  setScreen('drop');
473
671
  $('file').value = '';
474
672
  $('dropzone').querySelector('.dz-title').textContent = DROP_TITLE;
475
673
  $('scanfx').hidden = true;
476
- setTranscriptOpen(false);
477
674
  showError('');
478
675
  import('../detect/ocr.js').then((m) => m.disposeOcr()).catch(() => {});
479
676
  }
@@ -513,6 +710,52 @@ export function attachController(host, initial = {}) {
513
710
  for (const id of TEXT_TYPES) appendPrefSwitch(ul, id);
514
711
  appendPrefGroup(ul, 'Picture');
515
712
  for (const id of PICTURE_SCAN_TYPES) appendPrefSwitch(ul, id);
713
+ drawLangPrefs();
714
+ }
715
+
716
+ /** One language chip (English locked, optionals toggle). */
717
+ function appendLangChip(ul, { id, label, mark, detail, locked, on }) {
718
+ const li = document.createElement('li');
719
+ const btn = document.createElement('button');
720
+ btn.type = 'button';
721
+ btn.className = `lang-chip${on ? ' on' : ''}`;
722
+ btn.dataset.lang = id;
723
+ btn.setAttribute('role', 'switch');
724
+ btn.setAttribute('aria-checked', String(on));
725
+ if (locked) btn.setAttribute('aria-disabled', 'true');
726
+ if (detail) btn.title = detail;
727
+ btn.append(span('mark', mark), document.createTextNode(label));
728
+ li.append(btn);
729
+ ul.append(li);
730
+ }
731
+
732
+ /** Rebuild language chips on the drop screen and beside the field list. */
733
+ function drawLangPrefs() {
734
+ const lists = root.querySelectorAll('[data-lang-prefs]');
735
+ for (const ul of lists) {
736
+ ul.replaceChildren();
737
+ appendLangChip(ul, {
738
+ id: 'en', label: 'English', mark: 'A', locked: true, on: true,
739
+ });
740
+ for (const pack of OPTIONAL_LANGUAGES) {
741
+ appendLangChip(ul, {
742
+ id: pack.id,
743
+ label: pack.label,
744
+ mark: 'अ',
745
+ locked: false,
746
+ on: state.languages[pack.id] === true,
747
+ });
748
+ }
749
+ }
750
+ }
751
+
752
+ /** Toggle an optional language; rescan the open file so OCR matches. */
753
+ function toggleLanguage(id) {
754
+ if (!id || id === 'en') return;
755
+ state.languages = saveLanguagePrefs({ ...state.languages, [id]: state.languages[id] !== true });
756
+ drawLangPrefs();
757
+ applyDetectorScope();
758
+ if (state.doc) rescanCurrent();
516
759
  }
517
760
 
518
761
  /** Show rescan only while a file is open, and keep a single primary button. */
@@ -583,6 +826,11 @@ export function attachController(host, initial = {}) {
583
826
  $('prefs').addEventListener('keydown', (e) => {
584
827
  if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('cat')) { e.preventDefault(); e.target.click(); }
585
828
  });
829
+ root.addEventListener('click', (e) => {
830
+ const chip = e.target.closest?.('.lang-chip[data-lang]');
831
+ if (!chip || !root.contains(chip) || chip.getAttribute('aria-disabled') === 'true') return;
832
+ toggleLanguage(chip.dataset.lang);
833
+ });
586
834
 
587
835
  let dragDepth = 0;
588
836
  /** True when a file drag is aimed at this element, not at another control on the page. */
@@ -730,46 +978,19 @@ export function attachController(host, initial = {}) {
730
978
  overlay.addEventListener('pointerup', endDrag);
731
979
  overlay.addEventListener('pointercancel', endDrag);
732
980
 
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
- });
981
+ // The built-in Save button runs the same release path as a host action.
982
+ $('btn-save').addEventListener('click', () => runAction(state.actions.find((a) => a.builtin) || downloadAction(), $('btn-save')));
983
+
984
+ /** Show the thin transcript scrollbar only while the person is scrolling. */
985
+ {
986
+ const pre = $('transcript-text');
987
+ let hideTimer = 0;
988
+ pre.addEventListener('scroll', () => {
989
+ pre.classList.add('is-scrolling');
990
+ clearTimeout(hideTimer);
991
+ hideTimer = setTimeout(() => pre.classList.remove('is-scrolling'), 700);
992
+ }, { passive: true });
993
+ }
773
994
 
774
995
  /** Switch the reading between redacted (default) and the original words. */
775
996
  $('transcript-redact').addEventListener('click', () => {
@@ -778,7 +999,7 @@ export function attachController(host, initial = {}) {
778
999
  drawTranscript();
779
1000
  });
780
1001
 
781
- /** Copy every page. Works while the panel is still folded, in whichever mode is showing. */
1002
+ /** Copy every page from the preview, in whichever mode is showing. */
782
1003
  $('btn-transcript-copy').addEventListener('click', async () => {
783
1004
  if (!state.doc) return;
784
1005
  const view = transcriptView();
@@ -789,7 +1010,7 @@ export function attachController(host, initial = {}) {
789
1010
  toast(`${kind} transcript copied.`);
790
1011
  } catch (err) {
791
1012
  console.error(err);
792
- toast('Your browser blocked clipboard access. Expand the transcript and select the text.', 4500);
1013
+ toast('Your browser blocked clipboard access. Select the text in the reading instead.', 4500);
793
1014
  }
794
1015
  });
795
1016
 
@@ -814,6 +1035,13 @@ export function attachController(host, initial = {}) {
814
1035
 
815
1036
  if (initial.style) setStyle(initial.style);
816
1037
  if (initial.strength != null) setStrength(initial.strength);
1038
+ if (initial.regions != null) state.regions = initial.regions;
1039
+ if (initial.languages != null) {
1040
+ state.languages = saveLanguagePrefs(prefsFromLanguages(initial.languages));
1041
+ }
1042
+ applyDetectorScope();
1043
+ drawLangPrefs();
1044
+ setActions(initial.actions);
817
1045
  setScreen('drop');
818
1046
 
819
1047
  return {
@@ -823,8 +1051,15 @@ export function attachController(host, initial = {}) {
823
1051
  home,
824
1052
  setStyle,
825
1053
  setStrength,
1054
+ setActions,
1055
+ setScope,
1056
+ getActions: () => state.actions,
826
1057
  getStyle: () => state.style,
827
1058
  getStrength: () => state.strength,
1059
+ getScope: () => ({
1060
+ languages: languagesFromPrefs(state.languages),
1061
+ regions: [...state.regions],
1062
+ }),
828
1063
  /** Release page listeners. The element calls this when it leaves the document. */
829
1064
  dispose() {
830
1065
  cancelAnimationFrame(rafId);