@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
@@ -0,0 +1,286 @@
1
+ import { act, render, screen, waitFor } from "@testing-library/react";
2
+ import { createRef } from "react";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import { defaultPlugins, defaultViewPlugin } from "./defaultPlugins";
6
+ import { ImageEditor, type ImageEditorRef } from "./ImageEditor";
7
+ import { configureOpenCV } from "./useOpenCV";
8
+
9
+ /*
10
+ * What an app receives from the editor after a user's edits, set up the way the expenses
11
+ * app (default plugins, zoom, Done) and the delivery ticket scans app (ref-driven rotation)
12
+ * use it. OpenCV points at a port nothing listens on: border detection is unavailable, as
13
+ * when the CDN is unreachable, and nothing is downloaded.
14
+ */
15
+ configureOpenCV("http://127.0.0.1:1/opencv.js");
16
+
17
+ type Rgb = [number, number, number];
18
+ const RED: Rgb = [230, 30, 30];
19
+ const GREEN: Rgb = [30, 170, 60];
20
+ const BLUE: Rgb = [30, 60, 230];
21
+ const YELLOW: Rgb = [240, 220, 40];
22
+
23
+ const WIDTH = 400;
24
+ const HEIGHT = 200;
25
+
26
+ let source = "";
27
+
28
+ beforeEach(async () => {
29
+ source = await quadrantImage();
30
+ // The drags below are synthetic pointer events, which have no live pointer to capture.
31
+ vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation(() => {});
32
+ });
33
+
34
+ afterEach(() => {
35
+ vi.restoreAllMocks();
36
+ URL.revokeObjectURL(source);
37
+ });
38
+
39
+ /** A PNG with a different colour in each quadrant: red, green / blue, yellow. */
40
+ async function quadrantImage() {
41
+ let canvas = document.createElement("canvas");
42
+ canvas.width = WIDTH;
43
+ canvas.height = HEIGHT;
44
+ let ctx = canvas.getContext("2d")!;
45
+ let fill = ([r, g, b]: Rgb, x: number, y: number) => {
46
+ ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
47
+ ctx.fillRect(x, y, WIDTH / 2, HEIGHT / 2);
48
+ };
49
+ fill(RED, 0, 0);
50
+ fill(GREEN, WIDTH / 2, 0);
51
+ fill(BLUE, 0, HEIGHT / 2);
52
+ fill(YELLOW, WIDTH / 2, HEIGHT / 2);
53
+ let blob = await new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), "image/png"));
54
+ return URL.createObjectURL(blob);
55
+ }
56
+
57
+ async function read(blob: Blob) {
58
+ let bitmap = await createImageBitmap(blob);
59
+ let canvas = document.createElement("canvas");
60
+ canvas.width = bitmap.width;
61
+ canvas.height = bitmap.height;
62
+ let ctx = canvas.getContext("2d")!;
63
+ ctx.drawImage(bitmap, 0, 0);
64
+ let data = ctx.getImageData(0, 0, bitmap.width, bitmap.height).data;
65
+ let pixel = (x: number, y: number): Rgb => {
66
+ let i = (Math.floor(y) * bitmap.width + Math.floor(x)) * 4;
67
+ return [data[i], data[i + 1], data[i + 2]];
68
+ };
69
+ let { width: w, height: h } = bitmap;
70
+ return {
71
+ width: w,
72
+ height: h,
73
+ pixel,
74
+ /** Centre of each quadrant: top-left, top-right, bottom-right, bottom-left. */
75
+ quadrants: () => [
76
+ pixel(w / 4, h / 4),
77
+ pixel((3 * w) / 4, h / 4),
78
+ pixel((3 * w) / 4, (3 * h) / 4),
79
+ pixel(w / 4, (3 * h) / 4),
80
+ ],
81
+ };
82
+ }
83
+
84
+ function expectColour(actual: Rgb, expected: Rgb, tolerance = 30) {
85
+ let off = Math.max(...actual.map((v, i) => Math.abs(v - expected[i])));
86
+ expect(off, `rgb(${actual.join(", ")}) should be close to rgb(${expected.join(", ")})`).toBeLessThanOrEqual(
87
+ tolerance,
88
+ );
89
+ }
90
+
91
+ /** Renders the editor in a box the size of a phone screen, like the full-screen layer apps use. */
92
+ function renderEditor(props: { initialTool?: string; ref?: React.Ref<ImageEditorRef> } = {}) {
93
+ let onConfirm = vi.fn<(blob: Blob) => void>();
94
+ render(
95
+ <div style={{ position: "relative", width: 400, height: 600 }}>
96
+ <ImageEditor
97
+ ref={props.ref}
98
+ imageUrl={source}
99
+ plugins={defaultPlugins}
100
+ viewPlugin={defaultViewPlugin}
101
+ initialTool={props.initialTool}
102
+ onConfirm={onConfirm}
103
+ />
104
+ </div>,
105
+ );
106
+ return onConfirm;
107
+ }
108
+
109
+ function click(name: string) {
110
+ act(() => screen.getByRole("button", { name }).click());
111
+ }
112
+
113
+ /** Drags from one point to another, given as fractions of the element's box. */
114
+ function drag(element: Element, from: [number, number], to: [number, number]) {
115
+ let box = element.getBoundingClientRect();
116
+ let at = ([fx, fy]: [number, number]) => ({
117
+ clientX: box.left + fx * box.width,
118
+ clientY: box.top + fy * box.height,
119
+ });
120
+ let init = { bubbles: true, pointerId: 1, pointerType: "mouse", isPrimary: true };
121
+ act(() => {
122
+ element.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...at(from), buttons: 1 }));
123
+ });
124
+ for (let step = 1; step <= 4; step++) {
125
+ let t = step / 4;
126
+ let point: [number, number] = [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t];
127
+ act(() => {
128
+ element.dispatchEvent(new PointerEvent("pointermove", { ...init, ...at(point), buttons: 1 }));
129
+ });
130
+ }
131
+ act(() => {
132
+ element.dispatchEvent(new PointerEvent("pointerup", { ...init, ...at(to), buttons: 0 }));
133
+ });
134
+ }
135
+
136
+ /** Clicks Done and returns what the app's onConfirm received. */
137
+ async function done(onConfirm: ReturnType<typeof renderEditor>) {
138
+ await waitFor(() => expect(screen.getByRole("button", { name: "Done" })).toBeEnabled());
139
+ click("Done");
140
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce());
141
+ return onConfirm.mock.calls[0][0];
142
+ }
143
+
144
+ describe("ImageEditor output", () => {
145
+ it("returns the image unchanged when the user only presses Done", async () => {
146
+ let onConfirm = renderEditor();
147
+
148
+ let image = await read(await done(onConfirm));
149
+
150
+ expect([image.width, image.height]).toEqual([WIDTH, HEIGHT]);
151
+ let [tl, tr, br, bl] = image.quadrants();
152
+ expectColour(tl, RED, 0);
153
+ expectColour(tr, GREEN, 0);
154
+ expectColour(br, YELLOW, 0);
155
+ expectColour(bl, BLUE, 0);
156
+ });
157
+
158
+ it("returns the rotated image after Rotate right", async () => {
159
+ let onConfirm = renderEditor();
160
+
161
+ click("Rotate right");
162
+ await waitFor(() => expect(screen.getByRole("button", { name: "Undo" })).toBeEnabled());
163
+ let image = await read(await done(onConfirm));
164
+
165
+ expect([image.width, image.height]).toEqual([HEIGHT, WIDTH]);
166
+ let [tl, tr, br, bl] = image.quadrants();
167
+ expectColour(tl, BLUE);
168
+ expectColour(tr, RED);
169
+ expectColour(br, GREEN);
170
+ expectColour(bl, YELLOW);
171
+ });
172
+
173
+ it("returns the original again after a rotation is undone", async () => {
174
+ let onConfirm = renderEditor();
175
+
176
+ click("Rotate left");
177
+ await waitFor(() => expect(screen.getByRole("button", { name: "Undo" })).toBeEnabled());
178
+ click("Undo");
179
+ await waitFor(() => expect(screen.getByRole("button", { name: "Redo" })).toBeEnabled());
180
+ let image = await read(await done(onConfirm));
181
+
182
+ expect([image.width, image.height]).toEqual([WIDTH, HEIGHT]);
183
+ expectColour(image.quadrants()[0], RED, 0);
184
+ });
185
+
186
+ it("includes every rotation an external toolbar queued before reading the result", async () => {
187
+ let ref = createRef<ImageEditorRef>();
188
+ renderEditor({ ref });
189
+
190
+ // What the scans app does: fire rotations, then await whenIdle() before saving.
191
+ void ref.current!.executeAction("rotate-ccw");
192
+ void ref.current!.executeAction("rotate-ccw");
193
+ await act(() => ref.current!.whenIdle());
194
+ let image = await read(ref.current!.getCurrentBlob()!);
195
+
196
+ // Two quarter turns: upside down, same size.
197
+ expect([image.width, image.height]).toEqual([WIDTH, HEIGHT]);
198
+ let [tl, tr, br, bl] = image.quadrants();
199
+ expectColour(tl, YELLOW);
200
+ expectColour(tr, BLUE);
201
+ expectColour(br, RED);
202
+ expectColour(bl, GREEN);
203
+ });
204
+
205
+ it("crops to a rectangle the user draws, without OpenCV, at full resolution", async () => {
206
+ let onConfirm = renderEditor({ initialTool: "crop" });
207
+
208
+ // OpenCV cannot load: the tool says so but stays usable.
209
+ await screen.findByText("Automatic border detection is unavailable. Adjust the selection manually.");
210
+ click("Draw rectangle");
211
+ let surface = await screen.findByRole("application", { name: "Drag to draw a rectangle to crop to" });
212
+ // The green top-right quadrant, from its bottom-left corner to the image's top-right.
213
+ drag(surface, [0.5, 0.5], [1, 0]);
214
+ await waitFor(() => expect(screen.getByRole("button", { name: "Apply crop" })).toBeEnabled());
215
+ click("Apply crop");
216
+ await screen.findByRole("img", { name: "Image to edit" });
217
+
218
+ let blob = await done(onConfirm);
219
+ let image = await read(blob);
220
+
221
+ // Lossless, so receipt text stays sharp; within a pixel of the quadrant's size.
222
+ expect(blob.type).toBe("image/png");
223
+ expect(Math.abs(image.width - WIDTH / 2)).toBeLessThanOrEqual(2);
224
+ expect(Math.abs(image.height - HEIGHT / 2)).toBeLessThanOrEqual(2);
225
+ for (let [x, y] of [
226
+ [3, 3],
227
+ [image.width - 3, 3],
228
+ [image.width - 3, image.height - 3],
229
+ [3, image.height - 3],
230
+ ]) {
231
+ expectColour(image.pixel(x, y), GREEN, 0);
232
+ }
233
+ });
234
+
235
+ it("returns to the full image when a crop is undone", async () => {
236
+ let onConfirm = renderEditor({ initialTool: "crop" });
237
+ click("Draw rectangle");
238
+ drag(await screen.findByRole("application", { name: "Drag to draw a rectangle to crop to" }), [0, 0], [0.5, 0.5]);
239
+ await waitFor(() => expect(screen.getByRole("button", { name: "Apply crop" })).toBeEnabled());
240
+ click("Apply crop");
241
+ await waitFor(() => expect(screen.getByRole("button", { name: "Undo" })).toBeEnabled());
242
+
243
+ click("Undo");
244
+ await waitFor(() => expect(screen.getByRole("button", { name: "Redo" })).toBeEnabled());
245
+ let image = await read(await done(onConfirm));
246
+
247
+ expect([image.width, image.height]).toEqual([WIDTH, HEIGHT]);
248
+ });
249
+
250
+ it("blurs a region the user marks for redaction", async () => {
251
+ let onConfirm = renderEditor();
252
+
253
+ click("Redact");
254
+ let svg = await waitFor(() => {
255
+ let element = document.querySelector("svg.redact-svg");
256
+ expect(element).not.toBeNull();
257
+ return element!;
258
+ });
259
+ // Cover the middle of the red top-left quadrant.
260
+ drag(svg, [0.05, 0.1], [0.45, 0.4]);
261
+ click("Apply redact");
262
+ await screen.findByRole("img", { name: "Image to edit" });
263
+
264
+ let image = await read(await done(onConfirm));
265
+
266
+ expect([image.width, image.height]).toEqual([WIDTH, HEIGHT]);
267
+ let [tl, tr, br, bl] = image.quadrants();
268
+ let [r, g] = tl;
269
+ expect(r - g, `rgb(${tl.join(", ")}) should no longer be red`).toBeLessThan(60);
270
+ expectColour(tr, GREEN);
271
+ expectColour(br, YELLOW);
272
+ expectColour(bl, BLUE);
273
+ // Just outside the marked area the image is untouched.
274
+ expectColour(image.pixel(WIDTH * 0.02, HEIGHT * 0.05), RED);
275
+ });
276
+
277
+ it("closes the redact tool without an edit when nothing was marked", async () => {
278
+ renderEditor();
279
+
280
+ click("Redact");
281
+ click("Done");
282
+
283
+ await screen.findByRole("img", { name: "Image to edit" });
284
+ expect(screen.getByRole("button", { name: "Undo" })).toBeDisabled();
285
+ });
286
+ });
@@ -0,0 +1,299 @@
1
+ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
2
+ import { createContext, createRef, type ReactNode, use } from "react";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import { ImageEditor, type ImageEditorRef } from "./ImageEditor";
6
+ import type { ActionPlugin, ToolPlugin, ToolProviderProps, ViewPlugin } from "./types";
7
+
8
+ /*
9
+ * The editor shell with stand-in plugins: what the toolbar offers, how edits reach the
10
+ * history, and what the app gets back. Real image output is in ImageEditor.browser.test.tsx.
11
+ */
12
+
13
+ const SOURCE = "blob:source";
14
+
15
+ let counter = 0;
16
+
17
+ beforeEach(() => {
18
+ // Designsystemet's Spinner (shown while undo replays) syncs its animation through
19
+ // document.getAnimations(), which happy-dom does not implement.
20
+ if (!("getAnimations" in document)) {
21
+ Object.defineProperty(document, "getAnimations", { configurable: true, value: () => [] });
22
+ }
23
+ counter = 0;
24
+ vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:edit-${++counter}`);
25
+ vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
26
+ });
27
+
28
+ afterEach(() => {
29
+ vi.restoreAllMocks();
30
+ vi.unstubAllGlobals();
31
+ });
32
+
33
+ function Icon() {
34
+ return null;
35
+ }
36
+
37
+ /** An action plugin whose output records which image it was given. */
38
+ function actionPlugin(id: string, label: string, execute?: ActionPlugin["execute"]) {
39
+ let plugin: ActionPlugin = {
40
+ type: "action",
41
+ id,
42
+ label,
43
+ Icon,
44
+ execute: vi.fn(execute ?? (async (url: string) => new Blob([`${id}(${url})`]))),
45
+ };
46
+ return plugin;
47
+ }
48
+
49
+ /** A tool plugin whose toolbar can apply a fixed edit or cancel, like the crop and redact tools. */
50
+ function toolPlugin(id: string, label: string) {
51
+ let Context = createContext<ToolProviderProps | null>(null);
52
+ let applied = new Blob([`${id} result`]);
53
+ let plugin: ToolPlugin = {
54
+ type: "tool",
55
+ id,
56
+ label,
57
+ Icon,
58
+ Provider: (props: ToolProviderProps) => <Context value={props}>{props.children}</Context>,
59
+ Overlay: () => <div data-testid={`${id}-overlay`} data-image-url={use(Context)?.imageUrl} />,
60
+ Toolbar: () => {
61
+ let tool = use(Context);
62
+ return (
63
+ <>
64
+ <button onClick={() => tool?.onApply(applied, [{ type: id, params: { n: 1 } }])}>Apply {id}</button>
65
+ <button onClick={() => tool?.onCancel()}>Cancel {id}</button>
66
+ </>
67
+ );
68
+ },
69
+ actions: [{ type: id, apply: async () => applied }],
70
+ };
71
+ return { plugin, applied };
72
+ }
73
+
74
+ function image() {
75
+ return screen.getByRole<HTMLImageElement>("img", { name: "Image to edit" });
76
+ }
77
+
78
+ function button(name: string) {
79
+ return screen.getByRole("button", { name });
80
+ }
81
+
82
+ describe("ImageEditor", () => {
83
+ it("shows the image with undo, redo and reset disabled until something is edited", () => {
84
+ render(<ImageEditor imageUrl={SOURCE} plugins={[actionPlugin("rotate-cw", "Rotate right")]} />);
85
+
86
+ expect(image()).toHaveAttribute("src", SOURCE);
87
+ expect(button("Undo")).toBeDisabled();
88
+ expect(button("Redo")).toBeDisabled();
89
+ expect(button("Reset")).toBeDisabled();
90
+ expect(button("Rotate right")).toBeEnabled();
91
+ });
92
+
93
+ it("shows Back only when the app can cancel, and Done only when it takes a result", () => {
94
+ let { rerender } = render(<ImageEditor imageUrl={SOURCE} plugins={[]} />);
95
+ expect(screen.queryByRole("button", { name: "Back" })).not.toBeInTheDocument();
96
+ expect(screen.queryByRole("button", { name: "Done" })).not.toBeInTheDocument();
97
+
98
+ let onCancel = vi.fn();
99
+ rerender(<ImageEditor imageUrl={SOURCE} plugins={[]} onCancel={onCancel} onConfirm={() => {}} />);
100
+ fireEvent.click(button("Back"));
101
+
102
+ expect(onCancel).toHaveBeenCalledOnce();
103
+ expect(button("Done")).toBeInTheDocument();
104
+ });
105
+
106
+ it("runs an action on the current image and makes the result undoable", async () => {
107
+ let rotate = actionPlugin("rotate-cw", "Rotate right");
108
+ render(<ImageEditor imageUrl={SOURCE} plugins={[rotate]} />);
109
+
110
+ fireEvent.click(button("Rotate right"));
111
+
112
+ await waitFor(() => expect(image()).toHaveAttribute("src", "blob:edit-1"));
113
+ expect(rotate.execute).toHaveBeenCalledWith(SOURCE);
114
+ expect(button("Undo")).toBeEnabled();
115
+ expect(button("Reset")).toBeEnabled();
116
+ });
117
+
118
+ it("undo replays through the plugin and returns to the source", async () => {
119
+ let rotate = actionPlugin("rotate-cw", "Rotate right");
120
+ render(<ImageEditor imageUrl={SOURCE} plugins={[rotate]} />);
121
+ fireEvent.click(button("Rotate right"));
122
+ await waitFor(() => expect(button("Undo")).toBeEnabled());
123
+
124
+ fireEvent.click(button("Undo"));
125
+ await waitFor(() => expect(image()).toHaveAttribute("src", SOURCE));
126
+ expect(button("Redo")).toBeEnabled();
127
+
128
+ fireEvent.click(button("Redo"));
129
+ await waitFor(() => expect(button("Redo")).toBeDisabled());
130
+ // Redo replays the action from the source again.
131
+ expect(rotate.execute).toHaveBeenLastCalledWith(SOURCE);
132
+ expect(image().getAttribute("src")).not.toBe(SOURCE);
133
+ });
134
+
135
+ it("opens a tool in place of the image, with undo and Done unavailable while it is open", () => {
136
+ let crop = toolPlugin("crop", "Crop");
137
+ render(<ImageEditor imageUrl={SOURCE} plugins={[crop.plugin]} onConfirm={() => {}} />);
138
+
139
+ fireEvent.click(button("Crop"));
140
+
141
+ expect(screen.getByTestId("crop-overlay")).toBeInTheDocument();
142
+ expect(screen.queryByRole("img", { name: "Image to edit" })).not.toBeInTheDocument();
143
+ expect(screen.queryByRole("button", { name: "Done" })).not.toBeInTheDocument();
144
+ expect(button("Undo")).toBeDisabled();
145
+ expect(screen.getByTestId("crop-overlay")).toHaveAttribute("data-image-url", SOURCE);
146
+ });
147
+
148
+ it("records what a tool applies and closes it", async () => {
149
+ let crop = toolPlugin("crop", "Crop");
150
+ let ref = createRef<ImageEditorRef>();
151
+ render(<ImageEditor ref={ref} imageUrl={SOURCE} plugins={[crop.plugin]} />);
152
+
153
+ fireEvent.click(button("Crop"));
154
+ fireEvent.click(button("Apply crop"));
155
+
156
+ expect(screen.queryByTestId("crop-overlay")).not.toBeInTheDocument();
157
+ expect(image()).toHaveAttribute("src", "blob:edit-1");
158
+ expect(ref.current?.getCurrentBlob()).toBe(crop.applied);
159
+ expect(button("Undo")).toBeEnabled();
160
+ });
161
+
162
+ it("leaves the image untouched when a tool is cancelled", () => {
163
+ let crop = toolPlugin("crop", "Crop");
164
+ render(<ImageEditor imageUrl={SOURCE} plugins={[crop.plugin]} />);
165
+
166
+ fireEvent.click(button("Crop"));
167
+ fireEvent.click(button("Cancel crop"));
168
+
169
+ expect(image()).toHaveAttribute("src", SOURCE);
170
+ expect(button("Undo")).toBeDisabled();
171
+ });
172
+
173
+ it("can open straight into a tool, as the expenses app does with crop", () => {
174
+ let crop = toolPlugin("crop", "Crop");
175
+ render(<ImageEditor imageUrl={SOURCE} plugins={[crop.plugin]} initialTool="crop" />);
176
+
177
+ expect(screen.getByTestId("crop-overlay")).toBeInTheDocument();
178
+
179
+ fireEvent.click(button("Cancel crop"));
180
+ expect(image()).toHaveAttribute("src", SOURCE);
181
+ });
182
+
183
+ describe("Done", () => {
184
+ it("hands the app the edited image", async () => {
185
+ let onConfirm = vi.fn();
186
+ let rotate = actionPlugin("rotate-cw", "Rotate right");
187
+ render(<ImageEditor imageUrl={SOURCE} plugins={[rotate]} onConfirm={onConfirm} />);
188
+ fireEvent.click(button("Rotate right"));
189
+ await waitFor(() => expect(button("Undo")).toBeEnabled());
190
+
191
+ fireEvent.click(button("Done"));
192
+
193
+ expect(onConfirm).toHaveBeenCalledOnce();
194
+ expect(await (onConfirm.mock.calls[0][0] as Blob).text()).toBe(`rotate-cw(${SOURCE})`);
195
+ });
196
+
197
+ it("hands the app the original image when nothing was edited", async () => {
198
+ let original = new Blob(["original"]);
199
+ let fetchMock = vi.fn(async () => new Response(original));
200
+ vi.stubGlobal("fetch", fetchMock);
201
+ let onConfirm = vi.fn();
202
+ render(<ImageEditor imageUrl={SOURCE} plugins={[]} onConfirm={onConfirm} />);
203
+
204
+ fireEvent.click(button("Done"));
205
+
206
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce());
207
+ expect(fetchMock).toHaveBeenCalledWith(SOURCE);
208
+ expect(await (onConfirm.mock.calls[0][0] as Blob).text()).toBe("original");
209
+ });
210
+ });
211
+
212
+ describe("ref (external toolbars, as in the delivery ticket scans app)", () => {
213
+ it("runs actions one after another, each on the previous result", async () => {
214
+ let ref = createRef<ImageEditorRef>();
215
+ let rotate = actionPlugin("rotate-cw", "Rotate right");
216
+ render(<ImageEditor ref={ref} imageUrl={SOURCE} plugins={[rotate]} />);
217
+
218
+ let first = ref.current!.executeAction("rotate-cw");
219
+ let second = ref.current!.executeAction("rotate-cw");
220
+ await act(() => Promise.all([first, second]));
221
+
222
+ expect(rotate.execute).toHaveBeenNthCalledWith(1, SOURCE);
223
+ expect(rotate.execute).toHaveBeenNthCalledWith(2, "blob:edit-1");
224
+ });
225
+
226
+ it("whenIdle waits for queued actions, so a save never misses the last rotation", async () => {
227
+ let ref = createRef<ImageEditorRef>();
228
+ let rotate = actionPlugin("rotate-cw", "Rotate right");
229
+ render(<ImageEditor ref={ref} imageUrl={SOURCE} plugins={[rotate]} />);
230
+
231
+ void ref.current!.executeAction("rotate-cw");
232
+ void ref.current!.executeAction("rotate-cw");
233
+ expect(ref.current!.getCurrentBlob()).toBeNull();
234
+
235
+ await act(() => ref.current!.whenIdle());
236
+
237
+ expect(await ref.current!.getCurrentBlob()?.text()).toBe(`rotate-cw(blob:edit-1)`);
238
+ });
239
+
240
+ it("returns no blob before anything is edited", () => {
241
+ let ref = createRef<ImageEditorRef>();
242
+ render(<ImageEditor ref={ref} imageUrl={SOURCE} plugins={[]} />);
243
+
244
+ expect(ref.current!.getCurrentBlob()).toBeNull();
245
+ });
246
+
247
+ it("warns and does nothing for an action that is not registered", async () => {
248
+ let warn = vi.spyOn(console, "warn").mockImplementation(() => {});
249
+ let ref = createRef<ImageEditorRef>();
250
+ render(<ImageEditor ref={ref} imageUrl={SOURCE} plugins={[toolPlugin("crop", "Crop").plugin]} />);
251
+
252
+ // A tool id is not an action either.
253
+ await ref.current!.executeAction("crop");
254
+
255
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('"crop"'));
256
+ expect(image()).toHaveAttribute("src", SOURCE);
257
+ });
258
+
259
+ it("reports a failed action to the caller and keeps going with the next one", async () => {
260
+ let ref = createRef<ImageEditorRef>();
261
+ let fail = true;
262
+ let rotate = actionPlugin("rotate-cw", "Rotate right", async (url) => {
263
+ if (fail) throw new Error("Failed to load image");
264
+ return new Blob([`ok(${url})`]);
265
+ });
266
+ render(<ImageEditor ref={ref} imageUrl={SOURCE} plugins={[rotate]} />);
267
+
268
+ await act(() => expect(ref.current!.executeAction("rotate-cw")).rejects.toThrow("Failed to load image"));
269
+ expect(button("Rotate right")).toBeEnabled();
270
+
271
+ fail = false;
272
+ await act(() => ref.current!.executeAction("rotate-cw"));
273
+ expect(await ref.current!.getCurrentBlob()?.text()).toBe(`ok(${SOURCE})`);
274
+ });
275
+ });
276
+
277
+ it("wraps the canvas in the view plugin, with panning off while a tool is open", () => {
278
+ let panEnabled: (boolean | undefined)[] = [];
279
+ let view: ViewPlugin = {
280
+ type: "view",
281
+ id: "zoom",
282
+ Provider: ({ children }: { children: ReactNode }) => <>{children}</>,
283
+ CanvasWrapper: (props: { children: ReactNode; panEnabled?: boolean }) => {
284
+ panEnabled.push(props.panEnabled);
285
+ return <div data-testid="view">{props.children}</div>;
286
+ },
287
+ TopBarControls: () => <span>zoom controls</span>,
288
+ };
289
+ let crop = toolPlugin("crop", "Crop");
290
+ render(<ImageEditor imageUrl={SOURCE} plugins={[crop.plugin]} viewPlugin={view} />);
291
+
292
+ expect(screen.getByTestId("view")).toContainElement(image());
293
+ expect(screen.getByText("zoom controls")).toBeInTheDocument();
294
+ expect(panEnabled.at(-1)).toBe(true);
295
+
296
+ fireEvent.click(button("Crop"));
297
+ expect(panEnabled.at(-1)).toBe(false);
298
+ });
299
+ });