@olenbetong/synergi-react 5.0.0 → 5.1.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 (141) hide show
  1. package/es/components/Checkbox/index.js +1 -9
  2. package/es/components/CodeEditor/CodeEditor.css +6 -6
  3. package/es/components/FilePond.js +3 -12
  4. package/es/components/ImageEditor/plugins/redactPlugin/useRedactTool.js +18 -14
  5. package/es/components/ImageEditor/useImageHistory.js +13 -1
  6. package/es/components/MergeProgressDialog/MergeProgressDialogDs.js +1 -1
  7. package/es/components/MergeProgressDialog/useMergeJob.js +5 -4
  8. package/es/components/Portal/index.js +20 -20
  9. package/es/components/SplitContainer/index.js +3 -1
  10. package/es/components/Toolbar/Toolbar.css +137 -137
  11. package/es/components/Toolbar/index.js +6 -1
  12. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.js +8 -0
  13. package/es/elements/ElementLookupDialog/HIDScanner/useHIDScanner.js +3 -1
  14. package/es/elements-ds/DescriptionInput.d.ts +16 -0
  15. package/es/elements-ds/DescriptionInput.js +41 -0
  16. package/es/elements-ds/DuplicateElementDamage.d.ts +40 -0
  17. package/es/elements-ds/DuplicateElementDamage.js +57 -0
  18. package/es/elements-ds/ElementLookup.d.ts +23 -0
  19. package/es/elements-ds/ElementLookup.js +35 -0
  20. package/es/elements-ds/ElementLookupDialog.d.ts +7 -0
  21. package/es/elements-ds/ElementLookupDialog.js +84 -0
  22. package/es/elements-ds/FormFields.d.ts +43 -0
  23. package/es/elements-ds/FormFields.js +67 -0
  24. package/es/elements-ds/HIDScanner.d.ts +7 -0
  25. package/es/elements-ds/HIDScanner.js +36 -0
  26. package/es/elements-ds/ManualForm.d.ts +7 -0
  27. package/es/elements-ds/ManualForm.js +70 -0
  28. package/es/elements-ds/ProjectSelect.d.ts +28 -0
  29. package/es/elements-ds/ProjectSelect.js +45 -0
  30. package/es/elements-ds/elements-ds.css +157 -0
  31. package/es/elements-ds/index.d.ts +12 -0
  32. package/es/elements-ds/index.js +14 -0
  33. package/es/useTranslation/index.js +5 -3
  34. package/package.json +15 -3
  35. package/src/chrome/AppShell/AppShell.test.tsx +48 -0
  36. package/src/chrome/AppShell/index.tsx +29 -29
  37. package/src/chrome/openReport.test.ts +50 -0
  38. package/src/chrome/openReport.ts +34 -34
  39. package/src/colorScheme.test.ts +188 -0
  40. package/src/colorScheme.ts +125 -125
  41. package/src/components/Checkbox/Checkbox.browser.test.tsx +116 -0
  42. package/src/components/Checkbox/index.tsx +1 -10
  43. package/src/components/CodeEditor/CodeEditor.css +6 -6
  44. package/src/components/CodeEditor/CodeEditor.tsx +173 -173
  45. package/src/components/CodeEditor/index.ts +1 -1
  46. package/src/components/ColorCard/ColorCard.test.tsx +34 -0
  47. package/src/components/DateNavigator/DateNavigator.test.tsx +175 -0
  48. package/src/components/DateNavigator/index.tsx +186 -186
  49. package/src/components/FilePond.browser.test.tsx +389 -0
  50. package/src/components/FilePond.tsx +303 -312
  51. package/src/components/ImageEditor/ImageEditor.browser.test.tsx +286 -0
  52. package/src/components/ImageEditor/ImageEditor.test.tsx +299 -0
  53. package/src/components/ImageEditor/ImageEditor.tsx +348 -348
  54. package/src/components/ImageEditor/index.ts +9 -9
  55. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +165 -165
  56. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +48 -48
  57. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.test.ts +225 -0
  58. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +405 -405
  59. package/src/components/ImageEditor/plugins/plugins.browser.test.ts +252 -0
  60. package/src/components/ImageEditor/plugins/redactPlugin/RedactToolbar.tsx +47 -47
  61. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.test.ts +89 -0
  62. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.ts +16 -13
  63. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomContext.tsx +23 -23
  64. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomControls.tsx +40 -40
  65. package/src/components/ImageEditor/plugins/zoomPlugin/useZoomPan.test.ts +154 -0
  66. package/src/components/ImageEditor/useActiveTool.ts +21 -21
  67. package/src/components/ImageEditor/useEdgeDetection.test.ts +96 -0
  68. package/src/components/ImageEditor/useEdgeDetection.ts +319 -319
  69. package/src/components/ImageEditor/useImageHistory.test.ts +409 -0
  70. package/src/components/ImageEditor/useImageHistory.ts +206 -197
  71. package/src/components/ImageEditor/useOpenCV.test.ts +208 -0
  72. package/src/components/ImageEditor/useOpenCV.ts +184 -184
  73. package/src/components/LinkedCardList/index.scss +95 -95
  74. package/src/components/MergeProgressDialog/MergeProgressDialogDs.browser.test.tsx +156 -0
  75. package/src/components/MergeProgressDialog/MergeProgressDialogDs.tsx +1 -0
  76. package/src/components/MergeProgressDialog/useMergeJob.test.ts +326 -0
  77. package/src/components/MergeProgressDialog/useMergeJob.ts +4 -3
  78. package/src/components/PageBanner/index.tsx +80 -80
  79. package/src/components/PdfViewer/PdfViewer.browser.test.tsx +78 -0
  80. package/src/components/PdfViewer/PdfViewer.tsx +158 -158
  81. package/src/components/Portal/Portal.test.tsx +106 -0
  82. package/src/components/Portal/index.tsx +22 -25
  83. package/src/components/Sidebar/Sidebar.browser.test.tsx +57 -0
  84. package/src/components/Sidebar/Sidebar.test.tsx +123 -0
  85. package/src/components/SplitContainer/SplitContainer.browser.test.tsx +304 -0
  86. package/src/components/SplitContainer/index.tsx +335 -333
  87. package/src/components/Toolbar/Toolbar.css +137 -137
  88. package/src/components/Toolbar/Toolbar.test.tsx +216 -0
  89. package/src/components/Toolbar/ToolbarBreadcrumbs.browser.test.tsx +137 -0
  90. package/src/components/Toolbar/index.tsx +270 -265
  91. package/src/components/ValueToggleGroup/ValueToggleGroup.test.tsx +112 -0
  92. package/src/designsystemet-web-types.d.ts +24 -24
  93. package/src/elements/ElementDamage/DamageFormButtons.tsx +35 -35
  94. package/src/elements/ElementDamage/DescriptionInput.tsx +120 -120
  95. package/src/elements/ElementDamage/DuplicateDamage/DesktopView.tsx +82 -82
  96. package/src/elements/ElementDamage/DuplicateDamage/DublicateElementDamageDialog.tsx +67 -67
  97. package/src/elements/ElementDamage/DuplicateDamage/PhoneView.tsx +45 -45
  98. package/src/elements/ElementDamage/ElementNumberTextField.tsx +41 -41
  99. package/src/elements/ElementDamage/RegisterFix.tsx +100 -100
  100. package/src/elements/ElementDamage/SubmitButtons.tsx +40 -40
  101. package/src/elements/ElementDamage/TransportElementSelect.tsx +52 -52
  102. package/src/elements/ElementLookup.tsx +123 -123
  103. package/src/elements/ElementLookupDialog/BarcodeScanner/BarcodeScanner.browser.test.tsx +175 -0
  104. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.ts +8 -0
  105. package/src/elements/ElementLookupDialog/BarcodeScanner/engines.browser.test.ts +225 -0
  106. package/src/elements/ElementLookupDialog/HIDScanner/index.tsx +67 -67
  107. package/src/elements/ElementLookupDialog/HIDScanner/useHIDScanner.test.ts +124 -0
  108. package/src/elements/ElementLookupDialog/HIDScanner/useHIDScanner.ts +2 -1
  109. package/src/elements/ElementLookupDialog/Manual/ManualForm.tsx +141 -141
  110. package/src/elements/ElementLookupDialog/getElement.test.ts +133 -0
  111. package/src/elements/ElementLookupDialog/index.tsx +226 -226
  112. package/src/elements/ElementLookupDialog/utils/Giai.test.ts +53 -0
  113. package/src/elements/ElementLookupDialog/utils/Giai.ts +209 -209
  114. package/src/elements/ProjectSelect.tsx +130 -130
  115. package/src/elements/index.ts +15 -15
  116. package/src/elements-ds/DamageForm.browser.test.tsx +530 -0
  117. package/src/elements-ds/DescriptionInput.tsx +114 -0
  118. package/src/elements-ds/DuplicateElementDamage.tsx +185 -0
  119. package/src/elements-ds/ElementLookup.tsx +114 -0
  120. package/src/elements-ds/ElementLookupDialog.browser.test.tsx +207 -0
  121. package/src/elements-ds/ElementLookupDialog.tsx +196 -0
  122. package/src/elements-ds/FormFields.tsx +176 -0
  123. package/src/elements-ds/HIDScanner.tsx +53 -0
  124. package/src/elements-ds/ManualForm.tsx +129 -0
  125. package/src/elements-ds/ProjectSelect.tsx +120 -0
  126. package/src/elements-ds/elements-ds.css +157 -0
  127. package/src/elements-ds/index.ts +16 -0
  128. package/src/filter/index.ts +34 -34
  129. package/src/i18n.test.ts +31 -0
  130. package/src/i18n.ts +13 -13
  131. package/src/mui/MuiThemeProvider.tsx +135 -135
  132. package/src/test/fakeCamera.ts +98 -0
  133. package/src/test/fakeDataApi.ts +90 -0
  134. package/src/test/setup.browser.ts +21 -0
  135. package/src/test/setup.ts +23 -23
  136. package/src/useTranslation/index.ts +5 -3
  137. package/src/useTranslation/useTranslation.test.ts +128 -0
  138. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders.test.d.ts +0 -1
  139. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders.test.js +0 -103
  140. package/es/test/setup.d.ts +0 -6
  141. package/es/test/setup.js +0 -6
@@ -1,197 +1,206 @@
1
- import { useEffect, useRef, useState } from "react";
2
-
3
- import type { ActionRegistry, EditAction } from "./types.js";
4
-
5
- interface HistoryState {
6
- past: EditAction[][];
7
- future: EditAction[][];
8
- }
9
-
10
- interface CurrentState {
11
- url: string;
12
- blob: Blob | null;
13
- /** True if `url` is an object URL we created and must eventually revoke. */
14
- generated: boolean;
15
- }
16
-
17
- export interface UseImageHistoryResult {
18
- currentImageUrl: string;
19
- currentBlob: Blob | null;
20
- /** Synchronous read of the current image URL — valid immediately after `applyActions`. */
21
- getCurrentImageUrl: () => string;
22
- /** Synchronous read of the current blob — valid immediately after `applyActions`. */
23
- getCurrentBlob: () => Blob | null;
24
- canUndo: boolean;
25
- canRedo: boolean;
26
- /** True while an async replay (undo/redo) is in progress. */
27
- replaying: boolean;
28
- /** Applies a new blob to the current state and records it in history. Returns the new object URL. */
29
- applyActions: (blob: Blob, actions: EditAction[]) => string;
30
- undo: () => void;
31
- redo: () => void;
32
- reset: () => void;
33
- }
34
-
35
- /**
36
- * Manages undo/redo history for the image editor using action replay.
37
- *
38
- * Only action lists are stored — no intermediate blobs. Undo/redo replays
39
- * all remaining actions from the source image, keeping memory usage minimal
40
- * regardless of history depth. Only one blob is in memory at a time.
41
- */
42
- export function useImageHistory(sourceUrl: string, registry: ActionRegistry): UseImageHistoryResult {
43
- let [history, setHistory] = useState<HistoryState>({ past: [], future: [] });
44
- let [current, setCurrent] = useState<CurrentState>({ url: sourceUrl, blob: null, generated: false });
45
- let [replaying, setReplaying] = useState(false);
46
-
47
- let historyRef = useRef(history);
48
- historyRef.current = history;
49
- // Written synchronously by `replaceCurrent` so imperative callers can read the current
50
- // image/blob before React has committed the corresponding render.
51
- let currentRef = useRef(current);
52
- let isReplaying = useRef(false);
53
- let replayAbort = useRef<AbortController | null>(null);
54
-
55
- function replaceCurrent(next: CurrentState) {
56
- let prev = currentRef.current;
57
- if (prev.generated && prev.url !== next.url) URL.revokeObjectURL(prev.url);
58
- currentRef.current = next;
59
- setCurrent(next);
60
- }
61
-
62
- // When source changes (e.g. component remount with new image), reset fully.
63
- useEffect(() => {
64
- replayAbort.current?.abort();
65
- isReplaying.current = false;
66
- setReplaying(false);
67
- replaceCurrent({ url: sourceUrl, blob: null, generated: false });
68
- setHistory({ past: [], future: [] });
69
- }, [sourceUrl]);
70
-
71
- useEffect(() => {
72
- return () => {
73
- if (currentRef.current.generated) URL.revokeObjectURL(currentRef.current.url);
74
- replayAbort.current?.abort();
75
- };
76
- }, []);
77
-
78
- function applyActions(blob: Blob, actions: EditAction[]) {
79
- // A direct apply always takes priority — abort any in-flight replay.
80
- replayAbort.current?.abort();
81
- isReplaying.current = false;
82
- setReplaying(false);
83
-
84
- let newUrl = URL.createObjectURL(blob);
85
- replaceCurrent({ url: newUrl, blob, generated: true });
86
- setHistory((prev) => ({ past: [...prev.past, actions], future: [] }));
87
-
88
- return newUrl;
89
- }
90
-
91
- async function doReplay(newPast: EditAction[][], newFuture: EditAction[][]) {
92
- replayAbort.current?.abort();
93
- let abort = new AbortController();
94
- replayAbort.current = abort;
95
- isReplaying.current = true;
96
- setReplaying(true);
97
-
98
- try {
99
- let result = await replayAll(sourceUrl, newPast, registry, abort.signal);
100
- if (abort.signal.aborted) return;
101
-
102
- if (result) {
103
- replaceCurrent({ url: result.url, blob: result.blob, generated: true });
104
- } else {
105
- replaceCurrent({ url: sourceUrl, blob: null, generated: false });
106
- }
107
- setHistory({ past: newPast, future: newFuture });
108
- } finally {
109
- if (!abort.signal.aborted) {
110
- isReplaying.current = false;
111
- setReplaying(false);
112
- }
113
- }
114
- }
115
-
116
- function undo() {
117
- if (isReplaying.current) return;
118
- let { past, future } = historyRef.current;
119
- if (past.length === 0) return;
120
- doReplay(past.slice(0, -1), [past.at(-1)!, ...future]);
121
- }
122
-
123
- function redo() {
124
- if (isReplaying.current) return;
125
- let { past, future } = historyRef.current;
126
- if (future.length === 0) return;
127
- doReplay([...past, future[0]], future.slice(1));
128
- }
129
-
130
- function reset() {
131
- replayAbort.current?.abort();
132
- isReplaying.current = false;
133
- setReplaying(false);
134
- replaceCurrent({ url: sourceUrl, blob: null, generated: false });
135
- setHistory({ past: [], future: [] });
136
- }
137
-
138
- return {
139
- currentImageUrl: current.url,
140
- currentBlob: current.blob,
141
- getCurrentImageUrl: () => currentRef.current.url,
142
- getCurrentBlob: () => currentRef.current.blob,
143
- canUndo: history.past.length > 0,
144
- canRedo: history.future.length > 0,
145
- replaying,
146
- applyActions,
147
- undo,
148
- redo,
149
- reset,
150
- };
151
- }
152
-
153
- /**
154
- * Replays a sequence of action groups from a source URL.
155
- * Intermediate object URLs are revoked as soon as a new step succeeds.
156
- * Returns the final `{ url, blob }` or `null` if there were no actions.
157
- */
158
- async function replayAll(
159
- sourceUrl: string,
160
- actionGroups: EditAction[][],
161
- registry: ActionRegistry,
162
- signal: AbortSignal,
163
- ): Promise<{ url: string; blob: Blob } | null> {
164
- let prevUrl = sourceUrl;
165
- let prevGenerated = false;
166
- let lastBlob: Blob | null = null;
167
-
168
- for (let group of actionGroups) {
169
- for (let action of group) {
170
- if (signal.aborted) {
171
- if (prevGenerated) URL.revokeObjectURL(prevUrl);
172
- return null;
173
- }
174
-
175
- let apply = registry.get(action.type);
176
- if (!apply) {
177
- console.warn(`[ImageHistory] No replay handler for action type "${action.type}" — skipping`);
178
- continue;
179
- }
180
-
181
- let blob = await apply(prevUrl, action.params);
182
-
183
- if (signal.aborted) {
184
- if (prevGenerated) URL.revokeObjectURL(prevUrl);
185
- return null;
186
- }
187
-
188
- if (prevGenerated) URL.revokeObjectURL(prevUrl);
189
- lastBlob = blob;
190
- prevUrl = URL.createObjectURL(blob);
191
- prevGenerated = true;
192
- }
193
- }
194
-
195
- if (!lastBlob || !prevGenerated) return null;
196
- return { url: prevUrl, blob: lastBlob };
197
- }
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ import type { ActionRegistry, EditAction } from "./types.js";
4
+
5
+ interface HistoryState {
6
+ past: EditAction[][];
7
+ future: EditAction[][];
8
+ }
9
+
10
+ interface CurrentState {
11
+ url: string;
12
+ blob: Blob | null;
13
+ /** True if `url` is an object URL we created and must eventually revoke. */
14
+ generated: boolean;
15
+ }
16
+
17
+ export interface UseImageHistoryResult {
18
+ currentImageUrl: string;
19
+ currentBlob: Blob | null;
20
+ /** Synchronous read of the current image URL — valid immediately after `applyActions`. */
21
+ getCurrentImageUrl: () => string;
22
+ /** Synchronous read of the current blob — valid immediately after `applyActions`. */
23
+ getCurrentBlob: () => Blob | null;
24
+ canUndo: boolean;
25
+ canRedo: boolean;
26
+ /** True while an async replay (undo/redo) is in progress. */
27
+ replaying: boolean;
28
+ /** Applies a new blob to the current state and records it in history. Returns the new object URL. */
29
+ applyActions: (blob: Blob, actions: EditAction[]) => string;
30
+ undo: () => void;
31
+ redo: () => void;
32
+ reset: () => void;
33
+ }
34
+
35
+ /**
36
+ * Manages undo/redo history for the image editor using action replay.
37
+ *
38
+ * Only action lists are stored — no intermediate blobs. Undo/redo replays
39
+ * all remaining actions from the source image, keeping memory usage minimal
40
+ * regardless of history depth. Only one blob is in memory at a time.
41
+ */
42
+ export function useImageHistory(sourceUrl: string, registry: ActionRegistry): UseImageHistoryResult {
43
+ let [history, setHistory] = useState<HistoryState>({ past: [], future: [] });
44
+ let [current, setCurrent] = useState<CurrentState>({ url: sourceUrl, blob: null, generated: false });
45
+ let [replaying, setReplaying] = useState(false);
46
+
47
+ let historyRef = useRef(history);
48
+ historyRef.current = history;
49
+ // Written synchronously by `replaceCurrent` so imperative callers can read the current
50
+ // image/blob before React has committed the corresponding render.
51
+ let currentRef = useRef(current);
52
+ let isReplaying = useRef(false);
53
+ let replayAbort = useRef<AbortController | null>(null);
54
+
55
+ function replaceCurrent(next: CurrentState) {
56
+ let prev = currentRef.current;
57
+ if (prev.generated && prev.url !== next.url) URL.revokeObjectURL(prev.url);
58
+ currentRef.current = next;
59
+ setCurrent(next);
60
+ }
61
+
62
+ // When source changes (e.g. component remount with new image), reset fully.
63
+ useEffect(() => {
64
+ replayAbort.current?.abort();
65
+ isReplaying.current = false;
66
+ setReplaying(false);
67
+ replaceCurrent({ url: sourceUrl, blob: null, generated: false });
68
+ setHistory({ past: [], future: [] });
69
+ }, [sourceUrl]);
70
+
71
+ useEffect(() => {
72
+ return () => {
73
+ if (currentRef.current.generated) URL.revokeObjectURL(currentRef.current.url);
74
+ replayAbort.current?.abort();
75
+ };
76
+ }, []);
77
+
78
+ function applyActions(blob: Blob, actions: EditAction[]) {
79
+ // A direct apply always takes priority — abort any in-flight replay.
80
+ replayAbort.current?.abort();
81
+ isReplaying.current = false;
82
+ setReplaying(false);
83
+
84
+ let newUrl = URL.createObjectURL(blob);
85
+ replaceCurrent({ url: newUrl, blob, generated: true });
86
+ setHistory((prev) => ({ past: [...prev.past, actions], future: [] }));
87
+
88
+ return newUrl;
89
+ }
90
+
91
+ async function doReplay(newPast: EditAction[][], newFuture: EditAction[][]) {
92
+ replayAbort.current?.abort();
93
+ let abort = new AbortController();
94
+ replayAbort.current = abort;
95
+ isReplaying.current = true;
96
+ setReplaying(true);
97
+
98
+ try {
99
+ let result = await replayAll(sourceUrl, newPast, registry, abort.signal);
100
+ if (abort.signal.aborted) return;
101
+
102
+ if (result) {
103
+ replaceCurrent({ url: result.url, blob: result.blob, generated: true });
104
+ } else {
105
+ replaceCurrent({ url: sourceUrl, blob: null, generated: false });
106
+ }
107
+ setHistory({ past: newPast, future: newFuture });
108
+ } catch (err) {
109
+ // Leave image and history as they were, so the user can simply try again.
110
+ console.warn("[ImageHistory] Could not replay the edit history:", err);
111
+ } finally {
112
+ if (!abort.signal.aborted) {
113
+ isReplaying.current = false;
114
+ setReplaying(false);
115
+ }
116
+ }
117
+ }
118
+
119
+ function undo() {
120
+ if (isReplaying.current) return;
121
+ let { past, future } = historyRef.current;
122
+ if (past.length === 0) return;
123
+ doReplay(past.slice(0, -1), [past.at(-1)!, ...future]);
124
+ }
125
+
126
+ function redo() {
127
+ if (isReplaying.current) return;
128
+ let { past, future } = historyRef.current;
129
+ if (future.length === 0) return;
130
+ doReplay([...past, future[0]], future.slice(1));
131
+ }
132
+
133
+ function reset() {
134
+ replayAbort.current?.abort();
135
+ isReplaying.current = false;
136
+ setReplaying(false);
137
+ replaceCurrent({ url: sourceUrl, blob: null, generated: false });
138
+ setHistory({ past: [], future: [] });
139
+ }
140
+
141
+ return {
142
+ currentImageUrl: current.url,
143
+ currentBlob: current.blob,
144
+ getCurrentImageUrl: () => currentRef.current.url,
145
+ getCurrentBlob: () => currentRef.current.blob,
146
+ canUndo: history.past.length > 0,
147
+ canRedo: history.future.length > 0,
148
+ replaying,
149
+ applyActions,
150
+ undo,
151
+ redo,
152
+ reset,
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Replays a sequence of action groups from a source URL.
158
+ * Intermediate object URLs are revoked as soon as a new step succeeds.
159
+ * Returns the final `{ url, blob }` or `null` if there were no actions.
160
+ */
161
+ async function replayAll(
162
+ sourceUrl: string,
163
+ actionGroups: EditAction[][],
164
+ registry: ActionRegistry,
165
+ signal: AbortSignal,
166
+ ): Promise<{ url: string; blob: Blob } | null> {
167
+ let prevUrl = sourceUrl;
168
+ let prevGenerated = false;
169
+ let lastBlob: Blob | null = null;
170
+
171
+ for (let group of actionGroups) {
172
+ for (let action of group) {
173
+ if (signal.aborted) {
174
+ if (prevGenerated) URL.revokeObjectURL(prevUrl);
175
+ return null;
176
+ }
177
+
178
+ let apply = registry.get(action.type);
179
+ if (!apply) {
180
+ console.warn(`[ImageHistory] No replay handler for action type "${action.type}" — skipping`);
181
+ continue;
182
+ }
183
+
184
+ let blob: Blob;
185
+ try {
186
+ blob = await apply(prevUrl, action.params);
187
+ } catch (err) {
188
+ if (prevGenerated) URL.revokeObjectURL(prevUrl);
189
+ throw err;
190
+ }
191
+
192
+ if (signal.aborted) {
193
+ if (prevGenerated) URL.revokeObjectURL(prevUrl);
194
+ return null;
195
+ }
196
+
197
+ if (prevGenerated) URL.revokeObjectURL(prevUrl);
198
+ lastBlob = blob;
199
+ prevUrl = URL.createObjectURL(blob);
200
+ prevGenerated = true;
201
+ }
202
+ }
203
+
204
+ if (!lastBlob || !prevGenerated) return null;
205
+ return { url: prevUrl, blob: lastBlob };
206
+ }
@@ -0,0 +1,208 @@
1
+ import { act, renderHook, waitFor } from "@testing-library/react";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+
4
+ /*
5
+ * OpenCV.js is never downloaded: script tags the loader adds to <head> are captured, and
6
+ * each test decides whether that "download" fails or what it leaves on `window.cv`.
7
+ */
8
+ let scripts: HTMLScriptElement[] = [];
9
+
10
+ type OpenCVModule = typeof import("./useOpenCV");
11
+
12
+ /** A fresh copy of the module, since it caches the load in module state. */
13
+ async function freshModule(): Promise<OpenCVModule> {
14
+ vi.resetModules();
15
+ return import("./useOpenCV");
16
+ }
17
+
18
+ beforeEach(() => {
19
+ scripts = [];
20
+ vi.spyOn(console, "warn").mockImplementation(() => {});
21
+ let append = document.head.appendChild.bind(document.head);
22
+ vi.spyOn(document.head, "appendChild").mockImplementation(<T extends Node>(node: T): T => {
23
+ if (node instanceof HTMLScriptElement) {
24
+ scripts.push(node);
25
+ return node;
26
+ }
27
+ return append(node);
28
+ });
29
+ window.cv = undefined;
30
+ });
31
+
32
+ afterEach(() => {
33
+ vi.restoreAllMocks();
34
+ vi.useRealTimers();
35
+ window.cv = undefined;
36
+ });
37
+
38
+ /** Waits for the loader to request its next script. */
39
+ async function nextScript(count: number) {
40
+ await vi.waitFor(() => expect(scripts).toHaveLength(count));
41
+ return scripts[count - 1];
42
+ }
43
+
44
+ function fail(script: HTMLScriptElement) {
45
+ script.onerror?.(new Event("error"));
46
+ }
47
+
48
+ function succeed(script: HTMLScriptElement, cv: unknown = { Mat: class {}, imread: () => {} }) {
49
+ window.cv = cv;
50
+ script.onload?.(new Event("load"));
51
+ }
52
+
53
+ describe("loadOpenCV", () => {
54
+ it("tries the 5.x build first and falls back to 4.x when it cannot be loaded", async () => {
55
+ let { loadOpenCV, DEFAULT_OPENCV_URLS } = await freshModule();
56
+
57
+ let loading = loadOpenCV();
58
+ let first = await nextScript(1);
59
+ expect(first.src).toBe(DEFAULT_OPENCV_URLS[0]);
60
+ fail(first);
61
+
62
+ let second = await nextScript(2);
63
+ expect(second.src).toBe(DEFAULT_OPENCV_URLS[1]);
64
+ succeed(second);
65
+
66
+ await expect(loading).resolves.toBeUndefined();
67
+ expect(window.cv.Mat).toBeDefined();
68
+ });
69
+
70
+ it("rejects when no build can be loaded, naming every URL it tried", async () => {
71
+ let { loadOpenCV, configureOpenCV } = await freshModule();
72
+ configureOpenCV(["https://a.example/opencv.js", "https://b.example/opencv.js"]);
73
+
74
+ let loading = loadOpenCV();
75
+ fail(await nextScript(1));
76
+ fail(await nextScript(2));
77
+
78
+ let error = await loading.catch((e: Error) => e);
79
+ expect(error).toBeInstanceOf(Error);
80
+ expect((error as Error).message).toBe(
81
+ "Failed to load OpenCV.js from: https://a.example/opencv.js, https://b.example/opencv.js",
82
+ );
83
+ expect((error as Error).cause).toHaveLength(2);
84
+ });
85
+
86
+ it("tries again on the next call after a failure, e.g. once the network is back", async () => {
87
+ let { loadOpenCV, configureOpenCV } = await freshModule();
88
+ configureOpenCV("https://a.example/opencv.js");
89
+
90
+ let first = loadOpenCV();
91
+ fail(await nextScript(1));
92
+ await expect(first).rejects.toThrow();
93
+
94
+ let second = loadOpenCV();
95
+ succeed(await nextScript(2));
96
+ await expect(second).resolves.toBeUndefined();
97
+ });
98
+
99
+ it("shares one download between callers", async () => {
100
+ let { loadOpenCV } = await freshModule();
101
+
102
+ let a = loadOpenCV();
103
+ let b = loadOpenCV();
104
+ succeed(await nextScript(1));
105
+
106
+ await Promise.all([a, b]);
107
+ expect(a).toBe(b);
108
+ expect(scripts).toHaveLength(1);
109
+ });
110
+
111
+ it("uses an OpenCV the page already loaded", async () => {
112
+ let { loadOpenCV } = await freshModule();
113
+ window.cv = { Mat: class {} };
114
+
115
+ await loadOpenCV();
116
+
117
+ expect(scripts).toHaveLength(0);
118
+ });
119
+
120
+ it("unwraps a promise-style Emscripten build without resolving to the thenable module", async () => {
121
+ let { loadOpenCV } = await freshModule();
122
+ // The real module is thenable too: resolving a promise *with* it would never settle.
123
+ let instance = { Mat: class {} };
124
+ let pending = {
125
+ // oxlint-disable-next-line unicorn/no-thenable -- stands in for the Emscripten module
126
+ then(resolve: (value: unknown) => void) {
127
+ resolve(instance);
128
+ },
129
+ };
130
+
131
+ let loading = loadOpenCV();
132
+ succeed(await nextScript(1), pending);
133
+
134
+ await expect(loading).resolves.toBeUndefined();
135
+ expect(window.cv).toBe(instance);
136
+ });
137
+
138
+ it("waits for a build that initialises after its script has loaded, and gives up after a minute", async () => {
139
+ vi.useFakeTimers();
140
+ let { loadOpenCV, configureOpenCV } = await freshModule();
141
+ configureOpenCV(["https://slow.example/opencv.js", "https://b.example/opencv.js"]);
142
+
143
+ let loading = loadOpenCV();
144
+ await vi.advanceTimersByTimeAsync(0);
145
+ scripts[0].onload?.(new Event("load"));
146
+
147
+ await vi.advanceTimersByTimeAsync(59_000);
148
+ expect(scripts).toHaveLength(1);
149
+ await vi.advanceTimersByTimeAsync(1_000);
150
+ expect(scripts).toHaveLength(2);
151
+
152
+ // The second build initialises asynchronously, a moment after its script loaded.
153
+ scripts[1].onload?.(new Event("load"));
154
+ window.cv = { Mat: class {} };
155
+ await vi.advanceTimersByTimeAsync(100);
156
+
157
+ await expect(loading).resolves.toBeUndefined();
158
+ });
159
+
160
+ it("lets the app point at a self-hosted build before loading starts, and not after", async () => {
161
+ let { loadOpenCV, configureOpenCV } = await freshModule();
162
+
163
+ configureOpenCV("/lib/opencv.js");
164
+ let loading = loadOpenCV();
165
+ configureOpenCV("/other/opencv.js");
166
+ let script = await nextScript(1);
167
+ succeed(script);
168
+ await loading;
169
+
170
+ expect(script.src).toContain("/lib/opencv.js");
171
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("configureOpenCV() ignored"));
172
+ });
173
+ });
174
+
175
+ describe("useOpenCV", () => {
176
+ it("does not load anything until enabled", async () => {
177
+ let { useOpenCV } = await freshModule();
178
+
179
+ let { result } = renderHook(() => useOpenCV(false));
180
+
181
+ expect(result.current).toEqual({ cv: null, ready: false, error: null });
182
+ expect(scripts).toHaveLength(0);
183
+ });
184
+
185
+ it("reports ready with the loaded module", async () => {
186
+ let { useOpenCV } = await freshModule();
187
+ let cv = { Mat: class {} };
188
+
189
+ let { result } = renderHook(() => useOpenCV(true));
190
+ succeed(await nextScript(1), cv);
191
+
192
+ await waitFor(() => expect(result.current.ready).toBe(true));
193
+ expect(result.current.cv).toBe(cv);
194
+ expect(result.current.error).toBeNull();
195
+ });
196
+
197
+ it("reports a load failure as an error instead of throwing", async () => {
198
+ let { useOpenCV, configureOpenCV } = await freshModule();
199
+ configureOpenCV("https://a.example/opencv.js");
200
+
201
+ let { result } = renderHook(() => useOpenCV(true));
202
+ await act(async () => fail(await nextScript(1)));
203
+
204
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
205
+ expect(result.current.ready).toBe(false);
206
+ expect(result.current.cv).toBeNull();
207
+ });
208
+ });