@copio/sdk 0.0.0-stage → 0.1.1

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 (149) hide show
  1. package/README.md +204 -2
  2. package/css/container.css +177 -0
  3. package/css/cropper.css +306 -0
  4. package/css/main.css +139 -0
  5. package/css/reset.css +204 -0
  6. package/css/shoelace.css +485 -0
  7. package/css/utils.css +689 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +2 -0
  9. package/dist/adapters/image/canvas2d-adapter.js.map +7 -0
  10. package/dist/adapters/image/index.js +2 -0
  11. package/dist/adapters/image/index.js.map +7 -0
  12. package/dist/adapters/image/null-image-processor-adapter.js +2 -0
  13. package/dist/adapters/image/null-image-processor-adapter.js.map +7 -0
  14. package/dist/adapters/index.js +2 -0
  15. package/dist/adapters/index.js.map +7 -0
  16. package/dist/adapters/indexeddb-adapter.js +2 -0
  17. package/dist/adapters/indexeddb-adapter.js.map +7 -0
  18. package/dist/adapters/memory-adapter.js +2 -0
  19. package/dist/adapters/memory-adapter.js.map +7 -0
  20. package/dist/adapters/ocr/index.js +2 -0
  21. package/dist/adapters/ocr/index.js.map +7 -0
  22. package/dist/adapters/ocr/null-ocr-adapter.js +2 -0
  23. package/dist/adapters/ocr/null-ocr-adapter.js.map +7 -0
  24. package/dist/adapters/ocr/tesseract-wasm-adapter.js +2 -0
  25. package/dist/adapters/ocr/tesseract-wasm-adapter.js.map +7 -0
  26. package/dist/adapters/pdf/index.js +2 -0
  27. package/dist/adapters/pdf/index.js.map +7 -0
  28. package/dist/adapters/pdf/null-pdf-adapter.js +2 -0
  29. package/dist/adapters/pdf/null-pdf-adapter.js.map +7 -0
  30. package/dist/adapters/pdf/pdfkit-adapter.js +2 -0
  31. package/dist/adapters/pdf/pdfkit-adapter.js.map +7 -0
  32. package/dist/adapters/storage/index.js +2 -0
  33. package/dist/adapters/storage/index.js.map +7 -0
  34. package/dist/adapters/storage/indexeddb-adapter.js +2 -0
  35. package/dist/adapters/storage/indexeddb-adapter.js.map +7 -0
  36. package/dist/adapters/storage/memory-adapter.js +2 -0
  37. package/dist/adapters/storage/memory-adapter.js.map +7 -0
  38. package/dist/adapters/sync/index.js +2 -0
  39. package/dist/adapters/sync/index.js.map +7 -0
  40. package/dist/adapters/sync/null-sync-adapter.js +2 -0
  41. package/dist/adapters/sync/null-sync-adapter.js.map +7 -0
  42. package/dist/adapters/sync/peerjs-adapter.js +2 -0
  43. package/dist/adapters/sync/peerjs-adapter.js.map +7 -0
  44. package/dist/canvas-FAXPLPXN.js +2 -0
  45. package/dist/cdn.js +2770 -0
  46. package/dist/chunk-36F637QU.js +2 -0
  47. package/dist/chunk-4C666HHU.js +2 -0
  48. package/dist/chunk-4GEMGDRU.js +1 -0
  49. package/dist/chunk-4JPEWIT4.js +2 -0
  50. package/dist/chunk-A5G52Q2W.js +2 -0
  51. package/dist/chunk-B2EK6INF.js +2 -0
  52. package/dist/chunk-B5BEYYR2.js +8 -0
  53. package/dist/chunk-B7HT2X67.js +2 -0
  54. package/dist/chunk-BKZEOOH4.js +2 -0
  55. package/dist/chunk-CWCS22CQ.js +1 -0
  56. package/dist/chunk-DGGK5KEX.js +2 -0
  57. package/dist/chunk-E7JYVRJA.js +2 -0
  58. package/dist/chunk-G65H4ZTJ.js +2 -0
  59. package/dist/chunk-HN3336JN.js +2 -0
  60. package/dist/chunk-IUBYFIV6.js +12 -0
  61. package/dist/chunk-K6YP7EET.js +8 -0
  62. package/dist/chunk-K7RTGT3Q.js +2601 -0
  63. package/dist/chunk-KIMVF5UG.js +2 -0
  64. package/dist/chunk-LI54F6PA.js +2 -0
  65. package/dist/chunk-N4R55VRR.js +2 -0
  66. package/dist/chunk-N7Q34F2P.js +4 -0
  67. package/dist/chunk-OI4WCW7E.js +2 -0
  68. package/dist/chunk-PUJYN435.js +1 -0
  69. package/dist/chunk-PVNRK4OH.js +2 -0
  70. package/dist/chunk-QPUCXOOR.js +2 -0
  71. package/dist/chunk-SH4P4XSZ.js +2 -0
  72. package/dist/chunk-UCV3MQ6I.js +33 -0
  73. package/dist/chunk-V2FP4EEH.js +2 -0
  74. package/dist/chunk-V6E2SSSW.js +1 -0
  75. package/dist/chunk-XEN5VKAV.js +19 -0
  76. package/dist/chunk-YHLOPPXM.js +2 -0
  77. package/dist/core.js +2 -0
  78. package/dist/custom-elements.json +4779 -0
  79. package/dist/export.js +2 -0
  80. package/dist/fs-HJ6WWW73.js +2 -0
  81. package/dist/http-FKJJMT2N.js +2 -0
  82. package/dist/https-MUBFLDZM.js +2 -0
  83. package/dist/index.js +99 -0
  84. package/dist/ocr.js +2 -0
  85. package/dist/path2d-QWN6DFCC.js +2 -0
  86. package/dist/scanner.js +2631 -0
  87. package/dist/sync.js +2 -0
  88. package/dist/types/js/adapters/image/canvas2d-adapter.d.ts +42 -0
  89. package/dist/types/js/adapters/image/image-processor-port.d.ts +41 -0
  90. package/dist/types/js/adapters/image/index.d.ts +3 -0
  91. package/dist/types/js/adapters/image/null-image-processor-adapter.d.ts +13 -0
  92. package/dist/types/js/adapters/ocr/index.d.ts +3 -0
  93. package/dist/types/js/adapters/ocr/null-ocr-adapter.d.ts +39 -0
  94. package/dist/types/js/adapters/ocr/ocr-port.d.ts +139 -0
  95. package/dist/types/js/adapters/ocr/tesseract-wasm-adapter.d.ts +40 -0
  96. package/dist/types/js/adapters/pdf/index.d.ts +3 -0
  97. package/dist/types/js/adapters/pdf/null-pdf-adapter.d.ts +23 -0
  98. package/dist/types/js/adapters/pdf/pdf-port.d.ts +21 -0
  99. package/dist/types/js/adapters/pdf/pdfkit-adapter.d.ts +16 -0
  100. package/dist/types/js/adapters/storage/index.d.ts +22 -0
  101. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +109 -0
  102. package/dist/types/js/adapters/storage/memory-adapter.d.ts +101 -0
  103. package/dist/types/js/adapters/storage/storage-port.d.ts +113 -0
  104. package/dist/types/js/adapters/sync/index.d.ts +3 -0
  105. package/dist/types/js/adapters/sync/null-sync-adapter.d.ts +14 -0
  106. package/dist/types/js/adapters/sync/peerjs-adapter.d.ts +16 -0
  107. package/dist/types/js/adapters/sync/sync-port.d.ts +18 -0
  108. package/dist/types/js/components/copio-header.d.ts +19 -0
  109. package/dist/types/js/components/copio-loader.d.ts +6 -0
  110. package/dist/types/js/core/store.d.ts +2 -0
  111. package/dist/types/js/routes/add-edit/copio-add-edit-dialog.d.ts +9 -0
  112. package/dist/types/js/routes/doc/copio-carousel.d.ts +43 -0
  113. package/dist/types/js/routes/doc/copio-images.d.ts +37 -0
  114. package/dist/types/js/routes/home/copio-row.d.ts +49 -0
  115. package/dist/types/js/routes/ocr/copio-doc-ocr-dialog.d.ts +97 -0
  116. package/dist/types/js/routes/sync/copio-sync-dialog.d.ts +13 -0
  117. package/dist/types/js/services/doc-repository.d.ts +233 -0
  118. package/dist/types/js/services/export-utils.d.ts +42 -0
  119. package/dist/types/js/services/ice-servers.d.ts +1 -0
  120. package/dist/types/js/services/notify.d.ts +82 -0
  121. package/dist/types/js/services/ocr-service.d.ts +64 -0
  122. package/dist/types/js/services/sync-service.d.ts +11 -0
  123. package/dist/types/js/styles/cropper-styles.d.ts +5 -0
  124. package/dist/types/js/utils/module-loader.d.ts +76 -0
  125. package/dist/types/js/utils/pdf-utils.d.ts +7 -0
  126. package/dist/types/js/utils/utils.d.ts +54 -0
  127. package/dist/types/sdk/cdn.d.ts +7 -0
  128. package/dist/types/sdk/core.d.ts +310 -0
  129. package/dist/types/sdk/elements.d.ts +25 -0
  130. package/dist/types/sdk/events.d.ts +227 -0
  131. package/dist/types/sdk/index.d.ts +37 -0
  132. package/dist/types/sdk/license.d.ts +12 -0
  133. package/dist/types/sdk/models.d.ts +174 -0
  134. package/dist/types/sdk/scanner.d.ts +68 -0
  135. package/dist/types/sdk/styles.d.ts +21 -0
  136. package/dist/types/sdk/sync.d.ts +7 -0
  137. package/dist/types/sdk/version.d.ts +2 -0
  138. package/dist/url-ABJ6S2Y6.js +2 -0
  139. package/package.json +73 -4
  140. package/sdk/cdn.js +13 -0
  141. package/sdk/core.js +961 -0
  142. package/sdk/events.js +99 -0
  143. package/sdk/index.js +137 -0
  144. package/sdk/license.js +28 -0
  145. package/sdk/models.js +177 -0
  146. package/sdk/scanner.js +1597 -0
  147. package/sdk/styles.js +1236 -0
  148. package/sdk/sync.js +12 -0
  149. package/sdk/version.js +7 -0
package/sdk/scanner.js ADDED
@@ -0,0 +1,1597 @@
1
+ /**
2
+ * Copio Scanner Web Component (CPO-034, CPO-035, CPO-036, CPO-037, CPO-038, CPO-045)
3
+ *
4
+ * Embeddable, zero-config two-stage (viewfinder ↔ workbench) document scanner
5
+ * acting as the primary Driving UI Adapter over the headless CopioEngine.
6
+ */
7
+ import { CopioEngine } from './core.js';
8
+ import { COPIO_EVENTS, dispatchCopioEvent } from './events.js';
9
+ import { CopioImages } from '../js/routes/doc/copio-images.js';
10
+ import { CopioCarousel } from '../js/routes/doc/copio-carousel.js';
11
+ import { CopioAddEditDialog } from '../js/routes/add-edit/copio-add-edit-dialog.js';
12
+ import { CopioRow } from '../js/routes/home/copio-row.js';
13
+ import { CopioHeader } from '../js/components/copio-header.js';
14
+ import { CopioLoader } from '../js/components/copio-loader.js';
15
+ import { setAssetBase } from '../js/utils/module-loader.js';
16
+ import { setContainer, getContainer } from '../js/services/notify.js';
17
+ import { scannerCss, getScannerStyleSheet, adoptScannerStyles } from './styles.js';
18
+
19
+ /** @type {typeof HTMLElement} */
20
+ const BaseElement = typeof HTMLElement !== 'undefined' ? HTMLElement : /** @type {any} */ (class {});
21
+
22
+ export class CopioScanner extends BaseElement {
23
+ #engine = null;
24
+ #storage = null;
25
+ #unsubscribeRepo = null;
26
+ #isOpen = false;
27
+ #stage = 'viewfinder'; // 'viewfinder' | 'workbench'
28
+ #activePageIndex = 0;
29
+ #pageCount = 0;
30
+ #retaking = false;
31
+ #cropMode = false;
32
+ #draftCrop = null;
33
+ #undoTimer = null;
34
+ #undoRemaining = 0;
35
+ #renderPromise = null;
36
+ #sessionDocId = null;
37
+ #cameraStream = null;
38
+ onShutter = null;
39
+
40
+ get #targetDocId() {
41
+ if (this.docId) return this.docId;
42
+ if (!this.#sessionDocId) {
43
+ this.#sessionDocId = `doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
44
+ }
45
+ return this.#sessionDocId;
46
+ }
47
+
48
+ static get observedAttributes() {
49
+ return [
50
+ 'mode',
51
+ 'aspect',
52
+ 'stage',
53
+ 'doc-id',
54
+ 'features',
55
+ 'export-formats',
56
+ 'ocr-languages',
57
+ 'max-pages',
58
+ 'asset-base',
59
+ 'license-key',
60
+ 'theme',
61
+ 'ocr',
62
+ 'pdf',
63
+ ];
64
+ }
65
+
66
+ constructor() {
67
+ super();
68
+ if (typeof this.attachShadow === 'function') {
69
+ this.attachShadow({ mode: 'open' });
70
+ }
71
+ this.#initEngine();
72
+ }
73
+
74
+ #initEngine() {
75
+ const opts = {
76
+ storage: this.#storage,
77
+ };
78
+ if (typeof this.getAttribute === 'function') {
79
+ if (this.hasAttribute('features')) opts.features = this.getAttribute('features');
80
+ if (this.hasAttribute('export-formats')) opts.exportFormats = this.getAttribute('export-formats');
81
+ if (this.hasAttribute('ocr-languages')) opts.ocrLanguages = this.getAttribute('ocr-languages');
82
+ if (this.hasAttribute('max-pages')) opts.maxPages = this.getAttribute('max-pages');
83
+ if (this.hasAttribute('asset-base')) opts.assetBase = this.getAttribute('asset-base');
84
+ if (this.hasAttribute('license-key')) opts.licenseKey = this.getAttribute('license-key');
85
+ if (this.hasAttribute('ocr')) opts.ocr = this.getAttribute('ocr') !== 'false';
86
+ if (this.hasAttribute('pdf')) opts.pdf = this.getAttribute('pdf') !== 'false';
87
+ }
88
+ this.#engine = new CopioEngine(opts);
89
+ }
90
+
91
+ connectedCallback() {
92
+ if (this.shadowRoot) {
93
+ adoptScannerStyles(this.shadowRoot);
94
+ this.#buildInitialDom();
95
+ }
96
+
97
+ if (typeof setContainer === 'function' && typeof document !== 'undefined' && getContainer() === document.body) {
98
+ setContainer(this.shadowRoot?.querySelector('.copio-scanner-container') || this);
99
+ }
100
+
101
+ // Subscribe to engine repository changes
102
+ if (this.#engine) {
103
+ this.#unsubscribeRepo = this.#engine.subscribe(async () => {
104
+ const pages = await this.getPages();
105
+ this.dispatch(COPIO_EVENTS.PAGES_CHANGED, {
106
+ pages,
107
+ docId: this.docId,
108
+ });
109
+ this.#syncView();
110
+ });
111
+ }
112
+
113
+ if (this.hasAttribute && this.hasAttribute('asset-base')) {
114
+ setAssetBase(this.getAttribute('asset-base'));
115
+ }
116
+
117
+ this.#updateChildViews();
118
+ this.#syncView();
119
+ }
120
+
121
+ disconnectedCallback() {
122
+ this.#stopCameraStream();
123
+ if (typeof this.#unsubscribeRepo === 'function') {
124
+ this.#unsubscribeRepo();
125
+ this.#unsubscribeRepo = null;
126
+ }
127
+ if (this.#undoTimer) {
128
+ clearInterval(this.#undoTimer);
129
+ this.#undoTimer = null;
130
+ }
131
+ if (typeof setContainer === 'function' && typeof document !== 'undefined') {
132
+ const containerEl = this.shadowRoot?.querySelector('.copio-scanner-container') || this;
133
+ if (getContainer() === containerEl) {
134
+ setContainer(null);
135
+ }
136
+ }
137
+ }
138
+
139
+ attributeChangedCallback(name, oldValue, newValue) {
140
+ if (oldValue === newValue || !this.#engine) return;
141
+
142
+ switch (name) {
143
+ case 'features':
144
+ this.#engine.setFeatures(newValue);
145
+ this.#updateChildViews();
146
+ break;
147
+ case 'export-formats':
148
+ this.#engine.exportFormats = newValue;
149
+ this.#updateChildViews();
150
+ break;
151
+ case 'ocr-languages':
152
+ this.#engine.ocrLanguages = newValue;
153
+ break;
154
+ case 'asset-base':
155
+ this.#engine.assetBase = newValue;
156
+ break;
157
+ case 'license-key':
158
+ this.#engine.licenseKey = newValue;
159
+ break;
160
+ case 'ocr':
161
+ this.#engine.ocr = newValue !== 'false';
162
+ this.#updateChildViews();
163
+ break;
164
+ case 'pdf':
165
+ this.#engine.pdf = newValue !== 'false';
166
+ this.#updateChildViews();
167
+ break;
168
+ case 'stage':
169
+ if (newValue === 'viewfinder' || newValue === 'workbench') {
170
+ this.#stage = newValue;
171
+ const shadow = this.shadowRoot;
172
+ if (shadow) {
173
+ const vf = shadow.getElementById('viewfinder-section');
174
+ const wb = shadow.getElementById('workbench-section');
175
+ if (vf && wb) {
176
+ vf.style.display = newValue === 'viewfinder' ? 'flex' : 'none';
177
+ wb.style.display = newValue === 'workbench' ? 'flex' : 'none';
178
+ }
179
+ }
180
+ this.#syncView();
181
+ }
182
+ break;
183
+ case 'max-pages':
184
+ this.#engine.maxPages = newValue;
185
+ this.#syncView();
186
+ break;
187
+ case 'mode':
188
+ case 'aspect':
189
+ case 'theme':
190
+ this.#syncView();
191
+ break;
192
+ }
193
+ }
194
+
195
+ #updateChildViews() {
196
+ if (typeof this.querySelectorAll !== 'function') return;
197
+ const roots = [];
198
+ if (this.shadowRoot) roots.push(this.shadowRoot);
199
+ roots.push(this);
200
+
201
+ for (const root of roots) {
202
+ const children = root.querySelectorAll('copio-carousel, copio-row, copio-images');
203
+ for (const child of children) {
204
+ if ('ocr' in child) /** @type {any} */ (child).ocr = this.ocrEnabled;
205
+ if ('pdf' in child) /** @type {any} */ (child).pdf = this.pdf;
206
+ }
207
+ }
208
+ }
209
+
210
+ #buildInitialDom() {
211
+ if (!this.shadowRoot || this.shadowRoot.innerHTML) return;
212
+
213
+ let initialStepText = 'Align Document Inside Frame';
214
+ if (this.aspect === 'card') {
215
+ initialStepText = 'Step 1 of 2: Capture Front of ID Card';
216
+ } else if (this.mode === 'batch') {
217
+ initialStepText = 'Batch Capture · Page 1';
218
+ }
219
+
220
+ this.shadowRoot.innerHTML = `
221
+ <div class="copio-scanner-container copio-scanner-host" part="scanner-root">
222
+ <header class="copio-header" part="header">
223
+ <div class="copio-header-left">
224
+ <span class="copio-mode-badge" id="mode-badge">${(this.mode || 'single').toUpperCase()}</span>
225
+ <div class="copio-title-group">
226
+ <h2 class="copio-title" id="header-title">Copio Scanner</h2>
227
+ <p class="copio-subtitle" id="header-subtitle">Non-destructive mobile document scanner</p>
228
+ </div>
229
+ </div>
230
+ <div class="copio-header-actions" part="header-actions">
231
+ <div class="copio-stage-tabs" role="tablist" aria-label="Scanner Stage">
232
+ <button type="button" class="copio-stage-tab" id="tab-viewfinder" role="tab" aria-selected="true">Camera</button>
233
+ <button type="button" class="copio-stage-tab" id="tab-workbench" role="tab" aria-selected="false">Workbench</button>
234
+ </div>
235
+ <slot name="header-actions"></slot>
236
+ </div>
237
+ </header>
238
+
239
+ <!-- Viewfinder Stage -->
240
+ <div class="copio-viewfinder copio-viewfinder-stage" part="viewfinder" id="viewfinder-section">
241
+ <div class="copio-viewfinder-hud-top">
242
+ <div class="copio-step-pill" id="step-pill">
243
+ <span class="copio-status-dot"></span>
244
+ <span id="step-pill-text">${initialStepText}</span>
245
+ </div>
246
+ <div class="copio-privacy-pill" title="100% Local On-Device Processing">
247
+ <span>🔒 100% Local</span>
248
+ </div>
249
+ </div>
250
+
251
+ <div class="copio-camera-feed" id="camera-feed">
252
+ <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>
253
+ <slot name="viewfinder">
254
+ <div class="copio-framing-guide" id="framing-guide" data-aspect="${this.aspect}">
255
+ <span class="copio-corner tl"></span>
256
+ <span class="copio-corner tr"></span>
257
+ <span class="copio-corner bl"></span>
258
+ <span class="copio-corner br"></span>
259
+ <div class="copio-edge-quad"></div>
260
+ <div class="copio-camera-placeholder">
261
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
262
+ <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
263
+ <circle cx="12" cy="13" r="4"/>
264
+ </svg>
265
+ <span>Position document within guide lines</span>
266
+ </div>
267
+ </div>
268
+ </slot>
269
+ </div>
270
+
271
+ <div class="copio-shutter-dock" part="shutter-dock">
272
+ <div class="copio-shutter-side left">
273
+ <button type="button" class="copio-btn copio-btn-secondary" id="btn-import-file" title="Import image from file">
274
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
275
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
276
+ <polyline points="17 8 12 3 7 8"/>
277
+ <line x1="12" y1="3" x2="12" y2="15"/>
278
+ </svg>
279
+ <span>Import</span>
280
+ </button>
281
+ </div>
282
+
283
+ <slot name="shutter-dock">
284
+ <button type="button" class="copio-shutter-btn" id="btn-shutter" aria-label="Capture page">
285
+ <span class="copio-shutter-btn-inner"></span>
286
+ </button>
287
+ </slot>
288
+
289
+ <div class="copio-shutter-side right">
290
+ <button type="button" class="copio-stack-pill" id="btn-review" title="Review pages" style="display:none;">
291
+ <span id="review-pill-text">Review (0) →</span>
292
+ </button>
293
+ </div>
294
+ </div>
295
+ </div>
296
+
297
+ <!-- Workbench Stage -->
298
+ <div class="copio-workbench copio-workbench-stage" part="workbench" id="workbench-section" style="display: none;">
299
+ <div class="copio-workbench-main">
300
+ <div class="copio-canvas-viewport" id="canvas-viewport">
301
+ <div class="copio-card-side-switcher" id="card-side-switcher" style="display:none;" role="tablist" aria-label="Card side switcher">
302
+ <button type="button" role="tab" class="copio-side-pill active" id="btn-card-front" aria-selected="true">1. Front Side</button>
303
+ <button type="button" role="tab" class="copio-side-pill" id="btn-card-back" aria-selected="false">2. Back Side</button>
304
+ </div>
305
+
306
+ <div class="copio-canvas-wrapper" id="canvas-wrapper">
307
+ <img id="stage-img" class="copio-stage-image" alt="Active document page" />
308
+ </div>
309
+ </div>
310
+
311
+ <!-- Filmstrip Tray -->
312
+ <div class="copio-filmstrip" id="filmstrip-tray" part="filmstrip">
313
+ <div class="copio-filmstrip-scroll" id="filmstrip-scroll">
314
+ <slot name="filmstrip"></slot>
315
+ </div>
316
+ </div>
317
+ </div>
318
+
319
+ <!-- Bottom Action Toolbar -->
320
+ <footer class="copio-toolbar" part="toolbar" id="workbench-toolbar">
321
+ <div class="copio-toolbar-tools">
322
+ <button type="button" class="copio-tool-btn" id="btn-retake" title="Retake page">
323
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
324
+ <path d="M23 4v6h-6M1 20v-6h6"/>
325
+ <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
326
+ </svg>
327
+ <span>Retake</span>
328
+ </button>
329
+
330
+ <button type="button" class="copio-tool-btn" id="btn-crop" title="Adjust crop">
331
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
332
+ <path d="M6 2v14a2 2 0 0 0 2 2h14"/>
333
+ <path d="M18 22V8a2 2 0 0 0-2-2H2"/>
334
+ </svg>
335
+ <span id="crop-btn-label">Crop</span>
336
+ </button>
337
+
338
+ <button type="button" class="copio-tool-btn" id="btn-rotate" title="Rotate 90°">
339
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
340
+ <path d="M21.5 2v6h-6M21.34 15.57a10 10 0 1 1-.57-8.38l5.67-5.67"/>
341
+ </svg>
342
+ <span>Rotate</span>
343
+ </button>
344
+
345
+ <button type="button" class="copio-tool-btn" id="btn-filter-bw" title="Toggle B&W filter">
346
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
347
+ <circle cx="12" cy="12" r="10"/>
348
+ <path d="M12 2a10 10 0 0 1 0 20z" fill="currentColor"/>
349
+ </svg>
350
+ <span>B&W</span>
351
+ </button>
352
+
353
+ <button type="button" class="copio-tool-btn" id="btn-ocr" title="Recognize text">
354
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
355
+ <path d="M4 7V4h16v3M9 20h6M12 4v16"/>
356
+ </svg>
357
+ <span>OCR</span>
358
+ </button>
359
+
360
+ <button type="button" class="copio-tool-btn copio-btn-danger" id="btn-delete" title="Delete active page">
361
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
362
+ <polyline points="3 6 5 6 21 6"/>
363
+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
364
+ </svg>
365
+ <span>Delete</span>
366
+ </button>
367
+ </div>
368
+
369
+ <div class="copio-toolbar-actions">
370
+ <slot name="toolbar">
371
+ <button type="button" class="copio-btn copio-btn-primary" id="btn-primary-complete">
372
+ ✓ Use Photo
373
+ </button>
374
+ </slot>
375
+ </div>
376
+ </footer>
377
+
378
+ <!-- Scoped OCR Slide-out / Bottom Sheet -->
379
+ <div class="copio-ocr-sheet" id="ocr-sheet" style="display:none;" part="ocr-sheet">
380
+ <div class="copio-ocr-header">
381
+ <strong class="copio-ocr-title">Text Recognition (OCR)</strong>
382
+ <button type="button" class="copio-btn copio-btn-secondary" id="btn-close-ocr">✕</button>
383
+ </div>
384
+ <div class="copio-ocr-body" id="ocr-body">
385
+ <p class="copio-ocr-placeholder">Select text or extract full page data...</p>
386
+ </div>
387
+ </div>
388
+
389
+ <!-- Container-scoped Toast Region (5s undo) -->
390
+ <div class="copio-toast-region" id="toast-region" aria-live="polite"></div>
391
+ </div>
392
+
393
+ <!-- Hidden input for file picker fallback -->
394
+ <input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
395
+ <slot></slot>
396
+ </div>
397
+ `;
398
+
399
+ this.#bindEventListeners();
400
+ }
401
+
402
+ #bindEventListeners() {
403
+ const shadow = this.shadowRoot;
404
+ if (!shadow) return;
405
+
406
+ // Stage toggle tabs
407
+ shadow.getElementById('tab-viewfinder')?.addEventListener('click', () => {
408
+ this.stage = 'viewfinder';
409
+ });
410
+ shadow.getElementById('tab-workbench')?.addEventListener('click', () => {
411
+ this.stage = 'workbench';
412
+ });
413
+
414
+ // File input fallback
415
+ const fileInput = shadow.getElementById('internal-file-input');
416
+ shadow.getElementById('btn-import-file')?.addEventListener('click', () => {
417
+ fileInput?.click();
418
+ });
419
+
420
+ fileInput?.addEventListener('change', async (e) => {
421
+ const input = /** @type {HTMLInputElement} */ (e.target);
422
+ if (input.files && input.files.length > 0) {
423
+ await this.addFiles(input.files);
424
+ input.value = '';
425
+ }
426
+ });
427
+
428
+ // Shutter capture button
429
+ shadow.getElementById('btn-shutter')?.addEventListener('click', async () => {
430
+ await this.#handleShutterClick();
431
+ });
432
+
433
+ // Review pill
434
+ shadow.getElementById('btn-review')?.addEventListener('click', () => {
435
+ this.stage = 'workbench';
436
+ });
437
+
438
+ // Workbench tools
439
+ shadow.getElementById('btn-retake')?.addEventListener('click', () => {
440
+ this.#retaking = true;
441
+ this.#cropMode = false;
442
+ this.stage = 'viewfinder';
443
+ });
444
+
445
+ shadow.getElementById('btn-rotate')?.addEventListener('click', async () => {
446
+ await this.#rotateActivePage();
447
+ });
448
+
449
+ shadow.getElementById('btn-filter-bw')?.addEventListener('click', async () => {
450
+ await this.#toggleActivePageBw();
451
+ });
452
+
453
+ shadow.getElementById('btn-crop')?.addEventListener('click', async () => {
454
+ await this.#toggleCropMode();
455
+ });
456
+
457
+ shadow.getElementById('btn-delete')?.addEventListener('click', async () => {
458
+ await this.#deleteActivePageWithUndo();
459
+ });
460
+
461
+ shadow.getElementById('btn-ocr')?.addEventListener('click', async () => {
462
+ await this.#openOcrSheet();
463
+ });
464
+
465
+ shadow.getElementById('btn-close-ocr')?.addEventListener('click', () => {
466
+ this.#closeOcrSheet();
467
+ });
468
+
469
+ shadow.getElementById('btn-primary-complete')?.addEventListener('click', async () => {
470
+ await this.#handlePrimaryCtaClick();
471
+ });
472
+
473
+ // Card switcher buttons
474
+ shadow.getElementById('btn-card-front')?.addEventListener('click', () => {
475
+ this.#activePageIndex = 0;
476
+ this.#syncView();
477
+ });
478
+
479
+ shadow.getElementById('btn-card-back')?.addEventListener('click', () => {
480
+ this.#activePageIndex = 1;
481
+ this.#syncView();
482
+ });
483
+
484
+ // Crop handle dragging
485
+ this.#bindCropHandles();
486
+ }
487
+
488
+ #bindCropHandles() {
489
+ const shadow = this.shadowRoot;
490
+ if (!shadow) return;
491
+
492
+ const cropBox = shadow.getElementById('crop-box');
493
+ const handles = shadow.querySelectorAll('.copio-crop-handle');
494
+ if (!cropBox || handles.length === 0) return;
495
+
496
+ let activeHandle = null;
497
+ let isDraggingBox = false;
498
+ let startX = 0;
499
+ let startY = 0;
500
+ let initialCrop = null;
501
+
502
+ const onPointerDown = (e) => {
503
+ const handleEl = e.target.closest('.copio-crop-handle');
504
+ if (handleEl) {
505
+ activeHandle = handleEl.getAttribute('data-handle');
506
+ isDraggingBox = false;
507
+ } else if (e.target === cropBox || e.target.classList.contains('copio-crop-grid')) {
508
+ activeHandle = null;
509
+ isDraggingBox = true;
510
+ } else {
511
+ return;
512
+ }
513
+
514
+ e.preventDefault();
515
+ e.stopPropagation();
516
+
517
+ startX = e.clientX;
518
+ startY = e.clientY;
519
+ initialCrop = this.#draftCrop ? { ...this.#draftCrop } : { x: 0.05, y: 0.05, w: 0.9, h: 0.9 };
520
+
521
+ window.addEventListener('pointermove', onPointerMove);
522
+ window.addEventListener('pointerup', onPointerUp);
523
+ };
524
+
525
+ const onPointerMove = (e) => {
526
+ if ((!activeHandle && !isDraggingBox) || !initialCrop) return;
527
+ const wrapper = shadow.getElementById('canvas-wrapper') || shadow.getElementById('canvas-viewport');
528
+ const rect = wrapper?.getBoundingClientRect() || { width: 300, height: 400 };
529
+
530
+ const dx = (e.clientX - startX) / Math.max(rect.width, 1);
531
+ const dy = (e.clientY - startY) / Math.max(rect.height, 1);
532
+
533
+ let { x, y, w, h } = initialCrop;
534
+
535
+ if (isDraggingBox) {
536
+ x = Math.min(Math.max(0, x + dx), 1 - w);
537
+ y = Math.min(Math.max(0, y + dy), 1 - h);
538
+ } else if (activeHandle) {
539
+ if (activeHandle.includes('w')) {
540
+ const nextX = Math.min(Math.max(0, x + dx), x + w - 0.1);
541
+ w += x - nextX;
542
+ x = nextX;
543
+ }
544
+ if (activeHandle.includes('e')) {
545
+ w = Math.min(Math.max(0.1, w + dx), 1 - x);
546
+ }
547
+ if (activeHandle.includes('n')) {
548
+ const nextY = Math.min(Math.max(0, y + dy), y + h - 0.1);
549
+ h += y - nextY;
550
+ y = nextY;
551
+ }
552
+ if (activeHandle.includes('s')) {
553
+ h = Math.min(Math.max(0.1, h + dy), 1 - y);
554
+ }
555
+ }
556
+
557
+ this.#draftCrop = { x, y, w, h };
558
+ this.#updateCropBoxUi();
559
+ };
560
+
561
+ const onPointerUp = () => {
562
+ activeHandle = null;
563
+ isDraggingBox = false;
564
+ initialCrop = null;
565
+ window.removeEventListener('pointermove', onPointerMove);
566
+ window.removeEventListener('pointerup', onPointerUp);
567
+ };
568
+
569
+ cropBox.addEventListener('pointerdown', onPointerDown);
570
+ handles.forEach((handle) => {
571
+ handle.addEventListener('pointerdown', onPointerDown);
572
+ });
573
+ }
574
+
575
+ #updateCropBoxUi() {
576
+ const shadow = this.shadowRoot;
577
+ if (!shadow || !this.#draftCrop) return;
578
+ const cropBox = shadow.getElementById('crop-box');
579
+ if (!cropBox) return;
580
+
581
+ cropBox.style.left = `${(this.#draftCrop.x * 100).toFixed(1)}%`;
582
+ cropBox.style.top = `${(this.#draftCrop.y * 100).toFixed(1)}%`;
583
+ cropBox.style.width = `${(this.#draftCrop.w * 100).toFixed(1)}%`;
584
+ cropBox.style.height = `${(this.#draftCrop.h * 100).toFixed(1)}%`;
585
+ }
586
+
587
+ async #syncView() {
588
+ if (!this.shadowRoot) return;
589
+ if (this.#renderPromise) {
590
+ return this.#renderPromise;
591
+ }
592
+ this.#renderPromise = (async () => {
593
+ try {
594
+ await Promise.resolve();
595
+ await this.#doSyncView();
596
+ } finally {
597
+ this.#renderPromise = null;
598
+ }
599
+ })();
600
+ return this.#renderPromise;
601
+ }
602
+
603
+ async #doSyncView() {
604
+ if (!this.shadowRoot) return;
605
+
606
+ try {
607
+ const pages = await this.getPages();
608
+ this.#pageCount = pages.length;
609
+ const shadow = this.shadowRoot;
610
+
611
+ // Update badge, title, subtitle
612
+ const modeBadge = shadow.getElementById('mode-badge');
613
+ if (modeBadge) {
614
+ modeBadge.textContent = (this.mode || 'single').toUpperCase();
615
+ }
616
+
617
+ // Update tabs
618
+ const tabViewfinder = shadow.getElementById('tab-viewfinder');
619
+ const tabWorkbench = shadow.getElementById('tab-workbench');
620
+ if (tabViewfinder) tabViewfinder.setAttribute('aria-selected', String(this.#stage === 'viewfinder'));
621
+ if (tabWorkbench) tabWorkbench.setAttribute('aria-selected', String(this.#stage === 'workbench'));
622
+
623
+ // Viewfinder vs Workbench display
624
+ const vfSection = shadow.getElementById('viewfinder-section');
625
+ const wbSection = shadow.getElementById('workbench-section');
626
+ if (vfSection && wbSection) {
627
+ if (this.#stage === 'viewfinder') {
628
+ vfSection.style.display = 'flex';
629
+ wbSection.style.display = 'none';
630
+ } else {
631
+ vfSection.style.display = 'none';
632
+ wbSection.style.display = 'flex';
633
+ }
634
+ }
635
+
636
+ // Update aspect attribute on framing guide
637
+ const guide = shadow.getElementById('framing-guide');
638
+ if (guide) {
639
+ guide.setAttribute('data-aspect', this.aspect || 'auto');
640
+ }
641
+
642
+ // Step pill text in viewfinder
643
+ const stepPillText = shadow.getElementById('step-pill-text');
644
+ if (stepPillText) {
645
+ if (this.#cameraStream) {
646
+ stepPillText.textContent = 'Camera Active · Tap Shutter to Snap';
647
+ } else if (this.aspect === 'card' && this.maxPages === 2) {
648
+ stepPillText.textContent = pages.length === 0
649
+ ? 'Step 1 of 2: Capture Front of ID Card'
650
+ : 'Step 2 of 2: Capture Back of ID Card';
651
+ } else if (this.aspect === 'card') {
652
+ stepPillText.textContent = 'Align Card Inside Frame';
653
+ } else if (this.mode === 'batch') {
654
+ stepPillText.textContent = `Batch Capture · Page ${pages.length + 1}`;
655
+ } else {
656
+ stepPillText.textContent = 'Align Document Inside Frame';
657
+ }
658
+ }
659
+
660
+ // OCR toolbar button visibility
661
+ const btnOcr = shadow.getElementById('btn-ocr');
662
+ if (btnOcr) {
663
+ btnOcr.style.display = this.ocrEnabled && this.hasFeature('ocr') ? '' : 'none';
664
+ }
665
+
666
+ // Review pill in shutter dock
667
+ const reviewBtn = shadow.getElementById('btn-review');
668
+ const reviewText = shadow.getElementById('review-pill-text');
669
+ if (reviewBtn && reviewText) {
670
+ if (pages.length > 0) {
671
+ reviewBtn.style.display = 'inline-flex';
672
+ reviewText.textContent = `Review (${pages.length}) →`;
673
+ } else {
674
+ reviewBtn.style.display = 'none';
675
+ }
676
+ }
677
+
678
+ // Workbench view sync
679
+ if (pages.length === 0) {
680
+ if (this.#stage === 'workbench') {
681
+ this.stage = 'viewfinder';
682
+ }
683
+ return;
684
+ }
685
+
686
+ if (this.#activePageIndex >= pages.length) {
687
+ this.#activePageIndex = Math.max(0, pages.length - 1);
688
+ }
689
+ const activePage = pages[this.#activePageIndex];
690
+
691
+ // Card side switcher visibility
692
+ const cardSwitcher = shadow.getElementById('card-side-switcher');
693
+ if (cardSwitcher) {
694
+ const isCardGuided = this.aspect === 'card' && this.maxPages === 2;
695
+ cardSwitcher.style.display = isCardGuided ? 'flex' : 'none';
696
+ const btnFront = shadow.getElementById('btn-card-front');
697
+ const btnBack = shadow.getElementById('btn-card-back');
698
+ if (btnFront) {
699
+ btnFront.classList.toggle('active', this.#activePageIndex === 0);
700
+ btnFront.setAttribute('aria-selected', String(this.#activePageIndex === 0));
701
+ }
702
+ if (btnBack) {
703
+ btnBack.classList.toggle('active', this.#activePageIndex === 1);
704
+ btnBack.setAttribute('aria-selected', String(this.#activePageIndex === 1));
705
+ }
706
+ }
707
+
708
+ // Image in viewport: in crop mode show originalSrc, otherwise show src
709
+ const stageImg = /** @type {HTMLImageElement|null} */ (shadow.getElementById('stage-img'));
710
+ if (stageImg) {
711
+ stageImg.src = this.#cropMode
712
+ ? activePage.originalSrc || activePage.src || ''
713
+ : activePage.src || activePage.originalSrc || '';
714
+ }
715
+
716
+ let cropLayer = shadow.getElementById('crop-layer');
717
+ if (this.#cropMode) {
718
+ if (!cropLayer) {
719
+ const wrapper = shadow.getElementById('canvas-wrapper');
720
+ cropLayer = document.createElement('div');
721
+ cropLayer.className = 'copio-crop-layer';
722
+ cropLayer.id = 'crop-layer';
723
+ cropLayer.innerHTML = `
724
+ <div class="copio-crop-box" id="crop-box">
725
+ <div class="copio-crop-grid"></div>
726
+ <span class="copio-crop-handle nw" data-handle="nw"></span>
727
+ <span class="copio-crop-handle ne" data-handle="ne"></span>
728
+ <span class="copio-crop-handle se" data-handle="se"></span>
729
+ <span class="copio-crop-handle sw" data-handle="sw"></span>
730
+ <span class="copio-crop-handle n edge-n" data-handle="n"></span>
731
+ <span class="copio-crop-handle e edge-e" data-handle="e"></span>
732
+ <span class="copio-crop-handle s edge-s" data-handle="s"></span>
733
+ <span class="copio-crop-handle w edge-w" data-handle="w"></span>
734
+ </div>
735
+ `;
736
+ wrapper?.appendChild(cropLayer);
737
+ this.#bindCropHandles();
738
+ }
739
+ cropLayer.style.display = 'block';
740
+ this.#draftCrop = activePage.edits?.crop || { x: 0.05, y: 0.05, w: 0.9, h: 0.9 };
741
+ this.#updateCropBoxUi();
742
+ } else if (cropLayer) {
743
+ cropLayer.remove();
744
+ }
745
+
746
+ // Crop button text
747
+ const cropBtnLabel = shadow.getElementById('crop-btn-label');
748
+ if (cropBtnLabel) {
749
+ cropBtnLabel.textContent = this.#cropMode ? 'Apply' : 'Crop';
750
+ }
751
+
752
+ // Primary CTA label
753
+ const primaryCta = shadow.getElementById('btn-primary-complete');
754
+ if (primaryCta) {
755
+ if (this.aspect === 'card' && this.maxPages === 2 && pages.length === 1) {
756
+ primaryCta.textContent = 'Next: Capture Back (Step 2/2) →';
757
+ } else if (this.aspect === 'card' && pages.length >= 2) {
758
+ primaryCta.textContent = '✓ Complete ID Scan (2 Sides)';
759
+ } else if (this.mode === 'batch') {
760
+ primaryCta.textContent = `✓ Complete Scan (${pages.length} Pages)`;
761
+ } else {
762
+ primaryCta.textContent = '✓ Use Photo';
763
+ }
764
+ }
765
+
766
+ // Filmstrip rendering
767
+ this.#renderFilmstrip(pages);
768
+ } catch {
769
+ // Ignore background render errors during teardown
770
+ }
771
+ }
772
+
773
+ #renderFilmstrip(pages) {
774
+ const shadow = this.shadowRoot;
775
+ if (!shadow) return;
776
+ const scrollContainer = shadow.getElementById('filmstrip-scroll');
777
+ if (!scrollContainer) return;
778
+
779
+ scrollContainer.innerHTML = '';
780
+ pages.forEach((page, idx) => {
781
+ const item = document.createElement('div');
782
+ item.className = `copio-filmstrip-item ${idx === this.#activePageIndex ? 'is-active' : ''}`;
783
+ item.setAttribute('data-index', String(idx));
784
+
785
+ item.innerHTML = `
786
+ <div class="copio-thumb-container">
787
+ <img src="${page.src || page.originalSrc}" alt="Page ${idx + 1}" class="copio-thumb-img" />
788
+ <span class="copio-thumb-num">${idx + 1}</span>
789
+ </div>
790
+ ${this.mode === 'batch' ? `
791
+ <div class="copio-thumb-reorder">
792
+ <button type="button" class="copio-reorder-btn move-left" title="Move Left" ${idx === 0 ? 'disabled' : ''}>◀</button>
793
+ <button type="button" class="copio-reorder-btn move-right" title="Move Right" ${idx === pages.length - 1 ? 'disabled' : ''}>▶</button>
794
+ </div>
795
+ ` : ''}
796
+ `;
797
+
798
+ item.querySelector('.copio-thumb-container')?.addEventListener('click', () => {
799
+ this.#activePageIndex = idx;
800
+ this.#cropMode = false;
801
+ this.#syncView();
802
+ });
803
+
804
+ if (this.mode === 'batch') {
805
+ item.querySelector('.move-left')?.addEventListener('click', async (e) => {
806
+ e.stopPropagation();
807
+ await this.#movePage(idx, idx - 1);
808
+ });
809
+ item.querySelector('.move-right')?.addEventListener('click', async (e) => {
810
+ e.stopPropagation();
811
+ await this.#movePage(idx, idx + 1);
812
+ });
813
+ }
814
+
815
+ scrollContainer.appendChild(item);
816
+ });
817
+ }
818
+
819
+ async #movePage(fromIdx, toIdx) {
820
+ const pages = await this.getPages();
821
+ if (toIdx < 0 || toIdx >= pages.length || fromIdx === toIdx) return;
822
+
823
+ const pageIds = pages.map((p) => p.id);
824
+ const [moved] = pageIds.splice(fromIdx, 1);
825
+ pageIds.splice(toIdx, 0, moved);
826
+
827
+ await this.#engine.reorderPages(this.#targetDocId, pageIds);
828
+ this.#activePageIndex = toIdx;
829
+ this.#syncView();
830
+ }
831
+
832
+ #stopCameraStream() {
833
+ if (this.#cameraStream) {
834
+ this.#cameraStream.getTracks().forEach((track) => track.stop());
835
+ this.#cameraStream = null;
836
+ }
837
+ const shadow = this.shadowRoot;
838
+ const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
839
+ if (videoEl) {
840
+ videoEl.srcObject = null;
841
+ videoEl.style.display = 'none';
842
+ }
843
+ const placeholder = shadow?.querySelector('.copio-camera-placeholder');
844
+ if (placeholder) {
845
+ /** @type {HTMLElement} */ (placeholder).style.display = '';
846
+ }
847
+ }
848
+
849
+ async #handleShutterClick() {
850
+ if (typeof this.onShutter === 'function') {
851
+ const handled = await this.onShutter();
852
+ if (handled !== false) return;
853
+ }
854
+
855
+ const shadow = this.shadowRoot;
856
+ const videoEl = /** @type {HTMLVideoElement|null} */ (shadow?.getElementById('camera-video'));
857
+
858
+ // If camera stream is already active, capture a frame from the video element
859
+ if (this.#cameraStream && videoEl && videoEl.readyState >= 2) {
860
+ const canvas = document.createElement('canvas');
861
+ canvas.width = videoEl.videoWidth || 1280;
862
+ canvas.height = videoEl.videoHeight || 720;
863
+ const ctx = canvas.getContext('2d');
864
+ if (ctx) {
865
+ ctx.drawImage(videoEl, 0, 0, canvas.width, canvas.height);
866
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.92));
867
+ if (blob) {
868
+ this.#stopCameraStream();
869
+ const file = new File([blob], `capture_${Date.now()}.jpg`, { type: 'image/jpeg' });
870
+ await this.addFiles([file]);
871
+ return;
872
+ }
873
+ }
874
+ }
875
+
876
+ // Try opening live MediaDevices camera stream if supported in real browsers
877
+ const isAutomatedTest = typeof navigator !== 'undefined' && navigator.webdriver === true;
878
+ if (!isAutomatedTest && typeof navigator !== 'undefined' && navigator.mediaDevices?.getUserMedia && videoEl) {
879
+ try {
880
+ this.#cameraStream = await navigator.mediaDevices.getUserMedia({
881
+ video: { facingMode: { ideal: 'environment' }, width: { ideal: 1920 }, height: { ideal: 1080 } },
882
+ audio: false,
883
+ });
884
+ videoEl.srcObject = this.#cameraStream;
885
+ videoEl.style.display = 'block';
886
+ await videoEl.play();
887
+ const placeholder = shadow?.querySelector('.copio-camera-placeholder');
888
+ if (placeholder) {
889
+ /** @type {HTMLElement} */ (placeholder).style.display = 'none';
890
+ }
891
+ const stepPillText = shadow?.getElementById('step-pill-text');
892
+ if (stepPillText) {
893
+ stepPillText.textContent = 'Camera Active · Tap Shutter to Snap';
894
+ }
895
+ return;
896
+ } catch {
897
+ // Fallback to file input if camera permission denied or unavailable
898
+ }
899
+ }
900
+
901
+ const fileInput = shadow?.getElementById('internal-file-input');
902
+ if (fileInput && typeof fileInput.click === 'function') {
903
+ fileInput.click();
904
+ }
905
+ }
906
+
907
+ async #rotateActivePage() {
908
+ const pages = await this.getPages();
909
+ const activePage = pages[this.#activePageIndex];
910
+ if (!activePage) return;
911
+
912
+ const currentRotate = activePage.edits?.rotate || 0;
913
+ const newRotate = (currentRotate + 90) % 360;
914
+
915
+ await this.#engine.applyEdit(this.#targetDocId, activePage.id, {
916
+ rotate: newRotate,
917
+ });
918
+ await this.#syncView();
919
+ }
920
+
921
+ async #toggleActivePageBw() {
922
+ const pages = await this.getPages();
923
+ const activePage = pages[this.#activePageIndex];
924
+ if (!activePage) return;
925
+
926
+ const currentFilter = activePage.edits?.filter || 'none';
927
+ const newFilter = currentFilter === 'bw' ? 'none' : 'bw';
928
+
929
+ await this.#engine.applyEdit(this.#targetDocId, activePage.id, {
930
+ filter: newFilter,
931
+ });
932
+ await this.#syncView();
933
+ }
934
+
935
+ async #toggleCropMode() {
936
+ const pages = await this.getPages();
937
+ const activePage = pages[this.#activePageIndex];
938
+ if (!activePage) return;
939
+
940
+ if (this.#cropMode) {
941
+ this.#cropMode = false;
942
+ const draft = this.#draftCrop;
943
+ this.#draftCrop = null;
944
+ if (draft) {
945
+ await this.#engine.applyEdit(this.#targetDocId, activePage.id, {
946
+ crop: draft,
947
+ });
948
+ }
949
+ } else {
950
+ this.#cropMode = true;
951
+ }
952
+ await this.#syncView();
953
+ }
954
+
955
+ async #deleteActivePageWithUndo() {
956
+ const pages = await this.getPages();
957
+ const activePage = pages[this.#activePageIndex];
958
+ if (!activePage) return;
959
+
960
+ const deletedPageId = activePage.id;
961
+ await this.#engine.deletePage(this.#targetDocId, deletedPageId);
962
+
963
+ this.dispatch(COPIO_EVENTS.PAGE_REMOVED, {
964
+ pageId: deletedPageId,
965
+ docId: this.docId,
966
+ });
967
+
968
+ if (this.#activePageIndex >= pages.length - 1) {
969
+ this.#activePageIndex = Math.max(0, pages.length - 2);
970
+ }
971
+
972
+ this.#showUndoToast();
973
+ await this.#syncView();
974
+ }
975
+
976
+ #showUndoToast() {
977
+ const shadow = this.shadowRoot;
978
+ if (!shadow) return;
979
+ const toastRegion = shadow.getElementById('toast-region');
980
+ if (!toastRegion) return;
981
+
982
+ if (this.#undoTimer) {
983
+ clearInterval(this.#undoTimer);
984
+ }
985
+
986
+ this.#undoRemaining = 5;
987
+ const renderToast = () => {
988
+ toastRegion.innerHTML = `
989
+ <div class="copio-toast copio-toast-undo">
990
+ <span>Page deleted</span>
991
+ <button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
992
+ Undo (${this.#undoRemaining}s)
993
+ </button>
994
+ </div>
995
+ `;
996
+
997
+ shadow.getElementById('btn-toast-undo')?.addEventListener('click', async () => {
998
+ clearInterval(this.#undoTimer);
999
+ this.#undoTimer = null;
1000
+ toastRegion.innerHTML = '';
1001
+ await this.#engine.undo(this.#targetDocId);
1002
+ await this.#syncView();
1003
+ });
1004
+ };
1005
+
1006
+ renderToast();
1007
+ this.#undoTimer = setInterval(() => {
1008
+ this.#undoRemaining -= 1;
1009
+ if (this.#undoRemaining <= 0) {
1010
+ clearInterval(this.#undoTimer);
1011
+ this.#undoTimer = null;
1012
+ toastRegion.innerHTML = '';
1013
+ } else {
1014
+ renderToast();
1015
+ }
1016
+ }, 1000);
1017
+ }
1018
+
1019
+ async #openOcrSheet() {
1020
+ const shadow = this.shadowRoot;
1021
+ if (!shadow) return;
1022
+ const sheet = shadow.getElementById('ocr-sheet');
1023
+ const body = shadow.getElementById('ocr-body');
1024
+ if (!sheet || !body) return;
1025
+
1026
+ sheet.style.display = 'block';
1027
+ body.innerHTML = `<p class="copio-ocr-loading">Recognizing text...</p>`;
1028
+
1029
+ try {
1030
+ const pages = await this.getPages();
1031
+ const activePage = pages[this.#activePageIndex];
1032
+ const result = await this.ocr(activePage?.id || null);
1033
+
1034
+ const rawConf = result.averageConfidence || 0;
1035
+ const confPct = rawConf <= 1 && rawConf > 0 ? Math.round(rawConf * 100) : Math.round(rawConf);
1036
+
1037
+ body.innerHTML = `
1038
+ <div class="copio-ocr-content">
1039
+ <pre class="copio-ocr-text">${result.text || 'No text detected.'}</pre>
1040
+ <div class="copio-ocr-meta">
1041
+ <span>Confidence: ${confPct}%</span>
1042
+ </div>
1043
+ </div>
1044
+ `;
1045
+ } catch (err) {
1046
+ body.innerHTML = `<p class="copio-ocr-error">OCR recognition failed: ${err.message}</p>`;
1047
+ }
1048
+ }
1049
+
1050
+ #closeOcrSheet() {
1051
+ const shadow = this.shadowRoot;
1052
+ if (!shadow) return;
1053
+ const sheet = shadow.getElementById('ocr-sheet');
1054
+ if (sheet) sheet.style.display = 'none';
1055
+ }
1056
+
1057
+ async #handlePrimaryCtaClick() {
1058
+ if (this.aspect === 'card' && this.maxPages === 2 && this.#pageCount === 1) {
1059
+ this.stage = 'viewfinder';
1060
+ return;
1061
+ }
1062
+
1063
+ const pages = await this.getPages();
1064
+
1065
+ // Guided 2-step card mode: if on step 1, advance to viewfinder for step 2
1066
+ if (this.aspect === 'card' && this.maxPages === 2 && pages.length === 1) {
1067
+ this.stage = 'viewfinder';
1068
+ return;
1069
+ }
1070
+
1071
+ // Complete scan and emit unified copio:scan-complete
1072
+ const summarizedPages = pages.map((p, idx) => ({
1073
+ id: p.id,
1074
+ pageNumber: idx + 1,
1075
+ label: p.label || `Page ${idx + 1}`,
1076
+ originalSrc: p.originalSrc,
1077
+ src: p.src,
1078
+ originalPreserved: true,
1079
+ dimensions: { width: p.width || 0, height: p.height || 0 },
1080
+ edits: p.edits || { crop: { x: 0, y: 0, w: 1, h: 1 }, rotate: 0, filter: 'none' },
1081
+ ocrText: p.ocrText || null,
1082
+ blob: p.blob || null,
1083
+ }));
1084
+
1085
+ const payload = {
1086
+ mode: this.mode,
1087
+ aspect: this.aspect,
1088
+ docId: this.docId,
1089
+ pageCount: summarizedPages.length,
1090
+ pages: summarizedPages,
1091
+ };
1092
+
1093
+ if (this.mode === 'single') {
1094
+ payload.page = summarizedPages[0] || null;
1095
+ if (this.maxPages > 1) {
1096
+ payload.maxPages = this.maxPages;
1097
+ }
1098
+ }
1099
+
1100
+ this.dispatch(COPIO_EVENTS.SCAN_COMPLETE, payload);
1101
+ }
1102
+
1103
+ // --- Configuration Properties (CPO-034, CPO-035, CPO-038) ---
1104
+
1105
+ get theme() {
1106
+ return typeof this.getAttribute === 'function'
1107
+ ? /** @type {'dark'|'light'|'brand'|'auto'} */ (this.getAttribute('theme') || 'dark')
1108
+ : 'dark';
1109
+ }
1110
+
1111
+ set theme(val) {
1112
+ if (typeof this.setAttribute === 'function') {
1113
+ if (val) this.setAttribute('theme', val);
1114
+ else this.removeAttribute('theme');
1115
+ }
1116
+ }
1117
+
1118
+ get mode() {
1119
+ return typeof this.getAttribute === 'function'
1120
+ ? /** @type {'single'|'batch'|'document'} */ (this.getAttribute('mode') || 'document')
1121
+ : 'document';
1122
+ }
1123
+
1124
+ set mode(val) {
1125
+ if (typeof this.setAttribute === 'function') {
1126
+ this.setAttribute('mode', val);
1127
+ }
1128
+ }
1129
+
1130
+ get aspect() {
1131
+ return typeof this.getAttribute === 'function'
1132
+ ? /** @type {'receipt'|'card'|'a4'|'auto'} */ (this.getAttribute('aspect') || 'auto')
1133
+ : 'auto';
1134
+ }
1135
+
1136
+ set aspect(val) {
1137
+ if (typeof this.setAttribute === 'function') {
1138
+ this.setAttribute('aspect', val);
1139
+ }
1140
+ }
1141
+
1142
+ get stage() {
1143
+ return this.#stage;
1144
+ }
1145
+
1146
+ set stage(val) {
1147
+ if (val === 'viewfinder' || val === 'workbench') {
1148
+ this.#stage = val;
1149
+ if (typeof this.setAttribute === 'function' && this.getAttribute('stage') !== val) {
1150
+ this.setAttribute('stage', val);
1151
+ }
1152
+ const shadow = this.shadowRoot;
1153
+ if (shadow) {
1154
+ const vf = shadow.getElementById('viewfinder-section');
1155
+ const wb = shadow.getElementById('workbench-section');
1156
+ if (vf && wb) {
1157
+ vf.style.display = val === 'viewfinder' ? 'flex' : 'none';
1158
+ wb.style.display = val === 'workbench' ? 'flex' : 'none';
1159
+ }
1160
+ }
1161
+ this.#syncView();
1162
+ }
1163
+ }
1164
+
1165
+ get docId() {
1166
+ return typeof this.getAttribute === 'function' ? this.getAttribute('doc-id') : null;
1167
+ }
1168
+
1169
+ set docId(val) {
1170
+ if (typeof this.setAttribute === 'function') {
1171
+ if (val) this.setAttribute('doc-id', val);
1172
+ else this.removeAttribute('doc-id');
1173
+ }
1174
+ }
1175
+
1176
+ // --- Imperative UI Actions ---
1177
+
1178
+ async rotateActivePage() {
1179
+ return this.#rotateActivePage();
1180
+ }
1181
+
1182
+ async toggleActivePageBw() {
1183
+ return this.#toggleActivePageBw();
1184
+ }
1185
+
1186
+ async toggleCropMode() {
1187
+ return this.#toggleCropMode();
1188
+ }
1189
+
1190
+ async deleteActivePageWithUndo() {
1191
+ return this.#deleteActivePageWithUndo();
1192
+ }
1193
+
1194
+ get features() {
1195
+ return this.#engine ? this.#engine.features : [];
1196
+ }
1197
+
1198
+ set features(val) {
1199
+ if (typeof this.setAttribute === 'function') {
1200
+ const str = Array.isArray(val) ? val.join(' ') : String(val || '');
1201
+ this.setAttribute('features', str);
1202
+ }
1203
+ if (this.#engine) {
1204
+ this.#engine.setFeatures(val);
1205
+ }
1206
+ }
1207
+
1208
+ hasFeature(featureName) {
1209
+ return this.#engine ? this.#engine.hasFeature(featureName) : false;
1210
+ }
1211
+
1212
+ get ocrEnabled() {
1213
+ return this.#engine ? this.#engine.ocr : true;
1214
+ }
1215
+
1216
+ set ocrEnabled(val) {
1217
+ const enabled = Boolean(val);
1218
+ if (typeof this.setAttribute === 'function') {
1219
+ this.setAttribute('ocr', enabled ? 'true' : 'false');
1220
+ }
1221
+ if (this.#engine) {
1222
+ this.#engine.ocr = enabled;
1223
+ }
1224
+ this.#updateChildViews();
1225
+ }
1226
+
1227
+ get pdf() {
1228
+ return this.#engine ? this.#engine.pdf : true;
1229
+ }
1230
+
1231
+ set pdf(val) {
1232
+ const enabled = Boolean(val);
1233
+ if (typeof this.setAttribute === 'function') {
1234
+ this.setAttribute('pdf', enabled ? 'true' : 'false');
1235
+ }
1236
+ if (this.#engine) {
1237
+ this.#engine.pdf = enabled;
1238
+ }
1239
+ this.#updateChildViews();
1240
+ }
1241
+
1242
+ get exportFormats() {
1243
+ return this.#engine ? this.#engine.exportFormats : [];
1244
+ }
1245
+
1246
+ set exportFormats(val) {
1247
+ if (typeof this.setAttribute === 'function') {
1248
+ const str = Array.isArray(val) ? val.join(',') : String(val || '');
1249
+ this.setAttribute('export-formats', str);
1250
+ }
1251
+ if (this.#engine) {
1252
+ this.#engine.exportFormats = val;
1253
+ }
1254
+ }
1255
+
1256
+ get ocrLanguages() {
1257
+ return this.#engine ? this.#engine.ocrLanguages : [];
1258
+ }
1259
+
1260
+ set ocrLanguages(val) {
1261
+ if (typeof this.setAttribute === 'function') {
1262
+ const str = Array.isArray(val) ? val.join(',') : String(val || '');
1263
+ this.setAttribute('ocr-languages', str);
1264
+ }
1265
+ if (this.#engine) {
1266
+ this.#engine.ocrLanguages = val;
1267
+ }
1268
+ }
1269
+
1270
+ get maxPages() {
1271
+ return this.#engine ? this.#engine.maxPages : 0;
1272
+ }
1273
+
1274
+ set maxPages(val) {
1275
+ if (typeof this.setAttribute === 'function') {
1276
+ this.setAttribute('max-pages', String(val));
1277
+ }
1278
+ if (this.#engine) {
1279
+ this.#engine.maxPages = val;
1280
+ }
1281
+ }
1282
+
1283
+ get assetBase() {
1284
+ return this.#engine ? this.#engine.assetBase : '';
1285
+ }
1286
+
1287
+ set assetBase(val) {
1288
+ if (typeof this.setAttribute === 'function') {
1289
+ this.setAttribute('asset-base', String(val || ''));
1290
+ }
1291
+ if (this.#engine) {
1292
+ this.#engine.assetBase = val;
1293
+ }
1294
+ }
1295
+
1296
+ get licenseKey() {
1297
+ return this.#engine ? this.#engine.licenseKey : '';
1298
+ }
1299
+
1300
+ set licenseKey(val) {
1301
+ if (typeof this.setAttribute === 'function') {
1302
+ this.setAttribute('license-key', String(val || ''));
1303
+ }
1304
+ if (this.#engine) {
1305
+ this.#engine.licenseKey = val;
1306
+ }
1307
+ }
1308
+
1309
+ get storage() {
1310
+ return this.#storage;
1311
+ }
1312
+
1313
+ set storage(adapter) {
1314
+ this.#storage = adapter;
1315
+ if (this.#engine) {
1316
+ this.#engine.setStorage(adapter);
1317
+ }
1318
+ }
1319
+
1320
+ get engine() {
1321
+ return this.#engine;
1322
+ }
1323
+
1324
+ set engine(customEngine) {
1325
+ if (customEngine instanceof CopioEngine) {
1326
+ this.#engine = customEngine;
1327
+ }
1328
+ }
1329
+
1330
+ // --- Public Event Dispatcher Helper (CPO-036) ---
1331
+
1332
+ dispatch(eventName, detail = {}) {
1333
+ return dispatchCopioEvent(this, eventName, detail);
1334
+ }
1335
+
1336
+ // --- Public Methods API (CPO-037) ---
1337
+
1338
+ async open() {
1339
+ this.#isOpen = true;
1340
+ if (typeof this.focus === 'function') this.focus();
1341
+ }
1342
+
1343
+ async close() {
1344
+ this.#isOpen = false;
1345
+ this.#stopCameraStream();
1346
+ }
1347
+
1348
+ get isOpen() {
1349
+ return this.#isOpen;
1350
+ }
1351
+
1352
+ async capture() {
1353
+ return new Promise((resolve) => {
1354
+ const input = document.createElement('input');
1355
+ input.type = 'file';
1356
+ input.accept = 'image/*';
1357
+ input.capture = 'environment';
1358
+ input.style.display = 'none';
1359
+
1360
+ input.onchange = async () => {
1361
+ try {
1362
+ if (input.files && input.files.length > 0) {
1363
+ const added = await this.addFiles([input.files[0]]);
1364
+ resolve(added[0] || null);
1365
+ } else {
1366
+ resolve(null);
1367
+ }
1368
+ } catch (err) {
1369
+ this.dispatch(COPIO_EVENTS.ERROR, {
1370
+ code: 'CAPTURE_FAILED',
1371
+ message: err.message,
1372
+ error: err,
1373
+ });
1374
+ resolve(null);
1375
+ } finally {
1376
+ input.remove();
1377
+ }
1378
+ };
1379
+
1380
+ input.onerror = () => {
1381
+ input.remove();
1382
+ resolve(null);
1383
+ };
1384
+
1385
+ document.body.appendChild(input);
1386
+ input.click();
1387
+ });
1388
+ }
1389
+
1390
+ async addFiles(files) {
1391
+ try {
1392
+ const existingPages = await this.getPages();
1393
+ let replaceIndex = null;
1394
+
1395
+ if (existingPages.length > 0) {
1396
+ if (this.mode === 'single' && this.maxPages <= 1) {
1397
+ // Single-page mode: replace the current page when a new file is uploaded/captured
1398
+ await this.#engine.clear(this.#targetDocId);
1399
+ } else if (this.#retaking || (this.maxPages > 0 && existingPages.length >= this.maxPages)) {
1400
+ // Retaking active page or replacing active slot when at maxPages capacity
1401
+ const targetIdx = Math.min(this.#activePageIndex, existingPages.length - 1);
1402
+ const pageToReplace = existingPages[targetIdx];
1403
+ if (pageToReplace) {
1404
+ replaceIndex = targetIdx;
1405
+ await this.#engine.deletePage(this.#targetDocId, pageToReplace.id);
1406
+ }
1407
+ }
1408
+ }
1409
+ this.#retaking = false;
1410
+
1411
+ const newPages = await this.#engine.addFiles(files, this.#targetDocId);
1412
+ for (let i = 0; i < newPages.length; i++) {
1413
+ this.dispatch(COPIO_EVENTS.PAGE_ADDED, {
1414
+ page: newPages[i],
1415
+ pageNumber: i + 1,
1416
+ docId: this.docId,
1417
+ source: 'file',
1418
+ });
1419
+ }
1420
+
1421
+ let allPages = await this.getPages();
1422
+ if (replaceIndex !== null && newPages.length === 1 && replaceIndex < allPages.length - 1) {
1423
+ const pageIds = allPages.map((p) => p.id);
1424
+ const addedId = pageIds.pop();
1425
+ if (addedId) {
1426
+ pageIds.splice(replaceIndex, 0, addedId);
1427
+ await this.#engine.reorderPages(this.#targetDocId, pageIds);
1428
+ allPages = await this.getPages();
1429
+ }
1430
+ }
1431
+
1432
+ this.#pageCount = allPages.length;
1433
+ if (newPages.length > 0) {
1434
+ this.#activePageIndex = replaceIndex !== null
1435
+ ? Math.min(replaceIndex, Math.max(0, allPages.length - 1))
1436
+ : Math.max(0, allPages.length - 1);
1437
+ if (this.mode === 'single') {
1438
+ this.#stage = 'workbench';
1439
+ if (typeof this.setAttribute === 'function' && this.getAttribute('stage') !== 'workbench') {
1440
+ this.setAttribute('stage', 'workbench');
1441
+ }
1442
+ }
1443
+ }
1444
+
1445
+ this.dispatch(COPIO_EVENTS.PAGES_CHANGED, {
1446
+ pages: allPages,
1447
+ docId: this.docId,
1448
+ });
1449
+
1450
+ if (this.mode === 'single' && newPages.length > 0 && this.maxPages <= 1) {
1451
+ this.dispatch(COPIO_EVENTS.SCAN_COMPLETE, {
1452
+ mode: this.mode,
1453
+ aspect: this.aspect,
1454
+ docId: this.docId,
1455
+ pages: allPages,
1456
+ page: allPages[allPages.length - 1] || null,
1457
+ pageCount: allPages.length,
1458
+ });
1459
+ }
1460
+
1461
+ await this.#syncView();
1462
+ return newPages;
1463
+ } catch (err) {
1464
+ this.dispatch(COPIO_EVENTS.ERROR, {
1465
+ code: err.code || 'ADD_FILES_FAILED',
1466
+ message: err.message,
1467
+ error: err,
1468
+ });
1469
+ throw err;
1470
+ }
1471
+ }
1472
+
1473
+ async getPages() {
1474
+ return this.#engine.getPages(this.#targetDocId);
1475
+ }
1476
+
1477
+ async clear() {
1478
+ this.#stopCameraStream();
1479
+ this.#activePageIndex = 0;
1480
+ this.#pageCount = 0;
1481
+ this.#retaking = false;
1482
+ this.#cropMode = false;
1483
+ await this.#engine.clear(this.#targetDocId);
1484
+ this.dispatch(COPIO_EVENTS.PAGES_CHANGED, {
1485
+ pages: [],
1486
+ docId: this.docId,
1487
+ });
1488
+ await this.#syncView();
1489
+ }
1490
+
1491
+ async exportPdf(opts = {}) {
1492
+ try {
1493
+ const blob = await this.#engine.exportPdf(this.#targetDocId, opts);
1494
+ this.dispatch(COPIO_EVENTS.EXPORT_COMPLETE, {
1495
+ type: 'pdf',
1496
+ format: 'pdf',
1497
+ blob,
1498
+ docId: this.docId,
1499
+ });
1500
+ return blob;
1501
+ } catch (err) {
1502
+ this.dispatch(COPIO_EVENTS.ERROR, {
1503
+ code: err.code || 'EXPORT_FAILED',
1504
+ message: err.message,
1505
+ error: err,
1506
+ });
1507
+ throw err;
1508
+ }
1509
+ }
1510
+
1511
+ async exportZip(opts = {}) {
1512
+ try {
1513
+ const blob = await this.#engine.exportZip(this.#targetDocId, opts);
1514
+ this.dispatch(COPIO_EVENTS.EXPORT_COMPLETE, {
1515
+ type: 'zip',
1516
+ format: 'zip',
1517
+ blob,
1518
+ docId: this.docId,
1519
+ });
1520
+ return blob;
1521
+ } catch (err) {
1522
+ this.dispatch(COPIO_EVENTS.ERROR, {
1523
+ code: err.code || 'EXPORT_FAILED',
1524
+ message: err.message,
1525
+ error: err,
1526
+ });
1527
+ throw err;
1528
+ }
1529
+ }
1530
+
1531
+ async ocr(pageId = null, opts = {}) {
1532
+ try {
1533
+ const result = await this.#engine.runOcr(this.#targetDocId, pageId, opts);
1534
+ this.dispatch(COPIO_EVENTS.OCR_COMPLETE, {
1535
+ text: result.text,
1536
+ pages: result.pagesResults,
1537
+ averageConfidence: result.averageConfidence,
1538
+ docId: this.docId,
1539
+ pageId,
1540
+ });
1541
+ return result;
1542
+ } catch (err) {
1543
+ this.dispatch(COPIO_EVENTS.ERROR, {
1544
+ code: err.code || 'OCR_FAILED',
1545
+ message: err.message,
1546
+ error: err,
1547
+ });
1548
+ throw err;
1549
+ }
1550
+ }
1551
+
1552
+ async runOcr(pageId = null, opts = {}) {
1553
+ return this.ocr(pageId, opts);
1554
+ }
1555
+
1556
+ async sync(opts = {}) {
1557
+ try {
1558
+ const manager = await this.#engine.sync({
1559
+ onStateChange: (state) => {
1560
+ if (state && (state.step === 'connected' || state.step === 'syncing')) {
1561
+ this.dispatch(COPIO_EVENTS.SYNC_CONNECTED, {
1562
+ peerId: state.peerId,
1563
+ mode: state.mode,
1564
+ });
1565
+ }
1566
+ if (opts.onStateChange) opts.onStateChange(state);
1567
+ },
1568
+ });
1569
+ return manager;
1570
+ } catch (err) {
1571
+ this.dispatch(COPIO_EVENTS.ERROR, {
1572
+ code: err.code || 'SYNC_FAILED',
1573
+ message: err.message,
1574
+ error: err,
1575
+ });
1576
+ throw err;
1577
+ }
1578
+ }
1579
+ }
1580
+
1581
+ if (typeof customElements !== 'undefined' && !customElements.get('copio-scanner')) {
1582
+ customElements.define('copio-scanner', CopioScanner);
1583
+ }
1584
+
1585
+ export {
1586
+ CopioImages,
1587
+ CopioCarousel,
1588
+ CopioAddEditDialog,
1589
+ CopioRow,
1590
+ CopioHeader,
1591
+ CopioLoader,
1592
+ COPIO_EVENTS,
1593
+ dispatchCopioEvent,
1594
+ scannerCss,
1595
+ getScannerStyleSheet,
1596
+ adoptScannerStyles,
1597
+ };