@olenbetong/synergi-react 2.9.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/es/chrome/AppShell/index.d.ts +8 -0
  2. package/es/chrome/AppShell/index.js +10 -130
  3. package/es/components/ImageEditor/ImageEditor.css +10 -0
  4. package/es/components/ImageEditor/index.d.ts +1 -0
  5. package/es/components/ImageEditor/index.js +1 -0
  6. package/es/components/ImageEditor/plugins/cropPlugin/CropOverlay.js +27 -5
  7. package/es/components/ImageEditor/plugins/cropPlugin/CropToolbar.js +4 -3
  8. package/es/components/ImageEditor/plugins/cropPlugin/useCropTool.d.ts +20 -3
  9. package/es/components/ImageEditor/plugins/cropPlugin/useCropTool.js +216 -33
  10. package/es/components/ImageEditor/plugins/zoomPlugin/ZoomContext.d.ts +5 -0
  11. package/es/components/ImageEditor/plugins/zoomPlugin/ZoomContext.js +7 -0
  12. package/es/components/ImageEditor/useEdgeDetection.d.ts +0 -2
  13. package/es/components/ImageEditor/useEdgeDetection.js +11 -30
  14. package/es/components/ImageEditor/useOpenCV.d.ts +26 -1
  15. package/es/components/ImageEditor/useOpenCV.js +108 -42
  16. package/es/components/SplitContainer/index.js +2 -4
  17. package/es/filter/ChipListInput.d.ts +13 -0
  18. package/es/filter/ChipListInput.js +34 -0
  19. package/es/filter/FilterBuilder.css +152 -0
  20. package/es/filter/FilterBuilder.d.ts +115 -0
  21. package/es/filter/FilterBuilder.js +146 -0
  22. package/es/filter/FilterBuilder.test.d.ts +1 -0
  23. package/es/filter/FilterBuilder.test.js +120 -0
  24. package/es/filter/FilterEditor.css +231 -0
  25. package/es/filter/FilterEditor.d.ts +17 -0
  26. package/es/filter/FilterEditor.js +38 -0
  27. package/es/filter/FilterEditor.test.d.ts +1 -0
  28. package/es/filter/FilterEditor.test.js +183 -0
  29. package/es/filter/FilterGroupEditor.d.ts +22 -0
  30. package/es/filter/FilterGroupEditor.js +34 -0
  31. package/es/filter/FilterNameDialog.css +22 -0
  32. package/es/filter/FilterNameDialog.d.ts +18 -0
  33. package/es/filter/FilterNameDialog.js +32 -0
  34. package/es/filter/FilterRow.d.ts +14 -0
  35. package/es/filter/FilterRow.js +32 -0
  36. package/es/filter/FilterShareDialog.css +28 -0
  37. package/es/filter/FilterShareDialog.d.ts +23 -0
  38. package/es/filter/FilterShareDialog.js +63 -0
  39. package/es/filter/FilterStringField.d.ts +15 -0
  40. package/es/filter/FilterStringField.js +37 -0
  41. package/es/filter/FilterValueEditor.d.ts +16 -0
  42. package/es/filter/FilterValueEditor.js +85 -0
  43. package/es/filter/SavedFilterTree.css +107 -0
  44. package/es/filter/SavedFilterTree.d.ts +45 -0
  45. package/es/filter/SavedFilterTree.js +44 -0
  46. package/es/filter/SavedFilterTree.test.d.ts +1 -0
  47. package/es/filter/SavedFilterTree.test.js +75 -0
  48. package/es/filter/index.d.ts +11 -0
  49. package/es/filter/index.js +10 -0
  50. package/es/filter/types.d.ts +34 -0
  51. package/es/filter/types.js +1 -0
  52. package/es/index.d.ts +2 -1
  53. package/es/index.js +6 -1
  54. package/es/mui/MuiThemeProvider.d.ts +24 -0
  55. package/es/mui/MuiThemeProvider.js +152 -0
  56. package/es/mui/index.d.ts +1 -0
  57. package/es/mui/index.js +1 -0
  58. package/es/report/ReportLauncher.css +147 -0
  59. package/es/report/ReportLauncher.d.ts +55 -0
  60. package/es/report/ReportLauncher.js +142 -0
  61. package/es/report/ReportLauncher.test.d.ts +1 -0
  62. package/es/report/ReportLauncher.test.js +231 -0
  63. package/es/report/ReportParameters.css +29 -0
  64. package/es/report/ReportParameters.d.ts +46 -0
  65. package/es/report/ReportParameters.js +65 -0
  66. package/es/report/ReportParameters.test.d.ts +1 -0
  67. package/es/report/ReportParameters.test.js +84 -0
  68. package/es/report/index.d.ts +2 -0
  69. package/es/report/index.js +2 -0
  70. package/es/test/setup.d.ts +1 -0
  71. package/es/test/setup.js +6 -0
  72. package/package.json +22 -7
  73. package/src/chrome/AppShell/index.tsx +34 -171
  74. package/src/components/ImageEditor/ImageEditor.css +10 -0
  75. package/src/components/ImageEditor/index.ts +1 -0
  76. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +66 -20
  77. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +19 -3
  78. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +266 -39
  79. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomContext.tsx +8 -0
  80. package/src/components/ImageEditor/useEdgeDetection.ts +11 -51
  81. package/src/components/ImageEditor/useOpenCV.ts +112 -62
  82. package/src/components/SplitContainer/index.tsx +3 -4
  83. package/src/filter/ChipListInput.tsx +79 -0
  84. package/src/filter/FilterBuilder.css +152 -0
  85. package/src/filter/FilterBuilder.test.tsx +153 -0
  86. package/src/filter/FilterBuilder.tsx +435 -0
  87. package/src/filter/FilterEditor.css +231 -0
  88. package/src/filter/FilterEditor.test.tsx +259 -0
  89. package/src/filter/FilterEditor.tsx +74 -0
  90. package/src/filter/FilterGroupEditor.tsx +160 -0
  91. package/src/filter/FilterNameDialog.css +22 -0
  92. package/src/filter/FilterNameDialog.tsx +81 -0
  93. package/src/filter/FilterRow.tsx +117 -0
  94. package/src/filter/FilterShareDialog.css +28 -0
  95. package/src/filter/FilterShareDialog.tsx +201 -0
  96. package/src/filter/FilterStringField.tsx +77 -0
  97. package/src/filter/FilterValueEditor.tsx +220 -0
  98. package/src/filter/SavedFilterTree.css +107 -0
  99. package/src/filter/SavedFilterTree.test.tsx +94 -0
  100. package/src/filter/SavedFilterTree.tsx +222 -0
  101. package/src/filter/index.ts +11 -0
  102. package/src/filter/types.ts +38 -0
  103. package/src/index.ts +39 -1
  104. package/src/mui/MuiThemeProvider.tsx +174 -0
  105. package/src/mui/index.ts +1 -0
  106. package/src/report/ReportLauncher.css +147 -0
  107. package/src/report/ReportLauncher.test.tsx +281 -0
  108. package/src/report/ReportLauncher.tsx +421 -0
  109. package/src/report/ReportParameters.css +29 -0
  110. package/src/report/ReportParameters.test.tsx +133 -0
  111. package/src/report/ReportParameters.tsx +198 -0
  112. package/src/report/index.ts +2 -0
  113. package/src/test/setup.ts +8 -0
@@ -1,9 +1,14 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
2
  import { fullImageQuad, useEdgeDetection } from "../../useEdgeDetection.js";
3
3
  import { loadOpenCV, useOpenCV } from "../../useOpenCV.js";
4
+ /** Relative (0–1) tolerance for treating a quad as axis-aligned. */
5
+ const RECT_TOLERANCE = 0.001;
6
+ /** Minimum drag distance in CSS pixels before a drawn rectangle is accepted. */
7
+ const MIN_RECT_DRAG = 4;
4
8
  /**
5
- * Manages all state and logic for the perspective crop tool.
6
- * Loads OpenCV lazily, runs edge detection, and performs the warp.
9
+ * Manages all state and logic for the crop tool.
10
+ * OpenCV is loaded lazily for corner suggestion and perspective warping, but is optional:
11
+ * when it fails to load the tool stays fully usable, only the suggested border is missing.
7
12
  */
8
13
  export function useCropTool(imageUrl, enabled) {
9
14
  let { cv, ready: cvReady, error: cvError } = useOpenCV(enabled);
@@ -13,39 +18,115 @@ export function useCropTool(imageUrl, enabled) {
13
18
  let [canvasEl, setCanvasEl] = useState(null);
14
19
  let [cropping, setCropping] = useState(false);
15
20
  let [error, setError] = useState(null);
21
+ let [mode, setMode] = useState("corners");
22
+ let [rectDraft, setRectDraft] = useState(null);
16
23
  let canvasRef = useRef(null);
17
24
  let prevSuggested = useRef(null);
18
- let { corners: suggestedCorners, debugImageUrl } = useEdgeDetection(cvReady ? cv : null, canvasEl, cvReady && enabled);
25
+ // Selection stashed when entering rect mode, restored if the user backs out.
26
+ let stashedCorners = useRef(null);
27
+ // Mirrors rectDraft so pointer handlers never read a stale render closure.
28
+ let rectDraftRef = useRef(null);
29
+ // Set once the user has touched the selection, so a late suggestion can't overwrite it.
30
+ let userAdjusted = useRef(false);
31
+ let { corners: suggestedCorners } = useEdgeDetection(cvReady ? cv : null, canvasEl, cvReady && enabled);
19
32
  useEffect(() => {
20
33
  if (suggestedCorners && suggestedCorners !== prevSuggested.current) {
21
34
  prevSuggested.current = suggestedCorners;
22
- setCorners(suggestedCorners);
35
+ if (!userAdjusted.current)
36
+ setCorners(suggestedCorners);
23
37
  }
24
38
  }, [suggestedCorners]);
25
39
  // Reset when the source image changes (e.g. after a previous crop or rotate)
26
40
  useEffect(() => {
27
41
  prevSuggested.current = null;
42
+ stashedCorners.current = null;
43
+ rectDraftRef.current = null;
44
+ userAdjusted.current = false;
28
45
  setCorners(null);
29
46
  setCanvasEl(null);
47
+ setRectDraft(null);
48
+ setMode("corners");
30
49
  }, [imageUrl]);
31
- let activeCorners = corners ?? fullImageQuad(canvasPixelSize.width, canvasPixelSize.height);
50
+ let draftQuad = rectDraft ? draftToQuad(rectDraft) : null;
51
+ let hasSelection = mode === "corners" || draftQuad !== null;
52
+ let activeCorners = draftQuad ?? corners ?? fullImageQuad(canvasPixelSize.width, canvasPixelSize.height);
32
53
  let scale = displaySize.width > 0 ? displaySize.width / canvasPixelSize.width : 1;
33
54
  let handleCanvasReady = useCallback((canvas, w, h) => {
34
55
  setCanvasEl(canvas);
35
56
  setCanvasPixelSize({ width: w, height: h });
36
57
  setDisplaySize({ width: canvas.clientWidth, height: canvas.clientHeight });
37
58
  }, []);
59
+ /** Converts CSS-pixel overlay coords to canvas-pixel coords, clamped to the image. */
60
+ function toCanvasPoint(screenX, screenY) {
61
+ return {
62
+ x: Math.max(0, Math.min(canvasPixelSize.width, screenX / scale)),
63
+ y: Math.max(0, Math.min(canvasPixelSize.height, screenY / scale)),
64
+ };
65
+ }
38
66
  function updateCorner(index, screenX, screenY) {
39
- let pixelX = screenX / scale;
40
- let pixelY = screenY / scale;
67
+ if (mode !== "corners")
68
+ return;
69
+ let point = toCanvasPoint(screenX, screenY);
70
+ userAdjusted.current = true;
41
71
  setCorners((prev) => {
42
72
  let next = [...(prev ?? activeCorners)];
43
- next[index] = { x: pixelX, y: pixelY };
73
+ next[index] = point;
44
74
  return next;
45
75
  });
46
76
  }
77
+ function startRectMode() {
78
+ if (mode === "rect")
79
+ return;
80
+ stashedCorners.current = corners;
81
+ rectDraftRef.current = null;
82
+ userAdjusted.current = true;
83
+ setRectDraft(null);
84
+ setCorners(null);
85
+ setMode("rect");
86
+ }
87
+ function cancelRectMode() {
88
+ if (mode !== "rect")
89
+ return;
90
+ // Fall back to the suggested border when rect mode was entered before any selection existed.
91
+ setCorners(stashedCorners.current ?? prevSuggested.current);
92
+ stashedCorners.current = null;
93
+ rectDraftRef.current = null;
94
+ setRectDraft(null);
95
+ setMode("corners");
96
+ }
97
+ function startRectDraw(screenX, screenY) {
98
+ if (mode !== "rect")
99
+ return;
100
+ let { x, y } = toCanvasPoint(screenX, screenY);
101
+ rectDraftRef.current = { startX: x, startY: y, currentX: x, currentY: y };
102
+ setRectDraft(rectDraftRef.current);
103
+ }
104
+ function updateRectDraw(screenX, screenY) {
105
+ if (!rectDraftRef.current)
106
+ return;
107
+ let { x, y } = toCanvasPoint(screenX, screenY);
108
+ rectDraftRef.current = { ...rectDraftRef.current, currentX: x, currentY: y };
109
+ setRectDraft(rectDraftRef.current);
110
+ }
111
+ function finishRectDraw() {
112
+ let draft = rectDraftRef.current;
113
+ rectDraftRef.current = null;
114
+ setRectDraft(null);
115
+ if (!draft)
116
+ return;
117
+ let width = Math.abs(draft.currentX - draft.startX) * scale;
118
+ let height = Math.abs(draft.currentY - draft.startY) * scale;
119
+ // Ignore taps and stray micro-drags — stay in rect mode so the user can try again.
120
+ if (width < MIN_RECT_DRAG || height < MIN_RECT_DRAG)
121
+ return;
122
+ // The new rectangle replaces the stashed selection, so there is nothing left to restore.
123
+ stashedCorners.current = null;
124
+ setCorners(draftToQuad(draft));
125
+ setMode("corners");
126
+ }
47
127
  async function applyCrop() {
48
- if (!cv)
128
+ // Nothing to apply until the user has drawn their rectangle.
129
+ if (mode === "rect")
49
130
  return null;
50
131
  setCropping(true);
51
132
  setError(null);
@@ -58,8 +139,8 @@ export function useCropTool(imageUrl, enabled) {
58
139
  y: c.y / canvasPixelSize.height,
59
140
  }));
60
141
  // Warp the original image at its native resolution to avoid quality loss.
61
- let blob = await cropImageAtFullResolution(cv, imageUrl, relCorners);
62
- let actions = [{ type: "crop", params: { corners: relCorners } }];
142
+ let { blob, corners: usedCorners, geometry } = await cropAtFullResolution(cv, imageUrl, relCorners);
143
+ let actions = [{ type: "crop", params: { corners: usedCorners, mode: geometry } }];
63
144
  return { blob, actions };
64
145
  }
65
146
  catch (err) {
@@ -72,6 +153,8 @@ export function useCropTool(imageUrl, enabled) {
72
153
  }
73
154
  return {
74
155
  activeCorners,
156
+ mode,
157
+ hasSelection,
75
158
  scale,
76
159
  displaySize,
77
160
  canvasRef,
@@ -79,32 +162,132 @@ export function useCropTool(imageUrl, enabled) {
79
162
  cvError,
80
163
  cropping,
81
164
  error,
82
- debugImageUrl,
83
165
  handleCanvasReady,
84
166
  updateCorner,
167
+ startRectMode,
168
+ cancelRectMode,
169
+ startRectDraw,
170
+ updateRectDraw,
171
+ finishRectDraw,
85
172
  applyCrop,
86
173
  };
87
174
  }
88
- /** Loads the image at native resolution, maps relative corners, and warps. */
175
+ /** Normalises a drag into a TL, TR, BR, BL quad. */
176
+ function draftToQuad(draft) {
177
+ let x1 = Math.min(draft.startX, draft.currentX);
178
+ let x2 = Math.max(draft.startX, draft.currentX);
179
+ let y1 = Math.min(draft.startY, draft.currentY);
180
+ let y2 = Math.max(draft.startY, draft.currentY);
181
+ return [
182
+ { x: x1, y: y1 },
183
+ { x: x2, y: y1 },
184
+ { x: x2, y: y2 },
185
+ { x: x1, y: y2 },
186
+ ];
187
+ }
188
+ /** True when the quad's edges are horizontal/vertical, so a plain canvas crop is exact. */
189
+ function isAxisAlignedRect([tl, tr, br, bl]) {
190
+ return (Math.abs(tl.y - tr.y) <= RECT_TOLERANCE &&
191
+ Math.abs(bl.y - br.y) <= RECT_TOLERANCE &&
192
+ Math.abs(tl.x - bl.x) <= RECT_TOLERANCE &&
193
+ Math.abs(tr.x - br.x) <= RECT_TOLERANCE);
194
+ }
195
+ /** Axis-aligned bounding box of a quad, as a quad. */
196
+ function boundingQuad(corners) {
197
+ let xs = corners.map((c) => c.x);
198
+ let ys = corners.map((c) => c.y);
199
+ let x1 = Math.min(...xs);
200
+ let x2 = Math.max(...xs);
201
+ let y1 = Math.min(...ys);
202
+ let y2 = Math.max(...ys);
203
+ return [
204
+ { x: x1, y: y1 },
205
+ { x: x2, y: y1 },
206
+ { x: x2, y: y2 },
207
+ { x: x1, y: y2 },
208
+ ];
209
+ }
210
+ /**
211
+ * Ensures OpenCV is loaded, reporting success as a boolean instead of throwing.
212
+ *
213
+ * Deliberately does not *return* the module: Emscripten's module object is thenable
214
+ * (it has its own `.then`), so returning it from an async function makes the promise
215
+ * machinery adopt it and loop forever, freezing the tab. Callers read `window.cv`.
216
+ */
217
+ async function ensureOpenCV() {
218
+ try {
219
+ await loadOpenCV();
220
+ return typeof window.cv?.imread === "function";
221
+ }
222
+ catch {
223
+ return false;
224
+ }
225
+ }
226
+ /**
227
+ * Crops at native resolution, picking the cheapest technique that is exact:
228
+ * axis-aligned rectangles use plain canvas drawing, other quads need an OpenCV warp.
229
+ * When OpenCV cannot be loaded, a perspective crop degrades to its bounding box.
230
+ */
89
231
  // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
90
- function cropImageAtFullResolution(cv, imageUrl, relCorners) {
232
+ async function cropAtFullResolution(cv, imageUrl, relCorners) {
233
+ if (isAxisAlignedRect(relCorners)) {
234
+ return { blob: await rectCropAtFullResolution(imageUrl, relCorners), corners: relCorners, geometry: "rect" };
235
+ }
236
+ let cvInstance = cv ?? ((await ensureOpenCV()) ? window.cv : null);
237
+ if (!cvInstance) {
238
+ console.warn("[ImageEditor] OpenCV unavailable — cropping to the selection's bounding box without perspective correction.");
239
+ let bounds = boundingQuad(relCorners);
240
+ return { blob: await rectCropAtFullResolution(imageUrl, bounds), corners: bounds, geometry: "rect" };
241
+ }
242
+ return {
243
+ blob: await cropImageAtFullResolution(cvInstance, imageUrl, relCorners),
244
+ corners: relCorners,
245
+ geometry: "perspective",
246
+ };
247
+ }
248
+ /** Crops an axis-aligned rectangle with the 2D canvas API — no OpenCV required. */
249
+ async function rectCropAtFullResolution(imageUrl, relCorners) {
250
+ let img = await loadImage(imageUrl);
251
+ let [tl, , br] = boundingQuad(relCorners);
252
+ let x = Math.round(tl.x * img.naturalWidth);
253
+ let y = Math.round(tl.y * img.naturalHeight);
254
+ let width = Math.max(1, Math.round((br.x - tl.x) * img.naturalWidth));
255
+ let height = Math.max(1, Math.round((br.y - tl.y) * img.naturalHeight));
256
+ let canvas = document.createElement("canvas");
257
+ canvas.width = width;
258
+ canvas.height = height;
259
+ canvas.getContext("2d").drawImage(img, x, y, width, height, 0, 0, width, height);
260
+ return canvasToPngBlob(canvas);
261
+ }
262
+ function loadImage(url) {
91
263
  return new Promise((resolve, reject) => {
92
264
  let img = new Image();
93
- img.onload = () => {
94
- let canvas = document.createElement("canvas");
95
- canvas.width = img.naturalWidth;
96
- canvas.height = img.naturalHeight;
97
- canvas.getContext("2d").drawImage(img, 0, 0);
98
- let absCorners = relCorners.map((c) => ({
99
- x: c.x * img.naturalWidth,
100
- y: c.y * img.naturalHeight,
101
- }));
102
- perspectiveCrop(cv, canvas, absCorners).then(resolve, reject);
103
- };
265
+ img.onload = () => resolve(img);
104
266
  img.onerror = () => reject(new Error("Failed to load image for crop"));
105
- img.src = imageUrl;
267
+ img.src = url;
106
268
  });
107
269
  }
270
+ function canvasToPngBlob(canvas) {
271
+ return new Promise((resolve, reject) => {
272
+ // PNG is lossless — critical for receipts and screenshots where JPEG
273
+ // compression would make text unreadable.
274
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/png");
275
+ });
276
+ }
277
+ /** Loads the image at native resolution, maps relative corners, and warps. */
278
+ // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
279
+ async function cropImageAtFullResolution(cv, imageUrl, relCorners) {
280
+ let img = await loadImage(imageUrl);
281
+ let canvas = document.createElement("canvas");
282
+ canvas.width = img.naturalWidth;
283
+ canvas.height = img.naturalHeight;
284
+ canvas.getContext("2d").drawImage(img, 0, 0);
285
+ let absCorners = relCorners.map((c) => ({
286
+ x: c.x * img.naturalWidth,
287
+ y: c.y * img.naturalHeight,
288
+ }));
289
+ return perspectiveCrop(cv, canvas, absCorners);
290
+ }
108
291
  /** Performs a perspective warp using OpenCV.js. */
109
292
  // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
110
293
  function perspectiveCrop(cv, srcCanvas, corners) {
@@ -121,18 +304,18 @@ function perspectiveCrop(cv, srcCanvas, corners) {
121
304
  cv.imshow(outCanvas, dst);
122
305
  for (let m of [src, dst, srcPts, dstPts, M])
123
306
  m.delete();
124
- return new Promise((resolve, reject) => {
125
- // PNG is lossless — critical for receipts and screenshots where JPEG
126
- // compression would make text unreadable.
127
- outCanvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/png");
128
- });
307
+ return canvasToPngBlob(outCanvas);
129
308
  }
130
309
  /**
131
310
  * Standalone replay handler for the "crop" action type.
132
311
  * Corners are stored as relative (0–1) values so they work at any resolution.
312
+ * Rectangular crops replay without OpenCV; older actions without a stored mode
313
+ * are treated as perspective crops.
133
314
  */
134
315
  export async function replayCrop(imageUrl, params) {
135
- await loadOpenCV();
136
316
  let relCorners = params.corners;
137
- return cropImageAtFullResolution(window.cv, imageUrl, relCorners);
317
+ if (params.mode === "rect")
318
+ return rectCropAtFullResolution(imageUrl, relCorners);
319
+ let { blob } = await cropAtFullResolution(null, imageUrl, relCorners);
320
+ return blob;
138
321
  }
@@ -1,6 +1,11 @@
1
1
  import { type ReactNode } from "react";
2
2
  import { type ZoomPanResult } from "./useZoomPan.js";
3
3
  export declare function useZoom(): ZoomPanResult;
4
+ /**
5
+ * Current zoom factor, or 1 when no ZoomProvider is present.
6
+ * Lets tools convert screen-space coordinates to CSS pixels without requiring the zoom plugin.
7
+ */
8
+ export declare function useZoomLevel(): number;
4
9
  export declare function ZoomProvider({ children }: {
5
10
  children: ReactNode;
6
11
  }): import("react").JSX.Element;
@@ -8,6 +8,13 @@ export function useZoom() {
8
8
  throw new Error("useZoom must be used within ZoomProvider");
9
9
  return ctx;
10
10
  }
11
+ /**
12
+ * Current zoom factor, or 1 when no ZoomProvider is present.
13
+ * Lets tools convert screen-space coordinates to CSS pixels without requiring the zoom plugin.
14
+ */
15
+ export function useZoomLevel() {
16
+ return use(ZoomContext)?.zoom ?? 1;
17
+ }
11
18
  export function ZoomProvider({ children }) {
12
19
  let state = useZoomPan();
13
20
  return _jsx(ZoomContext, { value: state, children: children });
@@ -7,8 +7,6 @@ export type Quad = [Point, Point, Point, Point];
7
7
  export declare function fullImageQuad(width: number, height: number): Quad;
8
8
  interface UseEdgeDetectionResult {
9
9
  corners: Quad | null;
10
- /** Data URL of the Canny edge image, for debug visualisation */
11
- debugImageUrl: string | null;
12
10
  }
13
11
  /**
14
12
  * Runs Canny edge detection on the image to suggest document corners.
@@ -23,9 +23,6 @@ function findLargestQuad(cv, src, minAreaFraction = 0.1) {
23
23
  let kernel = cv.getStructuringElement(cv.MORPH_RECT, new cv.Size(3, 3));
24
24
  cv.dilate(edges, dilated, kernel);
25
25
  kernel.delete();
26
- // Build RGBA debug canvas so we can draw a coloured quad overlay
27
- let debugRgba = new cv.Mat();
28
- cv.cvtColor(dilated, debugRgba, cv.COLOR_GRAY2RGBA);
29
26
  cv.findContours(dilated, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE);
30
27
  let best = null;
31
28
  let bestArea = 0;
@@ -68,22 +65,8 @@ function findLargestQuad(cv, src, minAreaFraction = 0.1) {
68
65
  let tr = remaining[0].x > remaining[1].x ? remaining[0] : remaining[1];
69
66
  let bl = remaining[0].x < remaining[1].x ? remaining[0] : remaining[1];
70
67
  quad = [tl, tr, br, bl];
71
- // Draw the detected quad on the debug canvas in green
72
- let green = new cv.Scalar(0, 255, 0, 255);
73
- let ordered = [tl, tr, br, bl];
74
- for (let i = 0; i < 4; i++) {
75
- let a = ordered[i];
76
- let b = ordered[(i + 1) % 4];
77
- cv.line(debugRgba, new cv.Point(a.x, a.y), new cv.Point(b.x, b.y), green, 3);
78
- }
79
- for (let pt of ordered) {
80
- cv.circle(debugRgba, new cv.Point(pt.x, pt.y), 8, green, -1);
81
- }
82
68
  }
83
- let debugCanvas = document.createElement("canvas");
84
- cv.imshow(debugCanvas, debugRgba);
85
- debugRgba.delete();
86
- return { quad, debugCanvas };
69
+ return quad;
87
70
  }
88
71
  finally {
89
72
  gray.delete();
@@ -100,26 +83,24 @@ function findLargestQuad(cv, src, minAreaFraction = 0.1) {
100
83
  */
101
84
  export function useEdgeDetection(cv, canvas, enabled) {
102
85
  let [corners, setCorners] = useState(null);
103
- let [debugImageUrl, setDebugImageUrl] = useState(null);
104
86
  useEffect(() => {
105
- console.log("[useEdgeDetection] effect: enabled=", enabled, "cv=", typeof cv, "canvas=", canvas?.width, "x", canvas?.height);
106
87
  if (!enabled || !cv || !canvas)
107
88
  return;
108
89
  try {
109
- console.log("[useEdgeDetection] running findLargestQuad...");
110
90
  let src = cv.imread(canvas);
111
- let { quad, debugCanvas } = findLargestQuad(cv, src);
112
- src.delete();
113
- console.log("[useEdgeDetection] quad=", quad);
114
- setDebugImageUrl(debugCanvas.toDataURL());
91
+ let quad;
92
+ try {
93
+ quad = findLargestQuad(cv, src);
94
+ }
95
+ finally {
96
+ src.delete();
97
+ }
115
98
  setCorners(quad ?? fullImageQuad(canvas.width, canvas.height));
116
99
  }
117
100
  catch (err) {
118
- console.error("[useEdgeDetection] error:", err);
119
- if (canvas) {
120
- setCorners(fullImageQuad(canvas.width, canvas.height));
121
- }
101
+ console.warn("[ImageEditor] Edge detection failed, falling back to the full image:", err);
102
+ setCorners(fullImageQuad(canvas.width, canvas.height));
122
103
  }
123
104
  }, [cv, canvas, enabled]);
124
- return { corners, debugImageUrl };
105
+ return { corners };
125
106
  }
@@ -3,7 +3,32 @@ declare global {
3
3
  cv: any;
4
4
  }
5
5
  }
6
- export declare function loadOpenCV(): Promise<unknown>;
6
+ /**
7
+ * OpenCV.js builds to try, in order. Both are single-file builds with the WASM embedded,
8
+ * so no companion `.wasm` request is needed.
9
+ *
10
+ * Note: opencv.org only publishes rolling branch builds — pinned version paths such as
11
+ * `/4.10.0/opencv.js` were removed upstream and now return 404. `5.x` is the current
12
+ * development line and `4.x` the stable line; the 4.x entry is a fallback for the case
13
+ * where the 5.x build is temporarily broken or unavailable.
14
+ */
15
+ export declare const DEFAULT_OPENCV_URLS: string[];
16
+ /**
17
+ * Overrides which OpenCV.js build(s) to load — e.g. to self-host instead of using the CDN.
18
+ * Must be called before anything triggers a load; ignored once loading has started.
19
+ */
20
+ export declare function configureOpenCV(urls: string | string[]): void;
21
+ /**
22
+ * Lazily loads OpenCV.js, trying each configured build in order.
23
+ * Rejects only when every candidate fails. Callers read `window.cv`.
24
+ *
25
+ * IMPORTANT: this promise must never resolve *with* the OpenCV module. Emscripten's
26
+ * module object has its own `.then` method, so it is thenable — resolving a promise
27
+ * with it makes the promise machinery try to adopt it and call `.then` forever, which
28
+ * wedges the whole tab in an infinite microtask loop. Always resolve with `undefined`
29
+ * and let callers read `window.cv`.
30
+ */
31
+ export declare function loadOpenCV(): Promise<void>;
7
32
  interface UseOpenCVResult {
8
33
  cv: any | null;
9
34
  ready: boolean;
@@ -1,15 +1,40 @@
1
1
  import { useEffect, useState } from "react";
2
+ /**
3
+ * OpenCV.js builds to try, in order. Both are single-file builds with the WASM embedded,
4
+ * so no companion `.wasm` request is needed.
5
+ *
6
+ * Note: opencv.org only publishes rolling branch builds — pinned version paths such as
7
+ * `/4.10.0/opencv.js` were removed upstream and now return 404. `5.x` is the current
8
+ * development line and `4.x` the stable line; the 4.x entry is a fallback for the case
9
+ * where the 5.x build is temporarily broken or unavailable.
10
+ */
11
+ export const DEFAULT_OPENCV_URLS = ["https://docs.opencv.org/5.x/opencv.js", "https://docs.opencv.org/4.x/opencv.js"];
12
+ /** Milliseconds to wait for the WASM runtime to initialise before giving up on a build. */
13
+ const INIT_TIMEOUT_MS = 60_000;
14
+ let scriptUrls = [...DEFAULT_OPENCV_URLS];
2
15
  let loadPromise = null;
3
- function waitForCvMat(timeoutMs = 30_000) {
16
+ /**
17
+ * Overrides which OpenCV.js build(s) to load — e.g. to self-host instead of using the CDN.
18
+ * Must be called before anything triggers a load; ignored once loading has started.
19
+ */
20
+ export function configureOpenCV(urls) {
21
+ if (loadPromise) {
22
+ console.warn("[OpenCV] configureOpenCV() ignored — OpenCV is already loading or loaded");
23
+ return;
24
+ }
25
+ scriptUrls = Array.isArray(urls) ? [...urls] : [urls];
26
+ }
27
+ function isReady() {
28
+ return typeof window.cv?.Mat !== "undefined";
29
+ }
30
+ /** Polls for cv.Mat, which signals that the WASM runtime has fully initialised. */
31
+ function waitForCvMat(timeoutMs) {
4
32
  return new Promise((resolve, reject) => {
5
33
  let elapsed = 0;
6
34
  let interval = setInterval(() => {
7
- console.log("[OpenCV] polling... cv=", typeof window.cv, "cv.Mat=", typeof window.cv?.Mat);
8
- // cv.Mat signals that the WASM runtime has fully initialised
9
- if (window.cv?.Mat) {
35
+ if (isReady()) {
10
36
  clearInterval(interval);
11
- console.log("[OpenCV] cv.Mat found — ready!");
12
- resolve(); // callers read window.cv directly
37
+ resolve();
13
38
  return;
14
39
  }
15
40
  elapsed += 100;
@@ -20,73 +45,114 @@ function waitForCvMat(timeoutMs = 30_000) {
20
45
  }, 100);
21
46
  });
22
47
  }
23
- export function loadOpenCV() {
24
- if (loadPromise) {
25
- console.log("[OpenCV] loadOpenCV() — reusing existing promise");
26
- return loadPromise;
27
- }
28
- // Already initialised (e.g. hot-reload)
29
- if (window.cv?.Mat) {
30
- console.log("[OpenCV] already initialised on window.cv");
31
- loadPromise = Promise.resolve(window.cv);
32
- return loadPromise;
33
- }
34
- console.log("[OpenCV] injecting script tag...");
35
- loadPromise = new Promise((resolve, reject) => {
48
+ /** Loads a single OpenCV.js build, handling both the promise-based and polling Emscripten builds. */
49
+ function loadScript(url) {
50
+ return new Promise((resolve, reject) => {
51
+ // A previous failed attempt may have left a half-initialised global behind.
52
+ if (!isReady())
53
+ window.cv = undefined;
36
54
  let script = document.createElement("script");
37
- script.src = "https://docs.opencv.org/4.10.0/opencv.js";
55
+ script.src = url;
38
56
  script.async = true;
57
+ let settle = (err) => {
58
+ if (err) {
59
+ script.remove();
60
+ reject(err);
61
+ }
62
+ else {
63
+ resolve();
64
+ }
65
+ };
39
66
  script.onload = () => {
40
- console.log("[OpenCV] script onload fired. typeof window.cv=", typeof window.cv, "cv?.then=", typeof window.cv?.then, "cv?.Mat=", typeof window.cv?.Mat);
41
67
  if (typeof window.cv?.then === "function") {
42
- console.log("[OpenCV] promise-based build detected, awaiting cv...");
43
68
  // Emscripten promise-based build: cv itself is the promise.
44
- // IMPORTANT: we must NOT pass `instance` into resolve() — if the resolved
45
- // value is itself thenable, Promise will follow it forever and never settle.
46
- // Instead we mutate window.cv and signal readiness with undefined.
69
+ // IMPORTANT: never resolve *with* the instance — if the resolved value is
70
+ // itself thenable, the promise chain follows it forever and never settles.
71
+ // Instead mutate window.cv and signal readiness with undefined.
47
72
  window.cv.then((instance) => {
48
- console.log("[OpenCV] promise resolved, instance=", typeof instance, "hasReadMethod=", typeof instance?.imread);
49
73
  window.cv = instance;
50
- resolve(undefined); // signal only; callers read window.cv
51
- }, (err) => {
52
- console.error("[OpenCV] promise rejected", err);
53
- reject(err);
54
- });
74
+ settle();
75
+ }, (err) => settle(err instanceof Error ? err : new Error(String(err))));
76
+ }
77
+ else if (isReady()) {
78
+ settle();
55
79
  }
56
80
  else {
57
- console.log("[OpenCV] polling-based build, starting waitForCvMat...");
58
- // Polling build: WASM initialises asynchronously after script loads
59
- waitForCvMat().then(() => resolve(undefined), reject);
81
+ // Polling build: the WASM initialises asynchronously after the script loads.
82
+ waitForCvMat(INIT_TIMEOUT_MS).then(() => settle(), settle);
60
83
  }
61
84
  };
62
- script.onerror = (err) => {
63
- console.error("[OpenCV] script load error", err);
64
- loadPromise = null;
65
- reject(new Error("Failed to load OpenCV.js"));
66
- };
85
+ script.onerror = () => settle(new Error(`Failed to load OpenCV.js from ${url}`));
67
86
  document.head.appendChild(script);
68
87
  });
88
+ }
89
+ /**
90
+ * Lazily loads OpenCV.js, trying each configured build in order.
91
+ * Rejects only when every candidate fails. Callers read `window.cv`.
92
+ *
93
+ * IMPORTANT: this promise must never resolve *with* the OpenCV module. Emscripten's
94
+ * module object has its own `.then` method, so it is thenable — resolving a promise
95
+ * with it makes the promise machinery try to adopt it and call `.then` forever, which
96
+ * wedges the whole tab in an infinite microtask loop. Always resolve with `undefined`
97
+ * and let callers read `window.cv`.
98
+ */
99
+ export function loadOpenCV() {
100
+ if (loadPromise)
101
+ return loadPromise;
102
+ // Already initialised (e.g. hot-reload, or loaded by the host page)
103
+ if (isReady()) {
104
+ loadPromise = Promise.resolve();
105
+ return loadPromise;
106
+ }
107
+ loadPromise = (async () => {
108
+ let errors = [];
109
+ for (let url of scriptUrls) {
110
+ try {
111
+ await loadScript(url);
112
+ if (!isReady())
113
+ throw new Error(`OpenCV.js loaded from ${url} but exposes no cv.Mat`);
114
+ return; // never `return window.cv` — see the note above
115
+ }
116
+ catch (err) {
117
+ let error = err instanceof Error ? err : new Error(String(err));
118
+ errors.push(error);
119
+ console.warn(`[OpenCV] Could not load ${url}:`, error.message);
120
+ }
121
+ }
122
+ // Allow a later retry (e.g. after the network comes back) rather than caching the failure.
123
+ loadPromise = null;
124
+ throw new Error(`Failed to load OpenCV.js from: ${scriptUrls.join(", ")}`, { cause: errors });
125
+ })();
69
126
  return loadPromise;
70
127
  }
71
128
  /** Lazily loads OpenCV.js from CDN. Starts loading only when `enabled` is true. */
72
129
  export function useOpenCV(enabled = true) {
130
+ // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js has no bundled types
73
131
  let [cv, setCv] = useState(null);
74
132
  let [ready, setReady] = useState(false);
75
133
  let [error, setError] = useState(null);
76
134
  useEffect(() => {
77
135
  if (!enabled)
78
136
  return;
79
- console.log("[useOpenCV] enabled=true, calling loadOpenCV()");
137
+ let cancelled = false;
80
138
  loadOpenCV()
81
139
  .then(() => {
82
- console.log("[useOpenCV] loadOpenCV resolved. window.cv=", typeof window.cv, "imread=", typeof window.cv?.imread);
140
+ if (cancelled)
141
+ return;
83
142
  setCv(window.cv);
84
143
  setReady(true);
85
144
  })
86
145
  .catch((err) => {
87
- console.error("[useOpenCV] loadOpenCV rejected:", err);
146
+ if (cancelled)
147
+ return;
148
+ // OpenCV only powers optional features (border suggestion, perspective warp),
149
+ // so a load failure must never break the tools that depend on it.
150
+ console.warn("[useOpenCV] OpenCV failed to load — continuing without it:", err.message);
88
151
  setError(err);
89
152
  });
153
+ return () => {
154
+ cancelled = true;
155
+ };
90
156
  }, [enabled]);
91
157
  return { cv, ready, error };
92
158
  }