@olenbetong/synergi-react 5.2.0 → 5.3.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 (43) hide show
  1. package/es/components/ImageEditor/ImageEditor.d.ts +18 -1
  2. package/es/components/ImageEditor/ImageEditor.js +26 -9
  3. package/es/components/ImageEditor/encodeImage.d.ts +33 -0
  4. package/es/components/ImageEditor/encodeImage.js +60 -0
  5. package/es/components/ImageEditor/index.d.ts +2 -0
  6. package/es/components/ImageEditor/index.js +1 -0
  7. package/es/components/ImageEditor/plugins/cropPlugin/useCropTool.js +3 -9
  8. package/es/components/ImageEditor/plugins/redactPlugin/useRedactTool.js +3 -4
  9. package/es/components/ImageEditor/plugins/rotatePlugin.js +2 -1
  10. package/es/improve/ReportIssueAttachments.d.ts +6 -0
  11. package/es/improve/ReportIssueAttachments.js +45 -0
  12. package/es/improve/ReportIssueForm.css +133 -0
  13. package/es/improve/ReportIssueForm.d.ts +18 -0
  14. package/es/improve/ReportIssueForm.js +71 -0
  15. package/es/improve/data/dsReportIssueAreas.d.ts +8 -0
  16. package/es/improve/data/dsReportIssueAreas.js +37 -0
  17. package/es/improve/data/dsReportIssueFiles.d.ts +15 -0
  18. package/es/improve/data/dsReportIssueFiles.js +55 -0
  19. package/es/improve/data/index.d.ts +3 -0
  20. package/es/improve/data/index.js +3 -0
  21. package/es/improve/data/procReportIssue.d.ts +16 -0
  22. package/es/improve/data/procReportIssue.js +44 -0
  23. package/es/improve/index.d.ts +3 -0
  24. package/es/improve/index.js +3 -0
  25. package/package.json +6 -2
  26. package/src/components/ImageEditor/ImageEditor.browser.test.tsx +30 -5
  27. package/src/components/ImageEditor/ImageEditor.test.tsx +4 -3
  28. package/src/components/ImageEditor/ImageEditor.tsx +43 -10
  29. package/src/components/ImageEditor/encodeImage.browser.test.ts +88 -0
  30. package/src/components/ImageEditor/encodeImage.ts +80 -0
  31. package/src/components/ImageEditor/index.ts +2 -0
  32. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +3 -10
  33. package/src/components/ImageEditor/plugins/plugins.browser.test.ts +20 -2
  34. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.ts +3 -4
  35. package/src/components/ImageEditor/plugins/rotatePlugin.ts +2 -1
  36. package/src/improve/ReportIssueAttachments.tsx +138 -0
  37. package/src/improve/ReportIssueForm.css +133 -0
  38. package/src/improve/ReportIssueForm.tsx +218 -0
  39. package/src/improve/data/dsReportIssueAreas.ts +45 -0
  40. package/src/improve/data/dsReportIssueFiles.ts +66 -0
  41. package/src/improve/data/index.ts +3 -0
  42. package/src/improve/data/procReportIssue.ts +58 -0
  43. package/src/improve/index.ts +3 -0
@@ -1,8 +1,18 @@
1
+ import { type ImageOutputOptions } from "./encodeImage.js";
1
2
  import "./ImageEditor.css";
2
3
  import type { Plugin, ViewPlugin } from "./types.js";
3
4
  export type ImageEditorRef = {
4
- /** Returns the current edited blob, or null if no edits have been applied since the last source image. */
5
+ /**
6
+ * Returns the current edited blob, or null if no edits have been applied since the last source image.
7
+ * This is the editor's lossless intermediate (PNG): to save the result, use `getResultBlob()`.
8
+ */
5
9
  getCurrentBlob: () => Blob | null;
10
+ /**
11
+ * The edited image encoded once - what the Done button hands to `onConfirm` - or null if nothing has been
12
+ * edited. `options` override the output props for this call. Await `whenIdle()` first when an action may
13
+ * still be running.
14
+ */
15
+ getResultBlob: (options?: ImageOutputOptions) => Promise<Blob | null>;
6
16
  /**
7
17
  * Runs a registered action plugin (e.g. `"rotate-cw"`) against the current image.
8
18
  * Use this instead of calling `plugin.execute()` directly so external toolbars and
@@ -30,6 +40,13 @@ interface Props {
30
40
  * plain image. Cancelling the tool returns to the plain image as usual.
31
41
  */
32
42
  initialTool?: string;
43
+ /**
44
+ * How the image is handed out (default JPEG at 0.92, any size). Edits are kept lossless in between and
45
+ * encoded once, here, so repeated rotations or crops do not lose quality step by step. When set, it applies
46
+ * to an unedited image too, which is then re-encoded only when it is too large or of another type; without
47
+ * it an unedited image is handed back exactly as it came.
48
+ */
49
+ output?: ImageOutputOptions;
33
50
  }
34
51
  /**
35
52
  * Full-screen image editor shell.
@@ -2,6 +2,7 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { Button, Spinner, Tooltip } from "@digdir/designsystemet-react";
3
3
  import { ArrowCirclepathIcon, ArrowLeftIcon, ArrowRedoIcon, ArrowUndoIcon, CheckmarkIcon } from "@navikt/aksel-icons";
4
4
  import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from "react";
5
+ import { encodeImage } from "./encodeImage.js";
5
6
  import "./ImageEditor.css";
6
7
  import { ResponsiveButton } from "./ResponsiveButton.js";
7
8
  import { useActiveTool } from "./useActiveTool.js";
@@ -14,7 +15,7 @@ import { getLocalizedString } from "../../i18n.js";
14
15
  * Tool plugins contribute an overlay and toolbar; action plugins execute immediately.
15
16
  * Supports undo/redo: each applied transformation is recorded with its EditAction list.
16
17
  */
17
- export const ImageEditor = forwardRef(function ImageEditor({ imageUrl, onConfirm, onCancel, plugins, viewPlugin, initialTool }, ref) {
18
+ export const ImageEditor = forwardRef(function ImageEditor({ imageUrl, onConfirm, onCancel, plugins, viewPlugin, initialTool, output }, ref) {
18
19
  let registry = useMemo(() => buildActionRegistry(plugins), [plugins]);
19
20
  let history = useImageHistory(imageUrl, registry);
20
21
  let { activePlugin, activateTool, deactivateTool } = useActiveTool(plugins, initialTool ?? null);
@@ -30,6 +31,7 @@ export const ImageEditor = forwardRef(function ImageEditor({ imageUrl, onConfirm
30
31
  let actionQueueRef = useRef(Promise.resolve());
31
32
  useImperativeHandle(ref, () => ({
32
33
  getCurrentBlob: () => historyRef.current.getCurrentBlob(),
34
+ getResultBlob: (options) => getResultBlob(options),
33
35
  whenIdle: () => actionQueueRef.current,
34
36
  executeAction: (pluginId) => {
35
37
  let plugin = plugins.find((p) => p.type === "action" && p.id === pluginId);
@@ -60,20 +62,35 @@ export const ImageEditor = forwardRef(function ImageEditor({ imageUrl, onConfirm
60
62
  history.applyActions(blob, actions);
61
63
  deactivateTool();
62
64
  }
63
- function confirm() {
65
+ function outputOptions(options) {
66
+ return { ...output, ...options };
67
+ }
68
+ async function getResultBlob(options) {
69
+ let blob = historyRef.current.getCurrentBlob();
70
+ return blob ? encodeImage(blob, outputOptions(options)) : null;
71
+ }
72
+ async function confirm() {
64
73
  if (!onConfirm)
65
74
  return;
66
- if (history.currentBlob) {
67
- onConfirm(history.currentBlob);
68
- return;
75
+ setBusy(true);
76
+ try {
77
+ let blob = await getResultBlob();
78
+ if (!blob) {
79
+ // Nothing edited: the original as it came, unless the app set an output it must meet.
80
+ let response = await fetch(historyRef.current.getCurrentImageUrl());
81
+ blob = await response.blob();
82
+ if (output)
83
+ blob = await encodeImage(blob, output);
84
+ }
85
+ onConfirm(blob);
86
+ }
87
+ finally {
88
+ setBusy(false);
69
89
  }
70
- fetch(history.currentImageUrl)
71
- .then((r) => r.blob())
72
- .then(onConfirm);
73
90
  }
74
91
  let CanvasWrapper = viewPlugin?.CanvasWrapper;
75
92
  let TopBarControls = viewPlugin?.TopBarControls;
76
- let inner = (_jsxs("div", { className: "image-editor", children: [_jsxs("div", { className: "image-editor__topbar", children: [_jsxs("div", { className: "image-editor__toolbar-group", children: [onCancel && (_jsxs(_Fragment, { children: [_jsx(ResponsiveButton, { icon: _jsx(ArrowLeftIcon, { "aria-hidden": true }), label: getLocalizedString("Back"), onClick: onCancel, isSmall: isSmall }), _jsx("span", { className: "image-editor__topbar-divider", "aria-hidden": true })] })), _jsx(ResponsiveButton, { icon: _jsx(ArrowUndoIcon, { "aria-hidden": true }), label: getLocalizedString("Undo"), onClick: history.undo, disabled: disabled || !history.canUndo || !!activePlugin, isSmall: isSmall }), _jsx(ResponsiveButton, { icon: _jsx(ArrowRedoIcon, { "aria-hidden": true }), label: getLocalizedString("Redo"), onClick: history.redo, disabled: disabled || !history.canRedo || !!activePlugin, isSmall: isSmall }), _jsx(ResponsiveButton, { icon: _jsx(ArrowCirclepathIcon, { "aria-hidden": true }), label: getLocalizedString("Reset"), onClick: history.reset, disabled: disabled || !history.canUndo || !!activePlugin, isSmall: isSmall })] }), TopBarControls && (_jsx("div", { className: "image-editor__toolbar-group", children: _jsx(TopBarControls, { disabled: disabled, isSmall: isSmall }) }))] }), _jsxs("div", { className: "image-editor__canvas", children: [CanvasWrapper ? (_jsx(CanvasWrapper, { panEnabled: !activePlugin, children: activePlugin ? (_jsx(ActiveOverlay, { plugin: activePlugin })) : (_jsx("img", { src: history.currentImageUrl, alt: getLocalizedString("Image to edit"), className: "image-editor__img" })) })) : activePlugin ? (_jsx(ActiveOverlay, { plugin: activePlugin })) : (_jsx("img", { src: history.currentImageUrl, alt: getLocalizedString("Image to edit"), className: "image-editor__img" })), !activePlugin && onConfirm && (_jsxs(Button, { className: "image-editor__done", variant: "primary", icon: isSmall, "aria-label": isSmall ? getLocalizedString("Done") : undefined, onClick: confirm, disabled: disabled, children: [_jsx(CheckmarkIcon, { "aria-hidden": true }), !isSmall && getLocalizedString("Done")] })), history.replaying && (_jsx("div", { className: "image-editor__replay-overlay", children: _jsx(Spinner, { "aria-label": getLocalizedString("Loading") }) }))] }), _jsx("div", { className: "image-editor__toolbar", children: activePlugin ? (_jsx(ActiveToolbar, { plugin: activePlugin })) : (_jsx("div", { className: "image-editor__toolbar-group", children: plugins.map((p) => p.type === "tool" ? (_jsx(ToolButton, { plugin: p, busy: disabled, onActivate: () => activateTool(p.id), isSmall: isSmall }, p.id)) : (_jsx(ActionButton, { plugin: p, busy: disabled, onExecute: () => enqueueAction(p), isSmall: isSmall }, p.id))) })) })] }));
93
+ let inner = (_jsxs("div", { className: "image-editor", children: [_jsxs("div", { className: "image-editor__topbar", children: [_jsxs("div", { className: "image-editor__toolbar-group", children: [onCancel && (_jsxs(_Fragment, { children: [_jsx(ResponsiveButton, { icon: _jsx(ArrowLeftIcon, { "aria-hidden": true }), label: getLocalizedString("Back"), onClick: onCancel, isSmall: isSmall }), _jsx("span", { className: "image-editor__topbar-divider", "aria-hidden": true })] })), _jsx(ResponsiveButton, { icon: _jsx(ArrowUndoIcon, { "aria-hidden": true }), label: getLocalizedString("Undo"), onClick: history.undo, disabled: disabled || !history.canUndo || !!activePlugin, isSmall: isSmall }), _jsx(ResponsiveButton, { icon: _jsx(ArrowRedoIcon, { "aria-hidden": true }), label: getLocalizedString("Redo"), onClick: history.redo, disabled: disabled || !history.canRedo || !!activePlugin, isSmall: isSmall }), _jsx(ResponsiveButton, { icon: _jsx(ArrowCirclepathIcon, { "aria-hidden": true }), label: getLocalizedString("Reset"), onClick: history.reset, disabled: disabled || !history.canUndo || !!activePlugin, isSmall: isSmall })] }), TopBarControls && (_jsx("div", { className: "image-editor__toolbar-group", children: _jsx(TopBarControls, { disabled: disabled, isSmall: isSmall }) }))] }), _jsxs("div", { className: "image-editor__canvas", children: [CanvasWrapper ? (_jsx(CanvasWrapper, { panEnabled: !activePlugin, children: activePlugin ? (_jsx(ActiveOverlay, { plugin: activePlugin })) : (_jsx("img", { src: history.currentImageUrl, alt: getLocalizedString("Image to edit"), className: "image-editor__img" })) })) : activePlugin ? (_jsx(ActiveOverlay, { plugin: activePlugin })) : (_jsx("img", { src: history.currentImageUrl, alt: getLocalizedString("Image to edit"), className: "image-editor__img" })), !activePlugin && onConfirm && (_jsxs(Button, { className: "image-editor__done", variant: "primary", icon: isSmall, "aria-label": isSmall ? getLocalizedString("Done") : undefined, onClick: () => void confirm(), disabled: disabled, children: [_jsx(CheckmarkIcon, { "aria-hidden": true }), !isSmall && getLocalizedString("Done")] })), history.replaying && (_jsx("div", { className: "image-editor__replay-overlay", children: _jsx(Spinner, { "aria-label": getLocalizedString("Loading") }) }))] }), _jsx("div", { className: "image-editor__toolbar", children: activePlugin ? (_jsx(ActiveToolbar, { plugin: activePlugin })) : (_jsx("div", { className: "image-editor__toolbar-group", children: plugins.map((p) => p.type === "tool" ? (_jsx(ToolButton, { plugin: p, busy: disabled, onActivate: () => activateTool(p.id), isSmall: isSmall }, p.id)) : (_jsx(ActionButton, { plugin: p, busy: disabled, onExecute: () => enqueueAction(p), isSmall: isSmall }, p.id))) })) })] }));
77
94
  // Wrap with the active tool's provider so Overlay and Toolbar share context.
78
95
  if (activePlugin) {
79
96
  let ActiveProvider = activePlugin.Provider;
@@ -0,0 +1,33 @@
1
+ /** Edits are kept lossless between steps; this is the type every tool and replay handler produces. */
2
+ export declare const INTERMEDIATE_TYPE = "image/png";
3
+ /** Encodes a canvas without loss, for the editor's intermediate images. */
4
+ export declare function canvasToIntermediateBlob(canvas: HTMLCanvasElement): Promise<Blob>;
5
+ export type ImageOutputOptions = {
6
+ /** The type to hand the image out in (default `"image/jpeg"`). */
7
+ type?: string;
8
+ /** Quality for a lossy type, 0-1 (default 0.92). */
9
+ quality?: number;
10
+ /**
11
+ * Scales the image down to at most this many pixels, keeping its aspect ratio. A pixel count rather
12
+ * than a long edge, so a long, narrow receipt keeps the same text resolution as a square photo.
13
+ */
14
+ maxPixels?: number;
15
+ /**
16
+ * An image already of `type` and within `maxPixels` is still re-encoded when its file is larger than
17
+ * this (a phone JPEG saved at quality 95+, say). The original is kept if that comes out no smaller.
18
+ */
19
+ maxBytes?: number;
20
+ };
21
+ /** The size to draw an image at so it holds at most `maxPixels`, keeping its aspect ratio. */
22
+ export declare function scaledSize(width: number, height: number, maxPixels?: number): {
23
+ width: number;
24
+ height: number;
25
+ };
26
+ /**
27
+ * Encodes an image once, as the caller asked. Lossy formats are applied here and nowhere else, so a
28
+ * chain of edits (or an undo/redo replay) never stacks one JPEG generation on another.
29
+ *
30
+ * An image already of the requested type, within `maxPixels` and within `maxBytes` is returned untouched,
31
+ * as is one the browser cannot decode (HEIC outside Safari, for instance), so the caller never loses the file.
32
+ */
33
+ export declare function encodeImage(blob: Blob, options?: ImageOutputOptions): Promise<Blob>;
@@ -0,0 +1,60 @@
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
+ /** Encodes a canvas without loss, for the editor's intermediate images. */
4
+ export function canvasToIntermediateBlob(canvas) {
5
+ return new Promise((resolve, reject) => {
6
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), INTERMEDIATE_TYPE);
7
+ });
8
+ }
9
+ /** The size to draw an image at so it holds at most `maxPixels`, keeping its aspect ratio. */
10
+ export function scaledSize(width, height, maxPixels) {
11
+ let pixels = width * height;
12
+ if (!maxPixels || pixels <= maxPixels)
13
+ return { width, height };
14
+ let scale = Math.sqrt(maxPixels / pixels);
15
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
16
+ }
17
+ /**
18
+ * Encodes an image once, as the caller asked. Lossy formats are applied here and nowhere else, so a
19
+ * chain of edits (or an undo/redo replay) never stacks one JPEG generation on another.
20
+ *
21
+ * An image already of the requested type, within `maxPixels` and within `maxBytes` is returned untouched,
22
+ * as is one the browser cannot decode (HEIC outside Safari, for instance), so the caller never loses the file.
23
+ */
24
+ export async function encodeImage(blob, options = {}) {
25
+ let { type = "image/jpeg", quality = 0.92, maxPixels, maxBytes } = options;
26
+ let bitmap;
27
+ try {
28
+ // Applies the EXIF orientation, which the encoded image then no longer needs.
29
+ bitmap = await createImageBitmap(blob, { imageOrientation: "from-image" });
30
+ }
31
+ catch {
32
+ return blob;
33
+ }
34
+ try {
35
+ let size = scaledSize(bitmap.width, bitmap.height, maxPixels);
36
+ let resized = size.width !== bitmap.width || size.height !== bitmap.height;
37
+ let sameType = blob.type === type;
38
+ if (!resized && sameType && (maxBytes === undefined || blob.size <= maxBytes))
39
+ return blob;
40
+ let canvas = document.createElement("canvas");
41
+ canvas.width = size.width;
42
+ canvas.height = size.height;
43
+ let ctx = canvas.getContext("2d");
44
+ if (type === "image/jpeg") {
45
+ // JPEG has no transparency: put transparent areas on white instead of black.
46
+ ctx.fillStyle = "#fff";
47
+ ctx.fillRect(0, 0, size.width, size.height);
48
+ }
49
+ ctx.imageSmoothingQuality = "high";
50
+ ctx.drawImage(bitmap, 0, 0, size.width, size.height);
51
+ let encoded = await new Promise((resolve, reject) => {
52
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), type, quality);
53
+ });
54
+ // Re-encoded only for its size: no point handing out a file that did not shrink.
55
+ return !resized && sameType && encoded.size >= blob.size ? blob : encoded;
56
+ }
57
+ finally {
58
+ bitmap.close();
59
+ }
60
+ }
@@ -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";
@@ -1,5 +1,6 @@
1
1
  export { defaultPlugins, defaultViewPlugin } from "./defaultPlugins.js";
2
2
  export { ImageEditor } from "./ImageEditor.js";
3
+ export { encodeImage, scaledSize } from "./encodeImage.js";
3
4
  export { cropPlugin } from "./plugins/cropPlugin/index.js";
4
5
  export { redactPlugin } from "./plugins/redactPlugin/index.js";
5
6
  export { zoomPlugin } from "./plugins/zoomPlugin/index.js";
@@ -1,6 +1,7 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
2
  import { fullImageQuad, useEdgeDetection } from "../../useEdgeDetection.js";
3
3
  import { loadOpenCV, useOpenCV } from "../../useOpenCV.js";
4
+ import { canvasToIntermediateBlob } from "../../encodeImage.js";
4
5
  /** Relative (0–1) tolerance for treating a quad as axis-aligned. */
5
6
  const RECT_TOLERANCE = 0.001;
6
7
  /** Minimum drag distance in CSS pixels before a drawn rectangle is accepted. */
@@ -259,7 +260,7 @@ async function rectCropAtFullResolution(imageUrl, relCorners) {
259
260
  canvas.width = width;
260
261
  canvas.height = height;
261
262
  canvas.getContext("2d").drawImage(img, x, y, width, height, 0, 0, width, height);
262
- return canvasToPngBlob(canvas);
263
+ return canvasToIntermediateBlob(canvas);
263
264
  }
264
265
  function loadImage(url) {
265
266
  return new Promise((resolve, reject) => {
@@ -269,13 +270,6 @@ function loadImage(url) {
269
270
  img.src = url;
270
271
  });
271
272
  }
272
- function canvasToPngBlob(canvas) {
273
- return new Promise((resolve, reject) => {
274
- // PNG is lossless — critical for receipts and screenshots where JPEG
275
- // compression would make text unreadable.
276
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/png");
277
- });
278
- }
279
273
  /** Loads the image at native resolution, maps relative corners, and warps. */
280
274
  // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
281
275
  async function cropImageAtFullResolution(cv, imageUrl, relCorners) {
@@ -306,7 +300,7 @@ function perspectiveCrop(cv, srcCanvas, corners) {
306
300
  cv.imshow(outCanvas, dst);
307
301
  for (let m of [src, dst, srcPts, dstPts, M])
308
302
  m.delete();
309
- return canvasToPngBlob(outCanvas);
303
+ return canvasToIntermediateBlob(outCanvas);
310
304
  }
311
305
  /**
312
306
  * Standalone replay handler for the "crop" action type.
@@ -1,4 +1,5 @@
1
1
  import { useCallback, useRef, useState } from "react";
2
+ import { canvasToIntermediateBlob } from "../../encodeImage.js";
2
3
  /** Manages state and logic for the blur-redaction tool. */
3
4
  export function useRedactTool(imageUrl) {
4
5
  let [rects, setRects] = useState([]);
@@ -58,9 +59,7 @@ export function useRedactTool(imageUrl) {
58
59
  let nh = Math.round(r.h * scaleY);
59
60
  blurRegionOnCanvas(ctx, img, nx, ny, nw, nh);
60
61
  }
61
- let blob = await new Promise((resolve, reject) => {
62
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/jpeg", 0.92);
63
- });
62
+ let blob = await canvasToIntermediateBlob(canvas);
64
63
  // Store natural-pixel coords so replay doesn't need display size.
65
64
  let actions = rects.map((r) => ({
66
65
  type: "redact-blur",
@@ -106,7 +105,7 @@ export function replayRedactBlur(imageUrl, params) {
106
105
  let ctx = canvas.getContext("2d");
107
106
  ctx.drawImage(img, 0, 0);
108
107
  blurRegionOnCanvas(ctx, img, x, y, w, h);
109
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/jpeg", 0.92);
108
+ canvasToIntermediateBlob(canvas).then(resolve, reject);
110
109
  };
111
110
  img.onerror = () => reject(new Error("Failed to load image for redact replay"));
112
111
  img.src = imageUrl;
@@ -1,4 +1,5 @@
1
1
  import { RotateLeftIcon, RotateRightIcon } from "@navikt/aksel-icons";
2
+ import { canvasToIntermediateBlob } from "../encodeImage.js";
2
3
  function rotateBlob(imageUrl, direction) {
3
4
  return new Promise((resolve, reject) => {
4
5
  let img = new Image();
@@ -16,7 +17,7 @@ function rotateBlob(imageUrl, direction) {
16
17
  ctx.rotate(-Math.PI / 2);
17
18
  }
18
19
  ctx.drawImage(img, 0, 0);
19
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/jpeg", 0.92);
20
+ canvasToIntermediateBlob(canvas).then(resolve, reject);
20
21
  };
21
22
  img.onerror = () => reject(new Error("Failed to load image"));
22
23
  img.src = imageUrl;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The attachments of an issue that is still being written. They are uploaded at once, to the
3
+ * user's temp files, and the report moves them onto the issue. Files left there from a report that
4
+ * was never sent show up again the next time.
5
+ */
6
+ export declare function ReportIssueAttachments(): import("react").JSX.Element;
@@ -0,0 +1,45 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Alert, Button, Heading, Paragraph } from "@digdir/designsystemet-react";
3
+ import { FileIcon, TrashIcon, UploadIcon } from "@navikt/aksel-icons";
4
+ import { useData, useDragAndDropUpload, useFilter } from "@olenbetong/appframe-react";
5
+ import clsx from "clsx";
6
+ import { useRef, useState } from "react";
7
+ import { getLocalizedString } from "../i18n.js";
8
+ import { dsReportIssueFiles } from "./data/dsReportIssueFiles.js";
9
+ const IMAGE_EXTENSIONS = ["jpg", "jpeg", "png", "gif", "svg", "webp", "avif"];
10
+ function isImage(file) {
11
+ let extension = (file.Extension ?? file.FileName?.split(".").pop() ?? "").replace(/^\./, "").toLowerCase();
12
+ return IMAGE_EXTENSIONS.includes(extension);
13
+ }
14
+ /**
15
+ * File upload is broken in the old Synergi iOS app's webview, which Apple will not let us replace,
16
+ * so the form says to open the site in Safari instead.
17
+ */
18
+ function isIosWebview() {
19
+ return /(iPad|iPhone)/.test(navigator.userAgent) && !navigator.userAgent.includes("Safari");
20
+ }
21
+ function WebViewWarning() {
22
+ return (_jsxs(Paragraph, { "data-size": "sm", children: [getLocalizedString("File upload is unfortunately broken in the Synergi iOS application, and Apple's policies prevent us from publishing a new version to fix it."), " ", getLocalizedString("To upload attachments, please open"), " ", _jsx("a", { href: "https://synergi.olenbetong.no", target: "_blank", rel: "noopener noreferrer", children: "s.obet.no" }), " ", getLocalizedString("in Safari instead"), ".", " ", getLocalizedString("You can also add the website to your home screen using the share dialog in Safari for easy access.")] }));
23
+ }
24
+ /**
25
+ * The attachments of an issue that is still being written. They are uploaded at once, to the
26
+ * user's temp files, and the report moves them onto the issue. Files left there from a report that
27
+ * was never sent show up again the next time.
28
+ */
29
+ export function ReportIssueAttachments() {
30
+ let files = useData(dsReportIssueFiles);
31
+ let { dragProps, dragOver, removeStatus, status, upload } = useDragAndDropUpload({
32
+ dataObject: dsReportIssueFiles,
33
+ });
34
+ let inputRef = useRef(null);
35
+ let [webview] = useState(isIosWebview);
36
+ useFilter(dsReportIssueFiles, `[CreatedBy] = '${af.userSession.login.replace(/'/g, "''")}'`, "whereClause");
37
+ let uploading = status.filter((item) => !item.error && !item.complete);
38
+ let failed = status.filter((item) => item.error);
39
+ return (_jsxs("section", { className: "ObReportIssue-attachments", "aria-labelledby": "ObReportIssue-attachments-heading", children: [_jsx(Heading, { level: 2, "data-size": "xs", id: "ObReportIssue-attachments-heading", children: getLocalizedString("Attachments") }), webview ? (_jsx(WebViewWarning, {})) : (_jsxs("div", { className: clsx("ObReportIssue-dropzone", dragOver && "ObReportIssue-dropzone--over"), ...dragProps, children: [files.length > 0 && (_jsx("ul", { className: "ObReportIssue-files", children: files.map((file, index) => (_jsxs("li", { className: "ObReportIssue-file", children: [_jsx("div", { className: "ObReportIssue-thumbnail", children: isImage(file) ? (_jsx("img", { src: dsReportIssueFiles.getFileStoreURL(file), alt: "" })) : (_jsx(FileIcon, { "aria-hidden": true })) }), _jsx("span", { className: "ObReportIssue-fileName", children: file.FileName }), _jsx(Button, { variant: "tertiary", "data-size": "sm", icon: true, "aria-label": `${getLocalizedString("Delete")} ${file.FileName ?? ""}`, onClick: () => dsReportIssueFiles.deleteRow(index), children: _jsx(TrashIcon, { "aria-hidden": true }) })] }, file.PrimKey))) })), _jsxs("div", { className: "ObReportIssue-uploadActions", children: [_jsxs(Button, { variant: "secondary", onClick: () => inputRef.current?.click(), children: [_jsx(UploadIcon, { "aria-hidden": true }), getLocalizedString("Upload File")] }), _jsx("span", { className: "ObReportIssue-dropHint", children: getLocalizedString("or drag and drop from your computer") })] }), _jsx("input", { tabIndex: -1, type: "file", multiple: true, className: "ObReportIssue-fileInput", ref: inputRef, onChange: (event) => {
40
+ let selected = event.currentTarget.files;
41
+ if (selected && selected.length > 0)
42
+ upload(Array.from(selected));
43
+ event.currentTarget.value = "";
44
+ } })] })), uploading.map((item) => (_jsxs("div", { className: "ObReportIssue-progress", children: [_jsx("span", { children: item.name }), _jsx("progress", { max: item.progress.total, value: item.progress.loaded })] }, item.index))), failed.map((item) => (_jsxs(Alert, { "data-color": "danger", "data-size": "sm", className: "ObReportIssue-uploadError", children: [_jsxs("span", { children: [getLocalizedString("Failed to upload"), " ", `'${item.name}'`, ": ", item.error] }), _jsx(Button, { variant: "tertiary", "data-size": "sm", onClick: () => removeStatus(item.index), children: getLocalizedString("Close") })] }, item.index)))] }));
45
+ }
@@ -0,0 +1,133 @@
1
+ .ObReportIssue {
2
+ display: flex;
3
+ flex-direction: column;
4
+ gap: var(--ds-size-6, 1.5rem);
5
+ }
6
+
7
+ .ObReportIssue-checklist {
8
+ margin: var(--ds-size-2, 0.5rem) 0 0;
9
+ padding-inline-start: 1.5rem;
10
+ }
11
+
12
+ .ObReportIssue-actions {
13
+ display: flex;
14
+ flex-wrap: wrap;
15
+ gap: var(--ds-size-2, 0.5rem);
16
+ }
17
+
18
+ .ObReportIssue-submit {
19
+ flex-grow: 1;
20
+ }
21
+
22
+ .ObReportIssue-attachments {
23
+ display: flex;
24
+ flex-direction: column;
25
+ gap: var(--ds-size-3, 0.75rem);
26
+ }
27
+
28
+ .ObReportIssue-dropzone {
29
+ border-radius: var(--ds-border-radius-md, 0.25rem);
30
+ outline: 0 dashed var(--ds-color-neutral-border-default, rgba(0, 0, 0, 0.24));
31
+ outline-offset: 0.25rem;
32
+ transition: outline-width 50ms ease-out;
33
+ }
34
+
35
+ .ObReportIssue-dropzone--over {
36
+ outline-width: 0.125rem;
37
+ background-color: var(--ds-color-accent-surface-tinted);
38
+ }
39
+
40
+ .ObReportIssue-files {
41
+ display: grid;
42
+ grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));
43
+ gap: var(--ds-size-3, 0.75rem);
44
+ margin: 0 0 var(--ds-size-3, 0.75rem);
45
+ padding: 0;
46
+ list-style: none;
47
+ }
48
+
49
+ .ObReportIssue-file {
50
+ display: grid;
51
+ grid-template-columns: 1fr auto;
52
+ align-items: center;
53
+ gap: var(--ds-size-1, 0.25rem);
54
+ }
55
+
56
+ .ObReportIssue-thumbnail {
57
+ grid-column: 1 / -1;
58
+ display: grid;
59
+ place-items: center;
60
+ height: 6rem;
61
+ border-radius: var(--ds-border-radius-md, 0.25rem);
62
+ background-color: var(--ds-color-neutral-background-tinted);
63
+ overflow: hidden;
64
+
65
+ img {
66
+ width: 100%;
67
+ height: 100%;
68
+ object-fit: cover;
69
+ }
70
+
71
+ svg {
72
+ width: 2.5rem;
73
+ height: 2.5rem;
74
+ }
75
+ }
76
+
77
+ .ObReportIssue-fileName {
78
+ overflow: hidden;
79
+ text-overflow: ellipsis;
80
+ white-space: nowrap;
81
+ font-size: var(--ds-font-size-2, 0.875rem);
82
+ }
83
+
84
+ .ObReportIssue-uploadActions {
85
+ display: flex;
86
+ flex-wrap: wrap;
87
+ align-items: center;
88
+ gap: var(--ds-size-3, 0.75rem);
89
+ }
90
+
91
+ .ObReportIssue-dropHint {
92
+ color: var(--ds-color-neutral-text-subtle);
93
+ font-size: var(--ds-font-size-2, 0.875rem);
94
+ }
95
+
96
+ /* Touch devices have nothing to drag files from. */
97
+ @media (pointer: coarse) {
98
+ .ObReportIssue-dropHint {
99
+ display: none;
100
+ }
101
+ }
102
+
103
+ .ObReportIssue-fileInput {
104
+ position: absolute;
105
+ width: 1px;
106
+ height: 1px;
107
+ padding: 0;
108
+ margin: -1px;
109
+ overflow: hidden;
110
+ clip: rect(0, 0, 0, 0);
111
+ white-space: nowrap;
112
+ border: 0;
113
+ }
114
+
115
+ .ObReportIssue-progress {
116
+ display: flex;
117
+ align-items: center;
118
+ justify-content: space-between;
119
+ gap: var(--ds-size-4, 1rem);
120
+ font-size: var(--ds-font-size-2, 0.875rem);
121
+
122
+ progress {
123
+ flex-basis: 25%;
124
+ accent-color: var(--ds-color-accent-base-default);
125
+ }
126
+ }
127
+
128
+ .ObReportIssue-uploadError {
129
+ display: flex;
130
+ align-items: center;
131
+ justify-content: space-between;
132
+ gap: var(--ds-size-2, 0.5rem);
133
+ }
@@ -0,0 +1,18 @@
1
+ import "./ReportIssueForm.css";
2
+ export type ReportIssueType = "Issue" | "Suggestion";
3
+ export type ReportIssueFormProps = {
4
+ /** The type chosen when the form opens. The user can change it. Defaults to `Issue`. */
5
+ defaultType?: ReportIssueType;
6
+ /** Called with the new issue's number once it has been reported. */
7
+ onCreated: (issueId: number) => void;
8
+ /** Shows a Cancel button beside Send, for a form in a dialog. */
9
+ onCancel?: () => void;
10
+ className?: string;
11
+ };
12
+ /**
13
+ * The form for reporting an issue or a suggestion to Improve: the type, what happened, the area it
14
+ * belongs to and any attachments. It is the report-issue app's page, and the issue tracker opens it
15
+ * in a dialog. The form creates the issue itself and hands its number to `onCreated`; where to go
16
+ * from there is up to the app.
17
+ */
18
+ export declare function ReportIssueForm({ defaultType, onCreated, onCancel, className }: ReportIssueFormProps): import("react").JSX.Element;
@@ -0,0 +1,71 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import "./ReportIssueForm.css";
3
+ import { Alert, Button, Divider, Field, Fieldset, Heading, Label, Radio, Select, Textfield, } from "@digdir/designsystemet-react";
4
+ import { logError, startActivity } from "@olenbetong/appframe-core";
5
+ import { useData, useLoading } from "@olenbetong/appframe-react";
6
+ import clsx from "clsx";
7
+ import { useEffect, useId, useState } from "react";
8
+ import { getLocalizedString } from "../i18n.js";
9
+ import { dsReportIssueAreas } from "./data/dsReportIssueAreas.js";
10
+ import { procReportIssue } from "./data/procReportIssue.js";
11
+ import { ReportIssueAttachments } from "./ReportIssueAttachments.js";
12
+ /** Today at 08:00, as a `datetime-local` value: most incidents are reported the same day. */
13
+ function defaultIncidentDate() {
14
+ let now = new Date();
15
+ let pad = (value) => String(value).padStart(2, "0");
16
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T08:00`;
17
+ }
18
+ /**
19
+ * The form for reporting an issue or a suggestion to Improve: the type, what happened, the area it
20
+ * belongs to and any attachments. It is the report-issue app's page, and the issue tracker opens it
21
+ * in a dialog. The form creates the issue itself and hands its number to `onCreated`; where to go
22
+ * from there is up to the app.
23
+ */
24
+ export function ReportIssueForm({ defaultType = "Issue", onCreated, onCancel, className }) {
25
+ let areas = useData(dsReportIssueAreas);
26
+ let areasLoading = useLoading(dsReportIssueAreas);
27
+ let [issueType, setIssueType] = useState(defaultType);
28
+ let [incidentDate, setIncidentDate] = useState(defaultIncidentDate);
29
+ let [description, setDescription] = useState("");
30
+ let [cause, setCause] = useState("");
31
+ let [area, setArea] = useState("");
32
+ let [sending, setSending] = useState(false);
33
+ let [error, setError] = useState(null);
34
+ let areaId = useId();
35
+ useEffect(() => {
36
+ if (!dsReportIssueAreas.isDataLoaded())
37
+ dsReportIssueAreas.refreshDataSource();
38
+ }, []);
39
+ let isIssue = issueType === "Issue";
40
+ async function submit(event) {
41
+ event.preventDefault();
42
+ if (sending)
43
+ return;
44
+ let logActivity = startActivity("ReportIssue");
45
+ try {
46
+ setSending(true);
47
+ setError(null);
48
+ let result = await procReportIssue.execute({
49
+ IssueType: issueType,
50
+ Area: area,
51
+ Description: description,
52
+ IncidentDate: isIssue ? incidentDate : null,
53
+ CauseAnalysis: isIssue && cause.trim() ? cause : null,
54
+ SubmitFiles: true,
55
+ });
56
+ let issueId = result.Table?.[0]?.IssueID;
57
+ if (!issueId)
58
+ throw new Error(getLocalizedString("The issue was not created. Please try again."));
59
+ logActivity({ Area: area, IssueID: issueId });
60
+ onCreated(issueId);
61
+ }
62
+ catch (reason) {
63
+ logError(reason);
64
+ setError(reason instanceof Error ? reason.message : String(reason));
65
+ }
66
+ finally {
67
+ setSending(false);
68
+ }
69
+ }
70
+ return (_jsxs("form", { className: clsx("ObReportIssue", className), "aria-label": getLocalizedString("Report Issue"), onSubmit: submit, children: [_jsxs(Fieldset, { children: [_jsx(Fieldset.Legend, { children: _jsx(Heading, { level: 2, "data-size": "xs", children: getLocalizedString("Issue type") }) }), _jsx(Radio, { name: "IssueType", value: "Issue", checked: isIssue, onChange: () => setIssueType("Issue"), label: getLocalizedString("Report a non-conformity or RUH"), description: getLocalizedString("If something has happened that we should document and learn from, please tell us.") }), _jsx(Radio, { name: "IssueType", value: "Suggestion", checked: !isIssue, onChange: () => setIssueType("Suggestion"), label: getLocalizedString("Make a suggestion"), description: getLocalizedString("Make a suggestion and contribute to Ølen Betong’s best practices. It could be something new or something you think should be done differently.") })] }), isIssue && (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsxs(Heading, { level: 2, "data-size": "xs", children: [getLocalizedString("Remember to enter the following"), ":"] }), _jsxs("ul", { className: "ObReportIssue-checklist", children: [_jsx("li", { children: getLocalizedString("Where the event occured, and if there are any witnesses") }), _jsx("li", { children: getLocalizedString("Write in a few words - Your observation") }), _jsx("li", { children: getLocalizedString("Why did it happen?") }), _jsx("li", { children: getLocalizedString("Immediate measures performed") }), _jsx("li", { children: getLocalizedString("If possible - recommend measures") })] })] }), _jsx(Textfield, { type: "datetime-local", required: true, name: "IncidentDate", value: incidentDate, onChange: (event) => setIncidentDate(event.target.value), label: getLocalizedString("Incident date and time") })] })), _jsx(Textfield, { required: true, multiline: true, rows: 6, name: "Description", value: description, onChange: (event) => setDescription(event.target.value), label: getLocalizedString("Description") }), isIssue && (_jsx(Textfield, { multiline: true, rows: 3, name: "CauseAnalysis", value: cause, onChange: (event) => setCause(event.target.value), label: getLocalizedString("Cause - Describe why the incident occurred"), description: getLocalizedString("Try to find the root cause of the incident. Why did it happen? What were the contributing factors? This will help us find good measures to prevent similar incidents in the future. If the cause is unknown, leave the field blank.") })), _jsxs(Field, { children: [_jsxs(Label, { htmlFor: areaId, children: [getLocalizedString("Area"), " / ", getLocalizedString("Department")] }), _jsxs(Select, { id: areaId, name: "Area", required: true, value: area, onChange: (event) => setArea(event.target.value), children: [_jsx(Select.Option, { value: "", children: areasLoading ? getLocalizedString("Loading...") : "" }), areas.map((row) => (_jsx(Select.Option, { value: row.Area, children: row.Area }, row.Area)))] })] }), _jsx(Divider, {}), _jsx(ReportIssueAttachments, {}), _jsx(Divider, {}), error && (_jsx(Alert, { "data-color": "danger", "data-size": "sm", role: "alert", children: error })), _jsxs("div", { className: "ObReportIssue-actions", children: [_jsx(Button, { type: "submit", loading: sending, className: "ObReportIssue-submit", children: isIssue ? getLocalizedString("Send issue") : getLocalizedString("Send suggestion") }), onCancel && (_jsx(Button, { type: "button", variant: "secondary", onClick: onCancel, disabled: sending, children: getLocalizedString("Cancel") }))] })] }));
71
+ }
@@ -0,0 +1,8 @@
1
+ export type ReportIssueAreasRecord = {
2
+ Area: string;
3
+ Responsible: string;
4
+ SortOrder: string | null;
5
+ CompanySort: number;
6
+ };
7
+ /** The areas an issue can be reported to: the user's areas that are not archived. */
8
+ export declare const dsReportIssueAreas: import("@olenbetong/appframe-data").DataObject<ReportIssueAreasRecord>;
@@ -0,0 +1,37 @@
1
+ import { generateApiDataObject, SortOrder } from "@olenbetong/appframe-data";
2
+ /** The areas an issue can be reported to: the user's areas that are not archived. */
3
+ export const dsReportIssueAreas = generateApiDataObject({
4
+ resource: "aviw_Improve_MyAreas",
5
+ id: "dsReportIssueAreas",
6
+ allowUpdate: false,
7
+ allowInsert: false,
8
+ allowDelete: false,
9
+ dynamicLoading: false,
10
+ fields: [
11
+ {
12
+ name: "Area",
13
+ type: "string",
14
+ nullable: false,
15
+ },
16
+ {
17
+ name: "Responsible",
18
+ type: "string",
19
+ nullable: false,
20
+ },
21
+ {
22
+ name: "SortOrder",
23
+ type: "string",
24
+ nullable: true,
25
+ },
26
+ {
27
+ name: "CompanySort",
28
+ type: "number",
29
+ nullable: false,
30
+ },
31
+ ],
32
+ parameters: {
33
+ maxRecords: -1,
34
+ whereClause: "[Archived] IS NULL",
35
+ sortOrder: [{ CompanySort: SortOrder.Asc }, { SortOrder: SortOrder.Asc }, { Area: SortOrder.Asc }],
36
+ },
37
+ });