@olenbetong/synergi-react 5.0.0 → 5.2.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 (168) hide show
  1. package/dist/styles/styles.css +1 -1
  2. package/dist/styles/styles.css.map +1 -1
  3. package/es/components/Checkbox/index.css +1 -1
  4. package/es/components/Checkbox/index.js +1 -9
  5. package/es/components/CodeEditor/CodeEditor.css +6 -6
  6. package/es/components/ColorCard/index.css +17 -28
  7. package/es/components/DateNavigator/index.css +5 -7
  8. package/es/components/FilePond.js +3 -12
  9. package/es/components/ImageEditor/ImageEditor.css +10 -10
  10. package/es/components/ImageEditor/ImageEditor.js +4 -4
  11. package/es/components/ImageEditor/ResponsiveButton.js +2 -2
  12. package/es/components/ImageEditor/plugins/cropPlugin/CropToolbar.js +1 -1
  13. package/es/components/ImageEditor/plugins/redactPlugin/RedactToolbar.js +1 -1
  14. package/es/components/ImageEditor/plugins/redactPlugin/useRedactTool.js +18 -14
  15. package/es/components/ImageEditor/useImageHistory.js +13 -1
  16. package/es/components/MergeProgressDialog/MergeProgressDialogDs.js +3 -3
  17. package/es/components/MergeProgressDialog/useMergeJob.js +5 -4
  18. package/es/components/PageBanner/index.css +1 -1
  19. package/es/components/PdfViewer/PdfViewer.js +1 -1
  20. package/es/components/Portal/index.js +20 -20
  21. package/es/components/Spinner/index.css +1 -1
  22. package/es/components/SplitContainer/index.css +1 -1
  23. package/es/components/SplitContainer/index.js +3 -1
  24. package/es/components/Toolbar/Toolbar.css +137 -137
  25. package/es/components/Toolbar/index.js +6 -1
  26. package/es/components/ValueToggleGroup/index.css +2 -2
  27. package/es/elements/ElementLookupDialog/BarcodeScanner/BarcodeScanner.css +7 -7
  28. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.js +8 -0
  29. package/es/elements/ElementLookupDialog/HIDScanner/useHIDScanner.js +3 -1
  30. package/es/elements-ds/DescriptionInput.d.ts +16 -0
  31. package/es/elements-ds/DescriptionInput.js +41 -0
  32. package/es/elements-ds/DuplicateElementDamage.d.ts +40 -0
  33. package/es/elements-ds/DuplicateElementDamage.js +57 -0
  34. package/es/elements-ds/ElementLookup.d.ts +23 -0
  35. package/es/elements-ds/ElementLookup.js +35 -0
  36. package/es/elements-ds/ElementLookupDialog.d.ts +7 -0
  37. package/es/elements-ds/ElementLookupDialog.js +84 -0
  38. package/es/elements-ds/FormFields.d.ts +43 -0
  39. package/es/elements-ds/FormFields.js +67 -0
  40. package/es/elements-ds/HIDScanner.d.ts +7 -0
  41. package/es/elements-ds/HIDScanner.js +36 -0
  42. package/es/elements-ds/ManualForm.d.ts +7 -0
  43. package/es/elements-ds/ManualForm.js +70 -0
  44. package/es/elements-ds/ProjectSelect.d.ts +28 -0
  45. package/es/elements-ds/ProjectSelect.js +45 -0
  46. package/es/elements-ds/elements-ds.css +157 -0
  47. package/es/elements-ds/index.d.ts +12 -0
  48. package/es/elements-ds/index.js +14 -0
  49. package/es/index.css +1 -1
  50. package/es/useTranslation/index.js +5 -3
  51. package/package.json +16 -4
  52. package/src/chrome/AppShell/AppShell.test.tsx +48 -0
  53. package/src/chrome/AppShell/index.tsx +29 -29
  54. package/src/chrome/openReport.test.ts +50 -0
  55. package/src/chrome/openReport.ts +34 -34
  56. package/src/colorScheme.test.ts +188 -0
  57. package/src/colorScheme.ts +125 -125
  58. package/src/components/Checkbox/Checkbox.browser.test.tsx +116 -0
  59. package/src/components/Checkbox/index.scss +2 -2
  60. package/src/components/Checkbox/index.tsx +1 -10
  61. package/src/components/CodeEditor/CodeEditor.css +6 -6
  62. package/src/components/CodeEditor/CodeEditor.tsx +173 -173
  63. package/src/components/CodeEditor/index.ts +1 -1
  64. package/src/components/ColorCard/ColorCard.test.tsx +34 -0
  65. package/src/components/ColorCard/index.css +17 -28
  66. package/src/components/DateNavigator/DateNavigator.test.tsx +175 -0
  67. package/src/components/DateNavigator/index.css +5 -7
  68. package/src/components/DateNavigator/index.tsx +186 -186
  69. package/src/components/FilePond.browser.test.tsx +389 -0
  70. package/src/components/FilePond.tsx +303 -312
  71. package/src/components/ImageEditor/ImageEditor.browser.test.tsx +286 -0
  72. package/src/components/ImageEditor/ImageEditor.css +10 -10
  73. package/src/components/ImageEditor/ImageEditor.test.tsx +299 -0
  74. package/src/components/ImageEditor/ImageEditor.tsx +348 -348
  75. package/src/components/ImageEditor/ResponsiveButton.tsx +2 -2
  76. package/src/components/ImageEditor/index.ts +9 -9
  77. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +165 -165
  78. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +42 -48
  79. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.test.ts +225 -0
  80. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +405 -405
  81. package/src/components/ImageEditor/plugins/plugins.browser.test.ts +252 -0
  82. package/src/components/ImageEditor/plugins/redactPlugin/RedactToolbar.tsx +47 -47
  83. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.test.ts +89 -0
  84. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.ts +16 -13
  85. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomContext.tsx +23 -23
  86. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomControls.tsx +40 -40
  87. package/src/components/ImageEditor/plugins/zoomPlugin/useZoomPan.test.ts +154 -0
  88. package/src/components/ImageEditor/useActiveTool.ts +21 -21
  89. package/src/components/ImageEditor/useEdgeDetection.test.ts +96 -0
  90. package/src/components/ImageEditor/useEdgeDetection.ts +319 -319
  91. package/src/components/ImageEditor/useImageHistory.test.ts +409 -0
  92. package/src/components/ImageEditor/useImageHistory.ts +206 -197
  93. package/src/components/ImageEditor/useOpenCV.test.ts +208 -0
  94. package/src/components/ImageEditor/useOpenCV.ts +184 -184
  95. package/src/components/LinkedCardList/index.scss +95 -95
  96. package/src/components/MergeProgressDialog/MergeProgressDialogDs.browser.test.tsx +156 -0
  97. package/src/components/MergeProgressDialog/MergeProgressDialogDs.tsx +4 -3
  98. package/src/components/MergeProgressDialog/useMergeJob.test.ts +326 -0
  99. package/src/components/MergeProgressDialog/useMergeJob.ts +4 -3
  100. package/src/components/PageBanner/index.scss +10 -10
  101. package/src/components/PageBanner/index.tsx +80 -80
  102. package/src/components/PdfViewer/PdfViewer.browser.test.tsx +78 -0
  103. package/src/components/PdfViewer/PdfViewer.tsx +158 -158
  104. package/src/components/Portal/Portal.test.tsx +106 -0
  105. package/src/components/Portal/index.tsx +22 -25
  106. package/src/components/Sidebar/Sidebar.browser.test.tsx +57 -0
  107. package/src/components/Sidebar/Sidebar.test.tsx +123 -0
  108. package/src/components/Spinner/index.css +1 -1
  109. package/src/components/SplitContainer/SplitContainer.browser.test.tsx +304 -0
  110. package/src/components/SplitContainer/index.scss +5 -1
  111. package/src/components/SplitContainer/index.tsx +335 -333
  112. package/src/components/Toolbar/Toolbar.css +137 -137
  113. package/src/components/Toolbar/Toolbar.test.tsx +216 -0
  114. package/src/components/Toolbar/ToolbarBreadcrumbs.browser.test.tsx +137 -0
  115. package/src/components/Toolbar/index.tsx +270 -265
  116. package/src/components/ValueToggleGroup/ValueToggleGroup.test.tsx +112 -0
  117. package/src/components/ValueToggleGroup/index.css +2 -2
  118. package/src/designsystemet-web-types.d.ts +24 -24
  119. package/src/elements/ElementDamage/DamageFormButtons.tsx +35 -35
  120. package/src/elements/ElementDamage/DescriptionInput.tsx +120 -120
  121. package/src/elements/ElementDamage/DuplicateDamage/DesktopView.tsx +82 -82
  122. package/src/elements/ElementDamage/DuplicateDamage/DublicateElementDamageDialog.tsx +67 -67
  123. package/src/elements/ElementDamage/DuplicateDamage/PhoneView.tsx +45 -45
  124. package/src/elements/ElementDamage/ElementNumberTextField.tsx +41 -41
  125. package/src/elements/ElementDamage/RegisterFix.tsx +100 -100
  126. package/src/elements/ElementDamage/SubmitButtons.tsx +40 -40
  127. package/src/elements/ElementDamage/TransportElementSelect.tsx +52 -52
  128. package/src/elements/ElementLookup.tsx +123 -123
  129. package/src/elements/ElementLookupDialog/BarcodeScanner/BarcodeScanner.browser.test.tsx +175 -0
  130. package/src/elements/ElementLookupDialog/BarcodeScanner/BarcodeScanner.css +7 -7
  131. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.ts +8 -0
  132. package/src/elements/ElementLookupDialog/BarcodeScanner/engines.browser.test.ts +225 -0
  133. package/src/elements/ElementLookupDialog/HIDScanner/index.tsx +67 -67
  134. package/src/elements/ElementLookupDialog/HIDScanner/useHIDScanner.test.ts +124 -0
  135. package/src/elements/ElementLookupDialog/HIDScanner/useHIDScanner.ts +2 -1
  136. package/src/elements/ElementLookupDialog/Manual/ManualForm.tsx +141 -141
  137. package/src/elements/ElementLookupDialog/getElement.test.ts +133 -0
  138. package/src/elements/ElementLookupDialog/index.tsx +226 -226
  139. package/src/elements/ElementLookupDialog/utils/Giai.test.ts +53 -0
  140. package/src/elements/ElementLookupDialog/utils/Giai.ts +209 -209
  141. package/src/elements/ProjectSelect.tsx +130 -130
  142. package/src/elements/index.ts +15 -15
  143. package/src/elements-ds/DamageForm.browser.test.tsx +530 -0
  144. package/src/elements-ds/DescriptionInput.tsx +114 -0
  145. package/src/elements-ds/DuplicateElementDamage.tsx +185 -0
  146. package/src/elements-ds/ElementLookup.tsx +114 -0
  147. package/src/elements-ds/ElementLookupDialog.browser.test.tsx +207 -0
  148. package/src/elements-ds/ElementLookupDialog.tsx +194 -0
  149. package/src/elements-ds/FormFields.tsx +176 -0
  150. package/src/elements-ds/HIDScanner.tsx +53 -0
  151. package/src/elements-ds/ManualForm.tsx +129 -0
  152. package/src/elements-ds/ProjectSelect.tsx +120 -0
  153. package/src/elements-ds/elements-ds.css +157 -0
  154. package/src/elements-ds/index.ts +16 -0
  155. package/src/filter/index.ts +34 -34
  156. package/src/i18n.test.ts +31 -0
  157. package/src/i18n.ts +13 -13
  158. package/src/mui/MuiThemeProvider.tsx +135 -135
  159. package/src/test/fakeCamera.ts +98 -0
  160. package/src/test/fakeDataApi.ts +90 -0
  161. package/src/test/setup.browser.ts +21 -0
  162. package/src/test/setup.ts +23 -23
  163. package/src/useTranslation/index.ts +5 -3
  164. package/src/useTranslation/useTranslation.test.ts +128 -0
  165. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders.test.d.ts +0 -1
  166. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders.test.js +0 -103
  167. package/es/test/setup.d.ts +0 -6
  168. package/es/test/setup.js +0 -6
@@ -0,0 +1,252 @@
1
+ import { afterEach, describe, expect, it } from "vitest";
2
+
3
+ import { configureOpenCV } from "../useOpenCV";
4
+ import { replayCrop } from "./cropPlugin/useCropTool";
5
+ import { replayRedactBlur } from "./redactPlugin/useRedactTool";
6
+ import { rotateCcwPlugin, rotateCwPlugin } from "./rotatePlugin";
7
+
8
+ /*
9
+ * The images the plugins produce, checked pixel by pixel on small generated pictures.
10
+ * OpenCV is pointed at a port nothing listens on, so a perspective crop takes the
11
+ * no-OpenCV path a user gets when the CDN is unreachable, and nothing is downloaded.
12
+ */
13
+ configureOpenCV("http://127.0.0.1:1/opencv.js");
14
+
15
+ type Rgb = [number, number, number];
16
+ const RED: Rgb = [230, 30, 30];
17
+ const GREEN: Rgb = [30, 170, 60];
18
+ const BLUE: Rgb = [30, 60, 230];
19
+ const YELLOW: Rgb = [240, 220, 40];
20
+
21
+ let urls: string[] = [];
22
+
23
+ afterEach(() => {
24
+ for (let url of urls) URL.revokeObjectURL(url);
25
+ urls = [];
26
+ });
27
+
28
+ function toBlob(canvas: HTMLCanvasElement) {
29
+ return new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), "image/png"));
30
+ }
31
+
32
+ /** A PNG with a different colour in each quadrant: red, green / blue, yellow. */
33
+ async function quadrantImage(width = 80, height = 40) {
34
+ let canvas = document.createElement("canvas");
35
+ canvas.width = width;
36
+ canvas.height = height;
37
+ let ctx = canvas.getContext("2d")!;
38
+ let fill = ([r, g, b]: Rgb, x: number, y: number) => {
39
+ ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
40
+ ctx.fillRect(x, y, width / 2, height / 2);
41
+ };
42
+ fill(RED, 0, 0);
43
+ fill(GREEN, width / 2, 0);
44
+ fill(BLUE, 0, height / 2);
45
+ fill(YELLOW, width / 2, height / 2);
46
+ return objectUrl(await toBlob(canvas));
47
+ }
48
+
49
+ /** A white PNG with fine black stripes, standing in for printed text. */
50
+ async function stripedImage(width = 80, height = 40) {
51
+ let canvas = document.createElement("canvas");
52
+ canvas.width = width;
53
+ canvas.height = height;
54
+ let ctx = canvas.getContext("2d")!;
55
+ ctx.fillStyle = "white";
56
+ ctx.fillRect(0, 0, width, height);
57
+ ctx.fillStyle = "black";
58
+ for (let x = 0; x < width; x += 2) ctx.fillRect(x, 0, 1, height);
59
+ return objectUrl(await toBlob(canvas));
60
+ }
61
+
62
+ function objectUrl(blob: Blob) {
63
+ let url = URL.createObjectURL(blob);
64
+ urls.push(url);
65
+ return url;
66
+ }
67
+
68
+ async function read(blob: Blob) {
69
+ let bitmap = await createImageBitmap(blob);
70
+ let canvas = document.createElement("canvas");
71
+ canvas.width = bitmap.width;
72
+ canvas.height = bitmap.height;
73
+ let ctx = canvas.getContext("2d")!;
74
+ ctx.drawImage(bitmap, 0, 0);
75
+ let data = ctx.getImageData(0, 0, bitmap.width, bitmap.height).data;
76
+ return {
77
+ width: bitmap.width,
78
+ height: bitmap.height,
79
+ pixel(x: number, y: number): Rgb {
80
+ let i = (y * bitmap.width + x) * 4;
81
+ return [data[i], data[i + 1], data[i + 2]];
82
+ },
83
+ };
84
+ }
85
+
86
+ /** Colour match with room for JPEG compression. */
87
+ function expectColour(actual: Rgb, expected: Rgb, tolerance = 30) {
88
+ let off = Math.max(...actual.map((v, i) => Math.abs(v - expected[i])));
89
+ expect(off, `rgb(${actual.join(", ")}) should be close to rgb(${expected.join(", ")})`).toBeLessThanOrEqual(
90
+ tolerance,
91
+ );
92
+ }
93
+
94
+ type Image = Awaited<ReturnType<typeof read>>;
95
+
96
+ /** Samples the centre of each quadrant: top-left, top-right, bottom-right, bottom-left. */
97
+ function quadrants(image: Image): Rgb[] {
98
+ let { width: w, height: h } = image;
99
+ return [
100
+ image.pixel(Math.floor(w / 4), Math.floor(h / 4)),
101
+ image.pixel(Math.floor((3 * w) / 4), Math.floor(h / 4)),
102
+ image.pixel(Math.floor((3 * w) / 4), Math.floor((3 * h) / 4)),
103
+ image.pixel(Math.floor(w / 4), Math.floor((3 * h) / 4)),
104
+ ];
105
+ }
106
+
107
+ describe("rotate", () => {
108
+ it("turns the image a quarter clockwise", async () => {
109
+ let image = await read(await rotateCwPlugin.execute(await quadrantImage(80, 40)));
110
+
111
+ expect([image.width, image.height]).toEqual([40, 80]);
112
+ let [tl, tr, br, bl] = quadrants(image);
113
+ expectColour(tl, BLUE);
114
+ expectColour(tr, RED);
115
+ expectColour(br, GREEN);
116
+ expectColour(bl, YELLOW);
117
+ });
118
+
119
+ it("turns the image a quarter anticlockwise", async () => {
120
+ let image = await read(await rotateCcwPlugin.execute(await quadrantImage(80, 40)));
121
+
122
+ expect([image.width, image.height]).toEqual([40, 80]);
123
+ let [tl, tr, br, bl] = quadrants(image);
124
+ expectColour(tl, GREEN);
125
+ expectColour(tr, YELLOW);
126
+ expectColour(br, BLUE);
127
+ expectColour(bl, RED);
128
+ });
129
+
130
+ it("saves the result as JPEG", async () => {
131
+ let blob = await rotateCwPlugin.execute(await quadrantImage());
132
+
133
+ expect(blob.type).toBe("image/jpeg");
134
+ });
135
+
136
+ it("rejects when the image cannot be loaded", async () => {
137
+ await expect(rotateCwPlugin.execute("blob:http://localhost/missing")).rejects.toThrow("Failed to load image");
138
+ });
139
+ });
140
+
141
+ describe("crop", () => {
142
+ it("cuts out a rectangle at full resolution, losslessly", async () => {
143
+ let source = await quadrantImage(80, 40);
144
+ let corners = [
145
+ { x: 0.5, y: 0 },
146
+ { x: 1, y: 0 },
147
+ { x: 1, y: 0.5 },
148
+ { x: 0.5, y: 0.5 },
149
+ ];
150
+
151
+ let blob = await replayCrop(source, { corners, mode: "rect" });
152
+ let image = await read(blob);
153
+
154
+ expect(blob.type).toBe("image/png");
155
+ expect([image.width, image.height]).toEqual([40, 20]);
156
+ // PNG: every pixel is exactly the green quadrant, edges included.
157
+ for (let [x, y] of [
158
+ [0, 0],
159
+ [39, 0],
160
+ [39, 19],
161
+ [0, 19],
162
+ [20, 10],
163
+ ]) {
164
+ expectColour(image.pixel(x, y), GREEN, 0);
165
+ }
166
+ });
167
+
168
+ it("crops across quadrants at the exact pixel boundary", async () => {
169
+ let source = await quadrantImage(80, 40);
170
+ let corners = [
171
+ { x: 0.25, y: 0.25 },
172
+ { x: 0.75, y: 0.25 },
173
+ { x: 0.75, y: 0.75 },
174
+ { x: 0.25, y: 0.75 },
175
+ ];
176
+
177
+ let image = await read(await replayCrop(source, { corners, mode: "rect" }));
178
+
179
+ expect([image.width, image.height]).toEqual([40, 20]);
180
+ expectColour(image.pixel(19, 9), RED, 0);
181
+ expectColour(image.pixel(20, 9), GREEN, 0);
182
+ expectColour(image.pixel(19, 10), BLUE, 0);
183
+ expectColour(image.pixel(20, 10), YELLOW, 0);
184
+ });
185
+
186
+ it("crops a rectangle saved before crops recorded their mode, without OpenCV", async () => {
187
+ let source = await quadrantImage(80, 40);
188
+ let corners = [
189
+ { x: 0, y: 0.5 },
190
+ { x: 0.5, y: 0.5 },
191
+ { x: 0.5, y: 1 },
192
+ { x: 0, y: 1 },
193
+ ];
194
+
195
+ let image = await read(await replayCrop(source, { corners }));
196
+
197
+ expect([image.width, image.height]).toEqual([40, 20]);
198
+ expectColour(image.pixel(20, 10), BLUE, 0);
199
+ });
200
+
201
+ it("falls back to the selection's bounding box when OpenCV is unavailable for a skewed selection", async () => {
202
+ let source = await quadrantImage(80, 40);
203
+ // A slightly skewed quad around the green quadrant.
204
+ let corners = [
205
+ { x: 0.55, y: 0 },
206
+ { x: 1, y: 0.05 },
207
+ { x: 0.95, y: 0.5 },
208
+ { x: 0.5, y: 0.45 },
209
+ ];
210
+
211
+ let image = await read(await replayCrop(source, { corners, mode: "perspective" }));
212
+
213
+ expect([image.width, image.height]).toEqual([40, 20]);
214
+ expectColour(image.pixel(20, 10), GREEN, 0);
215
+ });
216
+ });
217
+
218
+ describe("redact", () => {
219
+ it("covers the region and leaves the rest of the image alone", async () => {
220
+ let source = await quadrantImage(80, 40);
221
+
222
+ let image = await read(await replayRedactBlur(source, { x: 0, y: 0, w: 40, h: 20 }));
223
+
224
+ expect([image.width, image.height]).toEqual([80, 40]);
225
+ let [tl, tr, br, bl] = quadrants(image);
226
+ // 85 % grey over the pixelated red: nowhere near the original colour.
227
+ expectColour(tl, [146, 113, 113]);
228
+ expect(tl[0] - tl[1]).toBeLessThan(60);
229
+ expectColour(tr, GREEN);
230
+ expectColour(br, YELLOW);
231
+ expectColour(bl, BLUE);
232
+ });
233
+
234
+ it("makes fine detail such as text unreadable", async () => {
235
+ let source = await stripedImage(80, 40);
236
+
237
+ let image = await read(await replayRedactBlur(source, { x: 0, y: 0, w: 40, h: 40 }));
238
+
239
+ // Inside the region the 1px stripes are gone: the luminance is nearly flat.
240
+ let inside: number[] = [];
241
+ for (let y = 4; y < 36; y++) for (let x = 4; x < 36; x++) inside.push(image.pixel(x, y)[0]);
242
+ expect(Math.max(...inside) - Math.min(...inside)).toBeLessThan(25);
243
+
244
+ // Outside it they are still there.
245
+ let outside = [image.pixel(60, 20)[0], image.pixel(61, 20)[0]];
246
+ expect(Math.abs(outside[0] - outside[1])).toBeGreaterThan(100);
247
+ });
248
+
249
+ it("rejects when the image cannot be loaded", async () => {
250
+ await expect(replayRedactBlur("blob:http://localhost/missing", { x: 0, y: 0, w: 1, h: 1 })).rejects.toThrow();
251
+ });
252
+ });
@@ -1,47 +1,47 @@
1
- import { Button, Spinner } from "@digdir/designsystemet-react";
2
- import { CheckmarkIcon, EraserIcon, XMarkIcon } from "@navikt/aksel-icons";
3
- import { useState } from "react";
4
-
5
- import { useRedactContext } from "./RedactContext.js";
6
- import { getLocalizedString } from "../../../../i18n.js";
7
-
8
- /** Toolbar shown while the redact tool is active. Reads state from RedactContext. */
9
- export function RedactToolbar() {
10
- let { rects, clearAll, applyRedact, onApply, onCancel } = useRedactContext();
11
- let [applying, setApplying] = useState(false);
12
-
13
- async function handleApply() {
14
- if (rects.length === 0) {
15
- onCancel();
16
- return;
17
- }
18
- setApplying(true);
19
- try {
20
- let result = await applyRedact();
21
- if (result) onApply(result.blob, result.actions);
22
- } finally {
23
- setApplying(false);
24
- }
25
- }
26
-
27
- return (
28
- <>
29
- <div className="image-editor__toolbar-group">
30
- <Button variant="tertiary" data-size="sm" onClick={onCancel} disabled={applying}>
31
- <XMarkIcon aria-hidden />
32
- {getLocalizedString("Cancel")}
33
- </Button>
34
- <Button variant="tertiary" data-size="sm" onClick={clearAll} disabled={applying || rects.length === 0}>
35
- <EraserIcon aria-hidden />
36
- {getLocalizedString("Clear all")}
37
- </Button>
38
- </div>
39
- <div className="image-editor__toolbar-group">
40
- <Button variant="primary" data-size="sm" onClick={handleApply} disabled={applying}>
41
- {applying ? <Spinner aria-hidden data-size="xs" /> : <CheckmarkIcon aria-hidden />}
42
- {rects.length === 0 ? getLocalizedString("Done") : getLocalizedString("Apply redact")}
43
- </Button>
44
- </div>
45
- </>
46
- );
47
- }
1
+ import { Button, Spinner } from "@digdir/designsystemet-react";
2
+ import { CheckmarkIcon, EraserIcon, XMarkIcon } from "@navikt/aksel-icons";
3
+ import { useState } from "react";
4
+
5
+ import { useRedactContext } from "./RedactContext.js";
6
+ import { getLocalizedString } from "../../../../i18n.js";
7
+
8
+ /** Toolbar shown while the redact tool is active. Reads state from RedactContext. */
9
+ export function RedactToolbar() {
10
+ let { rects, clearAll, applyRedact, onApply, onCancel } = useRedactContext();
11
+ let [applying, setApplying] = useState(false);
12
+
13
+ async function handleApply() {
14
+ if (rects.length === 0) {
15
+ onCancel();
16
+ return;
17
+ }
18
+ setApplying(true);
19
+ try {
20
+ let result = await applyRedact();
21
+ if (result) onApply(result.blob, result.actions);
22
+ } finally {
23
+ setApplying(false);
24
+ }
25
+ }
26
+
27
+ return (
28
+ <>
29
+ <div className="image-editor__toolbar-group">
30
+ <Button variant="tertiary" onClick={onCancel} disabled={applying}>
31
+ <XMarkIcon aria-hidden />
32
+ {getLocalizedString("Cancel")}
33
+ </Button>
34
+ <Button variant="tertiary" onClick={clearAll} disabled={applying || rects.length === 0}>
35
+ <EraserIcon aria-hidden />
36
+ {getLocalizedString("Clear all")}
37
+ </Button>
38
+ </div>
39
+ <div className="image-editor__toolbar-group">
40
+ <Button variant="primary" onClick={handleApply} disabled={applying}>
41
+ {applying ? <Spinner aria-hidden data-size="xs" /> : <CheckmarkIcon aria-hidden />}
42
+ {rects.length === 0 ? getLocalizedString("Done") : getLocalizedString("Apply redact")}
43
+ </Button>
44
+ </div>
45
+ </>
46
+ );
47
+ }
@@ -0,0 +1,89 @@
1
+ import { act, renderHook } from "@testing-library/react";
2
+ import { StrictMode } from "react";
3
+ import { describe, expect, it } from "vitest";
4
+
5
+ import { normRect, useRedactTool } from "./useRedactTool";
6
+
7
+ function setup(options?: { strict?: boolean }) {
8
+ return renderHook(() => useRedactTool("blob:image"), { wrapper: options?.strict ? StrictMode : undefined }).result;
9
+ }
10
+
11
+ type Tool = ReturnType<typeof setup>;
12
+
13
+ function draw(result: Tool, from: [number, number], to: [number, number]) {
14
+ act(() => result.current.startDrawing(...from));
15
+ act(() => result.current.updateDrawing(...to));
16
+ act(() => result.current.finishDrawing());
17
+ }
18
+
19
+ describe("normRect", () => {
20
+ it("turns a drag in any direction into a rect with positive size", () => {
21
+ expect(normRect({ startX: 50, startY: 40, currentX: 10, currentY: 60 })).toEqual({ x: 10, y: 40, w: 40, h: 20 });
22
+ expect(normRect({ startX: 10, startY: 60, currentX: 50, currentY: 40 })).toEqual({ x: 10, y: 40, w: 40, h: 20 });
23
+ });
24
+ });
25
+
26
+ describe("useRedactTool", () => {
27
+ it("shows the rectangle being drawn and keeps it when the pointer is released", () => {
28
+ let result = setup();
29
+
30
+ act(() => result.current.startDrawing(20, 30));
31
+ act(() => result.current.updateDrawing(80, 10));
32
+ expect(result.current.drawing).toEqual({ startX: 20, startY: 30, currentX: 80, currentY: 10 });
33
+
34
+ act(() => result.current.finishDrawing());
35
+ expect(result.current.drawing).toBeNull();
36
+ expect(result.current.rects).toEqual([{ x: 20, y: 10, w: 60, h: 20 }]);
37
+ });
38
+
39
+ it("ignores taps and tiny drags", () => {
40
+ let result = setup();
41
+
42
+ draw(result, [10, 10], [10, 10]);
43
+ draw(result, [10, 10], [14, 40]);
44
+ draw(result, [10, 10], [40, 14]);
45
+
46
+ expect(result.current.rects).toEqual([]);
47
+ });
48
+
49
+ it("collects several rectangles, and can delete one or clear them all", () => {
50
+ let result = setup();
51
+
52
+ draw(result, [0, 0], [10, 10]);
53
+ draw(result, [20, 20], [40, 40]);
54
+ draw(result, [50, 50], [70, 70]);
55
+ act(() => result.current.deleteRect(1));
56
+ expect(result.current.rects).toEqual([
57
+ { x: 0, y: 0, w: 10, h: 10 },
58
+ { x: 50, y: 50, w: 20, h: 20 },
59
+ ]);
60
+
61
+ act(() => result.current.clearAll());
62
+ expect(result.current.rects).toEqual([]);
63
+ });
64
+
65
+ it("does not move a rectangle when the pointer moves without a drag in progress", () => {
66
+ let result = setup();
67
+
68
+ act(() => result.current.updateDrawing(30, 30));
69
+ act(() => result.current.finishDrawing());
70
+
71
+ expect(result.current.drawing).toBeNull();
72
+ expect(result.current.rects).toEqual([]);
73
+ });
74
+
75
+ it("adds one rectangle per drag in React strict mode", () => {
76
+ // Apps render in <StrictMode> during development, which calls state updaters twice.
77
+ let result = setup({ strict: true });
78
+
79
+ draw(result, [0, 0], [30, 30]);
80
+
81
+ expect(result.current.rects).toEqual([{ x: 0, y: 0, w: 30, h: 30 }]);
82
+ });
83
+
84
+ it("has nothing to apply before a rectangle is drawn", async () => {
85
+ let result = setup();
86
+
87
+ await expect(result.current.applyRedact()).resolves.toBeNull();
88
+ });
89
+ });
@@ -41,6 +41,9 @@ export function useRedactTool(imageUrl: string): RedactToolState {
41
41
  let [displaySize, setDisplaySize] = useState({ width: 0, height: 0 });
42
42
  let imageUrlRef = useRef(imageUrl);
43
43
  imageUrlRef.current = imageUrl;
44
+ // Mirrors `drawing` so finishing a drag never reads a stale render closure, and so the
45
+ // new rect is added outside a state updater (React may call updaters more than once).
46
+ let drawingRef = useRef<Drawing | null>(null);
44
47
 
45
48
  let handleImageLoad = useCallback((e: React.SyntheticEvent<HTMLImageElement>) => {
46
49
  let img = e.currentTarget;
@@ -48,25 +51,25 @@ export function useRedactTool(imageUrl: string): RedactToolState {
48
51
  }, []);
49
52
 
50
53
  function startDrawing(x: number, y: number) {
51
- setDrawing({ startX: x, startY: y, currentX: x, currentY: y });
54
+ drawingRef.current = { startX: x, startY: y, currentX: x, currentY: y };
55
+ setDrawing(drawingRef.current);
52
56
  }
53
57
 
54
58
  function updateDrawing(x: number, y: number) {
55
- setDrawing((d) => (d ? { ...d, currentX: x, currentY: y } : null));
59
+ if (!drawingRef.current) return;
60
+ drawingRef.current = { ...drawingRef.current, currentX: x, currentY: y };
61
+ setDrawing(drawingRef.current);
56
62
  }
57
63
 
58
64
  function finishDrawing() {
59
- setDrawing((d) => {
60
- if (!d) return null;
61
- let x = Math.min(d.startX, d.currentX);
62
- let y = Math.min(d.startY, d.currentY);
63
- let w = Math.abs(d.currentX - d.startX);
64
- let h = Math.abs(d.currentY - d.startY);
65
- if (w > 4 && h > 4) {
66
- setRects((prev) => [...prev, { x, y, w, h }]);
67
- }
68
- return null;
69
- });
65
+ let d = drawingRef.current;
66
+ drawingRef.current = null;
67
+ setDrawing(null);
68
+ if (!d) return;
69
+ let rect = normRect(d);
70
+ if (rect.w > 4 && rect.h > 4) {
71
+ setRects((prev) => [...prev, rect]);
72
+ }
70
73
  }
71
74
 
72
75
  function deleteRect(index: number) {
@@ -1,23 +1,23 @@
1
- import { createContext, type ReactNode, use } from "react";
2
- import { useZoomPan, type ZoomPanResult } from "./useZoomPan.js";
3
-
4
- let ZoomContext = createContext<ZoomPanResult | null>(null);
5
-
6
- export function useZoom(): ZoomPanResult {
7
- let ctx = use(ZoomContext);
8
- if (!ctx) throw new Error("useZoom must be used within ZoomProvider");
9
- return ctx;
10
- }
11
-
12
- /**
13
- * Current zoom factor, or 1 when no ZoomProvider is present.
14
- * Lets tools convert screen-space coordinates to CSS pixels without requiring the zoom plugin.
15
- */
16
- export function useZoomLevel(): number {
17
- return use(ZoomContext)?.zoom ?? 1;
18
- }
19
-
20
- export function ZoomProvider({ children }: { children: ReactNode }) {
21
- let state = useZoomPan();
22
- return <ZoomContext value={state}>{children}</ZoomContext>;
23
- }
1
+ import { createContext, type ReactNode, use } from "react";
2
+ import { useZoomPan, type ZoomPanResult } from "./useZoomPan.js";
3
+
4
+ let ZoomContext = createContext<ZoomPanResult | null>(null);
5
+
6
+ export function useZoom(): ZoomPanResult {
7
+ let ctx = use(ZoomContext);
8
+ if (!ctx) throw new Error("useZoom must be used within ZoomProvider");
9
+ return ctx;
10
+ }
11
+
12
+ /**
13
+ * Current zoom factor, or 1 when no ZoomProvider is present.
14
+ * Lets tools convert screen-space coordinates to CSS pixels without requiring the zoom plugin.
15
+ */
16
+ export function useZoomLevel(): number {
17
+ return use(ZoomContext)?.zoom ?? 1;
18
+ }
19
+
20
+ export function ZoomProvider({ children }: { children: ReactNode }) {
21
+ let state = useZoomPan();
22
+ return <ZoomContext value={state}>{children}</ZoomContext>;
23
+ }
@@ -1,40 +1,40 @@
1
- import { ShrinkIcon, ZoomMinusIcon, ZoomPlusIcon } from "@navikt/aksel-icons";
2
- import { ResponsiveButton } from "../../ResponsiveButton.js";
3
- import { useZoom } from "./ZoomContext.js";
4
- import { getLocalizedString } from "../../../../i18n.js";
5
-
6
- interface Props {
7
- disabled?: boolean;
8
- isSmall?: boolean;
9
- }
10
-
11
- export function ZoomControls({ disabled, isSmall = false }: Props) {
12
- let { zoom, zoomIn, zoomOut, resetZoom, canZoomIn, canZoomOut, isZoomed } = useZoom();
13
-
14
- return (
15
- <>
16
- <ResponsiveButton
17
- icon={<ZoomMinusIcon aria-hidden />}
18
- label={getLocalizedString("Zoom out")}
19
- onClick={zoomOut}
20
- disabled={disabled || !canZoomOut}
21
- isSmall={isSmall}
22
- />
23
- <span className="image-editor__zoom-level">{Math.round(zoom * 100)}%</span>
24
- <ResponsiveButton
25
- icon={<ZoomPlusIcon aria-hidden />}
26
- label={getLocalizedString("Zoom in")}
27
- onClick={zoomIn}
28
- disabled={disabled || !canZoomIn}
29
- isSmall={isSmall}
30
- />
31
- <ResponsiveButton
32
- disabled={!isZoomed}
33
- icon={<ShrinkIcon aria-hidden />}
34
- label={getLocalizedString("Reset zoom")}
35
- onClick={resetZoom}
36
- isSmall={isSmall}
37
- />
38
- </>
39
- );
40
- }
1
+ import { ShrinkIcon, ZoomMinusIcon, ZoomPlusIcon } from "@navikt/aksel-icons";
2
+ import { ResponsiveButton } from "../../ResponsiveButton.js";
3
+ import { useZoom } from "./ZoomContext.js";
4
+ import { getLocalizedString } from "../../../../i18n.js";
5
+
6
+ interface Props {
7
+ disabled?: boolean;
8
+ isSmall?: boolean;
9
+ }
10
+
11
+ export function ZoomControls({ disabled, isSmall = false }: Props) {
12
+ let { zoom, zoomIn, zoomOut, resetZoom, canZoomIn, canZoomOut, isZoomed } = useZoom();
13
+
14
+ return (
15
+ <>
16
+ <ResponsiveButton
17
+ icon={<ZoomMinusIcon aria-hidden />}
18
+ label={getLocalizedString("Zoom out")}
19
+ onClick={zoomOut}
20
+ disabled={disabled || !canZoomOut}
21
+ isSmall={isSmall}
22
+ />
23
+ <span className="image-editor__zoom-level">{Math.round(zoom * 100)}%</span>
24
+ <ResponsiveButton
25
+ icon={<ZoomPlusIcon aria-hidden />}
26
+ label={getLocalizedString("Zoom in")}
27
+ onClick={zoomIn}
28
+ disabled={disabled || !canZoomIn}
29
+ isSmall={isSmall}
30
+ />
31
+ <ResponsiveButton
32
+ disabled={!isZoomed}
33
+ icon={<ShrinkIcon aria-hidden />}
34
+ label={getLocalizedString("Reset zoom")}
35
+ onClick={resetZoom}
36
+ isSmall={isSmall}
37
+ />
38
+ </>
39
+ );
40
+ }