@wordpress/media-editor 0.11.1 → 0.11.2-next.v.202606191442.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 (138) hide show
  1. package/build/components/media-editor/index.cjs.map +1 -1
  2. package/build/components/media-editor/use-crop-options.cjs.map +1 -1
  3. package/build/components/media-editor-canvas/index.cjs +63 -15
  4. package/build/components/media-editor-canvas/index.cjs.map +3 -3
  5. package/build/components/media-editor-fine-rotation/index.cjs.map +1 -1
  6. package/build/components/media-editor-image-controls/index.cjs +2 -2
  7. package/build/components/media-editor-image-controls/index.cjs.map +2 -2
  8. package/build/components/media-editor-keyboard-shortcuts-modal/index.cjs +4 -4
  9. package/build/components/media-editor-keyboard-shortcuts-modal/index.cjs.map +2 -2
  10. package/build/components/media-editor-modal/build-modifiers.cjs.map +1 -1
  11. package/build/components/rotation-ruler/index.cjs +1 -1
  12. package/build/components/rotation-ruler/index.cjs.map +1 -1
  13. package/build/components/rotation-ruler/use-ruler-drag.cjs.map +1 -1
  14. package/build/image-editor/core/camera.cjs +13 -0
  15. package/build/image-editor/core/camera.cjs.map +2 -2
  16. package/build/image-editor/core/constants.cjs +12 -3
  17. package/build/image-editor/core/constants.cjs.map +2 -2
  18. package/build/image-editor/core/containment.cjs.map +1 -1
  19. package/build/image-editor/core/crop-rect.cjs.map +1 -1
  20. package/build/image-editor/core/export/canvas-renderer.cjs.map +1 -1
  21. package/build/image-editor/core/interaction-controller.cjs +9 -7
  22. package/build/image-editor/core/interaction-controller.cjs.map +2 -2
  23. package/build/image-editor/core/math/sanitize.cjs.map +1 -1
  24. package/build/image-editor/core/setter-helpers.cjs.map +1 -1
  25. package/build/image-editor/core/source-region.cjs +111 -2
  26. package/build/image-editor/core/source-region.cjs.map +2 -2
  27. package/build/image-editor/core/state.cjs.map +1 -1
  28. package/build/image-editor/core/stencil-math.cjs +3 -4
  29. package/build/image-editor/core/stencil-math.cjs.map +2 -2
  30. package/build/image-editor/core/transform-style.cjs.map +1 -1
  31. package/build/image-editor/core/types.cjs.map +1 -1
  32. package/build/image-editor/react/components/cropper.cjs +232 -55
  33. package/build/image-editor/react/components/cropper.cjs.map +2 -2
  34. package/build/image-editor/react/components/overlays/dimensions-overlay.cjs.map +1 -1
  35. package/build/image-editor/react/components/overlays/dimming-overlay.cjs +1 -0
  36. package/build/image-editor/react/components/overlays/dimming-overlay.cjs.map +2 -2
  37. package/build/image-editor/react/components/stencils/rectangle-stencil.cjs +65 -19
  38. package/build/image-editor/react/components/stencils/rectangle-stencil.cjs.map +2 -2
  39. package/build/image-editor/react/hooks/build-cropper-setters.cjs.map +1 -1
  40. package/build/image-editor/react/hooks/use-cropper-reducer.cjs +1 -1
  41. package/build/image-editor/react/hooks/use-cropper-reducer.cjs.map +2 -2
  42. package/build/image-editor/react/hooks/use-interaction.cjs.map +1 -1
  43. package/build/image-editor/react/hooks/use-viewport-state.cjs.map +1 -1
  44. package/build/index.cjs.map +1 -1
  45. package/build/state/types.cjs.map +1 -1
  46. package/build/state/use-media-editor-state.cjs +1 -1
  47. package/build/state/use-media-editor-state.cjs.map +2 -2
  48. package/build-module/components/media-editor/index.mjs.map +1 -1
  49. package/build-module/components/media-editor/use-crop-options.mjs.map +1 -1
  50. package/build-module/components/media-editor-canvas/index.mjs +55 -17
  51. package/build-module/components/media-editor-canvas/index.mjs.map +2 -2
  52. package/build-module/components/media-editor-fine-rotation/index.mjs.map +1 -1
  53. package/build-module/components/media-editor-image-controls/index.mjs +2 -2
  54. package/build-module/components/media-editor-image-controls/index.mjs.map +2 -2
  55. package/build-module/components/media-editor-keyboard-shortcuts-modal/index.mjs +4 -4
  56. package/build-module/components/media-editor-keyboard-shortcuts-modal/index.mjs.map +2 -2
  57. package/build-module/components/media-editor-modal/build-modifiers.mjs.map +1 -1
  58. package/build-module/components/rotation-ruler/index.mjs +1 -1
  59. package/build-module/components/rotation-ruler/index.mjs.map +1 -1
  60. package/build-module/components/rotation-ruler/use-ruler-drag.mjs.map +1 -1
  61. package/build-module/image-editor/core/camera.mjs +12 -0
  62. package/build-module/image-editor/core/camera.mjs.map +2 -2
  63. package/build-module/image-editor/core/constants.mjs +8 -2
  64. package/build-module/image-editor/core/constants.mjs.map +2 -2
  65. package/build-module/image-editor/core/containment.mjs.map +1 -1
  66. package/build-module/image-editor/core/crop-rect.mjs.map +1 -1
  67. package/build-module/image-editor/core/export/canvas-renderer.mjs.map +1 -1
  68. package/build-module/image-editor/core/interaction-controller.mjs +9 -7
  69. package/build-module/image-editor/core/interaction-controller.mjs.map +2 -2
  70. package/build-module/image-editor/core/math/sanitize.mjs.map +1 -1
  71. package/build-module/image-editor/core/setter-helpers.mjs.map +1 -1
  72. package/build-module/image-editor/core/source-region.mjs +108 -1
  73. package/build-module/image-editor/core/source-region.mjs.map +2 -2
  74. package/build-module/image-editor/core/state.mjs.map +1 -1
  75. package/build-module/image-editor/core/stencil-math.mjs +3 -4
  76. package/build-module/image-editor/core/stencil-math.mjs.map +2 -2
  77. package/build-module/image-editor/core/transform-style.mjs.map +1 -1
  78. package/build-module/image-editor/react/components/cropper.mjs +242 -57
  79. package/build-module/image-editor/react/components/cropper.mjs.map +2 -2
  80. package/build-module/image-editor/react/components/overlays/dimensions-overlay.mjs.map +1 -1
  81. package/build-module/image-editor/react/components/overlays/dimming-overlay.mjs +1 -0
  82. package/build-module/image-editor/react/components/overlays/dimming-overlay.mjs.map +2 -2
  83. package/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs +65 -19
  84. package/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs.map +2 -2
  85. package/build-module/image-editor/react/hooks/build-cropper-setters.mjs.map +1 -1
  86. package/build-module/image-editor/react/hooks/use-cropper-reducer.mjs +1 -1
  87. package/build-module/image-editor/react/hooks/use-cropper-reducer.mjs.map +2 -2
  88. package/build-module/image-editor/react/hooks/use-interaction.mjs.map +1 -1
  89. package/build-module/image-editor/react/hooks/use-viewport-state.mjs.map +1 -1
  90. package/build-module/index.mjs.map +1 -1
  91. package/build-module/state/types.mjs.map +1 -1
  92. package/build-module/state/use-media-editor-state.mjs +1 -1
  93. package/build-module/state/use-media-editor-state.mjs.map +2 -2
  94. package/build-style/style-rtl.css +49 -6
  95. package/build-style/style.css +49 -6
  96. package/build-types/components/media-editor-canvas/index.d.ts.map +1 -1
  97. package/build-types/image-editor/core/camera.d.ts +25 -1
  98. package/build-types/image-editor/core/camera.d.ts.map +1 -1
  99. package/build-types/image-editor/core/constants.d.ts +20 -1
  100. package/build-types/image-editor/core/constants.d.ts.map +1 -1
  101. package/build-types/image-editor/core/interaction-controller.d.ts.map +1 -1
  102. package/build-types/image-editor/core/source-region.d.ts +23 -1
  103. package/build-types/image-editor/core/source-region.d.ts.map +1 -1
  104. package/build-types/image-editor/core/stencil-math.d.ts +10 -5
  105. package/build-types/image-editor/core/stencil-math.d.ts.map +1 -1
  106. package/build-types/image-editor/core/types.d.ts +14 -0
  107. package/build-types/image-editor/core/types.d.ts.map +1 -1
  108. package/build-types/image-editor/react/components/cropper.d.ts.map +1 -1
  109. package/build-types/image-editor/react/components/overlays/dimming-overlay.d.ts.map +1 -1
  110. package/build-types/image-editor/react/components/stencils/rectangle-stencil.d.ts +17 -14
  111. package/build-types/image-editor/react/components/stencils/rectangle-stencil.d.ts.map +1 -1
  112. package/package.json +25 -20
  113. package/src/components/media-editor/style.scss +21 -9
  114. package/src/components/media-editor-canvas/index.tsx +82 -13
  115. package/src/components/media-editor-canvas/style.scss +41 -0
  116. package/src/image-editor/core/camera.ts +60 -1
  117. package/src/image-editor/core/constants.ts +23 -1
  118. package/src/image-editor/core/interaction-controller.ts +25 -11
  119. package/src/image-editor/core/source-region.ts +202 -1
  120. package/src/image-editor/core/stencil-math.ts +23 -14
  121. package/src/image-editor/core/test/camera.ts +272 -1
  122. package/src/image-editor/core/test/interaction-controller.ts +100 -0
  123. package/src/image-editor/core/test/stencil-math.ts +120 -6
  124. package/src/image-editor/core/types.ts +17 -0
  125. package/src/image-editor/react/components/cropper.tsx +362 -72
  126. package/src/image-editor/react/components/overlays/dimming-overlay.tsx +1 -0
  127. package/src/image-editor/react/components/stencils/rectangle-stencil.tsx +101 -32
  128. package/src/image-editor/react/components/stencils/test/rectangle-stencil.tsx +169 -17
  129. package/src/image-editor/react/components/test/cropper.tsx +689 -6
  130. package/tsconfig.tsbuildinfo +1 -1
  131. package/build-types/components/media-editor-toolbar/index.d.ts +0 -24
  132. package/build-types/components/media-editor-toolbar/index.d.ts.map +0 -1
  133. package/build-types/components/media-editor-transform-controls/index.d.ts +0 -21
  134. package/build-types/components/media-editor-transform-controls/index.d.ts.map +0 -1
  135. package/build-types/components/media-form/sidebar-datetime-view.d.ts +0 -10
  136. package/build-types/components/media-form/sidebar-datetime-view.d.ts.map +0 -1
  137. package/build-types/image-editor/react/hooks/use-cropper-state.d.ts +0 -108
  138. package/build-types/image-editor/react/hooks/use-cropper-state.d.ts.map +0 -1
@@ -1,7 +1,14 @@
1
+ /**
2
+ * External dependencies
3
+ */
4
+ import clsx from 'clsx';
5
+
1
6
  /**
2
7
  * WordPress dependencies
3
8
  */
4
- import { useCallback, useEffect, useMemo } from '@wordpress/element';
9
+ import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
10
+ import { Spinner } from '@wordpress/components';
11
+ import { __ } from '@wordpress/i18n';
5
12
 
6
13
  /**
7
14
  * Internal dependencies
@@ -48,6 +55,13 @@ export default function MediaEditorCanvas( {
48
55
  const cropperImage = controller.state.image;
49
56
  const { beginGesture, endGesture, setImage } = controller;
50
57
 
58
+ // Tracks whether the image pixels have actually loaded. The cropper's
59
+ // geometry is driven by the known media dimensions, so its handles and
60
+ // overlays would otherwise appear before the image finishes streaming in.
61
+ const [ status, setStatus ] = useState< 'loading' | 'loaded' | 'error' >(
62
+ 'loading'
63
+ );
64
+
51
65
  // Resolved aspect ratio is derived from the preset key + the
52
66
  // loaded image (for the "Original" preset). The reducer doesn't
53
67
  // store this number — only the preset key — so it's a render-time
@@ -90,23 +104,78 @@ export default function MediaEditorCanvas( {
90
104
  } );
91
105
  }, [ cropperImage, mediaUrl, mediaWidth, mediaHeight, setImage ] );
92
106
 
93
- if ( ! mediaUrl || mediaType.type !== 'image' ) {
107
+ const isImage = mediaType.type === 'image';
108
+
109
+ // Probe the image to know when its pixels have loaded (or failed),
110
+ // independent of the cropper. The browser shares one fetch/cache with the
111
+ // cropper's own `<img>`, so this adds no network cost. The cropper stays
112
+ // framework-pure — load/error handling lives here in the wrapper layer.
113
+ useEffect( () => {
114
+ if ( ! mediaUrl || ! isImage ) {
115
+ return;
116
+ }
117
+ setStatus( 'loading' );
118
+ const probe = new window.Image();
119
+ probe.onload = () => setStatus( 'loaded' );
120
+ probe.onerror = () => setStatus( 'error' );
121
+ probe.src = mediaUrl;
122
+ // Cached images may already be complete before listeners attach.
123
+ if ( probe.complete ) {
124
+ setStatus( probe.naturalWidth > 0 ? 'loaded' : 'error' );
125
+ }
126
+ return () => {
127
+ probe.onload = null;
128
+ probe.onerror = null;
129
+ };
130
+ }, [ mediaUrl, isImage ] );
131
+
132
+ if ( ! mediaUrl || ! isImage ) {
94
133
  return null;
95
134
  }
96
135
 
136
+ if ( status === 'error' ) {
137
+ return (
138
+ <div className="media-editor-canvas">
139
+ <div className="media-editor-canvas__error" role="alert">
140
+ <p>{ __( 'Failed to load image.' ) }</p>
141
+ </div>
142
+ </div>
143
+ );
144
+ }
145
+
97
146
  return (
98
147
  <div className="media-editor-canvas">
99
- <Cropper
100
- src={ mediaUrl }
101
- controller={ controller }
102
- aspectRatio={ aspectRatio }
103
- freeformCrop
104
- focusOnMount={ focusOnMount }
105
- showGrid="interactive"
106
- isPlacementActive={ isPlacementActive }
107
- onGestureStart={ handleGestureStart }
108
- onGestureEnd={ handleGestureEnd }
109
- />
148
+ { status === 'loading' && (
149
+ <div className="media-editor-canvas__spinner">
150
+ <Spinner />
151
+ </div>
152
+ ) }
153
+ { /*
154
+ * The cropper stays mounted while loading (hidden behind the
155
+ * spinner) so the image decodes off-screen and reveals in one paint
156
+ * instead of streaming in top-to-bottom. Until it's revealed it's
157
+ * non-interactive (`pointer-events: none` in CSS), and focus is
158
+ * withheld by gating `focusOnMount` on the loaded state — the
159
+ * cropper's focus effect keys off that prop, so focus lands on the
160
+ * crop area only once it's visible.
161
+ */ }
162
+ <div
163
+ className={ clsx( 'media-editor-canvas__cropper', {
164
+ 'is-loaded': status === 'loaded',
165
+ } ) }
166
+ >
167
+ <Cropper
168
+ src={ mediaUrl }
169
+ controller={ controller }
170
+ aspectRatio={ aspectRatio }
171
+ freeformCrop
172
+ focusOnMount={ focusOnMount && status === 'loaded' }
173
+ showGrid="interactive"
174
+ isPlacementActive={ isPlacementActive }
175
+ onGestureStart={ handleGestureStart }
176
+ onGestureEnd={ handleGestureEnd }
177
+ />
178
+ </div>
110
179
  </div>
111
180
  );
112
181
  }
@@ -1,3 +1,6 @@
1
+ @use "@wordpress/base-styles/animations" as *;
2
+ @use "@wordpress/base-styles/colors" as *;
3
+
1
4
  // The canvas wrapper fills the modal's canvas area so the cropper has a
2
5
  // sized parent (the cropper uses 100% width/height of its container).
3
6
  // `position: relative` establishes a stacking context for any future
@@ -6,4 +9,42 @@
6
9
  position: relative;
7
10
  width: 100%;
8
11
  height: 100%;
12
+
13
+ // The cropper stays mounted while loading so the image decodes behind the
14
+ // spinner and reveals in one paint. It's hidden and non-interactive until
15
+ // the image has loaded, then fades in.
16
+ &__cropper {
17
+ width: 100%;
18
+ height: 100%;
19
+ opacity: 0;
20
+ pointer-events: none;
21
+
22
+ // Explicit `opacity: 1` (not just the animation's fill mode) keeps the
23
+ // cropper visible for reduced-motion users, since `animation__fade-in`
24
+ // is gated behind `@media not (prefers-reduced-motion)`.
25
+ &.is-loaded {
26
+ opacity: 1;
27
+ pointer-events: auto;
28
+ @include animation__fade-in( 0.2s );
29
+ }
30
+ }
31
+
32
+ &__spinner {
33
+ position: absolute;
34
+ top: 50%;
35
+ left: 50%;
36
+ transform: translate(-50%, -50%);
37
+ }
38
+
39
+ // Centered fallback shown in place of the cropper when the image
40
+ // fails to load.
41
+ &__error {
42
+ display: flex;
43
+ align-items: center;
44
+ justify-content: center;
45
+ width: 100%;
46
+ height: 100%;
47
+ color: $gray-700;
48
+ text-align: center;
49
+ }
9
50
  }
@@ -6,7 +6,13 @@ import { mat2d, vec2 } from 'gl-matrix';
6
6
  /**
7
7
  * Internal dependencies
8
8
  */
9
- import type { CropperState, NormalizedPoint, Size, Camera } from './types';
9
+ import type {
10
+ CropperState,
11
+ NormalizedPoint,
12
+ NormalizedRect,
13
+ Size,
14
+ Camera,
15
+ } from './types';
10
16
  import { degreesToRadians } from './math/rotation';
11
17
  import {
12
18
  isSafeNumber,
@@ -111,6 +117,59 @@ export function getImageFit(
111
117
  };
112
118
  }
113
119
 
120
+ /**
121
+ * Resolve the presentational view magnification that makes the crop fill the
122
+ * canvas.
123
+ *
124
+ * The crop overlay is laid out as `cropRect * visualSize` (the contain-fit
125
+ * footprint, with no zoom), so its on-screen size is capped by that footprint.
126
+ * When a crop's aspect differs from the image's, it can be much smaller than
127
+ * the canvas could show (e.g. a square crop in a tall image is bound by the
128
+ * footprint's narrow axis). Scaling `elementSize` and `visualSize` together by
129
+ * the returned factor uniformly magnifies the whole scene — image, crop
130
+ * overlay, and overlays — so the crop reaches `targetFill` of its constraining
131
+ * canvas axis, with the image bleeding past the canvas (clipped by the host).
132
+ *
133
+ * Purely presentational: it does not touch `zoom`/`pan`/`cropRect`/`rotation`,
134
+ * so the framed source region — and therefore the export — is unchanged.
135
+ *
136
+ * @param cropRect The crop rectangle, normalized to the footprint.
137
+ * @param canvasSize The canvas size in pixels.
138
+ * @param visualSize The contain-fit (rotated) image footprint in pixels.
139
+ * @param targetFill Fraction of the constraining canvas axis to fill (0–1].
140
+ * @param maxScale Upper bound on the magnification.
141
+ * @return A magnification factor in [1, maxScale]; 1 when none is needed.
142
+ */
143
+ export function getViewScale(
144
+ cropRect: NormalizedRect,
145
+ canvasSize: Size,
146
+ visualSize: Size,
147
+ targetFill: number,
148
+ maxScale: number
149
+ ): number {
150
+ const cropScreenW = cropRect.width * visualSize.width;
151
+ const cropScreenH = cropRect.height * visualSize.height;
152
+ // `> 0` comparisons (rather than `<= 0`) reject NaN as well as zero and
153
+ // negatives, so a non-finite rect/dimension/scale can't propagate to a
154
+ // `scale(NaN)`. `isValidSize` already guards finiteness of the sizes.
155
+ if (
156
+ ! isValidSize( canvasSize ) ||
157
+ ! isValidSize( visualSize ) ||
158
+ ! ( cropScreenW > 0 ) ||
159
+ ! ( cropScreenH > 0 ) ||
160
+ ! Number.isFinite( targetFill ) ||
161
+ ! Number.isFinite( maxScale ) ||
162
+ ! ( targetFill > 0 ) ||
163
+ ! ( maxScale >= 1 )
164
+ ) {
165
+ return 1;
166
+ }
167
+ const kW = ( targetFill * canvasSize.width ) / cropScreenW;
168
+ const kH = ( targetFill * canvasSize.height ) / cropScreenH;
169
+ const k = Math.min( kW, kH );
170
+ return Math.min( maxScale, Math.max( 1, k ) );
171
+ }
172
+
114
173
  /**
115
174
  * Compose a camera matrix from cropper state, container, and image dimensions.
116
175
  *
@@ -28,7 +28,7 @@ export const MAX_ZOOM = 10;
28
28
  * enough to allow tight crops (favicons, icons). Adjust here to tune the
29
29
  * floor globally.
30
30
  */
31
- export const MIN_CROP_PIXELS = 24;
31
+ export const MIN_CROP_PIXELS = 16;
32
32
 
33
33
  /**
34
34
  * Minimum on-screen crop rect dimension in CSS pixels. The source-pixel
@@ -41,6 +41,28 @@ export const MIN_CROP_PIXELS = 24;
41
41
  */
42
42
  export const MIN_CROP_SCREEN_PX = 44;
43
43
 
44
+ /**
45
+ * Fraction of the constraining canvas axis the settled crop should occupy on
46
+ * screen. When a crop is shown smaller than this (e.g. a square crop in a tall
47
+ * image, capped by the contain-fit footprint's narrow axis), the view magnifies
48
+ * to fill the canvas. `1` = always fill the canvas; lower = rescue only the
49
+ * under-filled cases. See `getViewScale`.
50
+ */
51
+ export const SETTLE_TARGET_CANVAS_FILL = 0.8;
52
+
53
+ /**
54
+ * Upper bound on the presentational view magnification (`getViewScale`).
55
+ * Prevents a near-degenerate crop from magnifying the scene without limit.
56
+ */
57
+ export const MAX_VIEW_SCALE = 8;
58
+
59
+ /**
60
+ * CSS pixels per source pixel required before resize handles snap the selected
61
+ * source region to whole-pixel edges. Below 1:1, a source pixel is sub-pixel on
62
+ * screen, so snapping would feel notchy without a visible pixel boundary.
63
+ */
64
+ export const PIXEL_SNAP_DISPLAY_SCALE = 1;
65
+
44
66
  /**
45
67
  * Wheel zoom sensitivity. A deltaY of 100 changes zoom by 0.25.
46
68
  * This could be made configurable as a prop to the Cropper component.
@@ -286,6 +286,11 @@ export class InteractionController {
286
286
  if ( e.button !== 0 ) {
287
287
  return;
288
288
  }
289
+ // Touch gestures are handled by touchstart/touchmove. Starting the
290
+ // pointer drag path too can briefly toggle drag UI before pinch begins.
291
+ if ( e.pointerType === 'touch' ) {
292
+ return;
293
+ }
289
294
  e.preventDefault();
290
295
 
291
296
  // Blur any focused handle so its focus ring doesn't linger,
@@ -568,6 +573,7 @@ export class InteractionController {
568
573
  if ( ! touch ) {
569
574
  return;
570
575
  }
576
+ moveEvent.preventDefault();
571
577
 
572
578
  cancelAnimationFrame( this.rafId );
573
579
  this.rafId = requestAnimationFrame( () => {
@@ -641,20 +647,28 @@ export class InteractionController {
641
647
  ? ( my - startMy ) / visSize.height
642
648
  : 0;
643
649
 
644
- // Focal-point zoom correction.
645
- const zoomRatio = s.zoom !== 0 ? 1 - newZoom / s.zoom : 0;
646
- const focalNormX = mx / visSize.width;
647
- const focalNormY = my / visSize.height;
648
- const zoomCropX =
649
- s.pan.x + ( focalNormX - s.pan.x ) * zoomRatio;
650
- const zoomCropY =
651
- s.pan.y + ( focalNormY - s.pan.y ) * zoomRatio;
650
+ // Focal-point zoom correction. Keep this based on the
651
+ // pinch-start state; using the current reducer state here
652
+ // compounds prior touchmove frames and makes a fixed pinch
653
+ // center drift after the image is already zoomed or panned.
654
+ const zoomRatio =
655
+ touch.startZoom !== 0
656
+ ? 1 - newZoom / touch.startZoom
657
+ : 0;
658
+ const startFocalNormX = startMx / visSize.width;
659
+ const startFocalNormY = startMy / visSize.height;
652
660
 
653
- // Combined: pan drift + zoom correction.
661
+ // Combined: midpoint drift + zoom around the pinch-start
662
+ // midpoint, so moving both fingers together pans while
663
+ // symmetric pinches keep the start center stationary.
654
664
  const newCropX =
655
- touch.startPanX + panDx + ( zoomCropX - s.pan.x );
665
+ touch.startPanX +
666
+ panDx +
667
+ ( startFocalNormX - touch.startPanX ) * zoomRatio;
656
668
  const newCropY =
657
- touch.startPanY + panDy + ( zoomCropY - s.pan.y );
669
+ touch.startPanY +
670
+ panDy +
671
+ ( startFocalNormY - touch.startPanY ) * zoomRatio;
658
672
 
659
673
  const { pan: clampedCrop } = restrictPanZoom(
660
674
  {
@@ -6,9 +6,15 @@ import { mat2d, vec2 } from 'gl-matrix';
6
6
  /**
7
7
  * Internal dependencies
8
8
  */
9
- import type { CropperState, Size } from './types';
9
+ import type {
10
+ CropperState,
11
+ HandlePosition,
12
+ NormalizedRect,
13
+ Size,
14
+ } from './types';
10
15
  import { createCamera, getRotatedBBox, getVisibleBounds } from './camera';
11
16
  import { isValidSize, sanitizeCropperState } from './math/sanitize';
17
+ import { normalizeRotation } from './math/rotation';
12
18
 
13
19
  /**
14
20
  * The selected image region in source-pixel coordinates.
@@ -127,6 +133,201 @@ export function getSourceRegion(
127
133
  };
128
134
  }
129
135
 
136
+ /**
137
+ * Convert a source-pixel region back to the cropper's normalized crop rect.
138
+ *
139
+ * The math intentionally mirrors `getSourceRegion`: map the requested source
140
+ * center through the current camera, then express that screen point inside the
141
+ * same base visible bounds used to position crop overlays.
142
+ *
143
+ * @param state The current cropper state.
144
+ * @param imageSize The natural dimensions of the source image.
145
+ * @param region The source-pixel region to represent as a crop rect.
146
+ * @return The normalized crop rect, or null when inputs cannot be mapped.
147
+ */
148
+ function getCropRectFromSourceRegion(
149
+ state: CropperState,
150
+ imageSize: Size,
151
+ region: SourceRegion
152
+ ): NormalizedRect | null {
153
+ if (
154
+ ! isValidSize( imageSize ) ||
155
+ region.width <= 0 ||
156
+ region.height <= 0
157
+ ) {
158
+ return null;
159
+ }
160
+
161
+ const safeState = sanitizeCropperState( state );
162
+ const syntheticContainer: Size = { width: 1000, height: 1000 };
163
+ const baseCamera = createCamera(
164
+ { ...safeState, pan: { x: 0, y: 0 }, zoom: 1 },
165
+ syntheticContainer,
166
+ imageSize
167
+ );
168
+ const visibleBounds = getVisibleBounds( baseCamera );
169
+ if ( visibleBounds.width <= 0 || visibleBounds.height <= 0 ) {
170
+ return null;
171
+ }
172
+
173
+ const sourceCenter = vec2.fromValues(
174
+ ( region.x + region.width / 2 ) / imageSize.width,
175
+ ( region.y + region.height / 2 ) / imageSize.height
176
+ );
177
+ const screenCenter = vec2.create();
178
+ const camera = createCamera( safeState, syntheticContainer, imageSize );
179
+ vec2.transformMat2d( screenCenter, sourceCenter, camera );
180
+
181
+ const snapRotation = Math.round( safeState.rotation / 90 ) * 90;
182
+ const { width: rotW, height: rotH } = getRotatedBBox(
183
+ imageSize.width,
184
+ imageSize.height,
185
+ snapRotation
186
+ );
187
+ if ( rotW <= 0 || rotH <= 0 ) {
188
+ return null;
189
+ }
190
+
191
+ const width = ( region.width * safeState.zoom ) / rotW;
192
+ const height = ( region.height * safeState.zoom ) / rotH;
193
+ const centerX =
194
+ ( screenCenter[ 0 ] - visibleBounds.left ) / visibleBounds.width;
195
+ const centerY =
196
+ ( screenCenter[ 1 ] - visibleBounds.top ) / visibleBounds.height;
197
+
198
+ return {
199
+ x: centerX - width / 2,
200
+ y: centerY - height / 2,
201
+ width,
202
+ height,
203
+ };
204
+ }
205
+
206
+ interface SourcePixelSnapEdges {
207
+ left: boolean;
208
+ top: boolean;
209
+ right: boolean;
210
+ bottom: boolean;
211
+ }
212
+
213
+ const CARDINAL_ROTATION_EPSILON = 1e-6;
214
+
215
+ /**
216
+ * Check whether a rotation is effectively at a 90-degree stop.
217
+ *
218
+ * @param rotation The rotation angle in degrees.
219
+ * @return Whether the rotation is close enough to a cardinal angle.
220
+ */
221
+ function isCardinalRotation( rotation: number ): boolean {
222
+ const normalizedRotation = normalizeRotation( rotation );
223
+ const nearestCardinal = Math.round( normalizedRotation / 90 ) * 90;
224
+ return (
225
+ Math.abs( normalizedRotation - nearestCardinal ) <
226
+ CARDINAL_ROTATION_EPSILON
227
+ );
228
+ }
229
+
230
+ /**
231
+ * Snap a crop rect so the selected source-region edges land on whole pixels.
232
+ *
233
+ * This is a display-time affordance for visible pixel grids; it does not alter
234
+ * pan/zoom/rotation. Callers decide when snapping is appropriate.
235
+ *
236
+ * @param state The current cropper state.
237
+ * @param imageSize The natural dimensions of the source image.
238
+ * @param cropRect The candidate crop rect from resize math.
239
+ * @param handle The active resize handle. Only edges moved by the handle snap.
240
+ * @return A crop rect whose selected source-region edges are whole pixels.
241
+ */
242
+ export function snapCropRectToSourcePixels(
243
+ state: CropperState,
244
+ imageSize: Size,
245
+ cropRect: NormalizedRect,
246
+ handle: HandlePosition
247
+ ): NormalizedRect {
248
+ const safeState = sanitizeCropperState( state );
249
+ if ( ! isCardinalRotation( safeState.rotation ) ) {
250
+ return cropRect;
251
+ }
252
+
253
+ return snapCropRectEdgesToSourcePixels( safeState, imageSize, cropRect, {
254
+ left: handle.includes( 'w' ),
255
+ top: handle.includes( 'n' ),
256
+ right: handle.includes( 'e' ),
257
+ bottom: handle.includes( 's' ),
258
+ } );
259
+ }
260
+
261
+ /**
262
+ * Snap all source-region edges for a crop rect to the nearest whole pixels.
263
+ *
264
+ * @param state The current cropper state.
265
+ * @param imageSize The natural dimensions of the source image.
266
+ * @param cropRect The crop rect to align to the source-pixel grid.
267
+ * @return A crop rect whose source-region edges are whole pixels.
268
+ */
269
+ export function snapCropRectToSourcePixelGrid(
270
+ state: CropperState,
271
+ imageSize: Size,
272
+ cropRect: NormalizedRect
273
+ ): NormalizedRect {
274
+ return snapCropRectEdgesToSourcePixels( state, imageSize, cropRect, {
275
+ left: true,
276
+ top: true,
277
+ right: true,
278
+ bottom: true,
279
+ } );
280
+ }
281
+
282
+ function snapCropRectEdgesToSourcePixels(
283
+ state: CropperState,
284
+ imageSize: Size,
285
+ cropRect: NormalizedRect,
286
+ edges: SourcePixelSnapEdges
287
+ ): NormalizedRect {
288
+ if ( ! isValidSize( imageSize ) ) {
289
+ return cropRect;
290
+ }
291
+
292
+ const stateWithCrop = sanitizeCropperState( { ...state, cropRect } );
293
+ const region = getSourceRegion( stateWithCrop, imageSize );
294
+ const shouldSnapX = edges.left || edges.right;
295
+ const shouldSnapY = edges.top || edges.bottom;
296
+ const left = edges.left ? Math.round( region.x ) : region.x;
297
+ const top = edges.top ? Math.round( region.y ) : region.y;
298
+ const right = edges.right
299
+ ? Math.round( region.x + region.width )
300
+ : region.x + region.width;
301
+ const bottom = edges.bottom
302
+ ? Math.round( region.y + region.height )
303
+ : region.y + region.height;
304
+ if ( right <= left || bottom <= top ) {
305
+ return cropRect;
306
+ }
307
+
308
+ const snappedCropRect = getCropRectFromSourceRegion(
309
+ stateWithCrop,
310
+ imageSize,
311
+ {
312
+ ...region,
313
+ x: left,
314
+ y: top,
315
+ width: right - left,
316
+ height: bottom - top,
317
+ }
318
+ );
319
+ if ( ! snappedCropRect ) {
320
+ return cropRect;
321
+ }
322
+
323
+ return {
324
+ x: shouldSnapX ? snappedCropRect.x : cropRect.x,
325
+ y: shouldSnapY ? snappedCropRect.y : cropRect.y,
326
+ width: shouldSnapX ? snappedCropRect.width : cropRect.width,
327
+ height: shouldSnapY ? snappedCropRect.height : cropRect.height,
328
+ };
329
+ }
330
+
130
331
  /**
131
332
  * The selected crop region expressed as percentages of the source image.
132
333
  */
@@ -6,6 +6,9 @@ import type { HandlePosition, NormalizedRect, Size } from './types';
6
6
 
7
7
  export type { HandlePosition };
8
8
 
9
+ /** Axis whose resize distance controls the locked-ratio size projection. */
10
+ export type ResizeDriverAxis = 'width' | 'height';
11
+
9
12
  /**
10
13
  * Resolve the minimum crop dimension, in source-image pixels, for the current
11
14
  * display scale.
@@ -14,11 +17,12 @@ export type { HandlePosition };
14
17
  * avoids sub-pixel crops, and an on-screen floor (`MIN_CROP_SCREEN_PX`) that
15
18
  * keeps the crop large enough to grab. The on-screen floor converted to source
16
19
  * pixels is `MIN_CROP_SCREEN_PX / displayScale`; the binding constraint is the
17
- * larger of the two. When zoomed out (small `displayScale`) the on-screen floor
18
- * dominates; once the image is shown large enough the source-pixel floor takes
19
- * over.
20
+ * larger of the two. When the image is shown small (small `displayScale`) the
21
+ * on-screen floor dominates; once it is shown large enough the source-pixel
22
+ * floor takes over.
20
23
  *
21
- * @param displayScale CSS pixels rendered per source pixel (fit scale × zoom).
24
+ * @param displayScale CSS pixels rendered per source pixel
25
+ * (fit scale × zoom × view scale).
22
26
  * @return Minimum crop dimension in source-image pixels.
23
27
  */
24
28
  export function getMinCropPixels( displayScale: number ): number {
@@ -141,6 +145,8 @@ export function computeFreeResizeRect(
141
145
  * @param bounds The allowed crop area bounds.
142
146
  * @param normalizedRatio The locked aspect ratio (width / height in normalized space).
143
147
  * @param minCropSize Minimum crop rect dimension in normalized space, per axis.
148
+ * @param driverAxis Optional explicit driver axis. Used for keyboard
149
+ * resize, where one arrow axis should determine the step.
144
150
  * @return The new crop rect in normalized coordinates.
145
151
  */
146
152
  export function computeLockedResizeRect(
@@ -150,7 +156,8 @@ export function computeLockedResizeRect(
150
156
  imageSize: Size,
151
157
  bounds: CropBounds,
152
158
  normalizedRatio: number,
153
- minCropSize: Size = DEFAULT_MIN_CROP_SIZE
159
+ minCropSize: Size = DEFAULT_MIN_CROP_SIZE,
160
+ driverAxis?: ResizeDriverAxis
154
161
  ): NormalizedRect {
155
162
  // The math below divides by `normalizedRatio` and `imageSize`, so
156
163
  // bail out with the start rect when any of them is zero. This can
@@ -198,16 +205,18 @@ export function computeLockedResizeRect(
198
205
  distW = Math.max( distW, minDistW );
199
206
  distH = Math.max( distH, minDistH );
200
207
 
201
- // Determine which axis "drives" — whichever the user moved more
202
- // (in pixel space) determines the size, the other follows. The
203
- // `normalizedRatio` is w/h in normalized space; the equivalent
204
- // pixel-space ratio is `normalizedRatio * imageW / imageH`. We
205
- // compare the pixel motion ratio against that pixel-space ratio
206
- // so the units line up (was a unit mismatch on non-square images).
207
- const pixelDistW = distW * imageSize.width;
208
- const pixelDistH = distH * imageSize.height;
208
+ // Determine which axis "drives". Pointer drags use the dragged-corner
209
+ // geometry so the projected crop changes continuously as the pointer moves.
210
+ // Keyboard resize passes an explicit axis because a single-axis arrow step
211
+ // should drive that axis instead of being cancelled by the unchanged axis.
209
212
  const pixelRatio = ( normalizedRatio * imageSize.width ) / imageSize.height;
210
- if ( pixelDistW / pixelDistH > pixelRatio ) {
213
+ const isWidthDriver =
214
+ driverAxis === 'width' ||
215
+ ( ! driverAxis &&
216
+ ( distW * imageSize.width ) / ( distH * imageSize.height ) >
217
+ pixelRatio );
218
+
219
+ if ( isWidthDriver ) {
211
220
  // Width is the driver — compute height from ratio.
212
221
  distH = distW / normalizedRatio;
213
222
  } else {