@olenbetong/synergi-react 5.2.0 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/styles/styles.css +1 -1
  2. package/dist/styles/styles.css.map +1 -1
  3. package/es/components/DateNavigator/index.css +11 -9
  4. package/es/components/ImageEditor/ImageEditor.d.ts +18 -1
  5. package/es/components/ImageEditor/ImageEditor.js +26 -9
  6. package/es/components/ImageEditor/encodeImage.d.ts +33 -0
  7. package/es/components/ImageEditor/encodeImage.js +60 -0
  8. package/es/components/ImageEditor/index.d.ts +2 -0
  9. package/es/components/ImageEditor/index.js +1 -0
  10. package/es/components/ImageEditor/plugins/cropPlugin/useCropTool.js +3 -9
  11. package/es/components/ImageEditor/plugins/redactPlugin/useRedactTool.js +3 -4
  12. package/es/components/ImageEditor/plugins/rotatePlugin.js +2 -1
  13. package/es/improve/ReportIssueAttachments.d.ts +6 -0
  14. package/es/improve/ReportIssueAttachments.js +45 -0
  15. package/es/improve/ReportIssueForm.css +133 -0
  16. package/es/improve/ReportIssueForm.d.ts +18 -0
  17. package/es/improve/ReportIssueForm.js +71 -0
  18. package/es/improve/data/dsReportIssueAreas.d.ts +8 -0
  19. package/es/improve/data/dsReportIssueAreas.js +37 -0
  20. package/es/improve/data/dsReportIssueFiles.d.ts +15 -0
  21. package/es/improve/data/dsReportIssueFiles.js +55 -0
  22. package/es/improve/data/index.d.ts +3 -0
  23. package/es/improve/data/index.js +3 -0
  24. package/es/improve/data/procReportIssue.d.ts +16 -0
  25. package/es/improve/data/procReportIssue.js +44 -0
  26. package/es/improve/index.d.ts +3 -0
  27. package/es/improve/index.js +3 -0
  28. package/es/index.css +1 -1
  29. package/package.json +6 -2
  30. package/src/components/DateNavigator/index.css +11 -9
  31. package/src/components/ImageEditor/ImageEditor.browser.test.tsx +30 -5
  32. package/src/components/ImageEditor/ImageEditor.test.tsx +4 -3
  33. package/src/components/ImageEditor/ImageEditor.tsx +43 -10
  34. package/src/components/ImageEditor/encodeImage.browser.test.ts +88 -0
  35. package/src/components/ImageEditor/encodeImage.ts +80 -0
  36. package/src/components/ImageEditor/index.ts +2 -0
  37. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +3 -10
  38. package/src/components/ImageEditor/plugins/plugins.browser.test.ts +20 -2
  39. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.ts +3 -4
  40. package/src/components/ImageEditor/plugins/rotatePlugin.ts +2 -1
  41. package/src/improve/ReportIssueAttachments.tsx +138 -0
  42. package/src/improve/ReportIssueForm.css +133 -0
  43. package/src/improve/ReportIssueForm.tsx +218 -0
  44. package/src/improve/data/dsReportIssueAreas.ts +45 -0
  45. package/src/improve/data/dsReportIssueFiles.ts +66 -0
  46. package/src/improve/data/index.ts +3 -0
  47. package/src/improve/data/procReportIssue.ts +58 -0
  48. package/src/improve/index.ts +3 -0
@@ -3,6 +3,7 @@ import { createRef } from "react";
3
3
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
4
 
5
5
  import { defaultPlugins, defaultViewPlugin } from "./defaultPlugins";
6
+ import type { ImageOutputOptions } from "./encodeImage";
6
7
  import { ImageEditor, type ImageEditorRef } from "./ImageEditor";
7
8
  import { configureOpenCV } from "./useOpenCV";
8
9
 
@@ -89,7 +90,9 @@ function expectColour(actual: Rgb, expected: Rgb, tolerance = 30) {
89
90
  }
90
91
 
91
92
  /** 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
+ function renderEditor(
94
+ props: { initialTool?: string; ref?: React.Ref<ImageEditorRef>; output?: ImageOutputOptions } = {},
95
+ ) {
93
96
  let onConfirm = vi.fn<(blob: Blob) => void>();
94
97
  render(
95
98
  <div style={{ position: "relative", width: 400, height: 600 }}>
@@ -99,6 +102,7 @@ function renderEditor(props: { initialTool?: string; ref?: React.Ref<ImageEditor
99
102
  plugins={defaultPlugins}
100
103
  viewPlugin={defaultViewPlugin}
101
104
  initialTool={props.initialTool}
105
+ output={props.output}
102
106
  onConfirm={onConfirm}
103
107
  />
104
108
  </div>,
@@ -187,11 +191,16 @@ describe("ImageEditor output", () => {
187
191
  let ref = createRef<ImageEditorRef>();
188
192
  renderEditor({ ref });
189
193
 
194
+ expect(await ref.current!.getResultBlob()).toBeNull();
195
+
190
196
  // What the scans app does: fire rotations, then await whenIdle() before saving.
191
197
  void ref.current!.executeAction("rotate-ccw");
192
198
  void ref.current!.executeAction("rotate-ccw");
193
199
  await act(() => ref.current!.whenIdle());
194
- let image = await read(ref.current!.getCurrentBlob()!);
200
+ let blob = (await ref.current!.getResultBlob())!;
201
+ let image = await read(blob);
202
+
203
+ expect(blob.type).toBe("image/jpeg");
195
204
 
196
205
  // Two quarter turns: upside down, same size.
197
206
  expect([image.width, image.height]).toEqual([WIDTH, HEIGHT]);
@@ -218,8 +227,8 @@ describe("ImageEditor output", () => {
218
227
  let blob = await done(onConfirm);
219
228
  let image = await read(blob);
220
229
 
221
- // Lossless, so receipt text stays sharp; within a pixel of the quadrant's size.
222
- expect(blob.type).toBe("image/png");
230
+ // Encoded once, as the default output type; within a pixel of the quadrant's size.
231
+ expect(blob.type).toBe("image/jpeg");
223
232
  expect(Math.abs(image.width - WIDTH / 2)).toBeLessThanOrEqual(2);
224
233
  expect(Math.abs(image.height - HEIGHT / 2)).toBeLessThanOrEqual(2);
225
234
  for (let [x, y] of [
@@ -228,10 +237,26 @@ describe("ImageEditor output", () => {
228
237
  [image.width - 3, image.height - 3],
229
238
  [3, image.height - 3],
230
239
  ]) {
231
- expectColour(image.pixel(x, y), GREEN, 0);
240
+ expectColour(image.pixel(x, y), GREEN);
232
241
  }
233
242
  });
234
243
 
244
+ it("hands out the requested output type without a lossy step", async () => {
245
+ let onConfirm = renderEditor({ initialTool: "crop", output: { type: "image/png" } });
246
+ click("Draw rectangle");
247
+ drag(await screen.findByRole("application", { name: "Drag to draw a rectangle to crop to" }), [0.5, 0.5], [1, 0]);
248
+ await waitFor(() => expect(screen.getByRole("button", { name: "Apply crop" })).toBeEnabled());
249
+ click("Apply crop");
250
+ await screen.findByRole("img", { name: "Image to edit" });
251
+
252
+ let blob = await done(onConfirm);
253
+ let image = await read(blob);
254
+
255
+ expect(blob.type).toBe("image/png");
256
+ expectColour(image.pixel(3, 3), GREEN, 0);
257
+ expectColour(image.pixel(image.width - 3, image.height - 3), GREEN, 0);
258
+ });
259
+
235
260
  it("returns to the full image when a crop is undone", async () => {
236
261
  let onConfirm = renderEditor({ initialTool: "crop" });
237
262
  click("Draw rectangle");
@@ -41,7 +41,7 @@ function actionPlugin(id: string, label: string, execute?: ActionPlugin["execute
41
41
  id,
42
42
  label,
43
43
  Icon,
44
- execute: vi.fn(execute ?? (async (url: string) => new Blob([`${id}(${url})`]))),
44
+ execute: vi.fn(execute ?? (async (url: string) => new Blob([`${id}(${url})`], { type: "image/png" }))),
45
45
  };
46
46
  return plugin;
47
47
  }
@@ -184,13 +184,14 @@ describe("ImageEditor", () => {
184
184
  it("hands the app the edited image", async () => {
185
185
  let onConfirm = vi.fn();
186
186
  let rotate = actionPlugin("rotate-cw", "Rotate right");
187
- render(<ImageEditor imageUrl={SOURCE} plugins={[rotate]} onConfirm={onConfirm} />);
187
+ // The fakes are not real images, so ask for the intermediate type: nothing to re-encode.
188
+ render(<ImageEditor imageUrl={SOURCE} plugins={[rotate]} onConfirm={onConfirm} output={{ type: "image/png" }} />);
188
189
  fireEvent.click(button("Rotate right"));
189
190
  await waitFor(() => expect(button("Undo")).toBeEnabled());
190
191
 
191
192
  fireEvent.click(button("Done"));
192
193
 
193
- expect(onConfirm).toHaveBeenCalledOnce();
194
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce());
194
195
  expect(await (onConfirm.mock.calls[0][0] as Blob).text()).toBe(`rotate-cw(${SOURCE})`);
195
196
  });
196
197
 
@@ -2,6 +2,7 @@ import { Button, Spinner, Tooltip } from "@digdir/designsystemet-react";
2
2
  import { ArrowCirclepathIcon, ArrowLeftIcon, ArrowRedoIcon, ArrowUndoIcon, CheckmarkIcon } from "@navikt/aksel-icons";
3
3
  import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from "react";
4
4
 
5
+ import { encodeImage, type ImageOutputOptions } from "./encodeImage.js";
5
6
  import "./ImageEditor.css";
6
7
  import { ResponsiveButton } from "./ResponsiveButton.js";
7
8
  import type { ActionPlugin, ActionRegistry, EditAction, Plugin, ToolPlugin, ViewPlugin } from "./types.js";
@@ -11,8 +12,17 @@ import { useIsSmall } from "./useIsSmall.js";
11
12
  import { getLocalizedString } from "../../i18n.js";
12
13
 
13
14
  export type ImageEditorRef = {
14
- /** Returns the current edited blob, or null if no edits have been applied since the last source image. */
15
+ /**
16
+ * Returns the current edited blob, or null if no edits have been applied since the last source image.
17
+ * This is the editor's lossless intermediate (PNG): to save the result, use `getResultBlob()`.
18
+ */
15
19
  getCurrentBlob: () => Blob | null;
20
+ /**
21
+ * The edited image encoded once - what the Done button hands to `onConfirm` - or null if nothing has been
22
+ * edited. `options` override the output props for this call. Await `whenIdle()` first when an action may
23
+ * still be running.
24
+ */
25
+ getResultBlob: (options?: ImageOutputOptions) => Promise<Blob | null>;
16
26
  /**
17
27
  * Runs a registered action plugin (e.g. `"rotate-cw"`) against the current image.
18
28
  * Use this instead of calling `plugin.execute()` directly so external toolbars and
@@ -41,6 +51,13 @@ interface Props {
41
51
  * plain image. Cancelling the tool returns to the plain image as usual.
42
52
  */
43
53
  initialTool?: string;
54
+ /**
55
+ * How the image is handed out (default JPEG at 0.92, any size). Edits are kept lossless in between and
56
+ * encoded once, here, so repeated rotations or crops do not lose quality step by step. When set, it applies
57
+ * to an unedited image too, which is then re-encoded only when it is too large or of another type; without
58
+ * it an unedited image is handed back exactly as it came.
59
+ */
60
+ output?: ImageOutputOptions;
44
61
  }
45
62
 
46
63
  /**
@@ -50,7 +67,7 @@ interface Props {
50
67
  * Supports undo/redo: each applied transformation is recorded with its EditAction list.
51
68
  */
52
69
  export const ImageEditor = forwardRef<ImageEditorRef, Props>(function ImageEditor(
53
- { imageUrl, onConfirm, onCancel, plugins, viewPlugin, initialTool }: Props,
70
+ { imageUrl, onConfirm, onCancel, plugins, viewPlugin, initialTool, output }: Props,
54
71
  ref,
55
72
  ) {
56
73
  let registry = useMemo(() => buildActionRegistry(plugins), [plugins]);
@@ -70,6 +87,7 @@ export const ImageEditor = forwardRef<ImageEditorRef, Props>(function ImageEdito
70
87
 
71
88
  useImperativeHandle(ref, () => ({
72
89
  getCurrentBlob: () => historyRef.current.getCurrentBlob(),
90
+ getResultBlob: (options?: ImageOutputOptions) => getResultBlob(options),
73
91
  whenIdle: () => actionQueueRef.current,
74
92
  executeAction: (pluginId: string) => {
75
93
  let plugin = plugins.find((p): p is ActionPlugin => p.type === "action" && p.id === pluginId);
@@ -103,15 +121,30 @@ export const ImageEditor = forwardRef<ImageEditorRef, Props>(function ImageEdito
103
121
  deactivateTool();
104
122
  }
105
123
 
106
- function confirm() {
124
+ function outputOptions(options?: ImageOutputOptions): ImageOutputOptions {
125
+ return { ...output, ...options };
126
+ }
127
+
128
+ async function getResultBlob(options?: ImageOutputOptions): Promise<Blob | null> {
129
+ let blob = historyRef.current.getCurrentBlob();
130
+ return blob ? encodeImage(blob, outputOptions(options)) : null;
131
+ }
132
+
133
+ async function confirm() {
107
134
  if (!onConfirm) return;
108
- if (history.currentBlob) {
109
- onConfirm(history.currentBlob);
110
- return;
135
+ setBusy(true);
136
+ try {
137
+ let blob = await getResultBlob();
138
+ if (!blob) {
139
+ // Nothing edited: the original as it came, unless the app set an output it must meet.
140
+ let response = await fetch(historyRef.current.getCurrentImageUrl());
141
+ blob = await response.blob();
142
+ if (output) blob = await encodeImage(blob, output);
143
+ }
144
+ onConfirm(blob);
145
+ } finally {
146
+ setBusy(false);
111
147
  }
112
- fetch(history.currentImageUrl)
113
- .then((r) => r.blob())
114
- .then(onConfirm);
115
148
  }
116
149
 
117
150
  let CanvasWrapper = viewPlugin?.CanvasWrapper;
@@ -190,7 +223,7 @@ export const ImageEditor = forwardRef<ImageEditorRef, Props>(function ImageEdito
190
223
  variant="primary"
191
224
  icon={isSmall}
192
225
  aria-label={isSmall ? getLocalizedString("Done") : undefined}
193
- onClick={confirm}
226
+ onClick={() => void confirm()}
194
227
  disabled={disabled}
195
228
  >
196
229
  <CheckmarkIcon aria-hidden />
@@ -0,0 +1,88 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { encodeImage, scaledSize } from "./encodeImage";
4
+
5
+ /** A noisy image, so its encoded size depends on the quality and resolution the way a photo's does. */
6
+ async function photo(width: number, height: number, type = "image/png", quality?: number) {
7
+ let canvas = document.createElement("canvas");
8
+ canvas.width = width;
9
+ canvas.height = height;
10
+ let ctx = canvas.getContext("2d")!;
11
+ let pixels = ctx.createImageData(width, height);
12
+ for (let i = 0; i < pixels.data.length; i += 4) {
13
+ let shade = 128 + ((i * 7919) % 97) - 48;
14
+ pixels.data[i] = shade;
15
+ pixels.data[i + 1] = shade;
16
+ pixels.data[i + 2] = shade;
17
+ pixels.data[i + 3] = 255;
18
+ }
19
+ ctx.putImageData(pixels, 0, 0);
20
+ return new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), type, quality));
21
+ }
22
+
23
+ async function size(blob: Blob) {
24
+ let bitmap = await createImageBitmap(blob);
25
+ let result = { width: bitmap.width, height: bitmap.height };
26
+ bitmap.close();
27
+ return result;
28
+ }
29
+
30
+ describe("scaledSize", () => {
31
+ it("leaves an image within the limit, or without one, as it is", () => {
32
+ expect(scaledSize(1600, 1200, 4_000_000)).toEqual({ width: 1600, height: 1200 });
33
+ expect(scaledSize(8000, 6000)).toEqual({ width: 8000, height: 6000 });
34
+ });
35
+
36
+ it("scales by pixel count, so a long, narrow receipt stays narrow", () => {
37
+ let { width, height } = scaledSize(1000, 8000, 4_000_000);
38
+ expect(width * height).toBeLessThanOrEqual(4_000_000);
39
+ expect(height / width).toBeCloseTo(8, 1);
40
+ });
41
+ });
42
+
43
+ describe("encodeImage", () => {
44
+ it("scales an image down to the pixel limit and encodes it as asked", async () => {
45
+ let result = await encodeImage(await photo(400, 300), { type: "image/jpeg", maxPixels: 30_000 });
46
+
47
+ expect(result.type).toBe("image/jpeg");
48
+ let { width, height } = await size(result);
49
+ expect(width * height).toBeLessThanOrEqual(30_000);
50
+ expect(width / height).toBeCloseTo(4 / 3, 1);
51
+ });
52
+
53
+ it("hands back an image of the right type and size untouched", async () => {
54
+ let source = await photo(200, 100, "image/jpeg", 0.8);
55
+
56
+ expect(await encodeImage(source, { type: "image/jpeg", maxPixels: 30_000 })).toBe(source);
57
+ });
58
+
59
+ it("re-encodes an image of the right type that is larger than maxBytes", async () => {
60
+ let source = await photo(200, 100, "image/jpeg", 1);
61
+
62
+ let result = await encodeImage(source, { type: "image/jpeg", quality: 0.5, maxBytes: 1000 });
63
+
64
+ expect(result).not.toBe(source);
65
+ expect(result.size).toBeLessThan(source.size);
66
+ });
67
+
68
+ it("puts transparent areas on white when encoding JPEG", async () => {
69
+ let canvas = document.createElement("canvas");
70
+ canvas.width = 10;
71
+ canvas.height = 10;
72
+ let png = await new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), "image/png"));
73
+
74
+ let result = await encodeImage(png, { type: "image/jpeg" });
75
+
76
+ let bitmap = await createImageBitmap(result);
77
+ let ctx = document.createElement("canvas").getContext("2d")!;
78
+ ctx.drawImage(bitmap, 0, 0);
79
+ let [r, g, b] = ctx.getImageData(5, 5, 1, 1).data;
80
+ expect(Math.min(r, g, b)).toBeGreaterThan(245);
81
+ });
82
+
83
+ it("hands back a file it cannot decode untouched", async () => {
84
+ let notAnImage = new Blob(["not an image"], { type: "image/heic" });
85
+
86
+ expect(await encodeImage(notAnImage, { type: "image/jpeg", maxPixels: 100 })).toBe(notAnImage);
87
+ });
88
+ });
@@ -0,0 +1,80 @@
1
+ /** Edits are kept lossless between steps; this is the type every tool and replay handler produces. */
2
+ export const INTERMEDIATE_TYPE = "image/png";
3
+
4
+ /** Encodes a canvas without loss, for the editor's intermediate images. */
5
+ export function canvasToIntermediateBlob(canvas: HTMLCanvasElement): Promise<Blob> {
6
+ return new Promise<Blob>((resolve, reject) => {
7
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), INTERMEDIATE_TYPE);
8
+ });
9
+ }
10
+
11
+ export type ImageOutputOptions = {
12
+ /** The type to hand the image out in (default `"image/jpeg"`). */
13
+ type?: string;
14
+ /** Quality for a lossy type, 0-1 (default 0.92). */
15
+ quality?: number;
16
+ /**
17
+ * Scales the image down to at most this many pixels, keeping its aspect ratio. A pixel count rather
18
+ * than a long edge, so a long, narrow receipt keeps the same text resolution as a square photo.
19
+ */
20
+ maxPixels?: number;
21
+ /**
22
+ * An image already of `type` and within `maxPixels` is still re-encoded when its file is larger than
23
+ * this (a phone JPEG saved at quality 95+, say). The original is kept if that comes out no smaller.
24
+ */
25
+ maxBytes?: number;
26
+ };
27
+
28
+ /** The size to draw an image at so it holds at most `maxPixels`, keeping its aspect ratio. */
29
+ export function scaledSize(width: number, height: number, maxPixels?: number): { width: number; height: number } {
30
+ let pixels = width * height;
31
+ if (!maxPixels || pixels <= maxPixels) return { width, height };
32
+ let scale = Math.sqrt(maxPixels / pixels);
33
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
34
+ }
35
+
36
+ /**
37
+ * Encodes an image once, as the caller asked. Lossy formats are applied here and nowhere else, so a
38
+ * chain of edits (or an undo/redo replay) never stacks one JPEG generation on another.
39
+ *
40
+ * An image already of the requested type, within `maxPixels` and within `maxBytes` is returned untouched,
41
+ * as is one the browser cannot decode (HEIC outside Safari, for instance), so the caller never loses the file.
42
+ */
43
+ export async function encodeImage(blob: Blob, options: ImageOutputOptions = {}): Promise<Blob> {
44
+ let { type = "image/jpeg", quality = 0.92, maxPixels, maxBytes } = options;
45
+
46
+ let bitmap: ImageBitmap;
47
+ try {
48
+ // Applies the EXIF orientation, which the encoded image then no longer needs.
49
+ bitmap = await createImageBitmap(blob, { imageOrientation: "from-image" });
50
+ } catch {
51
+ return blob;
52
+ }
53
+
54
+ try {
55
+ let size = scaledSize(bitmap.width, bitmap.height, maxPixels);
56
+ let resized = size.width !== bitmap.width || size.height !== bitmap.height;
57
+ let sameType = blob.type === type;
58
+ if (!resized && sameType && (maxBytes === undefined || blob.size <= maxBytes)) return blob;
59
+
60
+ let canvas = document.createElement("canvas");
61
+ canvas.width = size.width;
62
+ canvas.height = size.height;
63
+ let ctx = canvas.getContext("2d")!;
64
+ if (type === "image/jpeg") {
65
+ // JPEG has no transparency: put transparent areas on white instead of black.
66
+ ctx.fillStyle = "#fff";
67
+ ctx.fillRect(0, 0, size.width, size.height);
68
+ }
69
+ ctx.imageSmoothingQuality = "high";
70
+ ctx.drawImage(bitmap, 0, 0, size.width, size.height);
71
+
72
+ let encoded = await new Promise<Blob>((resolve, reject) => {
73
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), type, quality);
74
+ });
75
+ // Re-encoded only for its size: no point handing out a file that did not shrink.
76
+ return !resized && sameType && encoded.size >= blob.size ? blob : encoded;
77
+ } finally {
78
+ bitmap.close();
79
+ }
80
+ }
@@ -1,6 +1,8 @@
1
1
  export { defaultPlugins, defaultViewPlugin } from "./defaultPlugins.js";
2
2
  export type { ImageEditorRef } from "./ImageEditor.js";
3
3
  export { ImageEditor } from "./ImageEditor.js";
4
+ export type { ImageOutputOptions } from "./encodeImage.js";
5
+ export { encodeImage, scaledSize } from "./encodeImage.js";
4
6
  export { cropPlugin } from "./plugins/cropPlugin/index.js";
5
7
  export { redactPlugin } from "./plugins/redactPlugin/index.js";
6
8
  export { zoomPlugin } from "./plugins/zoomPlugin/index.js";
@@ -4,6 +4,7 @@ import type { CropCanvasHandle } from "../../CropCanvas.js";
4
4
  import type { EditAction } from "../../types.js";
5
5
  import { fullImageQuad, type Point, type Quad, useEdgeDetection } from "../../useEdgeDetection.js";
6
6
  import { loadOpenCV, useOpenCV } from "../../useOpenCV.js";
7
+ import { canvasToIntermediateBlob } from "../../encodeImage.js";
7
8
 
8
9
  export interface ApplyCropResult {
9
10
  blob: Blob;
@@ -335,7 +336,7 @@ async function rectCropAtFullResolution(imageUrl: string, relCorners: Quad): Pro
335
336
  canvas.height = height;
336
337
  canvas.getContext("2d")!.drawImage(img, x, y, width, height, 0, 0, width, height);
337
338
 
338
- return canvasToPngBlob(canvas);
339
+ return canvasToIntermediateBlob(canvas);
339
340
  }
340
341
 
341
342
  function loadImage(url: string): Promise<HTMLImageElement> {
@@ -347,14 +348,6 @@ function loadImage(url: string): Promise<HTMLImageElement> {
347
348
  });
348
349
  }
349
350
 
350
- function canvasToPngBlob(canvas: HTMLCanvasElement): Promise<Blob> {
351
- return new Promise<Blob>((resolve, reject) => {
352
- // PNG is lossless — critical for receipts and screenshots where JPEG
353
- // compression would make text unreadable.
354
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/png");
355
- });
356
- }
357
-
358
351
  /** Loads the image at native resolution, maps relative corners, and warps. */
359
352
  // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
360
353
  async function cropImageAtFullResolution(cv: any, imageUrl: string, relCorners: Quad): Promise<Blob> {
@@ -388,7 +381,7 @@ function perspectiveCrop(cv: any, srcCanvas: HTMLCanvasElement, corners: Quad):
388
381
  cv.imshow(outCanvas, dst);
389
382
  for (let m of [src, dst, srcPts, dstPts, M]) m.delete();
390
383
 
391
- return canvasToPngBlob(outCanvas);
384
+ return canvasToIntermediateBlob(outCanvas);
392
385
  }
393
386
 
394
387
  /**
@@ -127,10 +127,28 @@ describe("rotate", () => {
127
127
  expectColour(bl, RED);
128
128
  });
129
129
 
130
- it("saves the result as JPEG", async () => {
130
+ it("keeps its result lossless, as PNG", async () => {
131
131
  let blob = await rotateCwPlugin.execute(await quadrantImage());
132
132
 
133
- expect(blob.type).toBe("image/jpeg");
133
+ expect(blob.type).toBe("image/png");
134
+ });
135
+
136
+ it("gives back the original pixels after four quarter turns", async () => {
137
+ // The editor chains every edit on the previous result: a lossy step would compound here.
138
+ let source = await stripedImage(80, 40);
139
+ let url = source;
140
+ for (let i = 0; i < 4; i++) {
141
+ url = objectUrl(await rotateCwPlugin.execute(url));
142
+ }
143
+
144
+ let before = await read(await (await fetch(source)).blob());
145
+ let after = await read(await (await fetch(url)).blob());
146
+ expect([after.width, after.height]).toEqual([before.width, before.height]);
147
+ for (let y = 0; y < before.height; y++) {
148
+ for (let x = 0; x < before.width; x++) {
149
+ expect(after.pixel(x, y)).toEqual(before.pixel(x, y));
150
+ }
151
+ }
134
152
  });
135
153
 
136
154
  it("rejects when the image cannot be loaded", async () => {
@@ -1,6 +1,7 @@
1
1
  import { useCallback, useRef, useState } from "react";
2
2
 
3
3
  import type { EditAction } from "../../types.js";
4
+ import { canvasToIntermediateBlob } from "../../encodeImage.js";
4
5
 
5
6
  export interface RedactRect {
6
7
  x: number;
@@ -100,9 +101,7 @@ export function useRedactTool(imageUrl: string): RedactToolState {
100
101
  blurRegionOnCanvas(ctx, img, nx, ny, nw, nh);
101
102
  }
102
103
 
103
- let blob = await new Promise<Blob>((resolve, reject) => {
104
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/jpeg", 0.92);
105
- });
104
+ let blob = await canvasToIntermediateBlob(canvas);
106
105
  // Store natural-pixel coords so replay doesn't need display size.
107
106
  let actions: EditAction[] = rects.map((r) => ({
108
107
  type: "redact-blur",
@@ -152,7 +151,7 @@ export function replayRedactBlur(imageUrl: string, params: Record<string, unknow
152
151
  let ctx = canvas.getContext("2d")!;
153
152
  ctx.drawImage(img, 0, 0);
154
153
  blurRegionOnCanvas(ctx, img, x, y, w, h);
155
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/jpeg", 0.92);
154
+ canvasToIntermediateBlob(canvas).then(resolve, reject);
156
155
  };
157
156
  img.onerror = () => reject(new Error("Failed to load image for redact replay"));
158
157
  img.src = imageUrl;
@@ -1,5 +1,6 @@
1
1
  import { RotateLeftIcon, RotateRightIcon } from "@navikt/aksel-icons";
2
2
 
3
+ import { canvasToIntermediateBlob } from "../encodeImage.js";
3
4
  import type { ActionPlugin } from "../types.js";
4
5
 
5
6
  function rotateBlob(imageUrl: string, direction: "cw" | "ccw"): Promise<Blob> {
@@ -18,7 +19,7 @@ function rotateBlob(imageUrl: string, direction: "cw" | "ccw"): Promise<Blob> {
18
19
  ctx.rotate(-Math.PI / 2);
19
20
  }
20
21
  ctx.drawImage(img, 0, 0);
21
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/jpeg", 0.92);
22
+ canvasToIntermediateBlob(canvas).then(resolve, reject);
22
23
  };
23
24
  img.onerror = () => reject(new Error("Failed to load image"));
24
25
  img.src = imageUrl;
@@ -0,0 +1,138 @@
1
+ import { Alert, Button, Heading, Paragraph } from "@digdir/designsystemet-react";
2
+ import { FileIcon, TrashIcon, UploadIcon } from "@navikt/aksel-icons";
3
+ import { useData, useDragAndDropUpload, useFilter } from "@olenbetong/appframe-react";
4
+
5
+ import clsx from "clsx";
6
+ import { useRef, useState } from "react";
7
+
8
+ import { getLocalizedString } from "../i18n.js";
9
+ import { dsReportIssueFiles, type ReportIssueFilesRecord } from "./data/dsReportIssueFiles.js";
10
+
11
+ const IMAGE_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "svg", "webp", "avif"];
12
+
13
+ function isImage(file: ReportIssueFilesRecord) {
14
+ let extension = (file.Extension ?? file.FileName?.split(".").pop() ?? "").replace(/^\./, "").toLowerCase();
15
+
16
+ return IMAGE_EXTENSIONS.includes(extension);
17
+ }
18
+
19
+ /**
20
+ * File upload is broken in the old Synergi iOS app's webview, which Apple will not let us replace,
21
+ * so the form says to open the site in Safari instead.
22
+ */
23
+ function isIosWebview() {
24
+ return /(iPad|iPhone)/.test(navigator.userAgent) && !navigator.userAgent.includes("Safari");
25
+ }
26
+
27
+ function WebViewWarning() {
28
+ return (
29
+ <Paragraph data-size="sm">
30
+ {getLocalizedString(
31
+ "File upload is unfortunately broken in the Synergi iOS application, and Apple's policies prevent us from publishing a new version to fix it.",
32
+ )}{" "}
33
+ {getLocalizedString("To upload attachments, please open")}{" "}
34
+ <a href="https://synergi.olenbetong.no" target="_blank" rel="noopener noreferrer">
35
+ s.obet.no
36
+ </a>{" "}
37
+ {getLocalizedString("in Safari instead")}.{" "}
38
+ {getLocalizedString(
39
+ "You can also add the website to your home screen using the share dialog in Safari for easy access.",
40
+ )}
41
+ </Paragraph>
42
+ );
43
+ }
44
+
45
+ /**
46
+ * The attachments of an issue that is still being written. They are uploaded at once, to the
47
+ * user's temp files, and the report moves them onto the issue. Files left there from a report that
48
+ * was never sent show up again the next time.
49
+ */
50
+ export function ReportIssueAttachments() {
51
+ let files = useData(dsReportIssueFiles);
52
+ let { dragProps, dragOver, removeStatus, status, upload } = useDragAndDropUpload<ReportIssueFilesRecord>({
53
+ dataObject: dsReportIssueFiles,
54
+ });
55
+ let inputRef = useRef<HTMLInputElement>(null);
56
+ let [webview] = useState(isIosWebview);
57
+
58
+ useFilter(dsReportIssueFiles, `[CreatedBy] = '${af.userSession.login.replace(/'/g, "''")}'`, "whereClause");
59
+
60
+ let uploading = status.filter((item) => !item.error && !item.complete);
61
+ let failed = status.filter((item) => item.error);
62
+
63
+ return (
64
+ <section className="ObReportIssue-attachments" aria-labelledby="ObReportIssue-attachments-heading">
65
+ <Heading level={2} data-size="xs" id="ObReportIssue-attachments-heading">
66
+ {getLocalizedString("Attachments")}
67
+ </Heading>
68
+
69
+ {webview ? (
70
+ <WebViewWarning />
71
+ ) : (
72
+ <div className={clsx("ObReportIssue-dropzone", dragOver && "ObReportIssue-dropzone--over")} {...dragProps}>
73
+ {files.length > 0 && (
74
+ <ul className="ObReportIssue-files">
75
+ {files.map((file, index) => (
76
+ <li className="ObReportIssue-file" key={file.PrimKey}>
77
+ <div className="ObReportIssue-thumbnail">
78
+ {isImage(file) ? (
79
+ <img src={dsReportIssueFiles.getFileStoreURL(file)} alt="" />
80
+ ) : (
81
+ <FileIcon aria-hidden />
82
+ )}
83
+ </div>
84
+ <span className="ObReportIssue-fileName">{file.FileName}</span>
85
+ <Button
86
+ variant="tertiary"
87
+ data-size="sm"
88
+ icon
89
+ aria-label={`${getLocalizedString("Delete")} ${file.FileName ?? ""}`}
90
+ onClick={() => dsReportIssueFiles.deleteRow(index)}
91
+ >
92
+ <TrashIcon aria-hidden />
93
+ </Button>
94
+ </li>
95
+ ))}
96
+ </ul>
97
+ )}
98
+ <div className="ObReportIssue-uploadActions">
99
+ <Button variant="secondary" onClick={() => inputRef.current?.click()}>
100
+ <UploadIcon aria-hidden />
101
+ {getLocalizedString("Upload File")}
102
+ </Button>
103
+ <span className="ObReportIssue-dropHint">{getLocalizedString("or drag and drop from your computer")}</span>
104
+ </div>
105
+ <input
106
+ tabIndex={-1}
107
+ type="file"
108
+ multiple
109
+ className="ObReportIssue-fileInput"
110
+ ref={inputRef}
111
+ onChange={(event) => {
112
+ let selected = event.currentTarget.files;
113
+ if (selected && selected.length > 0) upload(Array.from(selected));
114
+ event.currentTarget.value = "";
115
+ }}
116
+ />
117
+ </div>
118
+ )}
119
+
120
+ {uploading.map((item) => (
121
+ <div className="ObReportIssue-progress" key={item.index}>
122
+ <span>{item.name}</span>
123
+ <progress max={item.progress.total} value={item.progress.loaded} />
124
+ </div>
125
+ ))}
126
+ {failed.map((item) => (
127
+ <Alert data-color="danger" data-size="sm" key={item.index} className="ObReportIssue-uploadError">
128
+ <span>
129
+ {getLocalizedString("Failed to upload")} {`'${item.name}'`}: {item.error}
130
+ </span>
131
+ <Button variant="tertiary" data-size="sm" onClick={() => removeStatus(item.index)}>
132
+ {getLocalizedString("Close")}
133
+ </Button>
134
+ </Alert>
135
+ ))}
136
+ </section>
137
+ );
138
+ }