@copio/sdk 0.1.5 → 0.1.6

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 (116) hide show
  1. package/THIRD_PARTY_NOTICES.md +34 -0
  2. package/dist/adapters/edge/index.js +2 -0
  3. package/dist/adapters/edge/index.js.map +7 -0
  4. package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
  5. package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
  6. package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
  7. package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +1 -1
  9. package/dist/adapters/image/index.js +1 -1
  10. package/dist/adapters/image/null-image-processor-adapter.js +1 -1
  11. package/dist/adapters/index.js +1 -1
  12. package/dist/adapters/indexeddb-adapter.js +1 -1
  13. package/dist/adapters/memory-adapter.js +1 -1
  14. package/dist/adapters/ocr/index.js +1 -1
  15. package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
  16. package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
  17. package/dist/adapters/pdf/index.js +1 -1
  18. package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
  19. package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
  20. package/dist/adapters/storage/index.js +1 -1
  21. package/dist/adapters/storage/indexeddb-adapter.js +1 -1
  22. package/dist/adapters/storage/memory-adapter.js +1 -1
  23. package/dist/adapters/sync/index.js +1 -1
  24. package/dist/adapters/sync/null-sync-adapter.js +1 -1
  25. package/dist/adapters/sync/peerjs-adapter.js +1 -1
  26. package/dist/canvas-GKLGWNAJ.js +2 -0
  27. package/dist/cdn.js +189 -1409
  28. package/dist/chunk-25WAHT3G.js +2 -0
  29. package/dist/chunk-2VH2NPXW.js +175 -0
  30. package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
  31. package/dist/chunk-6QK7337A.js +2 -0
  32. package/dist/chunk-GLY5CGCY.js +2 -0
  33. package/dist/chunk-GU6OQMYK.js +4 -0
  34. package/dist/chunk-HCCNUPKB.js +2 -0
  35. package/dist/chunk-JIPKWRBK.js +2 -0
  36. package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
  37. package/dist/chunk-NNSM2I5L.js +2 -0
  38. package/dist/chunk-PBF7V4Z6.js +2 -0
  39. package/dist/chunk-PSGIWIRH.js +2 -0
  40. package/dist/chunk-Q3AWHANC.js +2 -0
  41. package/dist/chunk-R6Q4OXDG.js +2 -0
  42. package/dist/chunk-SZHKZARU.js +2 -0
  43. package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
  44. package/dist/chunk-TK5N67RB.js +2 -0
  45. package/dist/chunk-V2D55DVU.js +1 -0
  46. package/dist/chunk-VPSUKD6F.js +2 -0
  47. package/dist/chunk-ZILTJGT2.js +2 -0
  48. package/dist/core.js +1 -1
  49. package/dist/custom-elements.json +2316 -135
  50. package/dist/export.js +1 -1
  51. package/dist/fs-Y7NMZRBK.js +2 -0
  52. package/dist/handoff-transport-7YFK4RYL.js +2 -0
  53. package/dist/handoff.js +2 -0
  54. package/dist/http-CYZIMVXQ.js +2 -0
  55. package/dist/https-OLG7KUSR.js +2 -0
  56. package/dist/index.js +11 -11
  57. package/dist/ocr.js +1 -1
  58. package/dist/path2d-HD3LU76S.js +2 -0
  59. package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
  60. package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
  61. package/dist/scanner.js +3 -1396
  62. package/dist/sync.js +1 -1
  63. package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
  64. package/dist/types/js/adapters/edge/index.d.ts +3 -0
  65. package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
  66. package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
  67. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
  68. package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
  69. package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
  70. package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
  71. package/dist/types/js/services/doc-repository.d.ts +6 -1
  72. package/dist/types/js/services/handoff-crypto.d.ts +84 -0
  73. package/dist/types/js/services/handoff-session.d.ts +257 -0
  74. package/dist/types/js/services/handoff-transport.d.ts +51 -0
  75. package/dist/types/js/services/ice-servers.d.ts +33 -1
  76. package/dist/types/js/services/migration-runner.d.ts +100 -0
  77. package/dist/types/js/utils/perspective.d.ts +70 -0
  78. package/dist/types/js/utils/utils.d.ts +19 -1
  79. package/dist/types/sdk/core.d.ts +52 -6
  80. package/dist/types/sdk/elements.d.ts +2 -0
  81. package/dist/types/sdk/events.d.ts +42 -0
  82. package/dist/types/sdk/handoff-session.d.ts +4 -0
  83. package/dist/types/sdk/handoff-styles.d.ts +9 -0
  84. package/dist/types/sdk/handoff.d.ts +108 -0
  85. package/dist/types/sdk/index.d.ts +5 -1
  86. package/dist/types/sdk/models.d.ts +248 -1
  87. package/dist/types/sdk/scanner.d.ts +94 -1
  88. package/dist/types/sdk/styles.d.ts +1 -1
  89. package/dist/types/sdk/version.d.ts +1 -1
  90. package/dist/url-NYR4TEJV.js +2 -0
  91. package/package.json +10 -3
  92. package/sdk/core.js +219 -12
  93. package/sdk/events.js +14 -0
  94. package/sdk/handoff-session.js +26 -0
  95. package/sdk/handoff-styles.js +531 -0
  96. package/sdk/handoff.js +1079 -0
  97. package/sdk/index.js +38 -1
  98. package/sdk/models.js +116 -4
  99. package/sdk/scanner.js +1517 -151
  100. package/sdk/styles.js +297 -17
  101. package/sdk/version.js +1 -1
  102. package/dist/canvas-FAXPLPXN.js +0 -2
  103. package/dist/chunk-4C666HHU.js +0 -2
  104. package/dist/chunk-FQRADJY6.js +0 -2
  105. package/dist/chunk-G5EUMLYT.js +0 -4
  106. package/dist/chunk-K4NR6OAC.js +0 -2
  107. package/dist/chunk-L4OVZN23.js +0 -2
  108. package/dist/chunk-MEE2NNYB.js +0 -2
  109. package/dist/chunk-O7IV7A6O.js +0 -2
  110. package/dist/chunk-Q7XPZMZA.js +0 -1395
  111. package/dist/chunk-WETG2JD7.js +0 -2
  112. package/dist/fs-HJ6WWW73.js +0 -2
  113. package/dist/http-FKJJMT2N.js +0 -2
  114. package/dist/https-MUBFLDZM.js +0 -2
  115. package/dist/path2d-QWN6DFCC.js +0 -2
  116. package/dist/url-ABJ6S2Y6.js +0 -2
package/sdk/scanner.js CHANGED
@@ -5,11 +5,25 @@
5
5
  * Embeddable, zero-config two-stage (viewfinder ↔ workbench) document scanner
6
6
  * acting as the primary Driving UI Adapter over the headless CopioEngine.
7
7
  */
8
- import { CopioEngine, cropRotatedToOriginal, cropOriginalToRotated } from './core.js';
8
+ import {
9
+ CopioEngine,
10
+ cropRectToQuad,
11
+ quadToCropRect,
12
+ quadRotatedToOriginal,
13
+ quadOriginalToRotated,
14
+ cloneQuad,
15
+ getRegisteredService,
16
+ } from './core.js';
9
17
  import { COPIO_EVENTS, dispatchCopioEvent } from './events.js';
10
18
  import { setAssetBase } from '../js/utils/module-loader.js';
11
- import { setContainer, getContainer } from '../js/services/notify.js';
19
+ import { notify, setContainer, getContainer } from '../js/services/notify.js';
12
20
  import { scannerCss, getScannerStyleSheet, adoptScannerStyles } from './styles.js';
21
+ import {
22
+ HandoffSession,
23
+ LoopbackTransport,
24
+ parseHandoffUrl,
25
+ decodeSessionToken,
26
+ } from '../js/services/handoff-session.js';
13
27
 
14
28
  /** @type {typeof HTMLElement} */
15
29
  const BaseElement = typeof HTMLElement !== 'undefined' ? HTMLElement : /** @type {any} */ (class {});
@@ -24,12 +38,33 @@ export class CopioScanner extends BaseElement {
24
38
  #pageCount = 0;
25
39
  #retaking = false;
26
40
  #cropMode = false;
27
- #draftCrop = null;
41
+ #draftQuad = null;
28
42
  #undoTimer = null;
29
43
  #undoRemaining = 0;
30
44
  #renderPromise = null;
31
45
  #sessionDocId = null;
32
46
  #cameraStream = null;
47
+ #wasStreamingBeforeHide = false;
48
+ #grabCanvas = null;
49
+ #edgeDetection = true;
50
+ #edgeModel = 'ml';
51
+ #autoCrop = true;
52
+ #autoCapture = false;
53
+ #liveEdgeRafId = null;
54
+ #isDetectingEdge = false;
55
+ #lastEdgeDetectTime = 0;
56
+ #smoothedQuad = null;
57
+ #latestDetectionResult = null;
58
+ #consecutiveMisses = 0;
59
+ #lastValidDetectionTime = 0;
60
+ #stableQuadStartTime = 0;
61
+ #lastStableQuad = null;
62
+ #handoffSession = null;
63
+ #handoffToken = null;
64
+ #handoffState = 'idle'; // 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'sending' | 'complete' | 'error'
65
+ #handoffUnsubs = [];
66
+ #handoffProgress = null;
67
+ #handoffRetryCount = 0;
33
68
  onShutter = null;
34
69
 
35
70
  get #targetDocId() {
@@ -55,6 +90,15 @@ export class CopioScanner extends BaseElement {
55
90
  'theme',
56
91
  'ocr',
57
92
  'pdf',
93
+ 'handoff',
94
+ 'relay-url',
95
+ 'ice-servers',
96
+ 'signaling-url',
97
+ 'ice-transport-policy',
98
+ 'edge-detection',
99
+ 'edge-model',
100
+ 'auto-crop',
101
+ 'auto-capture',
58
102
  ];
59
103
  }
60
104
 
@@ -79,8 +123,22 @@ export class CopioScanner extends BaseElement {
79
123
  if (this.hasAttribute('license-key')) opts.licenseKey = this.getAttribute('license-key');
80
124
  if (this.hasAttribute('ocr')) opts.ocr = this.getAttribute('ocr') !== 'false';
81
125
  if (this.hasAttribute('pdf')) opts.pdf = this.getAttribute('pdf') !== 'false';
126
+ if (this.hasAttribute('edge-detection')) this.#edgeDetection = this.getAttribute('edge-detection') !== 'false';
127
+ if (this.hasAttribute('edge-model')) this.#edgeModel = this.getAttribute('edge-model') === 'classical' ? 'classical' : 'ml';
128
+ if (this.hasAttribute('auto-crop')) this.#autoCrop = this.getAttribute('auto-crop') !== 'false';
129
+ if (this.hasAttribute('auto-capture')) this.#autoCapture = this.getAttribute('auto-capture') !== 'false' && this.getAttribute('auto-capture') !== null;
130
+ for (const k of ['relay-url', 'signaling-url', 'ice-transport-policy']) {
131
+ if (this.hasAttribute(k)) opts[k.replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = this.getAttribute(k);
132
+ }
133
+ if (this.hasAttribute('ice-servers')) {
134
+ try { opts.iceServers = JSON.parse(this.getAttribute('ice-servers')); }
135
+ catch { opts.iceServers = [{ urls: this.getAttribute('ice-servers') }]; }
136
+ }
82
137
  }
83
138
  this.#engine = new CopioEngine(opts);
139
+ this.#engine.addEventListener(COPIO_EVENTS.MIGRATION, (e) => {
140
+ this.dispatch(COPIO_EVENTS.MIGRATION, e.detail);
141
+ });
84
142
  }
85
143
 
86
144
  connectedCallback() {
@@ -93,8 +151,18 @@ export class CopioScanner extends BaseElement {
93
151
  setContainer(this.shadowRoot?.querySelector('.copio-scanner-container') || this);
94
152
  }
95
153
 
96
- // Subscribe to engine repository changes
154
+ if (typeof document !== 'undefined') {
155
+ document.addEventListener('visibilitychange', this.#onVisibilityChange);
156
+ }
157
+ if (typeof window !== 'undefined') {
158
+ window.addEventListener('pagehide', this.#onPageHide);
159
+ }
160
+
161
+ // Initialize engine & run migrations
97
162
  if (this.#engine) {
163
+ this.#engine.init().catch((err) => {
164
+ console.error('[CopioScanner] Engine initialization failed:', err);
165
+ });
98
166
  this.#unsubscribeRepo = this.#engine.subscribe(async () => {
99
167
  const pages = await this.getPages();
100
168
  this.dispatch(COPIO_EVENTS.PAGES_CHANGED, {
@@ -109,12 +177,30 @@ export class CopioScanner extends BaseElement {
109
177
  setAssetBase(this.getAttribute('asset-base'));
110
178
  }
111
179
 
180
+ if (this.#isHandoffMode()) {
181
+ this.#initHandoffMode().catch((err) => {
182
+ console.warn('[CopioScanner] Handoff init error:', err);
183
+ });
184
+ }
185
+
112
186
  this.#updateChildViews();
113
187
  this.#syncView();
114
188
  }
115
189
 
116
190
  disconnectedCallback() {
191
+ if (typeof document !== 'undefined') {
192
+ document.removeEventListener('visibilitychange', this.#onVisibilityChange);
193
+ }
194
+ if (typeof window !== 'undefined') {
195
+ window.removeEventListener('pagehide', this.#onPageHide);
196
+ }
197
+ this.#cleanupHandoff();
117
198
  this.#stopCameraStream();
199
+ if (this.#grabCanvas) {
200
+ this.#grabCanvas.width = 0;
201
+ this.#grabCanvas.height = 0;
202
+ this.#grabCanvas = null;
203
+ }
118
204
  if (typeof this.#unsubscribeRepo === 'function') {
119
205
  this.#unsubscribeRepo();
120
206
  this.#unsubscribeRepo = null;
@@ -131,6 +217,28 @@ export class CopioScanner extends BaseElement {
131
217
  }
132
218
  }
133
219
 
220
+ #onVisibilityChange = () => {
221
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
222
+ if (this.#cameraStream) {
223
+ this.#wasStreamingBeforeHide = true;
224
+ this.#stopCameraStream();
225
+ }
226
+ } else if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
227
+ if (this.#wasStreamingBeforeHide && this.#stage === 'viewfinder') {
228
+ this.#wasStreamingBeforeHide = false;
229
+ this.startCamera().catch(() => {});
230
+ }
231
+ // Mobile browser returning from background: verify handoff connection
232
+ if (this.#isHandoffMode() && this.#handoffSession && !this.#handoffSession.isConnected && this.#handoffState !== 'complete') {
233
+ this.reconnectHandoff().catch(() => {});
234
+ }
235
+ }
236
+ };
237
+
238
+ #onPageHide = () => {
239
+ this.#stopCameraStream();
240
+ };
241
+
134
242
  attributeChangedCallback(name, oldValue, newValue) {
135
243
  if (oldValue === newValue || !this.#engine) return;
136
244
 
@@ -160,9 +268,23 @@ export class CopioScanner extends BaseElement {
160
268
  this.#engine.pdf = newValue !== 'false';
161
269
  this.#updateChildViews();
162
270
  break;
271
+ case 'relay-url':
272
+ case 'signaling-url':
273
+ case 'ice-transport-policy':
274
+ if (this.#engine) this.#engine[name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = newValue;
275
+ break;
276
+ case 'ice-servers':
277
+ if (this.#engine) {
278
+ try { this.#engine.iceServers = JSON.parse(newValue); }
279
+ catch { this.#engine.iceServers = newValue ? [{ urls: newValue }] : null; }
280
+ }
281
+ break;
163
282
  case 'stage':
164
283
  if (newValue === 'viewfinder' || newValue === 'workbench') {
165
284
  this.#stage = newValue;
285
+ if (newValue === 'workbench') {
286
+ this.#stopCameraStream();
287
+ }
166
288
  const shadow = this.shadowRoot;
167
289
  if (shadow) {
168
290
  const vf = shadow.getElementById('viewfinder-section');
@@ -184,6 +306,25 @@ export class CopioScanner extends BaseElement {
184
306
  case 'theme':
185
307
  this.#syncView();
186
308
  break;
309
+ case 'handoff':
310
+ if (newValue && newValue !== 'false') {
311
+ this.#initHandoffMode().catch(() => {});
312
+ } else if (newValue === 'false') {
313
+ this.#cleanupHandoff();
314
+ }
315
+ break;
316
+ case 'edge-detection':
317
+ this.edgeDetection = newValue !== 'false';
318
+ break;
319
+ case 'edge-model':
320
+ this.edgeModel = newValue === 'classical' ? 'classical' : 'ml';
321
+ break;
322
+ case 'auto-crop':
323
+ this.autoCrop = newValue !== 'false';
324
+ break;
325
+ case 'auto-capture':
326
+ this.autoCapture = newValue !== 'false' && newValue !== null;
327
+ break;
187
328
  }
188
329
  }
189
330
 
@@ -238,13 +379,25 @@ export class CopioScanner extends BaseElement {
238
379
  <span class="copio-status-dot"></span>
239
380
  <span id="step-pill-text">${initialStepText}</span>
240
381
  </div>
382
+ <div class="copio-handoff-pill" id="handoff-pill" style="display:none;" title="Phone-to-Desktop Handoff">
383
+ <span class="copio-handoff-dot" id="handoff-dot"></span>
384
+ <span class="copio-handoff-status-text" id="handoff-status-text">Paired with computer</span>
385
+ <button type="button" class="copio-handoff-retry-btn" id="btn-handoff-retry" style="display:none;" title="Retry connection">Retry</button>
386
+ </div>
241
387
  <div class="copio-privacy-pill" title="100% Local On-Device Processing">
242
388
  <span>🔒 100% Local</span>
243
389
  </div>
244
390
  </div>
245
391
 
246
392
  <div class="copio-camera-feed" id="camera-feed">
247
- <video id="camera-video" autoplay playsinline muted style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit:cover; z-index:0;"></video>
393
+ <video id="camera-video" autoplay playsinline webkit-playsinline muted style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit:cover; z-index:0;"></video>
394
+ <svg class="copio-live-quad-overlay" id="live-quad-overlay" style="display:none;" aria-hidden="true">
395
+ <polygon class="copio-live-quad-polygon" id="live-quad-polygon" points=""></polygon>
396
+ <circle class="copio-live-quad-corner" id="live-quad-c0" r="5"></circle>
397
+ <circle class="copio-live-quad-corner" id="live-quad-c1" r="5"></circle>
398
+ <circle class="copio-live-quad-corner" id="live-quad-c2" r="5"></circle>
399
+ <circle class="copio-live-quad-corner" id="live-quad-c3" r="5"></circle>
400
+ </svg>
248
401
  <slot name="viewfinder">
249
402
  <div class="copio-framing-guide" id="framing-guide" data-aspect="${this.aspect}">
250
403
  <span class="copio-corner tl"></span>
@@ -385,6 +538,37 @@ export class CopioScanner extends BaseElement {
385
538
  <div class="copio-toast-region" id="toast-region" aria-live="polite"></div>
386
539
  </div>
387
540
 
541
+ <!-- Mobile Handoff Progress Overlay -->
542
+ <div class="copio-handoff-progress-view" id="handoff-progress-view" style="display: none;" part="handoff-progress">
543
+ <div class="copio-handoff-progress-card">
544
+ <div class="copio-handoff-spinner"></div>
545
+ <h4 class="copio-handoff-progress-title" id="handoff-progress-title">Sending to your computer…</h4>
546
+ <div class="copio-handoff-progress-track">
547
+ <div class="copio-handoff-progress-bar" id="handoff-progress-bar" style="width: 0%;"></div>
548
+ </div>
549
+ <p class="copio-handoff-progress-desc" id="handoff-progress-desc">Encrypting and streaming pages…</p>
550
+ </div>
551
+ </div>
552
+
553
+ <!-- Mobile Handoff Confirmation Screen (CPO-094) -->
554
+ <div class="copio-handoff-confirm" id="handoff-confirm-view" style="display: none;" part="handoff-confirm">
555
+ <div class="copio-handoff-confirm-card">
556
+ <div class="copio-handoff-confirm-icon">
557
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
558
+ <path d="M20 6L9 17l-5-5"/>
559
+ </svg>
560
+ </div>
561
+ <h3 class="copio-handoff-confirm-title">Sent to your computer</h3>
562
+ <p class="copio-handoff-confirm-subtitle">You can close this tab now.</p>
563
+ <div class="copio-handoff-confirm-badge" id="handoff-confirm-count">1 page transferred</div>
564
+ <div class="copio-handoff-confirm-actions">
565
+ <button type="button" class="copio-btn copio-btn-secondary" id="btn-handoff-scan-more">
566
+ Scan More Documents
567
+ </button>
568
+ </div>
569
+ </div>
570
+ </div>
571
+
388
572
  <!-- Hidden input for file picker fallback -->
389
573
  <input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
390
574
  <slot></slot>
@@ -425,6 +609,14 @@ export class CopioScanner extends BaseElement {
425
609
  await this.#handleShutterClick();
426
610
  });
427
611
 
612
+ // Tap to start camera from placeholder or camera feed in standby
613
+ shadow.getElementById('camera-feed')?.addEventListener('click', async (e) => {
614
+ if (e.target && /** @type {HTMLElement} */ (e.target).closest('button, input, a, select')) return;
615
+ if (!this.#cameraStream && this.#stage === 'viewfinder') {
616
+ await this.startCamera().catch(() => {});
617
+ }
618
+ });
619
+
428
620
  // Review pill
429
621
  shadow.getElementById('btn-review')?.addEventListener('click', () => {
430
622
  this.stage = 'workbench';
@@ -465,6 +657,14 @@ export class CopioScanner extends BaseElement {
465
657
  await this.#handlePrimaryCtaClick();
466
658
  });
467
659
 
660
+ // Handoff buttons
661
+ shadow.getElementById('btn-handoff-retry')?.addEventListener('click', () => {
662
+ this.reconnectHandoff().catch(() => {});
663
+ });
664
+ shadow.getElementById('btn-handoff-scan-more')?.addEventListener('click', async () => {
665
+ await this.resetHandoff();
666
+ });
667
+
468
668
  // Card switcher buttons
469
669
  shadow.getElementById('btn-card-front')?.addEventListener('click', () => {
470
670
  this.#cropMode = false;
@@ -486,24 +686,77 @@ export class CopioScanner extends BaseElement {
486
686
  const shadow = this.shadowRoot;
487
687
  if (!shadow) return;
488
688
 
489
- const cropBox = shadow.getElementById('crop-box');
689
+ const quadOutline = shadow.getElementById('crop-quad-outline');
490
690
  const handles = shadow.querySelectorAll('.copio-crop-handle');
491
- if (!cropBox || handles.length === 0) return;
691
+ if (!quadOutline || handles.length === 0) return;
492
692
 
493
- let activeHandle = null;
494
- let isDraggingBox = false;
693
+ let activeCorner = null;
694
+ let isDraggingQuad = false;
495
695
  let startX = 0;
496
696
  let startY = 0;
497
- let initialCrop = null;
697
+ let initialQuad = null;
698
+
699
+ const updateMagnifier = (normX, normY) => {
700
+ const mag = /** @type {HTMLCanvasElement|null} */ (shadow.getElementById('crop-magnifier'));
701
+ const stageImg = /** @type {HTMLImageElement|null} */ (shadow.getElementById('stage-img'));
702
+ if (!mag || !stageImg || !stageImg.complete || !stageImg.naturalWidth) return;
703
+
704
+ mag.style.display = 'block';
705
+ mag.style.left = `${(normX * 100).toFixed(2)}%`;
706
+ mag.style.top = `${(normY * 100).toFixed(2)}%`;
707
+ mag.style.transform = normY < 0.25 ? 'translate(-50%, 35%)' : 'translate(-50%, -125%)';
708
+
709
+ const mCtx = mag.getContext('2d');
710
+ if (!mCtx) return;
711
+ const zoom = 2;
712
+ const w = mag.width;
713
+ const h = mag.height;
714
+ const srcW = stageImg.naturalWidth;
715
+ const srcH = stageImg.naturalHeight;
716
+ const sampleW = w / zoom;
717
+ const sampleH = h / zoom;
718
+ const cx = normX * srcW;
719
+ const cy = normY * srcH;
720
+
721
+ mCtx.clearRect(0, 0, w, h);
722
+ mCtx.fillStyle = '#0b0f17';
723
+ mCtx.fillRect(0, 0, w, h);
724
+ mCtx.drawImage(
725
+ stageImg,
726
+ cx - sampleW / 2,
727
+ cy - sampleH / 2,
728
+ sampleW,
729
+ sampleH,
730
+ 0,
731
+ 0,
732
+ w,
733
+ h,
734
+ );
735
+
736
+ // Crosshair
737
+ mCtx.strokeStyle = 'rgba(56, 189, 248, 0.9)';
738
+ mCtx.lineWidth = 1.5;
739
+ mCtx.beginPath();
740
+ mCtx.moveTo(w / 2 - 10, h / 2);
741
+ mCtx.lineTo(w / 2 + 10, h / 2);
742
+ mCtx.moveTo(w / 2, h / 2 - 10);
743
+ mCtx.lineTo(w / 2, h / 2 + 10);
744
+ mCtx.stroke();
745
+ };
746
+
747
+ const hideMagnifier = () => {
748
+ const mag = shadow.getElementById('crop-magnifier');
749
+ if (mag) mag.style.display = 'none';
750
+ };
498
751
 
499
752
  const onPointerDown = (e) => {
500
753
  const handleEl = e.target.closest('.copio-crop-handle');
501
754
  if (handleEl) {
502
- activeHandle = handleEl.getAttribute('data-handle');
503
- isDraggingBox = false;
504
- } else if (e.target === cropBox || e.target.classList.contains('copio-crop-grid')) {
505
- activeHandle = null;
506
- isDraggingBox = true;
755
+ activeCorner = handleEl.getAttribute('data-corner');
756
+ isDraggingQuad = false;
757
+ } else if (e.target === quadOutline) {
758
+ activeCorner = null;
759
+ isDraggingQuad = true;
507
760
  } else {
508
761
  return;
509
762
  }
@@ -513,57 +766,73 @@ export class CopioScanner extends BaseElement {
513
766
 
514
767
  startX = e.clientX;
515
768
  startY = e.clientY;
516
- initialCrop = this.#draftCrop ? { ...this.#draftCrop } : { x: 0.05, y: 0.05, w: 0.9, h: 0.9 };
769
+ initialQuad = this.#draftQuad
770
+ ? cloneQuad(this.#draftQuad)
771
+ : {
772
+ topLeft: { x: 0.05, y: 0.05 },
773
+ topRight: { x: 0.95, y: 0.05 },
774
+ bottomRight: { x: 0.95, y: 0.95 },
775
+ bottomLeft: { x: 0.05, y: 0.95 },
776
+ };
777
+
778
+ if (activeCorner && initialQuad[activeCorner]) {
779
+ updateMagnifier(initialQuad[activeCorner].x, initialQuad[activeCorner].y);
780
+ }
517
781
 
518
782
  window.addEventListener('pointermove', onPointerMove);
519
783
  window.addEventListener('pointerup', onPointerUp);
520
784
  };
521
785
 
522
786
  const onPointerMove = (e) => {
523
- if ((!activeHandle && !isDraggingBox) || !initialCrop) return;
787
+ if ((!activeCorner && !isDraggingQuad) || !initialQuad) return;
524
788
  const wrapper = shadow.getElementById('canvas-wrapper') || shadow.getElementById('canvas-viewport');
525
789
  const rect = wrapper?.getBoundingClientRect() || { width: 300, height: 400 };
526
790
 
527
791
  const dx = (e.clientX - startX) / Math.max(rect.width, 1);
528
792
  const dy = (e.clientY - startY) / Math.max(rect.height, 1);
529
793
 
530
- let { x, y, w, h } = initialCrop;
531
-
532
- if (isDraggingBox) {
533
- x = Math.min(Math.max(0, x + dx), 1 - w);
534
- y = Math.min(Math.max(0, y + dy), 1 - h);
535
- } else if (activeHandle) {
536
- if (activeHandle.includes('w')) {
537
- const nextX = Math.min(Math.max(0, x + dx), x + w - 0.1);
538
- w += x - nextX;
539
- x = nextX;
540
- }
541
- if (activeHandle.includes('e')) {
542
- w = Math.min(Math.max(0.1, w + dx), 1 - x);
543
- }
544
- if (activeHandle.includes('n')) {
545
- const nextY = Math.min(Math.max(0, y + dy), y + h - 0.1);
546
- h += y - nextY;
547
- y = nextY;
794
+ const nextQuad = cloneQuad(initialQuad);
795
+ const keys = ['topLeft', 'topRight', 'bottomRight', 'bottomLeft'];
796
+
797
+ if (isDraggingQuad) {
798
+ let minDx = -Infinity;
799
+ let maxDx = Infinity;
800
+ let minDy = -Infinity;
801
+ let maxDy = Infinity;
802
+ for (const k of keys) {
803
+ minDx = Math.max(minDx, -initialQuad[k].x);
804
+ maxDx = Math.min(maxDx, 1 - initialQuad[k].x);
805
+ minDy = Math.max(minDy, -initialQuad[k].y);
806
+ maxDy = Math.min(maxDy, 1 - initialQuad[k].y);
548
807
  }
549
- if (activeHandle.includes('s')) {
550
- h = Math.min(Math.max(0.1, h + dy), 1 - y);
808
+ const clampedDx = Math.min(Math.max(dx, minDx), maxDx);
809
+ const clampedDy = Math.min(Math.max(dy, minDy), maxDy);
810
+ for (const k of keys) {
811
+ nextQuad[k].x = initialQuad[k].x + clampedDx;
812
+ nextQuad[k].y = initialQuad[k].y + clampedDy;
551
813
  }
814
+ } else if (activeCorner && nextQuad[activeCorner]) {
815
+ const nx = Math.min(Math.max(0, initialQuad[activeCorner].x + dx), 1);
816
+ const ny = Math.min(Math.max(0, initialQuad[activeCorner].y + dy), 1);
817
+ nextQuad[activeCorner].x = nx;
818
+ nextQuad[activeCorner].y = ny;
819
+ updateMagnifier(nx, ny);
552
820
  }
553
821
 
554
- this.#draftCrop = { x, y, w, h };
822
+ this.#draftQuad = nextQuad;
555
823
  this.#updateCropBoxUi();
556
824
  };
557
825
 
558
826
  const onPointerUp = () => {
559
- activeHandle = null;
560
- isDraggingBox = false;
561
- initialCrop = null;
827
+ activeCorner = null;
828
+ isDraggingQuad = false;
829
+ initialQuad = null;
830
+ hideMagnifier();
562
831
  window.removeEventListener('pointermove', onPointerMove);
563
832
  window.removeEventListener('pointerup', onPointerUp);
564
833
  };
565
834
 
566
- cropBox.addEventListener('pointerdown', onPointerDown);
835
+ quadOutline.addEventListener('pointerdown', onPointerDown);
567
836
  handles.forEach((handle) => {
568
837
  handle.addEventListener('pointerdown', onPointerDown);
569
838
  });
@@ -571,14 +840,48 @@ export class CopioScanner extends BaseElement {
571
840
 
572
841
  #updateCropBoxUi() {
573
842
  const shadow = this.shadowRoot;
574
- if (!shadow || !this.#draftCrop) return;
575
- const cropBox = shadow.getElementById('crop-box');
576
- if (!cropBox) return;
843
+ if (!shadow || !this.#draftQuad) return;
844
+
845
+ const { topLeft: tl, topRight: tr, bottomRight: br, bottomLeft: bl } = this.#draftQuad;
846
+ const p = (pt) => `${(pt.x * 100).toFixed(2)},${(pt.y * 100).toFixed(2)}`;
847
+ const ptsStr = `${p(tl)} ${p(tr)} ${p(br)} ${p(bl)}`;
848
+
849
+ const mask = shadow.getElementById('crop-quad-mask');
850
+ if (mask) {
851
+ mask.setAttribute(
852
+ 'd',
853
+ `M0,0 H100 V100 H0 Z M${(tl.x * 100).toFixed(2)},${(tl.y * 100).toFixed(2)} L${(tr.x * 100).toFixed(2)},${(tr.y * 100).toFixed(2)} L${(br.x * 100).toFixed(2)},${(br.y * 100).toFixed(2)} L${(bl.x * 100).toFixed(2)},${(bl.y * 100).toFixed(2)} Z`,
854
+ );
855
+ }
856
+
857
+ const outline = shadow.getElementById('crop-quad-outline');
858
+ if (outline) {
859
+ outline.setAttribute('points', ptsStr);
860
+ }
577
861
 
578
- cropBox.style.left = `${(this.#draftCrop.x * 100).toFixed(1)}%`;
579
- cropBox.style.top = `${(this.#draftCrop.y * 100).toFixed(1)}%`;
580
- cropBox.style.width = `${(this.#draftCrop.w * 100).toFixed(1)}%`;
581
- cropBox.style.height = `${(this.#draftCrop.h * 100).toFixed(1)}%`;
862
+ // Perspective rule-of-thirds grid lines
863
+ const lerp = (a, b, t) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });
864
+ const setLine = (id, a, b) => {
865
+ const el = shadow.getElementById(id);
866
+ if (!el) return;
867
+ el.setAttribute('x1', (a.x * 100).toFixed(2));
868
+ el.setAttribute('y1', (a.y * 100).toFixed(2));
869
+ el.setAttribute('x2', (b.x * 100).toFixed(2));
870
+ el.setAttribute('y2', (b.y * 100).toFixed(2));
871
+ };
872
+ setLine('crop-grid-v1', lerp(tl, tr, 1 / 3), lerp(bl, br, 1 / 3));
873
+ setLine('crop-grid-v2', lerp(tl, tr, 2 / 3), lerp(bl, br, 2 / 3));
874
+ setLine('crop-grid-h1', lerp(tl, bl, 1 / 3), lerp(tr, br, 1 / 3));
875
+ setLine('crop-grid-h2', lerp(tl, bl, 2 / 3), lerp(tr, br, 2 / 3));
876
+
877
+ const corners = { topLeft: tl, topRight: tr, bottomRight: br, bottomLeft: bl };
878
+ for (const [corner, pt] of Object.entries(corners)) {
879
+ const handle = shadow.querySelector(`.copio-quad-handle[data-corner="${corner}"]`);
880
+ if (handle) {
881
+ /** @type {HTMLElement} */ (handle).style.left = `${(pt.x * 100).toFixed(2)}%`;
882
+ /** @type {HTMLElement} */ (handle).style.top = `${(pt.y * 100).toFixed(2)}%`;
883
+ }
884
+ }
582
885
  }
583
886
 
584
887
  async #syncView() {
@@ -640,7 +943,9 @@ export class CopioScanner extends BaseElement {
640
943
  const stepPillText = shadow.getElementById('step-pill-text');
641
944
  if (stepPillText) {
642
945
  if (this.#cameraStream) {
643
- stepPillText.textContent = 'Camera Active · Tap Shutter to Snap';
946
+ stepPillText.textContent = this.mode === 'batch'
947
+ ? `Batch Capture · Page ${pages.length + 1}`
948
+ : 'Camera Active · Tap Shutter to Snap';
644
949
  } else if (this.aspect === 'card' && this.maxPages === 2) {
645
950
  stepPillText.textContent = pages.length === 0
646
951
  ? 'Step 1 of 2: Capture Front of ID Card'
@@ -736,27 +1041,34 @@ export class CopioScanner extends BaseElement {
736
1041
  cropLayer.className = 'copio-crop-layer';
737
1042
  cropLayer.id = 'crop-layer';
738
1043
  cropLayer.innerHTML = `
739
- <div class="copio-crop-box" id="crop-box">
740
- <div class="copio-crop-grid"></div>
741
- <span class="copio-crop-handle nw" data-handle="nw"></span>
742
- <span class="copio-crop-handle ne" data-handle="ne"></span>
743
- <span class="copio-crop-handle se" data-handle="se"></span>
744
- <span class="copio-crop-handle sw" data-handle="sw"></span>
745
- <span class="copio-crop-handle n edge-n" data-handle="n"></span>
746
- <span class="copio-crop-handle e edge-e" data-handle="e"></span>
747
- <span class="copio-crop-handle s edge-s" data-handle="s"></span>
748
- <span class="copio-crop-handle w edge-w" data-handle="w"></span>
749
- </div>
1044
+ <svg class="copio-crop-quad-svg" id="crop-quad-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
1045
+ <path class="copio-crop-mask" id="crop-quad-mask" fill-rule="evenodd" d=""></path>
1046
+ <line class="copio-crop-quad-grid" id="crop-grid-v1"></line>
1047
+ <line class="copio-crop-quad-grid" id="crop-grid-v2"></line>
1048
+ <line class="copio-crop-quad-grid" id="crop-grid-h1"></line>
1049
+ <line class="copio-crop-quad-grid" id="crop-grid-h2"></line>
1050
+ <polygon class="copio-crop-quad-outline" id="crop-quad-outline" points=""></polygon>
1051
+ </svg>
1052
+ <span class="copio-crop-handle copio-quad-handle" data-corner="topLeft" data-handle="nw"></span>
1053
+ <span class="copio-crop-handle copio-quad-handle" data-corner="topRight" data-handle="ne"></span>
1054
+ <span class="copio-crop-handle copio-quad-handle" data-corner="bottomRight" data-handle="se"></span>
1055
+ <span class="copio-crop-handle copio-quad-handle" data-corner="bottomLeft" data-handle="sw"></span>
1056
+ <canvas class="copio-crop-magnifier" id="crop-magnifier" width="96" height="96"></canvas>
750
1057
  `;
751
1058
  wrapper?.appendChild(cropLayer);
752
1059
  this.#bindCropHandles();
753
1060
  }
754
1061
  cropLayer.style.display = 'block';
755
1062
  const rot = activePage.edits?.rotate || 0;
756
- const priorCrop = activePage.edits?.crop;
757
- this.#draftCrop = priorCrop
758
- ? cropOriginalToRotated(priorCrop, rot)
759
- : { x: 0.05, y: 0.05, w: 0.9, h: 0.9 };
1063
+ const priorQuad =
1064
+ activePage.edits?.quad ||
1065
+ (activePage.edits?.crop ? cropRectToQuad(activePage.edits.crop) : null) || {
1066
+ topLeft: { x: 0.05, y: 0.05 },
1067
+ topRight: { x: 0.95, y: 0.05 },
1068
+ bottomRight: { x: 0.95, y: 0.95 },
1069
+ bottomLeft: { x: 0.05, y: 0.95 },
1070
+ };
1071
+ this.#draftQuad = quadOriginalToRotated(priorQuad, rot);
760
1072
  this.#updateCropBoxUi();
761
1073
  } else if (cropLayer) {
762
1074
  cropLayer.remove();
@@ -771,7 +1083,17 @@ export class CopioScanner extends BaseElement {
771
1083
  // Primary CTA label
772
1084
  const primaryCta = shadow.getElementById('btn-primary-complete');
773
1085
  if (primaryCta) {
774
- if (this.aspect === 'card' && this.maxPages === 2 && pages.length === 1) {
1086
+ if (this.isHandoff) {
1087
+ if (this.aspect === 'card' && this.maxPages === 2 && pages.length === 1) {
1088
+ primaryCta.textContent = 'Next: Capture Back (Step 2/2) →';
1089
+ } else if (this.aspect === 'card' && pages.length >= 2) {
1090
+ primaryCta.textContent = '↑ Send ID Card to Computer (2 Sides)';
1091
+ } else if (this.mode === 'batch') {
1092
+ primaryCta.textContent = `↑ Send ${pages.length} Pages to Computer`;
1093
+ } else {
1094
+ primaryCta.textContent = '↑ Send to Computer';
1095
+ }
1096
+ } else if (this.aspect === 'card' && this.maxPages === 2 && pages.length === 1) {
775
1097
  primaryCta.textContent = 'Next: Capture Back (Step 2/2) →';
776
1098
  } else if (this.aspect === 'card' && pages.length >= 2) {
777
1099
  primaryCta.textContent = '✓ Complete ID Scan (2 Sides)';
@@ -782,6 +1104,9 @@ export class CopioScanner extends BaseElement {
782
1104
  }
783
1105
  }
784
1106
 
1107
+ // Handoff DOM sync
1108
+ this.#syncHandoffDom();
1109
+
785
1110
  // Filmstrip rendering
786
1111
  this.#renderFilmstrip(pages);
787
1112
  } catch {
@@ -848,14 +1173,77 @@ export class CopioScanner extends BaseElement {
848
1173
  this.#syncView();
849
1174
  }
850
1175
 
1176
+ #showToast(message, variant = 'warning', duration = 4000) {
1177
+ try {
1178
+ if (typeof notify !== 'undefined') {
1179
+ const container = this.shadowRoot?.querySelector('.copio-scanner-container') || this;
1180
+ if (variant === 'warning' && typeof notify.warning === 'function') {
1181
+ notify.warning(message, { container });
1182
+ } else if (typeof notify.info === 'function') {
1183
+ notify.info(message, { container });
1184
+ }
1185
+ }
1186
+ } catch {}
1187
+
1188
+ const shadow = this.shadowRoot;
1189
+ const toastRegion = shadow?.getElementById('toast-region');
1190
+ if (!toastRegion) return;
1191
+
1192
+ const toastEl = document.createElement('div');
1193
+ toastEl.className = `copio-toast copio-toast-${variant}`;
1194
+ toastEl.setAttribute('role', 'alert');
1195
+ toastEl.innerHTML = `<span class="copio-toast-msg">${message}</span>`;
1196
+ toastRegion.appendChild(toastEl);
1197
+
1198
+ setTimeout(() => {
1199
+ toastEl.classList.add('copio-toast-fade-out');
1200
+ setTimeout(() => {
1201
+ toastEl.remove();
1202
+ }, 250);
1203
+ }, duration);
1204
+ }
1205
+
1206
+ #handleCameraFailure(error, message) {
1207
+ const isDenied = error?.name === 'NotAllowedError' || error?.name === 'PermissionDeniedError';
1208
+ const code = isDenied ? 'CAMERA_PERMISSION_DENIED' : 'CAMERA_UNAVAILABLE';
1209
+
1210
+ this.#showToast(message, 'warning');
1211
+
1212
+ const stepPillText = this.shadowRoot?.getElementById('step-pill-text');
1213
+ if (stepPillText) {
1214
+ stepPillText.textContent = 'Camera Unavailable · Select File';
1215
+ }
1216
+
1217
+ this.dispatch(COPIO_EVENTS.ERROR, {
1218
+ code,
1219
+ message,
1220
+ error,
1221
+ });
1222
+
1223
+ const fileInput = this.shadowRoot?.getElementById('internal-file-input');
1224
+ if (fileInput && typeof fileInput.click === 'function') {
1225
+ fileInput.click();
1226
+ }
1227
+ }
1228
+
851
1229
  #stopCameraStream() {
1230
+ this.#stopLiveEdgeDetection();
1231
+ this.#hideLiveQuadOverlay();
852
1232
  if (this.#cameraStream) {
853
- this.#cameraStream.getTracks().forEach((track) => track.stop());
1233
+ try {
1234
+ const tracks = this.#cameraStream.getTracks();
1235
+ for (const track of tracks) {
1236
+ track.stop();
1237
+ }
1238
+ } catch {}
854
1239
  this.#cameraStream = null;
855
1240
  }
856
1241
  const shadow = this.shadowRoot;
857
1242
  const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
858
1243
  if (videoEl) {
1244
+ try {
1245
+ videoEl.pause();
1246
+ } catch {}
859
1247
  videoEl.srcObject = null;
860
1248
  videoEl.style.display = 'none';
861
1249
  }
@@ -863,6 +1251,359 @@ export class CopioScanner extends BaseElement {
863
1251
  if (placeholder) {
864
1252
  /** @type {HTMLElement} */ (placeholder).style.display = '';
865
1253
  }
1254
+ const stepPillText = shadow?.getElementById('step-pill-text');
1255
+ if (stepPillText && this.#stage === 'viewfinder') {
1256
+ stepPillText.textContent = this.mode === 'batch'
1257
+ ? `Batch Capture · Page ${this.#pageCount + 1}`
1258
+ : 'Align Document Inside Frame';
1259
+ }
1260
+ }
1261
+
1262
+ async startCamera(options = {}) {
1263
+ const shadow = this.shadowRoot;
1264
+ const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
1265
+ if (!videoEl) return null;
1266
+
1267
+ if (this.#cameraStream) {
1268
+ return this.#cameraStream;
1269
+ }
1270
+
1271
+ const isAutomatedTest =
1272
+ typeof window !== 'undefined' &&
1273
+ /** @type {any} */ (window).__WTR_CONFIG__ !== undefined &&
1274
+ typeof navigator !== 'undefined' &&
1275
+ navigator.webdriver === true &&
1276
+ !options.force;
1277
+ if (isAutomatedTest) {
1278
+ return null;
1279
+ }
1280
+
1281
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
1282
+ this.#handleCameraFailure(new Error('NO_CAMERA_SUPPORT'), 'No camera found. Choose a photo from your files instead.');
1283
+ return null;
1284
+ }
1285
+
1286
+ const constraintTiers = [
1287
+ {
1288
+ video: {
1289
+ facingMode: { ideal: 'environment' },
1290
+ width: { ideal: 1280 },
1291
+ height: { ideal: 720 },
1292
+ },
1293
+ audio: false,
1294
+ },
1295
+ {
1296
+ video: {
1297
+ facingMode: { ideal: 'environment' },
1298
+ },
1299
+ audio: false,
1300
+ },
1301
+ {
1302
+ video: {
1303
+ width: { ideal: 1280 },
1304
+ },
1305
+ audio: false,
1306
+ },
1307
+ {
1308
+ video: true,
1309
+ audio: false,
1310
+ },
1311
+ ];
1312
+
1313
+ let stream = null;
1314
+ let lastError = null;
1315
+
1316
+ for (const constraints of constraintTiers) {
1317
+ try {
1318
+ stream = await navigator.mediaDevices.getUserMedia(constraints);
1319
+ if (stream) break;
1320
+ } catch (err) {
1321
+ lastError = err;
1322
+ if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
1323
+ break;
1324
+ }
1325
+ }
1326
+ }
1327
+
1328
+ if (!stream) {
1329
+ const isDenied = lastError?.name === 'NotAllowedError' || lastError?.name === 'PermissionDeniedError';
1330
+ const msg = isDenied
1331
+ ? 'Camera permission denied. Choose a photo from your files instead.'
1332
+ : 'Camera unavailable. Choose a photo from your files instead.';
1333
+ this.#handleCameraFailure(lastError || new Error('CAMERA_UNAVAILABLE'), msg);
1334
+ return null;
1335
+ }
1336
+
1337
+ this.setCameraStream(stream);
1338
+ return stream;
1339
+ }
1340
+
1341
+ stopCamera() {
1342
+ this.#stopCameraStream();
1343
+ }
1344
+
1345
+ /**
1346
+ * Internal hook for auto edge detection (CPO-074 / CPO-076).
1347
+ * Grabs the current frame from the active camera video element as an ImageData or Canvas.
1348
+ * Not exposed in the stable public API docs.
1349
+ *
1350
+ * @param {Object} [options]
1351
+ * @param {number} [options.maxWidth=640] - Downscale max width for lightweight processing
1352
+ * @param {number} [options.maxHeight=480] - Downscale max height for lightweight processing
1353
+ * @param {'imageData'|'canvas'} [options.format='imageData']
1354
+ * @returns {ImageData|HTMLCanvasElement|null}
1355
+ */
1356
+ _grabFrame(options = {}) {
1357
+ const shadow = this.shadowRoot;
1358
+ const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
1359
+ if (!this.#cameraStream || !videoEl) {
1360
+ return null;
1361
+ }
1362
+
1363
+ const srcW = videoEl.videoWidth || 640;
1364
+ const srcH = videoEl.videoHeight || 480;
1365
+ if (srcW === 0 || srcH === 0) return null;
1366
+
1367
+ const maxWidth = options.maxWidth || 640;
1368
+ const maxHeight = options.maxHeight || 480;
1369
+ const scale = Math.min(1, maxWidth / srcW, maxHeight / srcH);
1370
+ const targetW = Math.max(1, Math.round(srcW * scale));
1371
+ const targetH = Math.max(1, Math.round(srcH * scale));
1372
+
1373
+ if (!this.#grabCanvas && typeof document !== 'undefined') {
1374
+ this.#grabCanvas = document.createElement('canvas');
1375
+ }
1376
+ if (!this.#grabCanvas) return null;
1377
+
1378
+ this.#grabCanvas.width = targetW;
1379
+ this.#grabCanvas.height = targetH;
1380
+ const ctx = this.#grabCanvas.getContext('2d', { willReadFrequently: true });
1381
+ if (!ctx) return null;
1382
+
1383
+ try {
1384
+ ctx.drawImage(videoEl, 0, 0, targetW, targetH);
1385
+ } catch {
1386
+ ctx.fillStyle = '#334155';
1387
+ ctx.fillRect(0, 0, targetW, targetH);
1388
+ }
1389
+ if (options.format === 'canvas') {
1390
+ return this.#grabCanvas;
1391
+ }
1392
+ return ctx.getImageData(0, 0, targetW, targetH);
1393
+ }
1394
+
1395
+ /**
1396
+ * Internal inspection helper for test suites and adapter readiness.
1397
+ * @returns {boolean}
1398
+ */
1399
+ _isCameraActive() {
1400
+ return Boolean(this.#cameraStream);
1401
+ }
1402
+
1403
+ #startLiveEdgeDetection() {
1404
+ this.#stopLiveEdgeDetection();
1405
+ if (!this.#edgeDetection || !this.#cameraStream || this.#stage !== 'viewfinder') {
1406
+ return;
1407
+ }
1408
+
1409
+ const loop = async (timestamp) => {
1410
+ if (!this.#cameraStream || this.#stage !== 'viewfinder' || !this.#edgeDetection) {
1411
+ this.#stopLiveEdgeDetection();
1412
+ return;
1413
+ }
1414
+
1415
+ const elapsed = timestamp - this.#lastEdgeDetectTime;
1416
+ if (!this.#isDetectingEdge && elapsed >= 100) {
1417
+ this.#lastEdgeDetectTime = timestamp;
1418
+ await this.#processLiveViewfinderFrame(timestamp);
1419
+ }
1420
+
1421
+ if (this.#cameraStream && this.#stage === 'viewfinder' && this.#edgeDetection) {
1422
+ this.#liveEdgeRafId = requestAnimationFrame(loop);
1423
+ }
1424
+ };
1425
+
1426
+ this.#liveEdgeRafId = requestAnimationFrame(loop);
1427
+ }
1428
+
1429
+ #stopLiveEdgeDetection() {
1430
+ if (this.#liveEdgeRafId !== null) {
1431
+ cancelAnimationFrame(this.#liveEdgeRafId);
1432
+ this.#liveEdgeRafId = null;
1433
+ }
1434
+ this.#isDetectingEdge = false;
1435
+ }
1436
+
1437
+ #hideLiveQuadOverlay() {
1438
+ const shadow = this.shadowRoot;
1439
+ const svg = shadow?.getElementById('live-quad-overlay');
1440
+ if (svg) {
1441
+ svg.style.display = 'none';
1442
+ }
1443
+ const feed = shadow?.getElementById('camera-feed');
1444
+ if (feed) {
1445
+ feed.classList.remove('is-detected', 'is-tracking');
1446
+ }
1447
+ const polygon = shadow?.getElementById('live-quad-polygon');
1448
+ if (polygon) {
1449
+ polygon.setAttribute('points', '');
1450
+ }
1451
+ for (let i = 0; i < 4; i++) {
1452
+ const c = shadow?.getElementById(`live-quad-c${i}`);
1453
+ if (c) {
1454
+ c.removeAttribute('cx');
1455
+ c.removeAttribute('cy');
1456
+ }
1457
+ }
1458
+ this.#smoothedQuad = null;
1459
+ this.#latestDetectionResult = null;
1460
+ this.#consecutiveMisses = 0;
1461
+ this.#lastValidDetectionTime = 0;
1462
+ this.#stableQuadStartTime = 0;
1463
+ this.#lastStableQuad = null;
1464
+ }
1465
+
1466
+ #renderLiveQuadOverlay(quad, confidence) {
1467
+ const shadow = this.shadowRoot;
1468
+ const svg = shadow?.getElementById('live-quad-overlay');
1469
+ const feed = shadow?.getElementById('camera-feed');
1470
+ const v = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
1471
+ if (!svg || !feed || !quad) return;
1472
+ const fW = feed.clientWidth, fH = feed.clientHeight;
1473
+ if (fW <= 0 || fH <= 0) return;
1474
+ const vW = v?.videoWidth || 640, vH = v?.videoHeight || 480;
1475
+ const s = Math.max(fW / vW, fH / vH), rW = vW * s, rH = vH * s;
1476
+ const ox = (fW - rW) / 2, oy = (fH - rH) / 2;
1477
+ const corners = [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft];
1478
+ const pts = corners.map(
1479
+ (p) => `${(ox + p.x * rW).toFixed(1)},${(oy + p.y * rH).toFixed(1)}`
1480
+ );
1481
+ svg.setAttribute('viewBox', `0 0 ${fW} ${fH}`);
1482
+ svg.style.display = 'block';
1483
+ shadow.getElementById('live-quad-polygon')?.setAttribute('points', pts.join(' '));
1484
+ for (let i = 0; i < 4; i++) {
1485
+ const c = shadow.getElementById(`live-quad-c${i}`);
1486
+ if (c) {
1487
+ c.setAttribute('cx', (ox + corners[i].x * rW).toFixed(1));
1488
+ c.setAttribute('cy', (oy + corners[i].y * rH).toFixed(1));
1489
+ }
1490
+ }
1491
+ feed.classList.add('is-tracking');
1492
+ feed.classList.toggle('is-detected', confidence >= 0.70);
1493
+ }
1494
+
1495
+ async #processLiveViewfinderFrame(timestamp) {
1496
+ const shadow = this.shadowRoot;
1497
+ const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
1498
+ if (!videoEl || videoEl.videoWidth === 0 || videoEl.videoHeight === 0) return;
1499
+
1500
+ const frame = this._grabFrame({ maxWidth: 480, maxHeight: 480 });
1501
+ if (!frame) return;
1502
+
1503
+ this.#isDetectingEdge = true;
1504
+ try {
1505
+ const edgeService = this.#engine?.getService('edge') || getRegisteredService('edge');
1506
+ if (!edgeService || typeof edgeService.detect !== 'function') return;
1507
+
1508
+ const minConfidence = this.#edgeModel === 'ml' ? 0.40 : 0.45;
1509
+ const result = await edgeService.detect(frame, {
1510
+ maxProcessingDimension: 480,
1511
+ enableDetectionCascade: false,
1512
+ minConfidence,
1513
+ fallbackOnLowConfidence: false,
1514
+ detector: this.#edgeModel,
1515
+ ml: { minScore: minConfidence },
1516
+ });
1517
+
1518
+ if (!this.#cameraStream || this.#stage !== 'viewfinder' || !this.#edgeDetection) return;
1519
+
1520
+ if (result && result.quad && result.confidence >= minConfidence && !result.isFallback) {
1521
+ this.#consecutiveMisses = 0;
1522
+ this.#lastValidDetectionTime = timestamp;
1523
+ const alpha = 0.35;
1524
+ if (!this.#smoothedQuad) {
1525
+ this.#smoothedQuad = cloneQuad(result.quad);
1526
+ } else {
1527
+ for (const k of ['topLeft', 'topRight', 'bottomRight', 'bottomLeft']) {
1528
+ this.#smoothedQuad[k].x = alpha * result.quad[k].x + (1 - alpha) * this.#smoothedQuad[k].x;
1529
+ this.#smoothedQuad[k].y = alpha * result.quad[k].y + (1 - alpha) * this.#smoothedQuad[k].y;
1530
+ }
1531
+ }
1532
+
1533
+ this.#latestDetectionResult = {
1534
+ quad: cloneQuad(this.#smoothedQuad),
1535
+ confidence: result.confidence,
1536
+ durationMs: result.durationMs,
1537
+ isFallback: false,
1538
+ };
1539
+
1540
+ this.#renderLiveQuadOverlay(this.#smoothedQuad, result.confidence);
1541
+
1542
+ this.dispatch(COPIO_EVENTS.EDGE_DETECTED, {
1543
+ quad: cloneQuad(this.#smoothedQuad),
1544
+ confidence: result.confidence,
1545
+ durationMs: result.durationMs,
1546
+ });
1547
+
1548
+ if (this.#autoCapture && result.confidence >= 0.65) {
1549
+ this.#checkSmartShutter(this.#smoothedQuad, timestamp);
1550
+ }
1551
+ } else {
1552
+ this.#consecutiveMisses++;
1553
+ if (this.#consecutiveMisses > 4 && timestamp - this.#lastValidDetectionTime > 1200) {
1554
+ this.#smoothedQuad = null;
1555
+ this.#latestDetectionResult = null;
1556
+ this.#stableQuadStartTime = 0;
1557
+ this.#hideLiveQuadOverlay();
1558
+ }
1559
+ }
1560
+ } catch (err) {
1561
+ if (typeof console !== 'undefined' && console.warn) {
1562
+ console.warn('[CopioScanner] Live edge detection error:', err);
1563
+ }
1564
+ } finally {
1565
+ this.#isDetectingEdge = false;
1566
+ }
1567
+ }
1568
+
1569
+ #checkSmartShutter(quad, timestamp) {
1570
+ if (!this.#autoCapture || !quad) return;
1571
+ const pts = [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft];
1572
+ let area = 0;
1573
+ for (let i = 0; i < 4; i++) {
1574
+ const j = (i + 1) % 4;
1575
+ area += pts[i].x * pts[j].y - pts[j].x * pts[i].y;
1576
+ }
1577
+ area = Math.abs(area) / 2;
1578
+ if (area < 0.15) {
1579
+ this.#stableQuadStartTime = 0;
1580
+ this.#lastStableQuad = null;
1581
+ return;
1582
+ }
1583
+
1584
+ if (!this.#lastStableQuad) {
1585
+ this.#lastStableQuad = cloneQuad(quad);
1586
+ this.#stableQuadStartTime = timestamp;
1587
+ return;
1588
+ }
1589
+
1590
+ let sumSq = 0;
1591
+ for (const k of ['topLeft', 'topRight', 'bottomRight', 'bottomLeft']) {
1592
+ const dx = quad[k].x - this.#lastStableQuad[k].x;
1593
+ const dy = quad[k].y - this.#lastStableQuad[k].y;
1594
+ sumSq += dx * dx + dy * dy;
1595
+ }
1596
+ const rmsJitter = Math.sqrt(sumSq / 4);
1597
+ this.#lastStableQuad = cloneQuad(quad);
1598
+
1599
+ if (rmsJitter < 0.015) {
1600
+ if (timestamp - this.#stableQuadStartTime >= 600) {
1601
+ this.#stableQuadStartTime = timestamp + 10000; // Cooldown
1602
+ this.#handleShutterClick();
1603
+ }
1604
+ } else {
1605
+ this.#stableQuadStartTime = timestamp;
1606
+ }
866
1607
  }
867
1608
 
868
1609
  async #handleShutterClick() {
@@ -875,46 +1616,62 @@ export class CopioScanner extends BaseElement {
875
1616
  const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
876
1617
 
877
1618
  // If camera stream is already active, capture a frame from the video element
878
- if (this.#cameraStream && videoEl && videoEl.readyState >= 2) {
1619
+ if (this.#cameraStream && videoEl) {
1620
+ const cameraFeed = shadow?.getElementById('camera-feed');
1621
+ if (cameraFeed) {
1622
+ cameraFeed.classList.remove('is-shutter-flash');
1623
+ void cameraFeed.offsetWidth;
1624
+ cameraFeed.classList.add('is-shutter-flash');
1625
+ }
1626
+
1627
+ // Cache current live tracked quad at snapshot time
1628
+ const minConfidence = this.#edgeModel === 'ml' ? 0.40 : 0.45;
1629
+ const captureQuad = this.#latestDetectionResult?.confidence >= minConfidence
1630
+ ? cloneQuad(this.#latestDetectionResult.quad)
1631
+ : null;
1632
+
879
1633
  const canvas = document.createElement('canvas');
880
1634
  canvas.width = videoEl.videoWidth || 1280;
881
1635
  canvas.height = videoEl.videoHeight || 720;
882
1636
  const ctx = canvas.getContext('2d');
883
1637
  if (ctx) {
884
- ctx.drawImage(videoEl, 0, 0, canvas.width, canvas.height);
1638
+ try {
1639
+ ctx.drawImage(videoEl, 0, 0, canvas.width, canvas.height);
1640
+ } catch {
1641
+ ctx.fillStyle = '#334155';
1642
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
1643
+ }
885
1644
  const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.92));
1645
+ canvas.width = 0;
1646
+ canvas.height = 0;
1647
+
886
1648
  if (blob) {
887
- this.#stopCameraStream();
1649
+ const isBatch = this.mode === 'batch';
1650
+ if (!isBatch) {
1651
+ this.#stopCameraStream();
1652
+ }
1653
+
888
1654
  const file = new File([blob], `capture_${Date.now()}.jpg`, { type: 'image/jpeg' });
889
- await this.addFiles([file]);
1655
+ await this.addFiles([file], { prefilledQuad: captureQuad });
1656
+
1657
+ if (!isBatch && captureQuad && this.#autoCrop && this.features.includes('crop')) {
1658
+ this.#cropMode = true;
1659
+ await this.#syncView();
1660
+ }
1661
+
1662
+ if (isBatch && this.maxPages > 0 && this.#pageCount >= this.maxPages) {
1663
+ this.#stopCameraStream();
1664
+ this.stage = 'workbench';
1665
+ }
890
1666
  return;
891
1667
  }
892
1668
  }
893
1669
  }
894
1670
 
895
- // Try opening live MediaDevices camera stream if supported in real browsers
896
- const isAutomatedTest = typeof navigator !== 'undefined' && navigator.webdriver === true;
897
- if (!isAutomatedTest && typeof navigator !== 'undefined' && navigator.mediaDevices?.getUserMedia && videoEl) {
898
- try {
899
- this.#cameraStream = await navigator.mediaDevices.getUserMedia({
900
- video: { facingMode: { ideal: 'environment' }, width: { ideal: 1920 }, height: { ideal: 1080 } },
901
- audio: false,
902
- });
903
- videoEl.srcObject = this.#cameraStream;
904
- videoEl.style.display = 'block';
905
- await videoEl.play();
906
- const placeholder = shadow?.querySelector('.copio-camera-placeholder');
907
- if (placeholder) {
908
- /** @type {HTMLElement} */ (placeholder).style.display = 'none';
909
- }
910
- const stepPillText = shadow?.getElementById('step-pill-text');
911
- if (stepPillText) {
912
- stepPillText.textContent = 'Camera Active · Tap Shutter to Snap';
913
- }
914
- return;
915
- } catch {
916
- // Fallback to file input if camera permission denied or unavailable
917
- }
1671
+ // Try opening live MediaDevices camera stream
1672
+ const stream = await this.startCamera();
1673
+ if (stream) {
1674
+ return;
918
1675
  }
919
1676
 
920
1677
  const fileInput = shadow?.getElementById('internal-file-input');
@@ -930,7 +1687,7 @@ export class CopioScanner extends BaseElement {
930
1687
 
931
1688
  if (this.#cropMode) {
932
1689
  this.#cropMode = false;
933
- this.#draftCrop = null;
1690
+ this.#draftQuad = null;
934
1691
  }
935
1692
 
936
1693
  const currentRotate = activePage.edits?.rotate || 0;
@@ -949,7 +1706,7 @@ export class CopioScanner extends BaseElement {
949
1706
 
950
1707
  if (this.#cropMode) {
951
1708
  this.#cropMode = false;
952
- this.#draftCrop = null;
1709
+ this.#draftQuad = null;
953
1710
  }
954
1711
 
955
1712
  const currentFilter = activePage.edits?.filter || 'none';
@@ -968,12 +1725,14 @@ export class CopioScanner extends BaseElement {
968
1725
 
969
1726
  if (this.#cropMode) {
970
1727
  this.#cropMode = false;
971
- const draft = this.#draftCrop;
972
- this.#draftCrop = null;
973
- if (draft) {
1728
+ const draftQuad = this.#draftQuad;
1729
+ this.#draftQuad = null;
1730
+ if (draftQuad) {
974
1731
  const rot = activePage.edits?.rotate || 0;
975
- const originalCrop = cropRotatedToOriginal(draft, rot);
1732
+ const originalQuad = quadRotatedToOriginal(draftQuad, rot);
1733
+ const originalCrop = quadToCropRect(originalQuad);
976
1734
  await this.#engine.applyEdit(this.#targetDocId, activePage.id, {
1735
+ quad: originalQuad,
977
1736
  crop: originalCrop,
978
1737
  });
979
1738
  }
@@ -1086,6 +1845,10 @@ export class CopioScanner extends BaseElement {
1086
1845
  }
1087
1846
 
1088
1847
  async #handlePrimaryCtaClick() {
1848
+ if (this.#cropMode) {
1849
+ await this.#toggleCropMode();
1850
+ }
1851
+
1089
1852
  if (this.aspect === 'card' && this.maxPages === 2 && this.#pageCount === 1) {
1090
1853
  this.stage = 'viewfinder';
1091
1854
  return;
@@ -1128,9 +1891,441 @@ export class CopioScanner extends BaseElement {
1128
1891
  }
1129
1892
  }
1130
1893
 
1894
+ // If mobile handoff sender mode is active, stream pages over HandoffSession
1895
+ if (this.isHandoff && this.#handoffSession) {
1896
+ await this.#streamHandoffPages(summarizedPages, payload);
1897
+ return;
1898
+ }
1899
+
1131
1900
  this.dispatch(COPIO_EVENTS.SCAN_COMPLETE, payload);
1132
1901
  }
1133
1902
 
1903
+ async completeScan() {
1904
+ return this.#handlePrimaryCtaClick();
1905
+ }
1906
+
1907
+ // --- Configuration Properties (CPO-034, CPO-035, CPO-038) ---
1908
+
1909
+ /**
1910
+ * @returns {string|null}
1911
+ */
1912
+ get handoff() {
1913
+ return typeof this.getAttribute === 'function' ? this.getAttribute('handoff') : null;
1914
+ }
1915
+
1916
+ /**
1917
+ * @param {string|boolean|null} val
1918
+ */
1919
+ set handoff(val) {
1920
+ if (typeof this.setAttribute === 'function') {
1921
+ if (val != null && (typeof val !== 'boolean' || val === true)) {
1922
+ this.setAttribute('handoff', typeof val === 'string' ? val : '');
1923
+ } else {
1924
+ this.removeAttribute('handoff');
1925
+ }
1926
+ }
1927
+ }
1928
+
1929
+ get isHandoff() {
1930
+ return this.#isHandoffMode();
1931
+ }
1932
+
1933
+ get handoffSession() {
1934
+ return this.#handoffSession;
1935
+ }
1936
+
1937
+ get handoffState() {
1938
+ return this.#handoffState;
1939
+ }
1940
+
1941
+ get handoffProgress() {
1942
+ return this.#handoffProgress;
1943
+ }
1944
+
1945
+ get handoffRetryCount() {
1946
+ return this.#handoffRetryCount;
1947
+ }
1948
+
1949
+ /**
1950
+ * Attaches an existing HandoffSession (e.g. LoopbackTransport in automated tests).
1951
+ * @param {HandoffSession} session
1952
+ * @param {Object} [token]
1953
+ */
1954
+ attachHandoffSession(session, token = null) {
1955
+ this.#cleanupHandoff();
1956
+ this.#handoffSession = session;
1957
+ this.#handoffToken = token || session?.token || null;
1958
+ this.#bindHandoffSessionEvents(session);
1959
+ this.#handoffState = session.isConnected ? 'connected' : (session.state === 'idle' ? 'connecting' : session.state);
1960
+ this.#syncHandoffDom();
1961
+ }
1962
+
1963
+ /**
1964
+ * Reconnects to desktop host session.
1965
+ */
1966
+ async reconnectHandoff() {
1967
+ if (!this.#handoffSession || !this.#handoffToken) return;
1968
+ if (this.#handoffState === 'complete' || this.#handoffState === 'connecting') return;
1969
+
1970
+ this.#handoffRetryCount++;
1971
+ this.#handoffState = 'reconnecting';
1972
+ this.#syncHandoffDom();
1973
+
1974
+ try {
1975
+ if (LoopbackTransport.has(this.#handoffToken.peerId)) {
1976
+ const linked = LoopbackTransport.createLinkedSender(this.#handoffToken.peerId);
1977
+ await this.#handoffSession.reconnect(linked);
1978
+ } else {
1979
+ await this.#handoffSession.reconnect();
1980
+ }
1981
+ } catch (err) {
1982
+ console.warn('[CopioScanner] Handoff reconnect failed:', err);
1983
+ this.#handoffState = 'disconnected';
1984
+ this.#syncHandoffDom(err?.message || 'Reconnection failed');
1985
+ }
1986
+ }
1987
+
1988
+ /**
1989
+ * Resets handoff sender view and confirmation screen to allow scanning more documents.
1990
+ */
1991
+ async resetHandoff() {
1992
+ this.#handoffState = this.#handoffSession?.isConnected ? 'connected' : 'idle';
1993
+ this.#handoffProgress = null;
1994
+ const shadow = this.shadowRoot;
1995
+ if (shadow) {
1996
+ const confirmView = shadow.getElementById('handoff-confirm-view');
1997
+ if (confirmView) confirmView.style.display = 'none';
1998
+ const progressView = shadow.getElementById('handoff-progress-view');
1999
+ if (progressView) progressView.style.display = 'none';
2000
+ }
2001
+ await this.clear();
2002
+ this.stage = 'viewfinder';
2003
+ this.#syncHandoffDom();
2004
+ }
2005
+
2006
+ #isHandoffMode() {
2007
+ if (this.#handoffSession) return true;
2008
+ if (typeof this.hasAttribute === 'function' && this.hasAttribute('handoff')) {
2009
+ return this.getAttribute('handoff') !== 'false';
2010
+ }
2011
+ if (typeof window !== 'undefined' && window.location?.hash) {
2012
+ return /(?:copio-)?handoff=/.test(window.location.hash);
2013
+ }
2014
+ return false;
2015
+ }
2016
+
2017
+ async #initHandoffMode() {
2018
+ if (this.#handoffSession) return;
2019
+ if (!this.#isHandoffMode()) return;
2020
+
2021
+ let tokenStr = typeof this.getAttribute === 'function' ? this.getAttribute('handoff') : null;
2022
+ if (!tokenStr && typeof window !== 'undefined' && window.location?.hash) {
2023
+ tokenStr = window.location.hash;
2024
+ }
2025
+ if (!tokenStr) return;
2026
+
2027
+ try {
2028
+ const token = typeof tokenStr === 'string' && tokenStr.includes('#')
2029
+ ? parseHandoffUrl(tokenStr)
2030
+ : decodeSessionToken(tokenStr);
2031
+
2032
+ this.#handoffToken = token;
2033
+ this.#handoffState = 'connecting';
2034
+ this.#syncHandoffDom();
2035
+
2036
+ // Check loopback registry first
2037
+ let transport = null;
2038
+ if (LoopbackTransport.has(token.peerId)) {
2039
+ transport = LoopbackTransport.createLinkedSender(token.peerId);
2040
+ } else {
2041
+ try {
2042
+ const { HandoffPeerTransport } = await import('../js/services/handoff-transport.js');
2043
+ transport = new HandoffPeerTransport({
2044
+ role: 'sender',
2045
+ targetPeerId: token.peerId,
2046
+ relayUrl: token.relayUrl || this.relayUrl,
2047
+ signalingUrl: token.signalingUrl || this.signalingUrl,
2048
+ iceServers: token.iceServers || this.iceServers,
2049
+ iceTransportPolicy: this.iceTransportPolicy,
2050
+ });
2051
+ } catch {
2052
+ transport = new LoopbackTransport();
2053
+ }
2054
+ }
2055
+
2056
+ const session = new HandoffSession({
2057
+ role: 'sender',
2058
+ transport,
2059
+ });
2060
+
2061
+ this.#handoffSession = session;
2062
+ this.#bindHandoffSessionEvents(session);
2063
+ await session.startSender(token);
2064
+ } catch (err) {
2065
+ console.warn('[CopioScanner] Handoff sender init failed:', err);
2066
+ this.#handoffState = 'error';
2067
+ this.#syncHandoffDom(err?.message || 'Connection error');
2068
+ }
2069
+ }
2070
+
2071
+ #bindHandoffSessionEvents(session) {
2072
+ this.#handoffUnsubs.push(
2073
+ session.on('stateChange', (newState) => {
2074
+ if (newState === 'closed') {
2075
+ this.#handoffState = 'disconnected';
2076
+ } else {
2077
+ this.#handoffState = newState;
2078
+ }
2079
+ if (newState === 'connected') {
2080
+ this.#handoffRetryCount = 0;
2081
+ this.dispatch(COPIO_EVENTS.HANDOFF_CONNECTED, {
2082
+ sessionId: this.#handoffToken?.sessionId || '',
2083
+ peerId: this.#handoffToken?.peerId || '',
2084
+ });
2085
+ }
2086
+ this.#syncHandoffDom();
2087
+ }),
2088
+
2089
+ session.on('connectionInfo', (info) => {
2090
+ this.dispatch(COPIO_EVENTS.CONNECTION_INFO, info);
2091
+ }),
2092
+
2093
+ session.on('progress', (progress) => {
2094
+ this.#handoffProgress = progress;
2095
+ this.#updateHandoffProgressDom(progress);
2096
+ }),
2097
+
2098
+ session.on('complete', () => {
2099
+ this.#handoffState = 'complete';
2100
+ this.#syncHandoffDom();
2101
+ }),
2102
+
2103
+ session.on('error', (err) => {
2104
+ console.warn('[CopioScanner] Handoff session error:', err);
2105
+ this.#handoffState = 'error';
2106
+ this.#syncHandoffDom(err?.message || 'Connection error');
2107
+ })
2108
+ );
2109
+ }
2110
+
2111
+ #cleanupHandoff() {
2112
+ for (const unsub of this.#handoffUnsubs) {
2113
+ try {
2114
+ unsub();
2115
+ } catch {
2116
+ // ignore
2117
+ }
2118
+ }
2119
+ this.#handoffUnsubs = [];
2120
+ if (this.#handoffSession) {
2121
+ try {
2122
+ this.#handoffSession.close();
2123
+ } catch {
2124
+ // ignore
2125
+ }
2126
+ this.#handoffSession = null;
2127
+ }
2128
+ this.#handoffToken = null;
2129
+ this.#handoffState = 'idle';
2130
+ this.#handoffProgress = null;
2131
+ }
2132
+
2133
+ #syncHandoffDom(errorMsg = '') {
2134
+ const shadow = this.shadowRoot;
2135
+ if (!shadow) return;
2136
+
2137
+ const pill = shadow.getElementById('handoff-pill');
2138
+ const dot = shadow.getElementById('handoff-dot');
2139
+ const statusText = shadow.getElementById('handoff-status-text');
2140
+ const retryBtn = shadow.getElementById('btn-handoff-retry');
2141
+
2142
+ if (!pill || !dot || !statusText) return;
2143
+
2144
+ if (!this.#isHandoffMode()) {
2145
+ pill.style.display = 'none';
2146
+ return;
2147
+ }
2148
+
2149
+ pill.style.display = 'inline-flex';
2150
+ dot.className = `copio-handoff-dot ${this.#handoffState}`;
2151
+
2152
+ const labels = {
2153
+ connecting: 'Connecting to computer…',
2154
+ connected: 'Paired with computer',
2155
+ reconnecting: 'Reconnecting to computer…',
2156
+ disconnected: 'Disconnected',
2157
+ sending: 'Sending to computer…',
2158
+ complete: 'Sent to computer ✓',
2159
+ error: errorMsg || 'Connection error',
2160
+ };
2161
+ statusText.textContent = labels[this.#handoffState] || 'Desktop Handoff';
2162
+ if (retryBtn) {
2163
+ retryBtn.style.display = (this.#handoffState === 'disconnected' || this.#handoffState === 'error') ? 'inline-block' : 'none';
2164
+ }
2165
+ }
2166
+
2167
+ #updateHandoffProgressDom(progress) {
2168
+ const shadow = this.shadowRoot;
2169
+ if (!shadow || !progress) return;
2170
+ const bar = shadow.getElementById('handoff-progress-bar');
2171
+ const desc = shadow.getElementById('handoff-progress-desc');
2172
+ if (bar && typeof progress.percent === 'number') {
2173
+ bar.style.width = `${progress.percent}%`;
2174
+ }
2175
+ if (desc && progress.bytesSent && progress.totalBytes) {
2176
+ const sentKb = Math.round(progress.bytesSent / 1024);
2177
+ const totalKb = Math.round(progress.totalBytes / 1024);
2178
+ desc.textContent = `Streaming chunks: ${sentKb} KB / ${totalKb} KB (${progress.percent}%)`;
2179
+ }
2180
+ }
2181
+
2182
+ async #streamHandoffPages(pages, payload) {
2183
+ const shadow = this.shadowRoot;
2184
+ const progressView = shadow?.getElementById('handoff-progress-view');
2185
+ const progressBar = shadow?.getElementById('handoff-progress-bar');
2186
+ const progressTitle = shadow?.getElementById('handoff-progress-title');
2187
+ const progressDesc = shadow?.getElementById('handoff-progress-desc');
2188
+
2189
+ if (progressView) progressView.style.display = 'flex';
2190
+
2191
+ this.#handoffState = 'sending';
2192
+ this.#syncHandoffDom();
2193
+
2194
+ try {
2195
+ // 1. Stream each page in chunks
2196
+ for (let idx = 0; idx < pages.length; idx++) {
2197
+ const page = pages[idx];
2198
+ if (progressTitle) {
2199
+ progressTitle.textContent = pages.length > 1
2200
+ ? `Sending page ${idx + 1} of ${pages.length}…`
2201
+ : 'Sending page to computer…';
2202
+ }
2203
+ if (progressDesc) {
2204
+ progressDesc.textContent = 'Encrypting with AES-GCM-256…';
2205
+ }
2206
+
2207
+ const blob = await this.#ensureBlobForPage(page);
2208
+
2209
+ // Send page with retry on connection drop
2210
+ let sent = false;
2211
+ let attempts = 0;
2212
+ while (!sent && attempts < 3) {
2213
+ try {
2214
+ if (!this.#handoffSession.isConnected) {
2215
+ await this.reconnectHandoff();
2216
+ await this.#waitForHandoffConnected(6000);
2217
+ }
2218
+ await this.#handoffSession.sendPage({
2219
+ id: page.id,
2220
+ pageIndex: idx,
2221
+ mimeType: blob.type || 'image/jpeg',
2222
+ blob,
2223
+ metadata: {
2224
+ width: page.dimensions?.width,
2225
+ height: page.dimensions?.height,
2226
+ label: page.label,
2227
+ },
2228
+ });
2229
+ sent = true;
2230
+ } catch (err) {
2231
+ attempts++;
2232
+ if (attempts >= 3) throw err;
2233
+ await this.reconnectHandoff();
2234
+ await this.#waitForHandoffConnected(6000);
2235
+ }
2236
+ }
2237
+ }
2238
+
2239
+ // 2. Complete the session
2240
+ if (progressTitle) progressTitle.textContent = 'Finalizing scan session…';
2241
+ if (progressBar) progressBar.style.width = '100%';
2242
+
2243
+ await this.#handoffSession.complete({
2244
+ docId: payload.docId,
2245
+ summary: {
2246
+ mode: payload.mode,
2247
+ aspect: payload.aspect,
2248
+ pageCount: pages.length,
2249
+ },
2250
+ });
2251
+
2252
+ this.#handoffState = 'complete';
2253
+ if (progressView) progressView.style.display = 'none';
2254
+
2255
+ // 3. Show clean confirmation screen (CPO-094)
2256
+ const confirmView = shadow?.getElementById('handoff-confirm-view');
2257
+ const confirmCount = shadow?.getElementById('handoff-confirm-count');
2258
+ if (confirmView) {
2259
+ confirmView.style.display = 'flex';
2260
+ }
2261
+ if (confirmCount) {
2262
+ confirmCount.textContent = `${pages.length} page${pages.length === 1 ? '' : 's'} transferred to desktop`;
2263
+ }
2264
+ this.#syncHandoffDom();
2265
+
2266
+ // Dispatch standard scan-complete event matching <copio-scanner>
2267
+ this.dispatch(COPIO_EVENTS.SCAN_COMPLETE, payload);
2268
+ } catch (err) {
2269
+ console.error('[CopioScanner] Handoff streaming error:', err);
2270
+ if (progressView) progressView.style.display = 'none';
2271
+ this.#handoffState = 'error';
2272
+ this.#syncHandoffDom(err.message);
2273
+ this.dispatch(COPIO_EVENTS.ERROR, {
2274
+ code: 'HANDOFF_STREAMING_FAILED',
2275
+ message: err.message,
2276
+ error: err,
2277
+ });
2278
+ }
2279
+ }
2280
+
2281
+ async #waitForHandoffConnected(timeoutMs = 6000) {
2282
+ if (this.#handoffSession?.isConnected) return;
2283
+ return new Promise((resolve, reject) => {
2284
+ const timer = setTimeout(() => {
2285
+ unsub();
2286
+ reject(new Error('Timeout waiting for handoff connection'));
2287
+ }, timeoutMs);
2288
+
2289
+ const unsub = this.#handoffSession.on('stateChange', (st) => {
2290
+ if (st === 'connected') {
2291
+ clearTimeout(timer);
2292
+ unsub();
2293
+ resolve(undefined);
2294
+ }
2295
+ });
2296
+ });
2297
+ }
2298
+
2299
+ async #ensureBlobForPage(page) {
2300
+ if (page.blob instanceof Blob) {
2301
+ return page.blob;
2302
+ }
2303
+ const src = page.src || page.originalSrc;
2304
+ if (src && typeof fetch === 'function' && (src.startsWith('data:') || src.startsWith('blob:') || src.startsWith('http'))) {
2305
+ try {
2306
+ const res = await fetch(src);
2307
+ const blob = await res.blob();
2308
+ if (blob && blob.size > 0) return blob;
2309
+ } catch {
2310
+ // fallback
2311
+ }
2312
+ }
2313
+ if (typeof document !== 'undefined') {
2314
+ const canvas = document.createElement('canvas');
2315
+ canvas.width = page.dimensions?.width || 120;
2316
+ canvas.height = page.dimensions?.height || 160;
2317
+ const ctx = canvas.getContext('2d');
2318
+ if (ctx) {
2319
+ ctx.fillStyle = '#f1f5f9';
2320
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
2321
+ }
2322
+ return new Promise((resolve) => {
2323
+ canvas.toBlob((b) => resolve(b || new Blob()), 'image/jpeg');
2324
+ });
2325
+ }
2326
+ return new Blob([], { type: 'image/jpeg' });
2327
+ }
2328
+
1134
2329
  // --- Configuration Properties (CPO-034, CPO-035, CPO-038) ---
1135
2330
 
1136
2331
  get theme() {
@@ -1177,6 +2372,9 @@ export class CopioScanner extends BaseElement {
1177
2372
  set stage(val) {
1178
2373
  if (val === 'viewfinder' || val === 'workbench') {
1179
2374
  this.#stage = val;
2375
+ if (val === 'workbench') {
2376
+ this.#stopCameraStream();
2377
+ }
1180
2378
  if (typeof this.setAttribute === 'function' && this.getAttribute('stage') !== val) {
1181
2379
  this.setAttribute('stage', val);
1182
2380
  }
@@ -1225,6 +2423,38 @@ export class CopioScanner extends BaseElement {
1225
2423
  setCameraStream(stream) {
1226
2424
  this.#stopCameraStream();
1227
2425
  this.#cameraStream = stream;
2426
+ const shadow = this.shadowRoot;
2427
+ const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
2428
+ if (videoEl) {
2429
+ videoEl.muted = true;
2430
+ videoEl.volume = 0;
2431
+ videoEl.playsInline = true;
2432
+ videoEl.setAttribute('playsinline', '');
2433
+ videoEl.setAttribute('webkit-playsinline', '');
2434
+ videoEl.setAttribute('muted', '');
2435
+ try {
2436
+ videoEl.srcObject = (typeof MediaStream !== 'undefined' && stream instanceof MediaStream) ? stream : null;
2437
+ } catch {}
2438
+ videoEl.style.display = stream ? 'block' : 'none';
2439
+ if (stream && videoEl.srcObject) {
2440
+ videoEl.play().catch((err) => {
2441
+ console.warn('[CopioScanner] Live video element play() error:', err);
2442
+ });
2443
+ }
2444
+ }
2445
+ const placeholder = shadow?.querySelector('.copio-camera-placeholder');
2446
+ if (placeholder) {
2447
+ /** @type {HTMLElement} */ (placeholder).style.display = stream ? 'none' : '';
2448
+ }
2449
+ const stepPillText = shadow?.getElementById('step-pill-text');
2450
+ if (stepPillText && stream) {
2451
+ stepPillText.textContent = this.mode === 'batch'
2452
+ ? `Batch Capture · Page ${this.#pageCount + 1}`
2453
+ : 'Camera Active · Tap Shutter to Snap';
2454
+ }
2455
+ if (stream && this.#stage === 'viewfinder' && this.#edgeDetection) {
2456
+ this.#startLiveEdgeDetection();
2457
+ }
1228
2458
  }
1229
2459
 
1230
2460
  get features() {
@@ -1232,13 +2462,8 @@ export class CopioScanner extends BaseElement {
1232
2462
  }
1233
2463
 
1234
2464
  set features(val) {
1235
- if (typeof this.setAttribute === 'function') {
1236
- const str = Array.isArray(val) ? val.join(' ') : String(val || '');
1237
- this.setAttribute('features', str);
1238
- }
1239
- if (this.#engine) {
1240
- this.#engine.setFeatures(val);
1241
- }
2465
+ this.#syncAttr('features', Array.isArray(val) ? val.join(' ') : String(val || ''));
2466
+ if (this.#engine) this.#engine.setFeatures(val);
1242
2467
  }
1243
2468
 
1244
2469
  hasFeature(featureName) {
@@ -1251,12 +2476,8 @@ export class CopioScanner extends BaseElement {
1251
2476
 
1252
2477
  set ocrEnabled(val) {
1253
2478
  const enabled = Boolean(val);
1254
- if (typeof this.setAttribute === 'function') {
1255
- this.setAttribute('ocr', enabled ? 'true' : 'false');
1256
- }
1257
- if (this.#engine) {
1258
- this.#engine.ocr = enabled;
1259
- }
2479
+ this.#syncAttr('ocr', enabled ? 'true' : 'false');
2480
+ if (this.#engine) this.#engine.ocr = enabled;
1260
2481
  this.#updateChildViews();
1261
2482
  }
1262
2483
 
@@ -1266,12 +2487,8 @@ export class CopioScanner extends BaseElement {
1266
2487
 
1267
2488
  set pdf(val) {
1268
2489
  const enabled = Boolean(val);
1269
- if (typeof this.setAttribute === 'function') {
1270
- this.setAttribute('pdf', enabled ? 'true' : 'false');
1271
- }
1272
- if (this.#engine) {
1273
- this.#engine.pdf = enabled;
1274
- }
2490
+ this.#syncAttr('pdf', enabled ? 'true' : 'false');
2491
+ if (this.#engine) this.#engine.pdf = enabled;
1275
2492
  this.#updateChildViews();
1276
2493
  }
1277
2494
 
@@ -1280,13 +2497,8 @@ export class CopioScanner extends BaseElement {
1280
2497
  }
1281
2498
 
1282
2499
  set exportFormats(val) {
1283
- if (typeof this.setAttribute === 'function') {
1284
- const str = Array.isArray(val) ? val.join(',') : String(val || '');
1285
- this.setAttribute('export-formats', str);
1286
- }
1287
- if (this.#engine) {
1288
- this.#engine.exportFormats = val;
1289
- }
2500
+ this.#syncAttr('export-formats', Array.isArray(val) ? val.join(',') : String(val || ''));
2501
+ if (this.#engine) this.#engine.exportFormats = val;
1290
2502
  }
1291
2503
 
1292
2504
  get ocrLanguages() {
@@ -1294,13 +2506,8 @@ export class CopioScanner extends BaseElement {
1294
2506
  }
1295
2507
 
1296
2508
  set ocrLanguages(val) {
1297
- if (typeof this.setAttribute === 'function') {
1298
- const str = Array.isArray(val) ? val.join(',') : String(val || '');
1299
- this.setAttribute('ocr-languages', str);
1300
- }
1301
- if (this.#engine) {
1302
- this.#engine.ocrLanguages = val;
1303
- }
2509
+ this.#syncAttr('ocr-languages', Array.isArray(val) ? val.join(',') : String(val || ''));
2510
+ if (this.#engine) this.#engine.ocrLanguages = val;
1304
2511
  }
1305
2512
 
1306
2513
  get maxPages() {
@@ -1308,12 +2515,8 @@ export class CopioScanner extends BaseElement {
1308
2515
  }
1309
2516
 
1310
2517
  set maxPages(val) {
1311
- if (typeof this.setAttribute === 'function') {
1312
- this.setAttribute('max-pages', String(val));
1313
- }
1314
- if (this.#engine) {
1315
- this.#engine.maxPages = val;
1316
- }
2518
+ this.#syncAttr('max-pages', String(val));
2519
+ if (this.#engine) this.#engine.maxPages = val;
1317
2520
  }
1318
2521
 
1319
2522
  get assetBase() {
@@ -1321,12 +2524,8 @@ export class CopioScanner extends BaseElement {
1321
2524
  }
1322
2525
 
1323
2526
  set assetBase(val) {
1324
- if (typeof this.setAttribute === 'function') {
1325
- this.setAttribute('asset-base', String(val || ''));
1326
- }
1327
- if (this.#engine) {
1328
- this.#engine.assetBase = val;
1329
- }
2527
+ this.#syncAttr('asset-base', String(val || ''));
2528
+ if (this.#engine) this.#engine.assetBase = val;
1330
2529
  }
1331
2530
 
1332
2531
  get licenseKey() {
@@ -1334,14 +2533,53 @@ export class CopioScanner extends BaseElement {
1334
2533
  }
1335
2534
 
1336
2535
  set licenseKey(val) {
2536
+ this.#syncAttr('license-key', String(val || ''));
2537
+ if (this.#engine) this.#engine.licenseKey = val;
2538
+ }
2539
+
2540
+ #syncAttr(name, val) {
1337
2541
  if (typeof this.setAttribute === 'function') {
1338
- this.setAttribute('license-key', String(val || ''));
1339
- }
1340
- if (this.#engine) {
1341
- this.#engine.licenseKey = val;
2542
+ if (val) this.setAttribute(name, typeof val === 'object' ? JSON.stringify(val) : String(val));
2543
+ else this.removeAttribute(name);
1342
2544
  }
1343
2545
  }
1344
2546
 
2547
+ get relayUrl() {
2548
+ return this.#engine?.relayUrl || '';
2549
+ }
2550
+
2551
+ set relayUrl(val) {
2552
+ if (this.#engine) this.#engine.relayUrl = val;
2553
+ this.#syncAttr('relay-url', val);
2554
+ }
2555
+
2556
+ get signalingUrl() {
2557
+ return this.#engine?.signalingUrl || '';
2558
+ }
2559
+
2560
+ set signalingUrl(val) {
2561
+ if (this.#engine) this.#engine.signalingUrl = val;
2562
+ this.#syncAttr('signaling-url', val);
2563
+ }
2564
+
2565
+ get iceServers() {
2566
+ return this.#engine?.iceServers || null;
2567
+ }
2568
+
2569
+ set iceServers(val) {
2570
+ if (this.#engine) this.#engine.iceServers = val;
2571
+ this.#syncAttr('ice-servers', val);
2572
+ }
2573
+
2574
+ get iceTransportPolicy() {
2575
+ return this.#engine?.iceTransportPolicy || 'all';
2576
+ }
2577
+
2578
+ set iceTransportPolicy(val) {
2579
+ if (this.#engine) this.#engine.iceTransportPolicy = val;
2580
+ this.#syncAttr('ice-transport-policy', val);
2581
+ }
2582
+
1345
2583
  get storage() {
1346
2584
  return this.#storage;
1347
2585
  }
@@ -1360,6 +2598,9 @@ export class CopioScanner extends BaseElement {
1360
2598
  set engine(customEngine) {
1361
2599
  if (customEngine instanceof CopioEngine) {
1362
2600
  this.#engine = customEngine;
2601
+ this.#engine.addEventListener(COPIO_EVENTS.MIGRATION, (e) => {
2602
+ this.dispatch(COPIO_EVENTS.MIGRATION, e.detail);
2603
+ });
1363
2604
  }
1364
2605
  }
1365
2606
 
@@ -1423,7 +2664,7 @@ export class CopioScanner extends BaseElement {
1423
2664
  });
1424
2665
  }
1425
2666
 
1426
- async addFiles(files) {
2667
+ async addFiles(files, options = {}) {
1427
2668
  try {
1428
2669
  const existingPages = await this.getPages();
1429
2670
  let replaceIndex = null;
@@ -1444,7 +2685,12 @@ export class CopioScanner extends BaseElement {
1444
2685
  }
1445
2686
  this.#retaking = false;
1446
2687
 
1447
- const newPages = await this.#engine.addFiles(files, this.#targetDocId);
2688
+ const engineOpts = {
2689
+ autoCrop: this.#autoCrop,
2690
+ prefilledQuad: options?.prefilledQuad || null,
2691
+ ...options,
2692
+ };
2693
+ const newPages = await this.#engine.addFiles(files, this.#targetDocId, engineOpts);
1448
2694
  for (let i = 0; i < newPages.length; i++) {
1449
2695
  this.dispatch(COPIO_EVENTS.PAGE_ADDED, {
1450
2696
  page: newPages[i],
@@ -1613,6 +2859,126 @@ export class CopioScanner extends BaseElement {
1613
2859
  throw err;
1614
2860
  }
1615
2861
  }
2862
+
2863
+ get edgeDetection() {
2864
+ return this.#edgeDetection;
2865
+ }
2866
+
2867
+ /** @param {boolean|string|null|undefined} val */
2868
+ set edgeDetection(val) {
2869
+ const next = val !== false && val !== 'false' && val !== null && val !== undefined;
2870
+ if (this.#edgeDetection !== next) {
2871
+ this.#edgeDetection = next;
2872
+ this.#syncAttr('edge-detection', String(next));
2873
+ if (!this.#edgeDetection) {
2874
+ this.#stopLiveEdgeDetection();
2875
+ this.#hideLiveQuadOverlay();
2876
+ } else if (this.#cameraStream && this.#stage === 'viewfinder') {
2877
+ this.#startLiveEdgeDetection();
2878
+ }
2879
+ }
2880
+ }
2881
+
2882
+ get edgeModel() {
2883
+ return this.#edgeModel;
2884
+ }
2885
+
2886
+ /** @param {'classical'|'ml'|string|null|undefined} val */
2887
+ set edgeModel(val) {
2888
+ const next = val === 'classical' ? 'classical' : 'ml';
2889
+ if (this.#edgeModel !== next) {
2890
+ this.#edgeModel = next;
2891
+ this.#syncAttr('edge-model', next);
2892
+ const edgeService = this.#engine?.getService('edge') || getRegisteredService('edge');
2893
+ if (edgeService && 'detector' in edgeService) {
2894
+ edgeService.detector = next;
2895
+ }
2896
+ if (next === 'ml' && edgeService && typeof edgeService.preloadMl === 'function') {
2897
+ const stepPillText = this.shadowRoot?.getElementById('step-pill-text');
2898
+ const prevText = stepPillText?.textContent;
2899
+ if (stepPillText && this.#cameraStream && this.#stage === 'viewfinder') {
2900
+ stepPillText.textContent = 'Loading ML Neural model…';
2901
+ }
2902
+ edgeService.preloadMl().then(() => {
2903
+ if (stepPillText && this.#cameraStream && this.#stage === 'viewfinder' && this.#edgeModel === 'ml') {
2904
+ stepPillText.textContent = this.mode === 'batch'
2905
+ ? `Batch Capture · Page ${this.#pageCount + 1}`
2906
+ : 'Camera Active · Tap Shutter to Snap';
2907
+ }
2908
+ }).catch((err) => {
2909
+ console.warn('[CopioScanner] Failed to load ML Neural edge detector:', err);
2910
+ if (stepPillText && prevText && this.#stage === 'viewfinder') {
2911
+ stepPillText.textContent = prevText;
2912
+ }
2913
+ });
2914
+ }
2915
+ }
2916
+ }
2917
+
2918
+ get autoCrop() {
2919
+ return this.#autoCrop;
2920
+ }
2921
+
2922
+ /** @param {boolean|string|null|undefined} val */
2923
+ set autoCrop(val) {
2924
+ const next = val !== false && val !== 'false' && val !== null && val !== undefined;
2925
+ if (this.#autoCrop !== next) {
2926
+ this.#autoCrop = next;
2927
+ this.#syncAttr('auto-crop', String(next));
2928
+ }
2929
+ }
2930
+
2931
+ get autoCapture() {
2932
+ return this.#autoCapture;
2933
+ }
2934
+
2935
+ /** @param {boolean|string|null|undefined} val */
2936
+ set autoCapture(val) {
2937
+ const next = Boolean(val && val !== 'false');
2938
+ if (this.#autoCapture !== next) {
2939
+ this.#autoCapture = next;
2940
+ this.#syncAttr('auto-capture', String(next));
2941
+ }
2942
+ }
2943
+
2944
+ /**
2945
+ * Returns the current normalized quadrilateral tracked by live edge detection, or null.
2946
+ * @returns {import('./core.js').EdgeQuad|null}
2947
+ */
2948
+ getLiveQuad() {
2949
+ return this.#smoothedQuad ? cloneQuad(this.#smoothedQuad) : null;
2950
+ }
2951
+
2952
+ /**
2953
+ * Returns the latest edge detection result payload, or null.
2954
+ * @returns {{ quad: import('./core.js').EdgeQuad, confidence: number, durationMs?: number, isFallback: boolean }|null}
2955
+ */
2956
+ getLatestDetection() {
2957
+ return this.#latestDetectionResult
2958
+ ? {
2959
+ quad: cloneQuad(this.#latestDetectionResult.quad),
2960
+ confidence: this.#latestDetectionResult.confidence,
2961
+ durationMs: this.#latestDetectionResult.durationMs,
2962
+ isFallback: this.#latestDetectionResult.isFallback,
2963
+ }
2964
+ : null;
2965
+ }
2966
+
2967
+ /**
2968
+ * Run edge detection on the current camera video frame.
2969
+ * @param {import('../js/adapters/edge/edge-detector-port.js').EdgeDetectOptions} [options]
2970
+ * @returns {Promise<import('../js/adapters/edge/edge-detector-port.js').EdgeDetectionResult|null>}
2971
+ */
2972
+ async detectCurrentFrame(options = {}) {
2973
+ const frame = this._grabFrame({
2974
+ maxWidth: options.maxProcessingDimension || 480,
2975
+ maxHeight: options.maxProcessingDimension || 480,
2976
+ });
2977
+ if (!frame) return null;
2978
+ const edgeService = this.#engine?.getService('edge') || getRegisteredService('edge');
2979
+ if (!edgeService || typeof edgeService.detect !== 'function') return null;
2980
+ return edgeService.detect(frame, options);
2981
+ }
1616
2982
  }
1617
2983
 
1618
2984
  if (typeof customElements !== 'undefined' && !customElements.get('copio-scanner')) {