@wordpress/media-editor 0.19.0 → 0.20.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 (142) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/build/components/media-editor/index.cjs +132 -50
  3. package/build/components/media-editor/index.cjs.map +2 -2
  4. package/build/components/media-editor/use-crop-options.cjs +1 -1
  5. package/build/components/media-editor/use-crop-options.cjs.map +2 -2
  6. package/build/components/media-editor/use-save-media-editor.cjs +36 -20
  7. package/build/components/media-editor/use-save-media-editor.cjs.map +2 -2
  8. package/build/components/media-editor-canvas/index.cjs +8 -8
  9. package/build/components/media-editor-canvas/index.cjs.map +2 -2
  10. package/build/components/media-editor-fine-rotation/index.cjs +1 -1
  11. package/build/components/media-editor-fine-rotation/index.cjs.map +2 -2
  12. package/build/components/media-editor-image-controls/index.cjs +46 -29
  13. package/build/components/media-editor-image-controls/index.cjs.map +2 -2
  14. package/build/components/media-editor-modal/index.cjs +17 -9
  15. package/build/components/media-editor-modal/index.cjs.map +2 -2
  16. package/build/hooks/use-crop-gesture-handlers.cjs +1 -1
  17. package/build/hooks/use-crop-gesture-handlers.cjs.map +2 -2
  18. package/build/image-editor/core/interaction-controller.cjs +5 -0
  19. package/build/image-editor/core/interaction-controller.cjs.map +2 -2
  20. package/build/image-editor/react/components/cropper.cjs +3 -3
  21. package/build/image-editor/react/components/cropper.cjs.map +2 -2
  22. package/build/image-editor/react/components/stencils/rectangle-stencil.cjs +1 -1
  23. package/build/image-editor/react/components/stencils/rectangle-stencil.cjs.map +2 -2
  24. package/build/image-editor/react/hooks/use-aria-announcer.cjs +3 -1
  25. package/build/image-editor/react/hooks/use-aria-announcer.cjs.map +2 -2
  26. package/build/image-editor/react/hooks/use-interaction.cjs +1 -1
  27. package/build/image-editor/react/hooks/use-interaction.cjs.map +2 -2
  28. package/build/state/composite-reducer.cjs +3 -3
  29. package/build/state/composite-reducer.cjs.map +2 -2
  30. package/build/state/index.cjs.map +1 -1
  31. package/build/state/media-editor-state-provider.cjs +1 -6
  32. package/build/state/media-editor-state-provider.cjs.map +2 -2
  33. package/build/state/use-media-editor-state.cjs +38 -36
  34. package/build/state/use-media-editor-state.cjs.map +2 -2
  35. package/build/store/actions.cjs +2 -0
  36. package/build/store/actions.cjs.map +2 -2
  37. package/build/store/reducer.cjs +3 -1
  38. package/build/store/reducer.cjs.map +2 -2
  39. package/build/store/selectors.cjs +5 -0
  40. package/build/store/selectors.cjs.map +2 -2
  41. package/build-module/components/media-editor/index.mjs +145 -52
  42. package/build-module/components/media-editor/index.mjs.map +2 -2
  43. package/build-module/components/media-editor/use-crop-options.mjs +1 -1
  44. package/build-module/components/media-editor/use-crop-options.mjs.map +2 -2
  45. package/build-module/components/media-editor/use-save-media-editor.mjs +36 -20
  46. package/build-module/components/media-editor/use-save-media-editor.mjs.map +2 -2
  47. package/build-module/components/media-editor-canvas/index.mjs +8 -8
  48. package/build-module/components/media-editor-canvas/index.mjs.map +2 -2
  49. package/build-module/components/media-editor-fine-rotation/index.mjs +1 -1
  50. package/build-module/components/media-editor-fine-rotation/index.mjs.map +2 -2
  51. package/build-module/components/media-editor-image-controls/index.mjs +47 -36
  52. package/build-module/components/media-editor-image-controls/index.mjs.map +2 -2
  53. package/build-module/components/media-editor-modal/index.mjs +17 -9
  54. package/build-module/components/media-editor-modal/index.mjs.map +2 -2
  55. package/build-module/hooks/use-crop-gesture-handlers.mjs +1 -1
  56. package/build-module/hooks/use-crop-gesture-handlers.mjs.map +2 -2
  57. package/build-module/image-editor/core/interaction-controller.mjs +5 -0
  58. package/build-module/image-editor/core/interaction-controller.mjs.map +2 -2
  59. package/build-module/image-editor/react/components/cropper.mjs +3 -3
  60. package/build-module/image-editor/react/components/cropper.mjs.map +2 -2
  61. package/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs +1 -1
  62. package/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs.map +2 -2
  63. package/build-module/image-editor/react/hooks/use-aria-announcer.mjs +3 -1
  64. package/build-module/image-editor/react/hooks/use-aria-announcer.mjs.map +2 -2
  65. package/build-module/image-editor/react/hooks/use-interaction.mjs +1 -1
  66. package/build-module/image-editor/react/hooks/use-interaction.mjs.map +2 -2
  67. package/build-module/state/composite-reducer.mjs +3 -3
  68. package/build-module/state/composite-reducer.mjs.map +2 -2
  69. package/build-module/state/index.mjs.map +1 -1
  70. package/build-module/state/media-editor-state-provider.mjs +1 -6
  71. package/build-module/state/media-editor-state-provider.mjs.map +2 -2
  72. package/build-module/state/use-media-editor-state.mjs +38 -36
  73. package/build-module/state/use-media-editor-state.mjs.map +2 -2
  74. package/build-module/store/actions.mjs +2 -0
  75. package/build-module/store/actions.mjs.map +2 -2
  76. package/build-module/store/reducer.mjs +3 -1
  77. package/build-module/store/reducer.mjs.map +2 -2
  78. package/build-module/store/selectors.mjs +4 -0
  79. package/build-module/store/selectors.mjs.map +2 -2
  80. package/build-style/style-rtl.css +5 -5
  81. package/build-style/style.css +5 -5
  82. package/build-types/components/media-editor/index.d.ts +2 -2
  83. package/build-types/components/media-editor/index.d.ts.map +1 -1
  84. package/build-types/components/media-editor/use-save-media-editor.d.ts +15 -3
  85. package/build-types/components/media-editor/use-save-media-editor.d.ts.map +1 -1
  86. package/build-types/components/media-editor-canvas/index.d.ts.map +1 -1
  87. package/build-types/components/media-editor-image-controls/index.d.ts.map +1 -1
  88. package/build-types/components/media-editor-modal/index.d.ts.map +1 -1
  89. package/build-types/hooks/use-crop-gesture-handlers.d.ts.map +1 -1
  90. package/build-types/image-editor/core/interaction-controller.d.ts.map +1 -1
  91. package/build-types/image-editor/react/components/cropper.d.ts.map +1 -1
  92. package/build-types/image-editor/react/components/stencils/rectangle-stencil.d.ts.map +1 -1
  93. package/build-types/image-editor/react/hooks/use-aria-announcer.d.ts.map +1 -1
  94. package/build-types/image-editor/react/hooks/use-interaction.d.ts.map +1 -1
  95. package/build-types/state/composite-reducer.d.ts +5 -5
  96. package/build-types/state/composite-reducer.d.ts.map +1 -1
  97. package/build-types/state/index.d.ts +1 -1
  98. package/build-types/state/index.d.ts.map +1 -1
  99. package/build-types/state/media-editor-state-provider.d.ts +8 -16
  100. package/build-types/state/media-editor-state-provider.d.ts.map +1 -1
  101. package/build-types/state/use-media-editor-state.d.ts +37 -30
  102. package/build-types/state/use-media-editor-state.d.ts.map +1 -1
  103. package/build-types/store/actions.d.ts +9 -1
  104. package/build-types/store/actions.d.ts.map +1 -1
  105. package/build-types/store/reducer.d.ts +3 -0
  106. package/build-types/store/reducer.d.ts.map +1 -1
  107. package/build-types/store/selectors.d.ts +1 -0
  108. package/build-types/store/selectors.d.ts.map +1 -1
  109. package/package.json +27 -22
  110. package/src/components/media-editor/index.tsx +203 -59
  111. package/src/components/media-editor/test/restore-original.browser.test.tsx +227 -0
  112. package/src/components/media-editor/test/use-crop-options.jsdom.test.tsx +12 -10
  113. package/src/components/media-editor/use-crop-options.ts +1 -1
  114. package/src/components/media-editor/use-save-media-editor.ts +61 -20
  115. package/src/components/media-editor-canvas/index.tsx +7 -8
  116. package/src/components/media-editor-crop-panel/test/index.jsdom.test.tsx +2 -4
  117. package/src/components/media-editor-fine-rotation/index.tsx +1 -1
  118. package/src/components/media-editor-image-controls/index.tsx +41 -41
  119. package/src/components/media-editor-image-controls/test/index.jsdom.test.tsx +19 -13
  120. package/src/components/media-editor-modal/index.tsx +18 -10
  121. package/src/components/media-editor-modal/test/index.jsdom.test.tsx +18 -1
  122. package/src/hooks/use-crop-gesture-handlers.ts +3 -1
  123. package/src/image-editor/core/interaction-controller.ts +8 -0
  124. package/src/image-editor/core/test/interaction-controller.ts +45 -0
  125. package/src/image-editor/docs/architecture.md +6 -2
  126. package/src/image-editor/docs/recipes.md +8 -8
  127. package/src/image-editor/react/components/cropper.scss +5 -5
  128. package/src/image-editor/react/components/cropper.tsx +8 -3
  129. package/src/image-editor/react/components/stencils/rectangle-stencil.tsx +3 -1
  130. package/src/image-editor/react/components/test/cropper.browser.test.tsx +7 -5
  131. package/src/image-editor/react/hooks/use-aria-announcer.ts +3 -1
  132. package/src/image-editor/react/hooks/use-interaction.ts +3 -2
  133. package/src/state/composite-reducer.ts +6 -7
  134. package/src/state/index.ts +1 -1
  135. package/src/state/media-editor-state-provider.tsx +9 -22
  136. package/src/state/test/use-media-editor-state.browser.test.tsx +79 -0
  137. package/src/state/test/use-media-editor-state.jsdom.test.ts +126 -64
  138. package/src/state/use-media-editor-state.ts +79 -68
  139. package/src/store/actions.ts +9 -0
  140. package/src/store/reducer.ts +6 -1
  141. package/src/store/selectors.ts +4 -0
  142. package/tsconfig.build.tsbuildinfo +1 -1
@@ -5,7 +5,7 @@ import { useCallback, useState } from '@wordpress/element';
5
5
  import { __, sprintf } from '@wordpress/i18n';
6
6
  import { store as noticesStore } from '@wordpress/notices';
7
7
  import type { Media } from '../media-editor-provider';
8
- import type { MediaEditorController } from '../../state';
8
+ import type { MediaEditorSession } from '../../state';
9
9
  import {
10
10
  buildModifiers,
11
11
  type Modifier,
@@ -37,11 +37,23 @@ export interface MediaEditorSaveResult {
37
37
  }
38
38
 
39
39
  interface UseSaveMediaEditorArgs {
40
- cropper: MediaEditorController;
40
+ session: MediaEditorSession;
41
41
  id: number;
42
42
  isImage: boolean;
43
43
  media?: Media | null;
44
44
  onSaved?: ( result: MediaEditorSaveResult ) => void;
45
+ /**
46
+ * When another attachment has replaced the edited one (today, the original
47
+ * via "Restore original image"), the save targets the replacement:
48
+ * - with no fresh crop, the block is repointed at the replacement and any
49
+ * changed details are saved there (no `/edit`);
50
+ * - with a fresh crop, `/edit` runs against the replacement's id and url.
51
+ */
52
+ replacementSource?: {
53
+ id: number;
54
+ url?: string;
55
+ media: Media;
56
+ };
45
57
  }
46
58
 
47
59
  interface UseSaveMediaEditorReturn {
@@ -49,13 +61,14 @@ interface UseSaveMediaEditorReturn {
49
61
  save: () => Promise< void >;
50
62
  }
51
63
 
52
- function getCropModifiers( cropper: MediaEditorController ): Modifier[] {
53
- if ( ! cropper.isCropperDirty || ! cropper.state.image ) {
64
+ function getCropModifiers( session: MediaEditorSession ): Modifier[] {
65
+ const { state } = session.cropper;
66
+ if ( ! session.hasOutputEdits || ! state.image ) {
54
67
  return [];
55
68
  }
56
- return buildModifiers( cropper.state, {
57
- width: cropper.state.image.naturalWidth,
58
- height: cropper.state.image.naturalHeight,
69
+ return buildModifiers( state, {
70
+ width: state.image.naturalWidth,
71
+ height: state.image.naturalHeight,
59
72
  } );
60
73
  }
61
74
 
@@ -80,11 +93,12 @@ function getMetadataEdits(
80
93
  }
81
94
 
82
95
  export function useSaveMediaEditor( {
83
- cropper,
96
+ session,
84
97
  id,
85
98
  isImage,
86
99
  media,
87
100
  onSaved,
101
+ replacementSource,
88
102
  }: UseSaveMediaEditorArgs ): UseSaveMediaEditorReturn {
89
103
  const registry = useRegistry();
90
104
  const {
@@ -100,9 +114,18 @@ export function useSaveMediaEditor( {
100
114
  setIsSaving( true );
101
115
  try {
102
116
  let saved: Media | null | undefined;
103
- const modifiers = getCropModifiers( cropper );
117
+ const modifiers = getCropModifiers( session );
118
+
119
+ // A replacement retargets the save; without one the current
120
+ // attachment is both source and target as before.
121
+ const targetId = replacementSource?.id ?? id;
122
+ const targetUrl = replacementSource?.url ?? media?.source_url;
123
+ const targetMedia = replacementSource?.media ?? media;
124
+
125
+ // Both a fresh crop and a bare replacement swap the block's image,
126
+ // so both offer an Undo back to the current attachment.
104
127
  const previous =
105
- modifiers.length > 0 && media
128
+ ( modifiers.length > 0 || replacementSource ) && media
106
129
  ? {
107
130
  id,
108
131
  url: media.source_url,
@@ -115,15 +138,18 @@ export function useSaveMediaEditor( {
115
138
  .getEntityRecordNonTransientEdits(
116
139
  'postType',
117
140
  'attachment',
118
- id
141
+ targetId
119
142
  ) as PendingMetadataEdits;
120
- const metadataEdits = getMetadataEdits( pendingEdits, media );
143
+ const metadataEdits = getMetadataEdits(
144
+ pendingEdits,
145
+ targetMedia
146
+ );
121
147
 
122
148
  saved = ( await apiFetch( {
123
- path: `/wp/v2/media/${ id }/edit`,
149
+ path: `/wp/v2/media/${ targetId }/edit`,
124
150
  method: 'POST',
125
151
  data: {
126
- src: media?.source_url,
152
+ src: targetUrl,
127
153
  modifiers,
128
154
  ...metadataEdits,
129
155
  },
@@ -138,23 +164,37 @@ export function useSaveMediaEditor( {
138
164
  true
139
165
  );
140
166
  }
167
+ } else if (
168
+ replacementSource &&
169
+ ! registry
170
+ .select( coreStore )
171
+ .hasEditsForEntityRecord(
172
+ 'postType',
173
+ 'attachment',
174
+ targetId
175
+ )
176
+ ) {
177
+ // A bare replacement only repoints the block. The replacement
178
+ // already exists and has no changes to persist.
179
+ saved = replacementSource.media;
141
180
  } else {
142
181
  saved = ( await saveEditedEntityRecord(
143
182
  'postType',
144
183
  'attachment',
145
- id
184
+ targetId,
185
+ { throwOnError: true }
146
186
  ) ) as Media | undefined;
147
187
  }
148
188
 
149
- const next = ( saved ?? media ) as Media | null;
189
+ const next = ( saved ?? targetMedia ) as Media | null;
150
190
 
151
- if ( next && next.id !== id ) {
152
- clearEntityRecordEdits( 'postType', 'attachment', id );
191
+ if ( next && next.id !== targetId ) {
192
+ clearEntityRecordEdits( 'postType', 'attachment', targetId );
153
193
  }
154
194
 
155
195
  if ( next && next.id ) {
156
196
  if ( next.id === id ) {
157
- cropper.reset();
197
+ session.cropper.reset();
158
198
  }
159
199
  onSaved?.( {
160
200
  id: next.id,
@@ -192,7 +232,6 @@ export function useSaveMediaEditor( {
192
232
  }, [
193
233
  clearEntityRecordEdits,
194
234
  createErrorNotice,
195
- cropper,
196
235
  id,
197
236
  isImage,
198
237
  media,
@@ -200,7 +239,9 @@ export function useSaveMediaEditor( {
200
239
  receiveEntityRecords,
201
240
  registry,
202
241
  removeAllNotices,
242
+ replacementSource,
203
243
  saveEditedEntityRecord,
244
+ session,
204
245
  ] );
205
246
 
206
247
  return { isSaving, save };
@@ -42,10 +42,10 @@ export default function MediaEditorCanvas( {
42
42
  disabled = false,
43
43
  }: MediaEditorCanvasProps ) {
44
44
  const { media } = useMediaEditorContext();
45
- const controller = useMediaEditor();
46
- const { aspectRatioValue } = controller.cropOptions;
47
- const cropperImage = controller.state.image;
48
- const { beginGesture, endGesture, setImage } = controller;
45
+ const session = useMediaEditor();
46
+ const { aspectRatioValue } = session.cropOptions;
47
+ const cropperImage = session.cropper.state.image;
48
+ const { beginGesture, endGesture, setSourceImage } = session;
49
49
 
50
50
  // Tracks whether the image pixels have actually loaded. The cropper's
51
51
  // geometry is driven by the known media dimensions, so its handles and
@@ -80,7 +80,6 @@ export default function MediaEditorCanvas( {
80
80
 
81
81
  useEffect( () => {
82
82
  if (
83
- cropperImage ||
84
83
  ! mediaUrl ||
85
84
  ! Number.isFinite( mediaWidth ) ||
86
85
  ! Number.isFinite( mediaHeight ) ||
@@ -89,12 +88,12 @@ export default function MediaEditorCanvas( {
89
88
  ) {
90
89
  return;
91
90
  }
92
- setImage( {
91
+ setSourceImage( {
93
92
  src: mediaUrl,
94
93
  naturalWidth: mediaWidth,
95
94
  naturalHeight: mediaHeight,
96
95
  } );
97
- }, [ cropperImage, mediaUrl, mediaWidth, mediaHeight, setImage ] );
96
+ }, [ mediaUrl, mediaWidth, mediaHeight, setSourceImage ] );
98
97
 
99
98
  const isImage = mediaType.type === 'image';
100
99
 
@@ -159,7 +158,7 @@ export default function MediaEditorCanvas( {
159
158
  >
160
159
  <Cropper
161
160
  src={ mediaUrl }
162
- controller={ controller }
161
+ controller={ session.cropper }
163
162
  aspectRatio={ aspectRatio }
164
163
  freeformCrop
165
164
  showGrid="interactive"
@@ -3,13 +3,11 @@ import { fireEvent, render, screen } from '@testing-library/react';
3
3
  import MediaEditorCropPanel from '..';
4
4
  import type { MediaEditorCropPanelProps } from '..';
5
5
  import { MediaEditorStateProvider } from '../../../state';
6
- import type { CropperState } from '../../../image-editor';
7
6
 
8
7
  globalThis.wpVitest.mockMatchMedia();
9
8
 
10
9
  function setupCropPanel(
11
- overrides: Partial< MediaEditorCropPanelProps > = {},
12
- initialCropperState?: Partial< CropperState >
10
+ overrides: Partial< MediaEditorCropPanelProps > = {}
13
11
  ) {
14
12
  const props: MediaEditorCropPanelProps = {
15
13
  aspectRatioValue: '1',
@@ -23,7 +21,7 @@ function setupCropPanel(
23
21
  };
24
22
 
25
23
  render(
26
- <MediaEditorStateProvider initialCropperState={ initialCropperState }>
24
+ <MediaEditorStateProvider>
27
25
  <MediaEditorCropPanel { ...props } />
28
26
  </MediaEditorStateProvider>
29
27
  );
@@ -28,7 +28,7 @@ export default function MediaEditorFineRotation( {
28
28
  onPlacementControlInteraction,
29
29
  disabled = false,
30
30
  }: MediaEditorFineRotationProps ) {
31
- const { state, setRotation } = useMediaEditor();
31
+ const { state, setRotation } = useMediaEditor().cropper;
32
32
  // `commitOnKeyUp: false` lets rapid arrow-key adjustments coalesce
33
33
  // into one undo entry via the gesture idle window. Pointer-up still
34
34
  // closes pointer drags immediately.
@@ -1,13 +1,9 @@
1
- import {
2
- Button,
3
- DropdownMenu,
4
- MenuGroup,
5
- MenuItem,
6
- } from '@wordpress/components';
1
+ import { Button } from '@wordpress/components';
2
+ // eslint-disable-next-line @wordpress/use-recommended-components -- Intentional early adoption of the new Menu, pending WordPress/gutenberg#76135.
3
+ import { Menu } from '@wordpress/ui';
7
4
  import { __ } from '@wordpress/i18n';
8
5
  import {
9
6
  aspectRatio as aspectRatioIcon,
10
- check,
11
7
  rotateLeft,
12
8
  rotateRight,
13
9
  flipHorizontal,
@@ -81,7 +77,7 @@ export default function MediaEditorImageControls( {
81
77
  zoomFactor = DEFAULT_ZOOM_FACTOR,
82
78
  disabled = false,
83
79
  }: MediaEditorImageControlsProps ) {
84
- const { state, setFlip, snapRotate90, setZoom } = useMediaEditor();
80
+ const { state, setFlip, snapRotate90, setZoom } = useMediaEditor().cropper;
85
81
  const { aspectRatioValue, setAspectRatioValue, aspectRatioOptions } =
86
82
  useCropOptions( { aspectRatioPresets } );
87
83
  const hasAspectRatioControl = ! withLabels && showAspectRatioControl;
@@ -174,39 +170,43 @@ export default function MediaEditorImageControls( {
174
170
  );
175
171
 
176
172
  const aspectRatioDropdown = hasAspectRatioControl ? (
177
- <DropdownMenu
178
- icon={ aspectRatioIcon }
179
- label={ __( 'Aspect ratio' ) }
180
- popoverProps={ { placement: 'top' } }
181
- toggleProps={ { size: 'compact', disabled } }
182
- >
183
- { ( { onClose } ) => (
184
- <MenuGroup label={ __( 'Aspect ratio' ) }>
185
- { aspectRatioOptions.map( ( preset ) => {
186
- const value = preset.value.toString();
187
- const isSelected = value === aspectRatioValue;
188
- return (
189
- <MenuItem
190
- key={ value }
191
- role="menuitemradio"
192
- isSelected={ isSelected }
193
- icon={ isSelected ? check : undefined }
194
- disabled={ disabled }
195
- onClick={ () => {
196
- if ( disabled ) {
197
- return;
198
- }
199
- setAspectRatioValue( value );
200
- onClose();
201
- } }
202
- >
203
- { preset.label }
204
- </MenuItem>
205
- );
206
- } ) }
207
- </MenuGroup>
208
- ) }
209
- </DropdownMenu>
173
+ <Menu.Root>
174
+ <Menu.Trigger
175
+ disabled={ disabled }
176
+ render={
177
+ <Button
178
+ size="compact"
179
+ icon={ aspectRatioIcon }
180
+ label={ __( 'Aspect ratio' ) }
181
+ accessibleWhenDisabled
182
+ />
183
+ }
184
+ />
185
+ <Menu.Popup
186
+ positioner={ <Menu.Positioner side="top" align="center" /> }
187
+ >
188
+ <Menu.RadioGroup
189
+ value={ aspectRatioValue }
190
+ onValueChange={ ( value ) => {
191
+ if ( ! disabled ) {
192
+ setAspectRatioValue( value );
193
+ }
194
+ } }
195
+ >
196
+ <Menu.GroupLabel>{ __( 'Aspect ratio' ) }</Menu.GroupLabel>
197
+ { aspectRatioOptions.map( ( preset ) => (
198
+ <Menu.RadioItem
199
+ key={ preset.value }
200
+ value={ preset.value.toString() }
201
+ closeOnClick
202
+ disabled={ disabled }
203
+ >
204
+ <Menu.ItemLabel>{ preset.label }</Menu.ItemLabel>
205
+ </Menu.RadioItem>
206
+ ) ) }
207
+ </Menu.RadioGroup>
208
+ </Menu.Popup>
209
+ </Menu.Root>
210
210
  ) : null;
211
211
 
212
212
  if ( withLabels ) {
@@ -1,26 +1,32 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import { fireEvent, render, screen, waitFor } from '@testing-library/react';
3
- import { useState } from '@wordpress/element';
3
+ import { useEffect, useState } from '@wordpress/element';
4
4
  import MediaEditorImageControls from '..';
5
5
  import type { MediaEditorImageControlsProps } from '..';
6
6
  import { MediaEditorStateProvider, useMediaEditor } from '../../../state';
7
- import type { CropperState } from '../../../image-editor';
8
7
  import { MAX_ZOOM } from '../../../image-editor/core/constants';
9
8
 
10
- function setup(
11
- props: MediaEditorImageControlsProps = {},
12
- initialCropperState?: Partial< CropperState >
13
- ) {
9
+ function setup( props: MediaEditorImageControlsProps = {}, zoom?: number ) {
14
10
  render(
15
- <MediaEditorStateProvider initialCropperState={ initialCropperState }>
11
+ <MediaEditorStateProvider>
16
12
  <MediaEditorImageControls { ...props } />
17
- <CurrentState />
13
+ <CurrentState zoom={ zoom } />
18
14
  </MediaEditorStateProvider>
19
15
  );
20
16
  }
21
17
 
22
- function CurrentState() {
23
- const { state, cropOptions } = useMediaEditor();
18
+ function CurrentState( { zoom }: { zoom?: number } ) {
19
+ const {
20
+ cropper: { state, setZoom },
21
+ cropOptions,
22
+ } = useMediaEditor();
23
+ // Start the cases that need it zoomed in. `setZoom` is a session edit,
24
+ // so these cases begin with one undo entry; none of them checks history.
25
+ useEffect( () => {
26
+ if ( zoom !== undefined ) {
27
+ setZoom( zoom );
28
+ }
29
+ }, [ setZoom, zoom ] );
24
30
 
25
31
  return (
26
32
  <>
@@ -72,7 +78,7 @@ describe( 'MediaEditorImageControls', () => {
72
78
  } );
73
79
 
74
80
  it( 'zoom in multiplies the zoom and zoom out divides it', () => {
75
- setup( {}, { zoom: 2 } );
81
+ setup( {}, 2 );
76
82
 
77
83
  fireEvent.click( screen.getByRole( 'button', { name: 'Zoom in' } ) );
78
84
  const zoomedIn = Number(
@@ -87,7 +93,7 @@ describe( 'MediaEditorImageControls', () => {
87
93
  } );
88
94
 
89
95
  it( 'honors a custom zoomFactor', () => {
90
- setup( { zoomFactor: 2 }, { zoom: 2 } );
96
+ setup( { zoomFactor: 2 }, 2 );
91
97
 
92
98
  fireEvent.click( screen.getByRole( 'button', { name: 'Zoom in' } ) );
93
99
 
@@ -98,7 +104,7 @@ describe( 'MediaEditorImageControls', () => {
98
104
  } );
99
105
 
100
106
  it( 'disables Zoom in at the maximum zoom', () => {
101
- setup( {}, { zoom: MAX_ZOOM } );
107
+ setup( {}, MAX_ZOOM );
102
108
  // Buttons use `accessibleWhenDisabled`, so the disabled state is
103
109
  // expressed via aria-disabled, not the `disabled` attribute.
104
110
  expect(
@@ -49,16 +49,20 @@ export function MediaEditorModal( {
49
49
  fields = [],
50
50
  aspectRatioPresets,
51
51
  }: MediaEditorModalProps ) {
52
- const { isModalOpen, id, onUpdate, onClose } = useSelect( ( select ) => {
53
- const { isOpen, getId, getOnUpdate, getOnClose } =
54
- select( mediaEditorStore );
55
- return {
56
- isModalOpen: isOpen(),
57
- id: getId(),
58
- onUpdate: getOnUpdate(),
59
- onClose: getOnClose(),
60
- };
61
- }, [] );
52
+ const { isModalOpen, id, onUpdate, onUndo, onClose } = useSelect(
53
+ ( select ) => {
54
+ const { isOpen, getId, getOnUpdate, getOnUndo, getOnClose } =
55
+ select( mediaEditorStore );
56
+ return {
57
+ isModalOpen: isOpen(),
58
+ id: getId(),
59
+ onUpdate: getOnUpdate(),
60
+ onUndo: getOnUndo(),
61
+ onClose: getOnClose(),
62
+ };
63
+ },
64
+ []
65
+ );
62
66
 
63
67
  const { closeMediaEditorModal } = useDispatch( mediaEditorStore );
64
68
  const { createSuccessNotice } = useDispatch( noticesStore );
@@ -113,6 +117,10 @@ export function MediaEditorModal( {
113
117
  {
114
118
  label: __( 'Undo' ),
115
119
  onClick: () => {
120
+ if ( onUndo ) {
121
+ onUndo();
122
+ return;
123
+ }
116
124
  onUpdate( {
117
125
  id: previous.id,
118
126
  url: previous.url,
@@ -20,6 +20,7 @@ let mockSaveResult: {
20
20
  },
21
21
  };
22
22
  const mockOnUpdate = vi.fn();
23
+ let mockOnUndo: ( () => void ) | undefined;
23
24
  const mockOnClose = vi.fn();
24
25
  const mockCloseMediaEditorModal = vi.fn();
25
26
  const mockCreateSuccessNotice = vi.fn();
@@ -86,6 +87,7 @@ vi.mock( import( '../../media-editor' ), async () => {
86
87
  describe( 'MediaEditorModal', () => {
87
88
  beforeEach( () => {
88
89
  vi.clearAllMocks();
90
+ mockOnUndo = undefined;
89
91
  mockSaveResult = {
90
92
  id: 11,
91
93
  url: 'edited.jpg',
@@ -101,6 +103,7 @@ describe( 'MediaEditorModal', () => {
101
103
  isOpen: () => true,
102
104
  getId: () => 10,
103
105
  getOnUpdate: () => mockOnUpdate,
106
+ getOnUndo: () => mockOnUndo,
104
107
  getOnClose: () => mockOnClose,
105
108
  } ) )
106
109
  );
@@ -111,7 +114,7 @@ describe( 'MediaEditorModal', () => {
111
114
  );
112
115
  } );
113
116
 
114
- it( 'shows an undo snackbar after saving dirty image editor state', () => {
117
+ it( 'restores the previous attachment when no Undo callback is supplied', () => {
115
118
  render( <MediaEditorModal /> );
116
119
 
117
120
  fireEvent.click(
@@ -148,6 +151,20 @@ describe( 'MediaEditorModal', () => {
148
151
  } );
149
152
  } );
150
153
 
154
+ it( "uses the caller's Undo callback after saving an attachment change", () => {
155
+ mockOnUndo = vi.fn();
156
+ render( <MediaEditorModal /> );
157
+
158
+ fireEvent.click(
159
+ screen.getByRole( 'button', { name: 'Save result' } )
160
+ );
161
+ const noticeOptions = mockCreateSuccessNotice.mock.calls[ 0 ][ 1 ];
162
+ noticeOptions.actions[ 0 ].onClick();
163
+
164
+ expect( mockOnUndo ).toHaveBeenCalledTimes( 1 );
165
+ expect( mockOnUpdate ).toHaveBeenCalledTimes( 1 );
166
+ } );
167
+
151
168
  it( 'does not show the image edited snackbar for metadata-only saves', () => {
152
169
  mockSaveResult = {
153
170
  ...mockSaveResult,
@@ -43,7 +43,9 @@ export function useCropGestureHandlers(
43
43
  ) {
44
44
  const { commitOnKeyUp = true } = options;
45
45
  const { beginGesture, endGesture } = useMediaEditor();
46
- const keyboardTimerRef = useRef< ReturnType< typeof setTimeout > >();
46
+ const keyboardTimerRef = useRef<
47
+ ReturnType< typeof setTimeout > | undefined
48
+ >( undefined );
47
49
 
48
50
  const clearKeyboardTimer = useCallback( () => {
49
51
  clearTimeout( keyboardTimerRef.current );
@@ -305,6 +305,14 @@ export class InteractionController {
305
305
  // Capture pointer so drag works across iframe boundaries.
306
306
  el.setPointerCapture( e.pointerId );
307
307
 
308
+ // End a pending wheel gesture now, so its debounce timer cannot
309
+ // fire mid-drag and end the drag's gesture along with it.
310
+ if ( this.wheelGestureActive ) {
311
+ clearTimeout( this.wheelGestureTimer );
312
+ this.wheelGestureActive = false;
313
+ this.options.onGestureEnd?.();
314
+ }
315
+
308
316
  this.setStatus( { isDragging: true } );
309
317
  this.options.onGestureStart?.();
310
318
 
@@ -562,6 +562,51 @@ describe( 'InteractionController', () => {
562
562
 
563
563
  vi.useRealTimers();
564
564
  } );
565
+
566
+ it( 'does not end the gesture mid-drag when the drag starts within the wheel debounce', () => {
567
+ vi.useFakeTimers( {
568
+ toFake: [ 'setTimeout', 'clearTimeout' ],
569
+ } );
570
+ const state = makeState( { zoom: 2 } );
571
+ const calls: string[] = [];
572
+ const { controller } = createController( state, {
573
+ onGestureStart: () => calls.push( 'start' ),
574
+ onGestureEnd: () => calls.push( 'end' ),
575
+ } );
576
+ const el = createMockElement();
577
+
578
+ // Zoom, then start dragging before the 300ms debounce elapses.
579
+ controller.handleWheel(
580
+ createWheelEvent( { deltaY: -50, currentTarget: null } )
581
+ );
582
+ vi.advanceTimersByTime( 100 );
583
+ controller.handlePointerDown(
584
+ createPointerEvent( { clientX: 100, clientY: 100 } ),
585
+ el
586
+ );
587
+ const dragStartIndex = calls.lastIndexOf( 'start' );
588
+
589
+ // Keep dragging past the point where the debounce fires.
590
+ el._fire(
591
+ 'pointermove',
592
+ createPointerEvent( { clientX: 110, clientY: 100 } )
593
+ );
594
+ vi.advanceTimersByTime( 350 );
595
+ el._fire(
596
+ 'pointermove',
597
+ createPointerEvent( { clientX: 120, clientY: 100 } )
598
+ );
599
+ const callsDuringDrag = calls.slice( dragStartIndex + 1 );
600
+
601
+ el._fire( 'pointerup', createPointerEvent() );
602
+ vi.useRealTimers();
603
+
604
+ expect( actionMocks.setPan ).toHaveBeenCalledTimes( 2 );
605
+ // An end here closes the undo batch, so every later pan frame
606
+ // records its own undo entry.
607
+ expect( callsDuringDrag ).not.toContain( 'end' );
608
+ expect( calls[ calls.length - 1 ] ).toBe( 'end' );
609
+ } );
565
610
  } );
566
611
 
567
612
  describe( 'keyboard', () => {
@@ -8,7 +8,7 @@
8
8
  | React cropper | `src/image-editor/react/` | DOM measurement, interaction hooks, overlays, stencil rendering, and the pure `useCropperReducer` hook. |
9
9
  | Media editor state | `src/state/` | Composite state for the media editor: cropper state, crop options, undo/redo, and gesture boundaries. |
10
10
 
11
- The cropper layer does not own editor history. History belongs to the composite media editor controller because sidebar controls and cropper gestures need one shared undo stack.
11
+ The cropper layer does not own editor history. History belongs to the media editor session because sidebar controls and cropper gestures need one shared undo stack.
12
12
 
13
13
  ## Coordinate Spaces
14
14
 
@@ -37,6 +37,10 @@ The render path uses focused calculations for CSS transforms, stencil placement,
37
37
 
38
38
  The core reducer is framework-agnostic and serializable. React and media-editor layers add DOM measurement, gestures, undo/redo, save behavior, and UI state.
39
39
 
40
+ ### Session
41
+
42
+ `useMediaEditorState()` returns the media editor session. The session owns the source image, every editing slice, the shared undo/redo history, gesture boundaries, and whether the edits change the saved image (`hasOutputEdits`). The cropper is one participant: `session.cropper` is a geometry-only `CropperController` that a `<Cropper>` takes via its `controller` prop, and its `isDirty` covers geometry alone. Replacing the source image (`setSourceImage`, which the cropper's `setImage` also calls) starts a fresh session with default geometry and crop options, a clean baseline, and no history. Save code asks the session, not the cropper, whether image output needs saving.
43
+
40
44
  ### Viewport
41
45
 
42
46
  Viewport pan/zoom lets the user inspect or follow the crop area without changing the crop output. It is not part of export and should not create undo entries.
@@ -52,4 +56,4 @@ These APIs let code inside `@wordpress/media-editor` compose the cropper. They a
52
56
  | Crop data for REST requests | `getSourceRegion()` and `getSourceRegionPercent()`. |
53
57
  | Canvas export | `exportCroppedImage()` or `applyToCanvas()`. |
54
58
  | Shared cropper state across internal components | `CropperProvider` / `useCropper()`. |
55
- | Media editor history | `useMediaEditorState()` composite controller. |
59
+ | Media editor history | `useMediaEditorState()` session. |
@@ -76,29 +76,29 @@ function CropperPanel( { src }: { src: string } ) {
76
76
  }
77
77
  ```
78
78
 
79
- ## Use the Media Editor Composite Controller
79
+ ## Use the Media Editor Session
80
80
 
81
- Use the media editor controller when cropper state must share history with controls such as aspect ratio.
81
+ Use the media editor session when cropper state must share history with controls such as aspect ratio. The session owns history and gesture boundaries; pass its `cropper` controller to `<Cropper>`.
82
82
 
83
83
  ```tsx
84
84
  import { resolveAspectRatio, useMediaEditor } from '../../state';
85
85
  import { Cropper } from '../image-editor';
86
86
 
87
87
  function MediaEditorCanvas( { src }: { src: string } ) {
88
- const controller = useMediaEditor();
88
+ const session = useMediaEditor();
89
89
  const aspectRatio = resolveAspectRatio(
90
- controller.cropOptions.aspectRatioValue,
91
- controller.state.image
90
+ session.cropOptions.aspectRatioValue,
91
+ session.cropper.state.image
92
92
  );
93
93
 
94
94
  return (
95
95
  <Cropper
96
96
  src={ src }
97
- controller={ controller }
97
+ controller={ session.cropper }
98
98
  aspectRatio={ aspectRatio }
99
99
  freeformCrop
100
- onGestureStart={ controller.beginGesture }
101
- onGestureEnd={ controller.endGesture }
100
+ onGestureStart={ session.beginGesture }
101
+ onGestureEnd={ session.endGesture }
102
102
  />
103
103
  );
104
104
  }