@olenbetong/synergi-react 2.8.0 → 3.0.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 (128) hide show
  1. package/dist/styles/styles.css.map +1 -1
  2. package/es/chrome/AppShell/index.d.ts +8 -0
  3. package/es/chrome/AppShell/index.js +10 -130
  4. package/es/components/ImageEditor/ImageEditor.css +10 -0
  5. package/es/components/ImageEditor/ImageEditor.d.ts +12 -0
  6. package/es/components/ImageEditor/ImageEditor.js +27 -6
  7. package/es/components/ImageEditor/index.d.ts +3 -0
  8. package/es/components/ImageEditor/index.js +3 -0
  9. package/es/components/ImageEditor/plugins/cropPlugin/CropOverlay.js +27 -5
  10. package/es/components/ImageEditor/plugins/cropPlugin/CropToolbar.js +4 -3
  11. package/es/components/ImageEditor/plugins/cropPlugin/useCropTool.d.ts +20 -3
  12. package/es/components/ImageEditor/plugins/cropPlugin/useCropTool.js +216 -33
  13. package/es/components/ImageEditor/plugins/zoomPlugin/ZoomContext.d.ts +5 -0
  14. package/es/components/ImageEditor/plugins/zoomPlugin/ZoomContext.js +7 -0
  15. package/es/components/ImageEditor/plugins/zoomPlugin/ZoomControls.js +1 -1
  16. package/es/components/ImageEditor/useEdgeDetection.d.ts +0 -2
  17. package/es/components/ImageEditor/useEdgeDetection.js +11 -30
  18. package/es/components/ImageEditor/useImageHistory.d.ts +6 -1
  19. package/es/components/ImageEditor/useImageHistory.js +21 -23
  20. package/es/components/ImageEditor/useOpenCV.d.ts +26 -1
  21. package/es/components/ImageEditor/useOpenCV.js +108 -42
  22. package/es/components/SplitContainer/index.js +2 -4
  23. package/es/elements/ElementDamage/DamageFormButtons.d.ts +2 -3
  24. package/es/elements/ElementDamage/DamageFormButtons.js +1 -1
  25. package/es/elements/ElementDamage/TransportElementSelect.d.ts +1 -2
  26. package/es/elements/index.d.ts +5 -0
  27. package/es/elements/index.js +5 -0
  28. package/es/filter/ChipListInput.d.ts +13 -0
  29. package/es/filter/ChipListInput.js +34 -0
  30. package/es/filter/FilterBuilder.css +152 -0
  31. package/es/filter/FilterBuilder.d.ts +115 -0
  32. package/es/filter/FilterBuilder.js +146 -0
  33. package/es/filter/FilterBuilder.test.d.ts +1 -0
  34. package/es/filter/FilterBuilder.test.js +120 -0
  35. package/es/filter/FilterEditor.css +231 -0
  36. package/es/filter/FilterEditor.d.ts +17 -0
  37. package/es/filter/FilterEditor.js +38 -0
  38. package/es/filter/FilterEditor.test.d.ts +1 -0
  39. package/es/filter/FilterEditor.test.js +183 -0
  40. package/es/filter/FilterGroupEditor.d.ts +22 -0
  41. package/es/filter/FilterGroupEditor.js +34 -0
  42. package/es/filter/FilterNameDialog.css +22 -0
  43. package/es/filter/FilterNameDialog.d.ts +18 -0
  44. package/es/filter/FilterNameDialog.js +32 -0
  45. package/es/filter/FilterRow.d.ts +14 -0
  46. package/es/filter/FilterRow.js +32 -0
  47. package/es/filter/FilterShareDialog.css +28 -0
  48. package/es/filter/FilterShareDialog.d.ts +23 -0
  49. package/es/filter/FilterShareDialog.js +63 -0
  50. package/es/filter/FilterStringField.d.ts +15 -0
  51. package/es/filter/FilterStringField.js +37 -0
  52. package/es/filter/FilterValueEditor.d.ts +16 -0
  53. package/es/filter/FilterValueEditor.js +85 -0
  54. package/es/filter/SavedFilterTree.css +107 -0
  55. package/es/filter/SavedFilterTree.d.ts +45 -0
  56. package/es/filter/SavedFilterTree.js +44 -0
  57. package/es/filter/SavedFilterTree.test.d.ts +1 -0
  58. package/es/filter/SavedFilterTree.test.js +75 -0
  59. package/es/filter/index.d.ts +11 -0
  60. package/es/filter/index.js +10 -0
  61. package/es/filter/types.d.ts +34 -0
  62. package/es/filter/types.js +1 -0
  63. package/es/index.d.ts +2 -1
  64. package/es/index.js +6 -1
  65. package/es/mui/MuiThemeProvider.d.ts +24 -0
  66. package/es/mui/MuiThemeProvider.js +152 -0
  67. package/es/mui/index.d.ts +1 -0
  68. package/es/mui/index.js +1 -0
  69. package/es/report/ReportLauncher.css +147 -0
  70. package/es/report/ReportLauncher.d.ts +55 -0
  71. package/es/report/ReportLauncher.js +142 -0
  72. package/es/report/ReportLauncher.test.d.ts +1 -0
  73. package/es/report/ReportLauncher.test.js +231 -0
  74. package/es/report/ReportParameters.css +29 -0
  75. package/es/report/ReportParameters.d.ts +46 -0
  76. package/es/report/ReportParameters.js +65 -0
  77. package/es/report/ReportParameters.test.d.ts +1 -0
  78. package/es/report/ReportParameters.test.js +84 -0
  79. package/es/report/index.d.ts +2 -0
  80. package/es/report/index.js +2 -0
  81. package/es/test/setup.d.ts +1 -0
  82. package/es/test/setup.js +6 -0
  83. package/package.json +22 -7
  84. package/src/chrome/AppShell/index.tsx +34 -171
  85. package/src/components/ImageEditor/ImageEditor.css +10 -0
  86. package/src/components/ImageEditor/ImageEditor.tsx +40 -5
  87. package/src/components/ImageEditor/index.ts +1 -0
  88. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +66 -20
  89. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +19 -3
  90. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +266 -39
  91. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomContext.tsx +8 -0
  92. package/src/components/ImageEditor/useEdgeDetection.ts +11 -51
  93. package/src/components/ImageEditor/useImageHistory.ts +27 -19
  94. package/src/components/ImageEditor/useOpenCV.ts +112 -62
  95. package/src/components/LinkedCardList/index.scss +4 -2
  96. package/src/components/ProgressBar/index.scss +4 -2
  97. package/src/components/SplitContainer/index.tsx +3 -4
  98. package/src/filter/ChipListInput.tsx +79 -0
  99. package/src/filter/FilterBuilder.css +152 -0
  100. package/src/filter/FilterBuilder.test.tsx +153 -0
  101. package/src/filter/FilterBuilder.tsx +435 -0
  102. package/src/filter/FilterEditor.css +231 -0
  103. package/src/filter/FilterEditor.test.tsx +259 -0
  104. package/src/filter/FilterEditor.tsx +74 -0
  105. package/src/filter/FilterGroupEditor.tsx +160 -0
  106. package/src/filter/FilterNameDialog.css +22 -0
  107. package/src/filter/FilterNameDialog.tsx +81 -0
  108. package/src/filter/FilterRow.tsx +117 -0
  109. package/src/filter/FilterShareDialog.css +28 -0
  110. package/src/filter/FilterShareDialog.tsx +201 -0
  111. package/src/filter/FilterStringField.tsx +77 -0
  112. package/src/filter/FilterValueEditor.tsx +220 -0
  113. package/src/filter/SavedFilterTree.css +107 -0
  114. package/src/filter/SavedFilterTree.test.tsx +94 -0
  115. package/src/filter/SavedFilterTree.tsx +222 -0
  116. package/src/filter/index.ts +11 -0
  117. package/src/filter/types.ts +38 -0
  118. package/src/index.ts +39 -1
  119. package/src/mui/MuiThemeProvider.tsx +174 -0
  120. package/src/mui/index.ts +1 -0
  121. package/src/report/ReportLauncher.css +147 -0
  122. package/src/report/ReportLauncher.test.tsx +281 -0
  123. package/src/report/ReportLauncher.tsx +421 -0
  124. package/src/report/ReportParameters.css +29 -0
  125. package/src/report/ReportParameters.test.tsx +133 -0
  126. package/src/report/ReportParameters.tsx +198 -0
  127. package/src/report/index.ts +2 -0
  128. package/src/test/setup.ts +8 -0
@@ -1,9 +1,10 @@
1
- import { Alert, Paragraph, Spinner } from "@digdir/designsystemet-react";
1
+ import { Paragraph, Spinner } from "@digdir/designsystemet-react";
2
2
  import { getLocalizedString } from "@olenbetong/appframe-core";
3
3
 
4
4
  import { CropCanvas } from "../../CropCanvas.js";
5
5
  import { DragHandle } from "../../DragHandle.js";
6
6
  import { EdgeHandle } from "../../EdgeHandle.js";
7
+ import { useZoomLevel } from "../zoomPlugin/ZoomContext.js";
7
8
  import { useCropContext } from "./CropContext.js";
8
9
 
9
10
  /** Canvas-area overlay for the crop tool. Reads all state from CropContext. */
@@ -11,6 +12,8 @@ export function CropOverlay() {
11
12
  let {
12
13
  imageUrl,
13
14
  activeCorners,
15
+ mode,
16
+ hasSelection,
14
17
  scale,
15
18
  displaySize,
16
19
  canvasRef,
@@ -20,14 +23,51 @@ export function CropOverlay() {
20
23
  error,
21
24
  handleCanvasReady,
22
25
  updateCorner,
26
+ startRectDraw,
27
+ updateRectDraw,
28
+ finishRectDraw,
23
29
  } = useCropContext();
24
30
 
31
+ let zoom = useZoomLevel();
32
+ let showHandles = mode === "corners" && displaySize.width > 0;
33
+
34
+ function pointerPosition(e: React.PointerEvent<HTMLDivElement>) {
35
+ // getBoundingClientRect() is screen-space (affected by the zoom transform),
36
+ // so divide by zoom to get back to the CSS-pixel space the tool expects.
37
+ let rect = e.currentTarget.getBoundingClientRect();
38
+ return { x: (e.clientX - rect.left) / zoom, y: (e.clientY - rect.top) / zoom };
39
+ }
40
+
41
+ function onPointerDown(e: React.PointerEvent<HTMLDivElement>) {
42
+ e.currentTarget.setPointerCapture(e.pointerId);
43
+ let { x, y } = pointerPosition(e);
44
+ startRectDraw(x, y);
45
+ }
46
+
47
+ function onPointerMove(e: React.PointerEvent<HTMLDivElement>) {
48
+ if (!(e.buttons & 1)) return;
49
+ let { x, y } = pointerPosition(e);
50
+ updateRectDraw(x, y);
51
+ }
52
+
25
53
  return (
26
54
  <div className="crop-root">
27
55
  <div className="crop-inner">
28
56
  <CropCanvas ref={canvasRef} imageUrl={imageUrl} corners={activeCorners} onReady={handleCanvasReady} />
29
57
 
30
- {displaySize.width > 0 &&
58
+ {mode === "rect" && displaySize.width > 0 && (
59
+ <div
60
+ role="application"
61
+ aria-label={getLocalizedString("Drag to draw a rectangle to crop to")}
62
+ className="crop-draw-surface"
63
+ onPointerDown={onPointerDown}
64
+ onPointerMove={onPointerMove}
65
+ onPointerUp={finishRectDraw}
66
+ onPointerCancel={finishRectDraw}
67
+ />
68
+ )}
69
+
70
+ {showHandles &&
31
71
  activeCorners.map((corner, i) => (
32
72
  <DragHandle
33
73
  key={i}
@@ -39,7 +79,7 @@ export function CropOverlay() {
39
79
  />
40
80
  ))}
41
81
 
42
- {displaySize.width > 0 &&
82
+ {showHandles &&
43
83
  (() => {
44
84
  let [tl, tr, br, bl] = activeCorners;
45
85
  let s = scale;
@@ -90,30 +130,36 @@ export function CropOverlay() {
90
130
  })()}
91
131
  </div>
92
132
 
93
- {!cvReady && !cvError && (
133
+ {/* Status line. OpenCV only powers the border suggestion, so a load failure is
134
+ informational — cropping stays available either way. */}
135
+ {cropping ? (
94
136
  <div className="crop-loading">
95
137
  <Spinner aria-hidden data-size="xs" />
96
- <Paragraph data-size="sm">{getLocalizedString("Loading OpenCV…")}</Paragraph>
97
138
  </div>
98
- )}
99
- {cvError && (
139
+ ) : error ? (
100
140
  <div className="crop-loading">
101
- <Alert data-color="danger" data-size="sm">
102
- {getLocalizedString("Crop tool failed to load")}
103
- </Alert>
141
+ <Paragraph data-size="sm">{error}</Paragraph>
142
+ </div>
143
+ ) : mode === "rect" ? (
144
+ <div className="crop-loading">
145
+ <Paragraph data-size="sm">
146
+ {hasSelection
147
+ ? getLocalizedString("Release to use this rectangle")
148
+ : getLocalizedString("Drag to draw a rectangle to crop to")}
149
+ </Paragraph>
150
+ </div>
151
+ ) : !cvReady && !cvError ? (
152
+ <div className="crop-loading">
153
+ <Spinner aria-hidden data-size="xs" />
154
+ <Paragraph data-size="sm">{getLocalizedString("Detecting borders…")}</Paragraph>
104
155
  </div>
105
- )}
106
- {(error || cropping) && (
156
+ ) : cvError ? (
107
157
  <div className="crop-loading">
108
- {cropping ? (
109
- <Spinner aria-hidden data-size="xs" />
110
- ) : (
111
- <Alert data-color="danger" data-size="sm">
112
- {error}
113
- </Alert>
114
- )}
158
+ <Paragraph data-size="sm">
159
+ {getLocalizedString("Automatic border detection is unavailable. Adjust the selection manually.")}
160
+ </Paragraph>
115
161
  </div>
116
- )}
162
+ ) : null}
117
163
  </div>
118
164
  );
119
165
  }
@@ -1,12 +1,13 @@
1
1
  import { Button, Spinner } from "@digdir/designsystemet-react";
2
- import { CheckmarkIcon, XMarkIcon } from "@navikt/aksel-icons";
2
+ import { CheckmarkIcon, ExpandIcon, SquareIcon, XMarkIcon } from "@navikt/aksel-icons";
3
3
  import { getLocalizedString } from "@olenbetong/appframe-core";
4
4
 
5
5
  import { useCropContext } from "./CropContext.js";
6
6
 
7
7
  /** Toolbar shown while the crop tool is active. Reads state from CropContext. */
8
8
  export function CropToolbar() {
9
- let { applyCrop, cropping, cvReady, cvError, onApply, onCancel } = useCropContext();
9
+ let { applyCrop, cropping, mode, hasSelection, startRectMode, cancelRectMode, onApply, onCancel } = useCropContext();
10
+ let inRectMode = mode === "rect";
10
11
 
11
12
  async function handleApply() {
12
13
  let result = await applyCrop();
@@ -22,7 +23,22 @@ export function CropToolbar() {
22
23
  </Button>
23
24
  </div>
24
25
  <div className="image-editor__toolbar-group">
25
- <Button variant="primary" data-size="sm" onClick={handleApply} disabled={cropping || !cvReady || !!cvError}>
26
+ <Button
27
+ variant="tertiary"
28
+ data-size="sm"
29
+ aria-pressed={inRectMode}
30
+ onClick={inRectMode ? cancelRectMode : startRectMode}
31
+ disabled={cropping}
32
+ >
33
+ {inRectMode ? <ExpandIcon aria-hidden /> : <SquareIcon aria-hidden />}
34
+ {inRectMode ? getLocalizedString("Adjust corners") : getLocalizedString("Draw rectangle")}
35
+ </Button>
36
+ <Button
37
+ variant="primary"
38
+ data-size="sm"
39
+ onClick={handleApply}
40
+ disabled={cropping || inRectMode || !hasSelection}
41
+ >
26
42
  {cropping ? <Spinner aria-hidden data-size="xs" /> : <CheckmarkIcon aria-hidden />}
27
43
  {getLocalizedString("Apply crop")}
28
44
  </Button>
@@ -10,8 +10,27 @@ export interface ApplyCropResult {
10
10
  actions: EditAction[];
11
11
  }
12
12
 
13
+ /**
14
+ * `corners` — drag the four corner/edge handles of the current selection.
15
+ * `rect` — drag out a brand new axis-aligned rectangle.
16
+ */
17
+ export type CropMode = "corners" | "rect";
18
+
19
+ /** How a stored crop action must be replayed. Axis-aligned rects need no OpenCV. */
20
+ type CropGeometry = "perspective" | "rect";
21
+
22
+ interface RectDraft {
23
+ startX: number;
24
+ startY: number;
25
+ currentX: number;
26
+ currentY: number;
27
+ }
28
+
13
29
  export interface CropToolState {
14
30
  activeCorners: Quad;
31
+ mode: CropMode;
32
+ /** False while the user is in rect mode and has not drawn a rectangle yet. */
33
+ hasSelection: boolean;
15
34
  scale: number;
16
35
  displaySize: { width: number; height: number };
17
36
  canvasRef: React.RefObject<CropCanvasHandle | null>;
@@ -19,15 +38,27 @@ export interface CropToolState {
19
38
  cvError: Error | null;
20
39
  cropping: boolean;
21
40
  error: string | null;
22
- debugImageUrl: string | null;
23
41
  handleCanvasReady: (canvas: HTMLCanvasElement, w: number, h: number) => void;
24
42
  updateCorner: (index: number, screenX: number, screenY: number) => void;
43
+ /** Enters rect mode, temporarily clearing (and remembering) the current selection. */
44
+ startRectMode: () => void;
45
+ /** Leaves rect mode without drawing, restoring the selection that was active before. */
46
+ cancelRectMode: () => void;
47
+ startRectDraw: (screenX: number, screenY: number) => void;
48
+ updateRectDraw: (screenX: number, screenY: number) => void;
49
+ finishRectDraw: () => void;
25
50
  applyCrop: () => Promise<ApplyCropResult | null>;
26
51
  }
27
52
 
53
+ /** Relative (0–1) tolerance for treating a quad as axis-aligned. */
54
+ const RECT_TOLERANCE = 0.001;
55
+ /** Minimum drag distance in CSS pixels before a drawn rectangle is accepted. */
56
+ const MIN_RECT_DRAG = 4;
57
+
28
58
  /**
29
- * Manages all state and logic for the perspective crop tool.
30
- * Loads OpenCV lazily, runs edge detection, and performs the warp.
59
+ * Manages all state and logic for the crop tool.
60
+ * OpenCV is loaded lazily for corner suggestion and perspective warping, but is optional:
61
+ * when it fails to load the tool stays fully usable, only the suggested border is missing.
31
62
  */
32
63
  export function useCropTool(imageUrl: string, enabled: boolean): CropToolState {
33
64
  let { cv, ready: cvReady, error: cvError } = useOpenCV(enabled);
@@ -37,30 +68,41 @@ export function useCropTool(imageUrl: string, enabled: boolean): CropToolState {
37
68
  let [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);
38
69
  let [cropping, setCropping] = useState(false);
39
70
  let [error, setError] = useState<string | null>(null);
71
+ let [mode, setMode] = useState<CropMode>("corners");
72
+ let [rectDraft, setRectDraft] = useState<RectDraft | null>(null);
40
73
  let canvasRef = useRef<CropCanvasHandle>(null);
41
74
  let prevSuggested = useRef<Quad | null>(null);
75
+ // Selection stashed when entering rect mode, restored if the user backs out.
76
+ let stashedCorners = useRef<Quad | null>(null);
77
+ // Mirrors rectDraft so pointer handlers never read a stale render closure.
78
+ let rectDraftRef = useRef<RectDraft | null>(null);
79
+ // Set once the user has touched the selection, so a late suggestion can't overwrite it.
80
+ let userAdjusted = useRef(false);
42
81
 
43
- let { corners: suggestedCorners, debugImageUrl } = useEdgeDetection(
44
- cvReady ? cv : null,
45
- canvasEl,
46
- cvReady && enabled,
47
- );
82
+ let { corners: suggestedCorners } = useEdgeDetection(cvReady ? cv : null, canvasEl, cvReady && enabled);
48
83
 
49
84
  useEffect(() => {
50
85
  if (suggestedCorners && suggestedCorners !== prevSuggested.current) {
51
86
  prevSuggested.current = suggestedCorners;
52
- setCorners(suggestedCorners);
87
+ if (!userAdjusted.current) setCorners(suggestedCorners);
53
88
  }
54
89
  }, [suggestedCorners]);
55
90
 
56
91
  // Reset when the source image changes (e.g. after a previous crop or rotate)
57
92
  useEffect(() => {
58
93
  prevSuggested.current = null;
94
+ stashedCorners.current = null;
95
+ rectDraftRef.current = null;
96
+ userAdjusted.current = false;
59
97
  setCorners(null);
60
98
  setCanvasEl(null);
99
+ setRectDraft(null);
100
+ setMode("corners");
61
101
  }, [imageUrl]);
62
102
 
63
- let activeCorners: Quad = corners ?? fullImageQuad(canvasPixelSize.width, canvasPixelSize.height);
103
+ let draftQuad = rectDraft ? draftToQuad(rectDraft) : null;
104
+ let hasSelection = mode === "corners" || draftQuad !== null;
105
+ let activeCorners: Quad = draftQuad ?? corners ?? fullImageQuad(canvasPixelSize.width, canvasPixelSize.height);
64
106
  let scale = displaySize.width > 0 ? displaySize.width / canvasPixelSize.width : 1;
65
107
 
66
108
  let handleCanvasReady = useCallback((canvas: HTMLCanvasElement, w: number, h: number) => {
@@ -69,18 +111,79 @@ export function useCropTool(imageUrl: string, enabled: boolean): CropToolState {
69
111
  setDisplaySize({ width: canvas.clientWidth, height: canvas.clientHeight });
70
112
  }, []);
71
113
 
114
+ /** Converts CSS-pixel overlay coords to canvas-pixel coords, clamped to the image. */
115
+ function toCanvasPoint(screenX: number, screenY: number): Point {
116
+ return {
117
+ x: Math.max(0, Math.min(canvasPixelSize.width, screenX / scale)),
118
+ y: Math.max(0, Math.min(canvasPixelSize.height, screenY / scale)),
119
+ };
120
+ }
121
+
72
122
  function updateCorner(index: number, screenX: number, screenY: number) {
73
- let pixelX = screenX / scale;
74
- let pixelY = screenY / scale;
123
+ if (mode !== "corners") return;
124
+ let point = toCanvasPoint(screenX, screenY);
125
+ userAdjusted.current = true;
75
126
  setCorners((prev) => {
76
127
  let next = [...(prev ?? activeCorners)] as Quad;
77
- next[index] = { x: pixelX, y: pixelY } as Point;
128
+ next[index] = point;
78
129
  return next;
79
130
  });
80
131
  }
81
132
 
133
+ function startRectMode() {
134
+ if (mode === "rect") return;
135
+ stashedCorners.current = corners;
136
+ rectDraftRef.current = null;
137
+ userAdjusted.current = true;
138
+ setRectDraft(null);
139
+ setCorners(null);
140
+ setMode("rect");
141
+ }
142
+
143
+ function cancelRectMode() {
144
+ if (mode !== "rect") return;
145
+ // Fall back to the suggested border when rect mode was entered before any selection existed.
146
+ setCorners(stashedCorners.current ?? prevSuggested.current);
147
+ stashedCorners.current = null;
148
+ rectDraftRef.current = null;
149
+ setRectDraft(null);
150
+ setMode("corners");
151
+ }
152
+
153
+ function startRectDraw(screenX: number, screenY: number) {
154
+ if (mode !== "rect") return;
155
+ let { x, y } = toCanvasPoint(screenX, screenY);
156
+ rectDraftRef.current = { startX: x, startY: y, currentX: x, currentY: y };
157
+ setRectDraft(rectDraftRef.current);
158
+ }
159
+
160
+ function updateRectDraw(screenX: number, screenY: number) {
161
+ if (!rectDraftRef.current) return;
162
+ let { x, y } = toCanvasPoint(screenX, screenY);
163
+ rectDraftRef.current = { ...rectDraftRef.current, currentX: x, currentY: y };
164
+ setRectDraft(rectDraftRef.current);
165
+ }
166
+
167
+ function finishRectDraw() {
168
+ let draft = rectDraftRef.current;
169
+ rectDraftRef.current = null;
170
+ setRectDraft(null);
171
+ if (!draft) return;
172
+
173
+ let width = Math.abs(draft.currentX - draft.startX) * scale;
174
+ let height = Math.abs(draft.currentY - draft.startY) * scale;
175
+ // Ignore taps and stray micro-drags — stay in rect mode so the user can try again.
176
+ if (width < MIN_RECT_DRAG || height < MIN_RECT_DRAG) return;
177
+
178
+ // The new rectangle replaces the stashed selection, so there is nothing left to restore.
179
+ stashedCorners.current = null;
180
+ setCorners(draftToQuad(draft));
181
+ setMode("corners");
182
+ }
183
+
82
184
  async function applyCrop(): Promise<ApplyCropResult | null> {
83
- if (!cv) return null;
185
+ // Nothing to apply until the user has drawn their rectangle.
186
+ if (mode === "rect") return null;
84
187
  setCropping(true);
85
188
  setError(null);
86
189
  try {
@@ -90,10 +193,11 @@ export function useCropTool(imageUrl: string, enabled: boolean): CropToolState {
90
193
  let relCorners = activeCorners.map((c) => ({
91
194
  x: c.x / canvasPixelSize.width,
92
195
  y: c.y / canvasPixelSize.height,
93
- }));
196
+ })) as Quad;
197
+
94
198
  // Warp the original image at its native resolution to avoid quality loss.
95
- let blob = await cropImageAtFullResolution(cv, imageUrl, relCorners as Quad);
96
- let actions: EditAction[] = [{ type: "crop", params: { corners: relCorners } }];
199
+ let { blob, corners: usedCorners, geometry } = await cropAtFullResolution(cv, imageUrl, relCorners);
200
+ let actions: EditAction[] = [{ type: "crop", params: { corners: usedCorners, mode: geometry } }];
97
201
  return { blob, actions };
98
202
  } catch (err) {
99
203
  setError(err instanceof Error ? err.message : "Crop failed");
@@ -105,6 +209,8 @@ export function useCropTool(imageUrl: string, enabled: boolean): CropToolState {
105
209
 
106
210
  return {
107
211
  activeCorners,
212
+ mode,
213
+ hasSelection,
108
214
  scale,
109
215
  displaySize,
110
216
  canvasRef,
@@ -112,34 +218,156 @@ export function useCropTool(imageUrl: string, enabled: boolean): CropToolState {
112
218
  cvError,
113
219
  cropping,
114
220
  error,
115
- debugImageUrl,
116
221
  handleCanvasReady,
117
222
  updateCorner,
223
+ startRectMode,
224
+ cancelRectMode,
225
+ startRectDraw,
226
+ updateRectDraw,
227
+ finishRectDraw,
118
228
  applyCrop,
119
229
  };
120
230
  }
121
231
 
122
- /** Loads the image at native resolution, maps relative corners, and warps. */
232
+ /** Normalises a drag into a TL, TR, BR, BL quad. */
233
+ function draftToQuad(draft: RectDraft): Quad {
234
+ let x1 = Math.min(draft.startX, draft.currentX);
235
+ let x2 = Math.max(draft.startX, draft.currentX);
236
+ let y1 = Math.min(draft.startY, draft.currentY);
237
+ let y2 = Math.max(draft.startY, draft.currentY);
238
+ return [
239
+ { x: x1, y: y1 },
240
+ { x: x2, y: y1 },
241
+ { x: x2, y: y2 },
242
+ { x: x1, y: y2 },
243
+ ];
244
+ }
245
+
246
+ /** True when the quad's edges are horizontal/vertical, so a plain canvas crop is exact. */
247
+ function isAxisAlignedRect([tl, tr, br, bl]: Quad): boolean {
248
+ return (
249
+ Math.abs(tl.y - tr.y) <= RECT_TOLERANCE &&
250
+ Math.abs(bl.y - br.y) <= RECT_TOLERANCE &&
251
+ Math.abs(tl.x - bl.x) <= RECT_TOLERANCE &&
252
+ Math.abs(tr.x - br.x) <= RECT_TOLERANCE
253
+ );
254
+ }
255
+
256
+ /** Axis-aligned bounding box of a quad, as a quad. */
257
+ function boundingQuad(corners: Quad): Quad {
258
+ let xs = corners.map((c) => c.x);
259
+ let ys = corners.map((c) => c.y);
260
+ let x1 = Math.min(...xs);
261
+ let x2 = Math.max(...xs);
262
+ let y1 = Math.min(...ys);
263
+ let y2 = Math.max(...ys);
264
+ return [
265
+ { x: x1, y: y1 },
266
+ { x: x2, y: y1 },
267
+ { x: x2, y: y2 },
268
+ { x: x1, y: y2 },
269
+ ];
270
+ }
271
+
272
+ /**
273
+ * Ensures OpenCV is loaded, reporting success as a boolean instead of throwing.
274
+ *
275
+ * Deliberately does not *return* the module: Emscripten's module object is thenable
276
+ * (it has its own `.then`), so returning it from an async function makes the promise
277
+ * machinery adopt it and loop forever, freezing the tab. Callers read `window.cv`.
278
+ */
279
+ async function ensureOpenCV(): Promise<boolean> {
280
+ try {
281
+ await loadOpenCV();
282
+ return typeof window.cv?.imread === "function";
283
+ } catch {
284
+ return false;
285
+ }
286
+ }
287
+
288
+ interface CropOutput {
289
+ blob: Blob;
290
+ /** The corners actually used — a bounding box when a perspective crop had to be downgraded. */
291
+ corners: Quad;
292
+ geometry: CropGeometry;
293
+ }
294
+
295
+ /**
296
+ * Crops at native resolution, picking the cheapest technique that is exact:
297
+ * axis-aligned rectangles use plain canvas drawing, other quads need an OpenCV warp.
298
+ * When OpenCV cannot be loaded, a perspective crop degrades to its bounding box.
299
+ */
123
300
  // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
124
- function cropImageAtFullResolution(cv: any, imageUrl: string, relCorners: Quad): Promise<Blob> {
301
+ async function cropAtFullResolution(cv: any | null, imageUrl: string, relCorners: Quad): Promise<CropOutput> {
302
+ if (isAxisAlignedRect(relCorners)) {
303
+ return { blob: await rectCropAtFullResolution(imageUrl, relCorners), corners: relCorners, geometry: "rect" };
304
+ }
305
+
306
+ let cvInstance = cv ?? ((await ensureOpenCV()) ? window.cv : null);
307
+ if (!cvInstance) {
308
+ console.warn(
309
+ "[ImageEditor] OpenCV unavailable — cropping to the selection's bounding box without perspective correction.",
310
+ );
311
+ let bounds = boundingQuad(relCorners);
312
+ return { blob: await rectCropAtFullResolution(imageUrl, bounds), corners: bounds, geometry: "rect" };
313
+ }
314
+
315
+ return {
316
+ blob: await cropImageAtFullResolution(cvInstance, imageUrl, relCorners),
317
+ corners: relCorners,
318
+ geometry: "perspective",
319
+ };
320
+ }
321
+
322
+ /** Crops an axis-aligned rectangle with the 2D canvas API — no OpenCV required. */
323
+ async function rectCropAtFullResolution(imageUrl: string, relCorners: Quad): Promise<Blob> {
324
+ let img = await loadImage(imageUrl);
325
+ let [tl, , br] = boundingQuad(relCorners);
326
+ let x = Math.round(tl.x * img.naturalWidth);
327
+ let y = Math.round(tl.y * img.naturalHeight);
328
+ let width = Math.max(1, Math.round((br.x - tl.x) * img.naturalWidth));
329
+ let height = Math.max(1, Math.round((br.y - tl.y) * img.naturalHeight));
330
+
331
+ let canvas = document.createElement("canvas");
332
+ canvas.width = width;
333
+ canvas.height = height;
334
+ canvas.getContext("2d")!.drawImage(img, x, y, width, height, 0, 0, width, height);
335
+
336
+ return canvasToPngBlob(canvas);
337
+ }
338
+
339
+ function loadImage(url: string): Promise<HTMLImageElement> {
125
340
  return new Promise((resolve, reject) => {
126
341
  let img = new Image();
127
- img.onload = () => {
128
- let canvas = document.createElement("canvas");
129
- canvas.width = img.naturalWidth;
130
- canvas.height = img.naturalHeight;
131
- canvas.getContext("2d")!.drawImage(img, 0, 0);
132
- let absCorners = relCorners.map((c) => ({
133
- x: c.x * img.naturalWidth,
134
- y: c.y * img.naturalHeight,
135
- })) as Quad;
136
- perspectiveCrop(cv, canvas, absCorners).then(resolve, reject);
137
- };
342
+ img.onload = () => resolve(img);
138
343
  img.onerror = () => reject(new Error("Failed to load image for crop"));
139
- img.src = imageUrl;
344
+ img.src = url;
345
+ });
346
+ }
347
+
348
+ function canvasToPngBlob(canvas: HTMLCanvasElement): Promise<Blob> {
349
+ return new Promise<Blob>((resolve, reject) => {
350
+ // PNG is lossless — critical for receipts and screenshots where JPEG
351
+ // compression would make text unreadable.
352
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/png");
140
353
  });
141
354
  }
142
355
 
356
+ /** Loads the image at native resolution, maps relative corners, and warps. */
357
+ // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
358
+ async function cropImageAtFullResolution(cv: any, imageUrl: string, relCorners: Quad): Promise<Blob> {
359
+ let img = await loadImage(imageUrl);
360
+ let canvas = document.createElement("canvas");
361
+ canvas.width = img.naturalWidth;
362
+ canvas.height = img.naturalHeight;
363
+ canvas.getContext("2d")!.drawImage(img, 0, 0);
364
+ let absCorners = relCorners.map((c) => ({
365
+ x: c.x * img.naturalWidth,
366
+ y: c.y * img.naturalHeight,
367
+ })) as Quad;
368
+ return perspectiveCrop(cv, canvas, absCorners);
369
+ }
370
+
143
371
  /** Performs a perspective warp using OpenCV.js. */
144
372
  // oxlint-disable-next-line typescript/no-explicit-any -- OpenCV.js types
145
373
  function perspectiveCrop(cv: any, srcCanvas: HTMLCanvasElement, corners: Quad): Promise<Blob> {
@@ -158,19 +386,18 @@ function perspectiveCrop(cv: any, srcCanvas: HTMLCanvasElement, corners: Quad):
158
386
  cv.imshow(outCanvas, dst);
159
387
  for (let m of [src, dst, srcPts, dstPts, M]) m.delete();
160
388
 
161
- return new Promise<Blob>((resolve, reject) => {
162
- // PNG is lossless — critical for receipts and screenshots where JPEG
163
- // compression would make text unreadable.
164
- outCanvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), "image/png");
165
- });
389
+ return canvasToPngBlob(outCanvas);
166
390
  }
167
391
 
168
392
  /**
169
393
  * Standalone replay handler for the "crop" action type.
170
394
  * Corners are stored as relative (0–1) values so they work at any resolution.
395
+ * Rectangular crops replay without OpenCV; older actions without a stored mode
396
+ * are treated as perspective crops.
171
397
  */
172
398
  export async function replayCrop(imageUrl: string, params: Record<string, unknown>): Promise<Blob> {
173
- await loadOpenCV();
174
399
  let relCorners = params.corners as Quad;
175
- return cropImageAtFullResolution(window.cv, imageUrl, relCorners);
400
+ if (params.mode === "rect") return rectCropAtFullResolution(imageUrl, relCorners);
401
+ let { blob } = await cropAtFullResolution(null, imageUrl, relCorners);
402
+ return blob;
176
403
  }
@@ -9,6 +9,14 @@ export function useZoom(): ZoomPanResult {
9
9
  return ctx;
10
10
  }
11
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
+
12
20
  export function ZoomProvider({ children }: { children: ReactNode }) {
13
21
  let state = useZoomPan();
14
22
  return <ZoomContext value={state}>{children}</ZoomContext>;