@wordpress/media-editor 0.8.1-next.v.202605131032.0 → 0.10.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 (292) hide show
  1. package/build/components/media-editor/index.cjs +34 -135
  2. package/build/components/media-editor/index.cjs.map +3 -3
  3. package/build/components/media-editor/use-crop-options.cjs +87 -0
  4. package/build/components/media-editor/use-crop-options.cjs.map +7 -0
  5. package/build/components/media-editor/use-save-media-editor.cjs +185 -0
  6. package/build/components/media-editor/use-save-media-editor.cjs.map +7 -0
  7. package/build/components/media-editor-canvas/index.cjs +32 -11
  8. package/build/components/media-editor-canvas/index.cjs.map +2 -2
  9. package/build/components/media-editor-crop-panel/index.cjs +66 -83
  10. package/build/components/media-editor-crop-panel/index.cjs.map +2 -2
  11. package/build/components/media-editor-modal/index.cjs +40 -11
  12. package/build/components/media-editor-modal/index.cjs.map +3 -3
  13. package/build/components/media-editor-toolbar/index.cjs +7 -3
  14. package/build/components/media-editor-toolbar/index.cjs.map +2 -2
  15. package/build/components/media-form/index.cjs +19 -1
  16. package/build/components/media-form/index.cjs.map +3 -3
  17. package/build/components/media-form/sidebar-datetime-view.cjs +53 -0
  18. package/build/components/media-form/sidebar-datetime-view.cjs.map +7 -0
  19. package/build/components/rotation-ruler/index.cjs +8 -2
  20. package/build/components/rotation-ruler/index.cjs.map +2 -2
  21. package/build/hooks/use-crop-gesture-handlers.cjs +41 -4
  22. package/build/hooks/use-crop-gesture-handlers.cjs.map +2 -2
  23. package/build/image-editor/core/camera.cjs +29 -11
  24. package/build/image-editor/core/camera.cjs.map +2 -2
  25. package/build/image-editor/core/constants.cjs +6 -0
  26. package/build/image-editor/core/constants.cjs.map +2 -2
  27. package/build/image-editor/core/containment.cjs +71 -34
  28. package/build/image-editor/core/containment.cjs.map +2 -2
  29. package/build/image-editor/core/crop-rect.cjs +48 -0
  30. package/build/image-editor/core/crop-rect.cjs.map +7 -0
  31. package/build/image-editor/core/index.cjs +12 -0
  32. package/build/image-editor/core/index.cjs.map +2 -2
  33. package/build/image-editor/core/interaction-controller.cjs.map +2 -2
  34. package/build/image-editor/core/math/sanitize.cjs +92 -0
  35. package/build/image-editor/core/math/sanitize.cjs.map +7 -0
  36. package/build/image-editor/core/setter-helpers.cjs +64 -0
  37. package/build/image-editor/core/setter-helpers.cjs.map +7 -0
  38. package/build/image-editor/core/source-region.cjs +16 -14
  39. package/build/image-editor/core/source-region.cjs.map +2 -2
  40. package/build/image-editor/core/state.cjs +20 -10
  41. package/build/image-editor/core/state.cjs.map +2 -2
  42. package/build/image-editor/core/stencil-math.cjs +31 -20
  43. package/build/image-editor/core/stencil-math.cjs.map +2 -2
  44. package/build/image-editor/core/transform-style.cjs +12 -6
  45. package/build/image-editor/core/transform-style.cjs.map +2 -2
  46. package/build/image-editor/core/types.cjs.map +1 -1
  47. package/build/image-editor/index.cjs +12 -2
  48. package/build/image-editor/index.cjs.map +2 -2
  49. package/build/image-editor/react/components/cropper-provider.cjs +2 -2
  50. package/build/image-editor/react/components/cropper-provider.cjs.map +2 -2
  51. package/build/image-editor/react/components/cropper.cjs +121 -48
  52. package/build/image-editor/react/components/cropper.cjs.map +2 -2
  53. package/build/image-editor/react/components/overlays/dimensions-overlay.cjs +172 -0
  54. package/build/image-editor/react/components/overlays/dimensions-overlay.cjs.map +7 -0
  55. package/build/image-editor/react/components/stencils/rectangle-stencil.cjs +20 -10
  56. package/build/image-editor/react/components/stencils/rectangle-stencil.cjs.map +2 -2
  57. package/build/image-editor/react/hooks/build-cropper-setters.cjs +71 -0
  58. package/build/image-editor/react/hooks/build-cropper-setters.cjs.map +7 -0
  59. package/build/image-editor/react/hooks/index.cjs +6 -3
  60. package/build/image-editor/react/hooks/index.cjs.map +2 -2
  61. package/build/image-editor/react/hooks/use-aria-announcer.cjs +3 -1
  62. package/build/image-editor/react/hooks/use-aria-announcer.cjs.map +2 -2
  63. package/build/image-editor/react/hooks/use-cropper-reducer.cjs +113 -0
  64. package/build/image-editor/react/hooks/use-cropper-reducer.cjs.map +7 -0
  65. package/build/image-editor/react/hooks/use-interaction.cjs +1 -1
  66. package/build/image-editor/react/hooks/use-interaction.cjs.map +2 -2
  67. package/build/state/composite-reducer.cjs +115 -0
  68. package/build/state/composite-reducer.cjs.map +7 -0
  69. package/build/state/index.cjs +48 -0
  70. package/build/state/index.cjs.map +7 -0
  71. package/build/state/media-editor-state-provider.cjs +58 -0
  72. package/build/state/media-editor-state-provider.cjs.map +7 -0
  73. package/build/state/types.cjs +34 -0
  74. package/build/state/types.cjs.map +7 -0
  75. package/build/state/use-media-editor-state.cjs +298 -0
  76. package/build/state/use-media-editor-state.cjs.map +7 -0
  77. package/build-module/components/media-editor/index.mjs +40 -140
  78. package/build-module/components/media-editor/index.mjs.map +2 -2
  79. package/build-module/components/media-editor/use-crop-options.mjs +61 -0
  80. package/build-module/components/media-editor/use-crop-options.mjs.map +7 -0
  81. package/build-module/components/media-editor/use-save-media-editor.mjs +151 -0
  82. package/build-module/components/media-editor/use-save-media-editor.mjs.map +7 -0
  83. package/build-module/components/media-editor-canvas/index.mjs +33 -12
  84. package/build-module/components/media-editor-canvas/index.mjs.map +2 -2
  85. package/build-module/components/media-editor-crop-panel/index.mjs +68 -83
  86. package/build-module/components/media-editor-crop-panel/index.mjs.map +2 -2
  87. package/build-module/components/media-editor-modal/index.mjs +40 -11
  88. package/build-module/components/media-editor-modal/index.mjs.map +2 -2
  89. package/build-module/components/media-editor-toolbar/index.mjs +7 -3
  90. package/build-module/components/media-editor-toolbar/index.mjs.map +2 -2
  91. package/build-module/components/media-form/index.mjs +9 -1
  92. package/build-module/components/media-form/index.mjs.map +2 -2
  93. package/build-module/components/media-form/sidebar-datetime-view.mjs +32 -0
  94. package/build-module/components/media-form/sidebar-datetime-view.mjs.map +7 -0
  95. package/build-module/components/rotation-ruler/index.mjs +8 -2
  96. package/build-module/components/rotation-ruler/index.mjs.map +2 -2
  97. package/build-module/hooks/use-crop-gesture-handlers.mjs +41 -4
  98. package/build-module/hooks/use-crop-gesture-handlers.mjs.map +2 -2
  99. package/build-module/image-editor/core/camera.mjs +34 -11
  100. package/build-module/image-editor/core/camera.mjs.map +2 -2
  101. package/build-module/image-editor/core/constants.mjs +4 -0
  102. package/build-module/image-editor/core/constants.mjs.map +2 -2
  103. package/build-module/image-editor/core/containment.mjs +75 -34
  104. package/build-module/image-editor/core/containment.mjs.map +2 -2
  105. package/build-module/image-editor/core/crop-rect.mjs +23 -0
  106. package/build-module/image-editor/core/crop-rect.mjs.map +7 -0
  107. package/build-module/image-editor/core/index.mjs +12 -0
  108. package/build-module/image-editor/core/index.mjs.map +2 -2
  109. package/build-module/image-editor/core/interaction-controller.mjs.map +2 -2
  110. package/build-module/image-editor/core/math/sanitize.mjs +63 -0
  111. package/build-module/image-editor/core/math/sanitize.mjs.map +7 -0
  112. package/build-module/image-editor/core/setter-helpers.mjs +39 -0
  113. package/build-module/image-editor/core/setter-helpers.mjs.map +7 -0
  114. package/build-module/image-editor/core/source-region.mjs +16 -14
  115. package/build-module/image-editor/core/source-region.mjs.map +2 -2
  116. package/build-module/image-editor/core/state.mjs +25 -11
  117. package/build-module/image-editor/core/state.mjs.map +2 -2
  118. package/build-module/image-editor/core/stencil-math.mjs +30 -19
  119. package/build-module/image-editor/core/stencil-math.mjs.map +2 -2
  120. package/build-module/image-editor/core/transform-style.mjs +12 -6
  121. package/build-module/image-editor/core/transform-style.mjs.map +2 -2
  122. package/build-module/image-editor/index.mjs +11 -2
  123. package/build-module/image-editor/index.mjs.map +2 -2
  124. package/build-module/image-editor/react/components/cropper-provider.mjs +3 -3
  125. package/build-module/image-editor/react/components/cropper-provider.mjs.map +2 -2
  126. package/build-module/image-editor/react/components/cropper.mjs +122 -49
  127. package/build-module/image-editor/react/components/cropper.mjs.map +2 -2
  128. package/build-module/image-editor/react/components/overlays/dimensions-overlay.mjs +147 -0
  129. package/build-module/image-editor/react/components/overlays/dimensions-overlay.mjs.map +7 -0
  130. package/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs +20 -10
  131. package/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs.map +2 -2
  132. package/build-module/image-editor/react/hooks/build-cropper-setters.mjs +46 -0
  133. package/build-module/image-editor/react/hooks/build-cropper-setters.mjs.map +7 -0
  134. package/build-module/image-editor/react/hooks/index.mjs +4 -2
  135. package/build-module/image-editor/react/hooks/index.mjs.map +2 -2
  136. package/build-module/image-editor/react/hooks/use-aria-announcer.mjs +3 -1
  137. package/build-module/image-editor/react/hooks/use-aria-announcer.mjs.map +2 -2
  138. package/build-module/image-editor/react/hooks/use-cropper-reducer.mjs +100 -0
  139. package/build-module/image-editor/react/hooks/use-cropper-reducer.mjs.map +7 -0
  140. package/build-module/image-editor/react/hooks/use-interaction.mjs +1 -1
  141. package/build-module/image-editor/react/hooks/use-interaction.mjs.map +2 -2
  142. package/build-module/state/composite-reducer.mjs +94 -0
  143. package/build-module/state/composite-reducer.mjs.map +7 -0
  144. package/build-module/state/index.mjs +26 -0
  145. package/build-module/state/index.mjs.map +7 -0
  146. package/build-module/state/media-editor-state-provider.mjs +34 -0
  147. package/build-module/state/media-editor-state-provider.mjs.map +7 -0
  148. package/build-module/state/types.mjs +9 -0
  149. package/build-module/state/types.mjs.map +7 -0
  150. package/build-module/state/use-media-editor-state.mjs +289 -0
  151. package/build-module/state/use-media-editor-state.mjs.map +7 -0
  152. package/build-style/style-rtl.css +46 -9
  153. package/build-style/style.css +46 -9
  154. package/build-types/components/media-editor/index.d.ts +4 -7
  155. package/build-types/components/media-editor/index.d.ts.map +1 -1
  156. package/build-types/components/media-editor/use-crop-options.d.ts +37 -0
  157. package/build-types/components/media-editor/use-crop-options.d.ts.map +1 -0
  158. package/build-types/components/media-editor/use-save-media-editor.d.ts +29 -0
  159. package/build-types/components/media-editor/use-save-media-editor.d.ts.map +1 -0
  160. package/build-types/components/media-editor-canvas/index.d.ts +5 -10
  161. package/build-types/components/media-editor-canvas/index.d.ts.map +1 -1
  162. package/build-types/components/media-editor-crop-panel/index.d.ts +4 -16
  163. package/build-types/components/media-editor-crop-panel/index.d.ts.map +1 -1
  164. package/build-types/components/media-editor-modal/index.d.ts.map +1 -1
  165. package/build-types/components/media-editor-toolbar/index.d.ts.map +1 -1
  166. package/build-types/components/media-form/index.d.ts.map +1 -1
  167. package/build-types/components/media-form/sidebar-datetime-view.d.ts +10 -0
  168. package/build-types/components/media-form/sidebar-datetime-view.d.ts.map +1 -0
  169. package/build-types/components/rotation-ruler/index.d.ts.map +1 -1
  170. package/build-types/hooks/use-crop-gesture-handlers.d.ts +13 -14
  171. package/build-types/hooks/use-crop-gesture-handlers.d.ts.map +1 -1
  172. package/build-types/image-editor/core/camera.d.ts.map +1 -1
  173. package/build-types/image-editor/core/constants.d.ts +18 -0
  174. package/build-types/image-editor/core/constants.d.ts.map +1 -1
  175. package/build-types/image-editor/core/containment.d.ts +10 -0
  176. package/build-types/image-editor/core/containment.d.ts.map +1 -1
  177. package/build-types/image-editor/core/crop-rect.d.ts +19 -0
  178. package/build-types/image-editor/core/crop-rect.d.ts.map +1 -0
  179. package/build-types/image-editor/core/index.d.ts +3 -1
  180. package/build-types/image-editor/core/index.d.ts.map +1 -1
  181. package/build-types/image-editor/core/interaction-controller.d.ts +5 -1
  182. package/build-types/image-editor/core/interaction-controller.d.ts.map +1 -1
  183. package/build-types/image-editor/core/math/sanitize.d.ts +70 -0
  184. package/build-types/image-editor/core/math/sanitize.d.ts.map +1 -0
  185. package/build-types/image-editor/core/setter-helpers.d.ts +24 -0
  186. package/build-types/image-editor/core/setter-helpers.d.ts.map +1 -0
  187. package/build-types/image-editor/core/source-region.d.ts.map +1 -1
  188. package/build-types/image-editor/core/state.d.ts +12 -0
  189. package/build-types/image-editor/core/state.d.ts.map +1 -1
  190. package/build-types/image-editor/core/stencil-math.d.ts +23 -18
  191. package/build-types/image-editor/core/stencil-math.d.ts.map +1 -1
  192. package/build-types/image-editor/core/transform-style.d.ts.map +1 -1
  193. package/build-types/image-editor/core/types.d.ts +23 -4
  194. package/build-types/image-editor/core/types.d.ts.map +1 -1
  195. package/build-types/image-editor/index.d.ts +4 -4
  196. package/build-types/image-editor/index.d.ts.map +1 -1
  197. package/build-types/image-editor/react/components/cropper-provider.d.ts +11 -7
  198. package/build-types/image-editor/react/components/cropper-provider.d.ts.map +1 -1
  199. package/build-types/image-editor/react/components/cropper.d.ts +6 -4
  200. package/build-types/image-editor/react/components/cropper.d.ts.map +1 -1
  201. package/build-types/image-editor/react/components/overlays/dimensions-overlay.d.ts +36 -0
  202. package/build-types/image-editor/react/components/overlays/dimensions-overlay.d.ts.map +1 -0
  203. package/build-types/image-editor/react/components/stencils/rectangle-stencil.d.ts +2 -1
  204. package/build-types/image-editor/react/components/stencils/rectangle-stencil.d.ts.map +1 -1
  205. package/build-types/image-editor/react/hooks/build-cropper-setters.d.ts +47 -0
  206. package/build-types/image-editor/react/hooks/build-cropper-setters.d.ts.map +1 -0
  207. package/build-types/image-editor/react/hooks/index.d.ts +4 -2
  208. package/build-types/image-editor/react/hooks/index.d.ts.map +1 -1
  209. package/build-types/image-editor/react/hooks/use-aria-announcer.d.ts.map +1 -1
  210. package/build-types/image-editor/react/hooks/use-cropper-reducer.d.ts +58 -0
  211. package/build-types/image-editor/react/hooks/use-cropper-reducer.d.ts.map +1 -0
  212. package/build-types/image-editor/react/hooks/use-interaction.d.ts.map +1 -1
  213. package/build-types/image-editor/stories/rectangle-crop.story.d.ts.map +1 -1
  214. package/build-types/state/composite-reducer.d.ts +39 -0
  215. package/build-types/state/composite-reducer.d.ts.map +1 -0
  216. package/build-types/state/index.d.ts +7 -0
  217. package/build-types/state/index.d.ts.map +1 -0
  218. package/build-types/state/media-editor-state-provider.d.ts +34 -0
  219. package/build-types/state/media-editor-state-provider.d.ts.map +1 -0
  220. package/build-types/state/types.d.ts +104 -0
  221. package/build-types/state/types.d.ts.map +1 -0
  222. package/build-types/state/use-media-editor-state.d.ts +104 -0
  223. package/build-types/state/use-media-editor-state.d.ts.map +1 -0
  224. package/package.json +19 -17
  225. package/src/components/media-editor/index.tsx +52 -188
  226. package/src/components/media-editor/test/use-crop-options.tsx +164 -0
  227. package/src/components/media-editor/use-crop-options.ts +115 -0
  228. package/src/components/media-editor/use-save-media-editor.ts +214 -0
  229. package/src/components/media-editor-canvas/index.tsx +56 -24
  230. package/src/components/media-editor-crop-panel/index.tsx +25 -61
  231. package/src/components/media-editor-crop-panel/test/index.tsx +17 -43
  232. package/src/components/media-editor-modal/index.tsx +50 -12
  233. package/src/components/media-editor-modal/test/build-modifiers.test.ts +14 -0
  234. package/src/components/media-editor-modal/test/index.tsx +143 -0
  235. package/src/components/media-editor-toolbar/index.tsx +9 -5
  236. package/src/components/media-form/index.tsx +15 -1
  237. package/src/components/media-form/sidebar-datetime-view.tsx +47 -0
  238. package/src/components/media-form/test/sidebar-datetime-view.test.tsx +96 -0
  239. package/src/components/rotation-ruler/README.md +11 -25
  240. package/src/components/rotation-ruler/index.tsx +17 -2
  241. package/src/components/rotation-ruler/style.scss +49 -13
  242. package/src/hooks/use-crop-gesture-handlers.ts +66 -17
  243. package/src/image-editor/README.md +28 -129
  244. package/src/image-editor/core/camera.ts +51 -26
  245. package/src/image-editor/core/constants.ts +19 -0
  246. package/src/image-editor/core/containment.ts +102 -49
  247. package/src/image-editor/core/crop-rect.ts +45 -0
  248. package/src/image-editor/core/index.ts +16 -4
  249. package/src/image-editor/core/interaction-controller.ts +5 -1
  250. package/src/image-editor/core/math/sanitize.ts +158 -0
  251. package/src/image-editor/core/math/test/sanitize.ts +244 -0
  252. package/src/image-editor/core/setter-helpers.ts +66 -0
  253. package/src/image-editor/core/source-region.ts +21 -14
  254. package/src/image-editor/core/state.ts +67 -15
  255. package/src/image-editor/core/stencil-math.ts +55 -35
  256. package/src/image-editor/core/test/camera.ts +367 -1
  257. package/src/image-editor/core/test/state.ts +101 -8
  258. package/src/image-editor/core/test/stencil-math.ts +193 -0
  259. package/src/image-editor/core/transform-style.ts +21 -6
  260. package/src/image-editor/core/types.ts +24 -4
  261. package/src/image-editor/docs/architecture.md +48 -89
  262. package/src/image-editor/docs/recipes.md +123 -659
  263. package/src/image-editor/index.ts +12 -3
  264. package/src/image-editor/react/components/cropper-provider.tsx +16 -12
  265. package/src/image-editor/react/components/cropper.scss +23 -4
  266. package/src/image-editor/react/components/cropper.tsx +197 -90
  267. package/src/image-editor/react/components/overlays/dimensions-overlay.tsx +269 -0
  268. package/src/image-editor/react/components/stencils/rectangle-stencil.tsx +22 -9
  269. package/src/image-editor/react/components/test/cropper.tsx +55 -13
  270. package/src/image-editor/react/hooks/build-cropper-setters.ts +105 -0
  271. package/src/image-editor/react/hooks/index.ts +4 -2
  272. package/src/image-editor/react/hooks/test/{use-cropper-state.ts → use-cropper-reducer.ts} +142 -286
  273. package/src/image-editor/react/hooks/use-aria-announcer.ts +3 -1
  274. package/src/image-editor/react/hooks/use-cropper-reducer.ts +204 -0
  275. package/src/image-editor/react/hooks/use-interaction.ts +3 -2
  276. package/src/image-editor/stories/rectangle-crop.story.tsx +7 -17
  277. package/src/state/composite-reducer.ts +152 -0
  278. package/src/state/index.ts +20 -0
  279. package/src/state/media-editor-state-provider.tsx +70 -0
  280. package/src/state/test/use-media-editor-state.ts +402 -0
  281. package/src/state/types.ts +107 -0
  282. package/src/state/use-media-editor-state.ts +488 -0
  283. package/tsconfig.json +2 -0
  284. package/tsconfig.tsbuildinfo +1 -1
  285. package/build/image-editor/react/hooks/use-cropper-state.cjs +0 -277
  286. package/build/image-editor/react/hooks/use-cropper-state.cjs.map +0 -7
  287. package/build-module/image-editor/react/hooks/use-cropper-state.mjs +0 -262
  288. package/build-module/image-editor/react/hooks/use-cropper-state.mjs.map +0 -7
  289. package/build-types/image-editor/react/hooks/use-cropper-state.d.ts +0 -97
  290. package/build-types/image-editor/react/hooks/use-cropper-state.d.ts.map +0 -1
  291. package/src/image-editor/docs/roadmap.md +0 -66
  292. package/src/image-editor/react/hooks/use-cropper-state.ts +0 -457
@@ -1,720 +1,184 @@
1
- # Recipes and Getting Started
1
+ # Image Editor Recipes
2
2
 
3
- > **Status: internal.** The module is not exported from `@wordpress/media-editor`'s public API. Code examples use the relative path `../image-editor` because only internal callers can reach the module. When it's promoted to the package's public surface, swap the import for `@wordpress/media-editor`.
3
+ > **Status: internal.** Import from `../image-editor` only inside `@wordpress/media-editor`.
4
4
 
5
- Getting started, extension points, and integration patterns.
6
-
7
- ## Getting started
8
-
9
- ### Step 1: Mount a basic cropper
10
-
11
- ```tsx
12
- import { Cropper, useCropperState } from '../image-editor';
13
-
14
- function ImageEditor() {
15
- const controller = useCropperState();
16
- return (
17
- <Cropper
18
- src="https://example.com/photo.jpg"
19
- controller={ controller }
20
- showDimming
21
- showGrid
22
- />
23
- );
24
- }
25
- ```
26
-
27
- The cropper fills its parent container. Wrap it in a sized element:
5
+ ## Mount a Cropper
28
6
 
29
7
  ```tsx
30
- <div style={ { width: 600, height: 400 } }>
31
- <Cropper src={ imageUrl } controller={ controller } />
32
- </div>
33
- ```
34
-
35
- ### Step 2: Add controls
36
-
37
- `useCropperState` returns a single `controller` object bundling the state and a named setter for every supported transition:
38
-
39
- ```tsx
40
- const controller = useCropperState();
41
- const {
42
- state,
43
- setZoom, setZoomAtPoint, setRotation, setFlip, snapRotate90, setCropRect,
44
- applyOperation, reset, isDirty, getCroppedImage,
45
- } = controller;
46
-
47
- // Zoom slider
48
- <input type="range" min={ 1 } max={ 10 } step={ 0.1 }
49
- value={ state.zoom } onChange={ e => setZoom( parseFloat( e.target.value ) ) } />
50
-
51
- // Rotation buttons
52
- <button onClick={ () => snapRotate90( -1 ) }>Rotate left</button>
53
- <button onClick={ () => snapRotate90( 1 ) }>Rotate right</button>
54
-
55
- // Flip
56
- <button onClick={ () => setFlip( { horizontal: !state.flip.horizontal, vertical: state.flip.vertical } ) }>
57
- Flip H
58
- </button>
59
-
60
- // Reset
61
- <button onClick={ () => reset() } disabled={ !isDirty }>Reset</button>
62
- ```
63
-
64
- ### Step 3: Export the result
65
-
66
- ```tsx
67
- // As a Blob (for upload or further processing):
68
- const blob = await getCroppedImage( 'image/jpeg', 0.9 );
69
-
70
- // As source-pixel coordinates (for server-side processing):
71
- import { getSourceRegion } from '../image-editor';
72
- const region = getSourceRegion( state, { width: naturalWidth, height: naturalHeight } );
73
-
74
- // As percentages (for WP REST API /edit endpoint):
75
- import { getSourceRegionPercent } from '../image-editor';
76
- const pct = getSourceRegionPercent( state, { width: naturalWidth, height: naturalHeight } );
77
- ```
8
+ import { Cropper, useCropperReducer } from '../image-editor';
78
9
 
79
- ## Architecture overview
10
+ function ImageCropper( { src }: { src: string } ) {
11
+ const controller = useCropperReducer();
80
12
 
81
- ```
82
- Consumer (plugin/theme/AI agent)
83
- |
84
- v
85
- useCropperState() -- State management (reducer + convenience setters)
86
- |
87
- v
88
- <Cropper> -- Orchestrates rendering and interaction
89
- |
90
- +-- stencil prop -- Pluggable crop area UI (StencilProps interface)
91
- +-- useInteraction() -- Mouse/touch/keyboard → named controller actions
92
- +-- useTransformStyle()-- State → CSS matrix
93
- |
94
- v
95
- Pipeline / Export -- TransformOperation[] → canvas → Blob
96
- ```
97
-
98
- ## Extension points
99
-
100
- ### 1. Custom stencils
101
-
102
- The crop area UI is fully pluggable. Any component that implements `StencilProps` can replace the default `RectangleStencil`.
103
-
104
- ```tsx
105
- import { Cropper, useCropperState } from '../image-editor';
106
- import type { StencilProps } from '../image-editor';
107
-
108
- function CircularStencil( { cropRect, containerSize, imageSize, onCropChange }: StencilProps ) {
109
- // Render a circular crop overlay using cropRect bounds.
110
- // Call onCropChange() when the user resizes.
111
- return <div className="circular-stencil">...</div>;
112
- }
113
-
114
- function MyCropper() {
115
- const controller = useCropperState();
116
- return <Cropper src="image.jpg" controller={ controller } stencil={ CircularStencil } />;
13
+ return (
14
+ <div style={ { width: 600, height: 400 } }>
15
+ <Cropper
16
+ src={ src }
17
+ controller={ controller }
18
+ freeformCrop
19
+ showDimming
20
+ showGrid="interactive"
21
+ />
22
+ </div>
23
+ );
117
24
  }
118
25
  ```
119
26
 
120
- **StencilProps contract:**
121
-
122
- | Prop | Type | Description |
123
- |------|------|-------------|
124
- | `cropRect` | `NormalizedRect` | Current crop area in [0,1] normalized space |
125
- | `containerSize` | `Size` | Container pixel dimensions |
126
- | `imageSize` | `Size` | Visual (rotated) image pixel dimensions |
127
- | `onCropChange` | `(rect) => void` | Call during drag to update the crop |
128
- | `onResizeEnd` | `() => void` | Call on mouseup to trigger settle animation |
129
- | `aspectRatio` | `number?` | Locked aspect ratio (width/height) |
130
- | `freeformCrop` | `boolean?` | Whether handles are shown |
131
- | `stencilTransition` | `string?` | CSS transition for settle animation |
132
- | `cropBounds` | `{minX,minY,maxX,maxY}?` | Allowed crop handle limits |
133
-
134
- ### 2. Transform pipeline (AI agent integration)
27
+ The cropper fills its parent. Always render it inside a sized container.
135
28
 
136
- The pipeline is the primary interface for programmatic control. Operations are JSON-serializable, making them ideal for AI agents, undo/redo stacks, and remote control.
137
-
138
- ```typescript
139
- import { useCropperState } from '../image-editor';
140
- import type { TransformOperation } from '../image-editor';
141
-
142
- // An AI agent generates a list of operations:
143
- const operations: TransformOperation[] = [
144
- { type: 'crop', rect: { x: 0.1, y: 0.1, width: 0.8, height: 0.8 } },
145
- { type: 'rotate', degrees: 15 },
146
- { type: 'zoom', factor: 1.5 },
147
- { type: 'flip', direction: 'horizontal' },
148
- ];
149
-
150
- // Apply them:
151
- const { applyOperation } = useCropperState();
152
- for ( const op of operations ) {
153
- applyOperation( op );
154
- }
155
- ```
156
-
157
- **Replay from scratch:**
158
-
159
- ```typescript
160
- import { stateFromPipeline } from '../image-editor';
161
-
162
- // Replay a pipeline from initial state:
163
- const finalState = stateFromPipeline( operations );
164
-
165
- // Serialize for storage (operations are plain JSON):
166
- const json = JSON.stringify( operations );
167
-
168
- // Deserialize:
169
- const ops = JSON.parse( json );
170
- ```
171
-
172
- **Adding new operation types:**
173
-
174
- 1. Add the operation variant to `TransformOperation` in `core/types.ts`
175
- 2. Handle it in `applyOperationToState()` in `core/transforms/pipeline.ts`
176
-
177
- ### 3. Custom export pipelines
178
-
179
- The export system converts cropper state to canvas output. Use `applyToCanvas()` to chain custom processing with the cropper transforms.
180
-
181
- ```typescript
182
- import { applyToCanvas } from '../image-editor';
183
-
184
- // 1. Apply your own processing first (brightness, filters, etc.):
185
- const processedCanvas = applyBrightness( sourceImage, { brightness: 1.2 } );
186
-
187
- // 2. Apply the cropper transforms on top:
188
- const finalCanvas = applyToCanvas(
189
- processedCanvas,
190
- { width: processedCanvas.width, height: processedCanvas.height },
191
- cropperState
192
- );
193
-
194
- // 3. Export however you need:
195
- const blob = await new Promise( ( resolve ) =>
196
- finalCanvas.toBlob( resolve, 'image/jpeg', 0.9 )
197
- );
198
- ```
199
-
200
- `applyToCanvas()` accepts any `CanvasImageSource`: `HTMLImageElement`, `HTMLCanvasElement`, `OffscreenCanvas`, `ImageBitmap`, `HTMLVideoElement`.
201
-
202
- ### 4. State management patterns
203
-
204
- The state is a plain object and the hook returns one `controller` bundle of state + named setters. There are two ways to wire it up depending on your component structure.
205
-
206
- **Direct hook (simple case):**
207
-
208
- When the cropper and controls are in the same component:
29
+ ## Add Controls
209
30
 
210
31
  ```tsx
211
- import { Cropper, useCropperState } from '../image-editor';
212
-
213
- function ImageEditor() {
214
- const controller = useCropperState();
215
- const { state, setZoom, snapRotate90, reset } = controller;
216
- return (
217
- <div>
218
- <button onClick={ () => setZoom( state.zoom + 0.5 ) }>Zoom In</button>
219
- <button onClick={ () => snapRotate90( 1 ) }>Rotate 90</button>
220
- <button onClick={ () => reset() }>Reset</button>
221
- <Cropper src="image.jpg" controller={ controller } />
222
- </div>
223
- );
224
- }
225
- ```
226
-
227
- **Provider pattern (deep component trees):**
228
-
229
- When controls and the cropper are in different parts of the tree, use `CropperProvider` to avoid prop-drilling. Any descendant can call `useCropper()` to access the controller:
32
+ function ImageCropperWithControls( { src }: { src: string } ) {
33
+ const controller = useCropperReducer();
34
+ const { state, setZoom, snapRotate90, toggleFlip, reset } = controller;
35
+
36
+ return (
37
+ <>
38
+ <button onClick={ () => setZoom( state.zoom + 0.5 ) }>
39
+ Zoom in
40
+ </button>
41
+ <button onClick={ () => snapRotate90( 1 ) }>Rotate right</button>
42
+ <button onClick={ () => toggleFlip( 'horizontal' ) }>
43
+ Flip horizontal
44
+ </button>
45
+ <button onClick={ () => reset() } disabled={ ! controller.isDirty }>
46
+ Reset
47
+ </button>
48
+ <Cropper src={ src } controller={ controller } freeformCrop />
49
+ </>
50
+ );
51
+ }
52
+ ```
53
+
54
+ When internal controls are split across components, use `CropperProvider`.
230
55
 
231
56
  ```tsx
232
57
  import { Cropper, CropperProvider, useCropper } from '../image-editor';
233
58
 
234
- function ImageEditor() {
235
- return (
236
- <CropperProvider>
237
- <Toolbar />
238
- <CropperPanel />
239
- <Sidebar />
240
- </CropperProvider>
241
- );
59
+ function Editor( { src }: { src: string } ) {
60
+ return (
61
+ <CropperProvider>
62
+ <Toolbar />
63
+ <CropperPanel src={ src } />
64
+ </CropperProvider>
65
+ );
242
66
  }
243
67
 
244
68
  function Toolbar() {
245
- const { state, setZoom, snapRotate90 } = useCropper();
246
- return (
247
- <div>
248
- <button onClick={ () => setZoom( state.zoom + 0.5 ) }>Zoom In</button>
249
- <button onClick={ () => snapRotate90( 1 ) }>Rotate 90</button>
250
- </div>
251
- );
69
+ const { snapRotate90 } = useCropper();
70
+ return <button onClick={ () => snapRotate90( 1 ) }>Rotate right</button>;
252
71
  }
253
72
 
254
- function CropperPanel() {
255
- const controller = useCropper();
256
- return <Cropper src="image.jpg" controller={ controller } freeformCrop />;
257
- }
258
-
259
- function Sidebar() {
260
- const { state } = useCropper();
261
- return <p>Zoom: { Math.round( state.zoom * 100 ) }%</p>;
73
+ function CropperPanel( { src }: { src: string } ) {
74
+ const controller = useCropper();
75
+ return <Cropper src={ src } controller={ controller } freeformCrop />;
262
76
  }
263
77
  ```
264
78
 
265
- **Programmatic control:**
266
-
267
- ```typescript
268
- // Observe state:
269
- useEffect( () => {
270
- console.log( 'Crop changed:', state.cropRect );
271
- // Send to analytics, sync with server, update AI context, etc.
272
- }, [ state ] );
273
-
274
- // Control programmatically — use the named setters:
275
- controller.setZoom( 2.0 );
276
- controller.setRotation( 45 );
277
- controller.snapRotate90( 1 );
278
- controller.settleCrop();
279
- ```
280
-
281
- ### 5. Source region for external tools
282
-
283
- `getSourceRegion()` converts the current crop state to source-pixel coordinates. This is the bridge between the cropper and external tools (image processing libraries, AI APIs, server-side processing) that work in source-pixel coordinates.
79
+ ## Use the Media Editor Composite Controller
284
80
 
285
- ```typescript
286
- import { getSourceRegion } from '../image-editor';
287
-
288
- const region = getSourceRegion( state, { width: naturalWidth, height: naturalHeight } );
289
- // region = { x, y, width, height, rotation, flip, zoom }
290
-
291
- // Send to server for processing:
292
- fetch( '/api/process', {
293
- method: 'POST',
294
- body: JSON.stringify( {
295
- imageId: 123,
296
- crop: { x: region.x, y: region.y, width: region.width, height: region.height },
297
- rotation: region.rotation,
298
- flip: region.flip,
299
- } ),
300
- } );
301
-
302
- // Send to AI API for region-specific editing:
303
- const aiRequest = {
304
- region: { x: region.x, y: region.y, width: region.width, height: region.height },
305
- prompt: 'Remove the background in this area',
306
- };
307
- ```
308
-
309
- ### 6. Multi-step editing pipelines
310
-
311
- `applyToCanvas()` applies the cropper's transform to an existing canvas or image source. This enables multi-step editing where an upstream tool (brightness, color, filters) has already processed the image.
312
-
313
- ```typescript
314
- import { applyToCanvas } from '../image-editor';
315
-
316
- // Step 1: Apply brightness/color adjustments to a canvas
317
- const processedCanvas = applyBrightness( sourceImage, { brightness: 1.2 } );
318
-
319
- // Step 2: Apply the crop/rotate/flip on top
320
- const finalCanvas = applyToCanvas(
321
- processedCanvas,
322
- { width: processedCanvas.width, height: processedCanvas.height },
323
- cropperState
324
- );
325
-
326
- // Step 3: Export
327
- const blob = await canvasToBlob( finalCanvas, 'image/jpeg', 0.9 );
328
- ```
329
-
330
- Accepts any `CanvasImageSource`: `HTMLImageElement`, `HTMLCanvasElement`, `OffscreenCanvas`, `ImageBitmap`, `HTMLVideoElement`.
331
-
332
- ### 7. State change notifications
333
-
334
- The `Cropper` component provides two notification mechanisms:
335
-
336
- - **`onStateChange`** — fires on every state change (every frame during a drag). Use for real-time syncing, live previews, or analytics.
337
- - **`onGestureStart` / `onGestureEnd`** — fire at gesture boundaries (pointerdown/pointerup, wheel burst start/end). Use for undo/redo snapshots, debounced saves, or "user finished editing" detection.
81
+ Use the media editor controller when cropper state must share history with controls such as aspect ratio and freeform crop.
338
82
 
339
83
  ```tsx
340
- <Cropper
341
- src="image.jpg"
342
- controller={ controller }
343
- onStateChange={ ( currentState ) => {
344
- // Fires every frame during drag — good for live preview.
345
- updateLivePreview( currentState );
346
- } }
347
- onGestureStart={ () => {
348
- // User started interacting — snapshot for undo.
349
- saveSnapshot( state );
350
- } }
351
- onGestureEnd={ () => {
352
- // User finished interacting — safe to save/sync.
353
- autosaveDraft( state );
354
- } }
355
- />
356
- ```
84
+ import { resolveAspectRatio, useMediaEditor } from '../../state';
85
+ import { Cropper } from '../image-editor';
357
86
 
358
- ### 8. Theming and styling
87
+ function MediaEditorCanvas( { src }: { src: string } ) {
88
+ const controller = useMediaEditor();
89
+ const aspectRatio = resolveAspectRatio(
90
+ controller.cropOptions.aspectRatioValue,
91
+ controller.state.image
92
+ );
359
93
 
360
- The component uses BEM-style CSS classes that themes can override:
361
-
362
- ```
363
- .wp-media-editor-image-editor -- Container (cursor: grab)
364
- .wp-media-editor-image-editor--dragging -- Applied during image pan drag (cursor: grabbing)
365
- .wp-media-editor-image-editor__image -- The image element
366
- .wp-media-editor-image-editor__stencil -- Crop area container (pointer-events: none)
367
- .wp-media-editor-image-editor__stencil-rect -- Crop border rectangle
368
- .wp-media-editor-image-editor__handle -- Resize handle (all, pointer-events: auto)
369
- .wp-media-editor-image-editor__handle--n -- North handle (cursor: ns-resize)
370
- .wp-media-editor-image-editor__handle--s -- South handle (cursor: ns-resize)
371
- .wp-media-editor-image-editor__handle--e -- East handle (cursor: ew-resize)
372
- .wp-media-editor-image-editor__handle--w -- West handle (cursor: ew-resize)
373
- .wp-media-editor-image-editor__handle--nw -- North-west handle (cursor: nwse-resize)
374
- .wp-media-editor-image-editor__handle--ne -- North-east handle (cursor: nesw-resize)
375
- .wp-media-editor-image-editor__handle--sw -- South-west handle (cursor: nesw-resize)
376
- .wp-media-editor-image-editor__handle--se -- South-east handle (cursor: nwse-resize)
377
- .wp-media-editor-image-editor__dimming -- Dimming overlay outside crop area
378
- .wp-media-editor-image-editor__grid -- Grid overlay container
379
- .wp-media-editor-image-editor__grid-line -- Individual grid line
380
- ```
381
-
382
- All styles are in CSS classes with no inline style overrides, so consumers can override anything with equal or higher specificity.
383
-
384
- **Override handles and dimming:**
385
-
386
- ```css
387
- .wp-media-editor-image-editor__handle {
388
- background: var(--wp--preset--color--primary);
389
- border-radius: 50%;
390
- }
391
- .wp-media-editor-image-editor__dimming {
392
- background: rgba(0, 0, 0, 0.6);
393
- }
394
- ```
395
-
396
- **Override cursors:**
397
-
398
- ```css
399
- /* Use crosshair instead of grab */
400
- .wp-media-editor-image-editor {
401
- cursor: crosshair;
402
- }
403
- .wp-media-editor-image-editor--dragging {
404
- cursor: move;
405
- }
406
- /* Custom handle cursor */
407
- .wp-media-editor-image-editor__handle {
408
- cursor: pointer;
94
+ return (
95
+ <Cropper
96
+ src={ src }
97
+ controller={ controller }
98
+ aspectRatio={ aspectRatio }
99
+ freeformCrop={ controller.cropOptions.freeformCrop }
100
+ onGestureStart={ controller.beginGesture }
101
+ onGestureEnd={ controller.endGesture }
102
+ />
103
+ );
409
104
  }
410
105
  ```
411
106
 
412
- **Override handle appearance per position:**
413
-
414
- ```css
415
- /* Only show corner handles, hide edge handles */
416
- .wp-media-editor-image-editor__handle--n,
417
- .wp-media-editor-image-editor__handle--s,
418
- .wp-media-editor-image-editor__handle--e,
419
- .wp-media-editor-image-editor__handle--w {
420
- display: none;
421
- }
422
- ```
423
-
424
- ## AI agent integration patterns
425
-
426
- ### Driving the cropper from an AI agent
107
+ ## Get Source Coordinates
427
108
 
428
- The pipeline API is designed for AI agents. An agent can:
109
+ Use source-region helpers when saving crop data instead of rendering a `Blob`.
429
110
 
430
- 1. **Analyze the image** and determine the optimal crop
431
- 2. **Generate a `TransformOperation[]`** with crop, rotation, zoom
432
- 3. **Apply it** via `applyOperation()` or `stateFromPipeline()`
433
- 4. **Export the result** via `exportCroppedImage()`
111
+ ```ts
112
+ import { getSourceRegion, getSourceRegionPercent } from '../image-editor';
434
113
 
435
- ```typescript
436
- // Agent generates instructions:
437
- const agentInstructions = {
438
- crop: { x: 0.1, y: 0.05, width: 0.8, height: 0.9 },
439
- rotation: 2, // slight straighten
440
- zoom: 1.1,
441
- };
442
-
443
- // Apply:
444
- applyOperation( { type: 'crop', rect: agentInstructions.crop } );
445
- applyOperation( { type: 'rotate', degrees: agentInstructions.rotation } );
446
- applyOperation( { type: 'zoom', factor: agentInstructions.zoom } );
114
+ const imageSize = { width: naturalWidth, height: naturalHeight };
115
+ const region = getSourceRegion( controller.state, imageSize );
116
+ const percent = getSourceRegionPercent( controller.state, imageSize );
447
117
  ```
448
118
 
449
- ### Headless editing (no React, no DOM)
450
-
451
- The core layer is pure functions — no React or browser required for steps 1-2:
452
-
453
- ```typescript
454
- import {
455
- stateFromPipeline,
456
- getSourceRegion,
457
- exportCroppedImage,
458
- } from '../image-editor';
459
-
460
- // 1. Build state from operations (pure — runs in Node, workers, anywhere)
461
- const state = stateFromPipeline( [
462
- { type: 'crop', rect: { x: 0.1, y: 0.1, width: 0.8, height: 0.8 } },
463
- { type: 'rotate', degrees: 5 },
464
- { type: 'zoom', factor: 1.2 },
465
- { type: 'flip', direction: 'horizontal' },
466
- ] );
467
-
468
- // 2. Get source-pixel region (pure — for server-side FFmpeg/ImageMagick)
469
- const region = getSourceRegion( state, { width: 4000, height: 3000 } );
470
- // → { x: 400, y: 300, width: 3200, height: 2400, rotation: 5, flip: {...}, zoom: 1.2 }
119
+ `getSourceRegionPercent()` matches the crop data shape used by the WordPress attachments `/edit` endpoint.
471
120
 
472
- // Pass to server:
473
- // ffmpeg -i input.jpg -vf "crop=3200:2400:400:300,rotate=0.087" output.jpg
121
+ ## Export a Cropped Image
474
122
 
475
- // 3. Or export to Blob (needs canvas — browser or node-canvas)
476
- const blob = await exportCroppedImage( imageUrl, state, 'image/jpeg', 0.9 );
123
+ ```ts
124
+ const blob = await controller.getCroppedImage( 'image/jpeg', 0.9 );
477
125
  ```
478
126
 
479
- Steps 1 and 2 are pure functions with zero DOM dependencies. Step 3 needs `canvas` and `Image` (browser, jsdom, or node-canvas).
480
-
481
- ## Multi-step editing integration
482
-
483
- The package is designed to be one step in a broader image editing pipeline. Key integration patterns:
484
-
485
- ### Crop as a step (Google Photos style)
486
-
487
- The state is external and serializable. You can:
488
- 1. Mount the Cropper, let the user crop
489
- 2. Snapshot `state` (it's a plain object)
490
- 3. Switch to a brightness/color tab (unmount Cropper, the state persists)
491
- 4. Switch back — restore `state`, remount Cropper, pick up where you left off
127
+ For a custom canvas pipeline, use `applyToCanvas()`.
492
128
 
493
- ```typescript
494
- // Save state when switching tabs:
495
- const savedCropState = { ...state };
129
+ ```ts
130
+ import { applyToCanvas } from '../image-editor';
496
131
 
497
- // Restore when coming back:
498
- const controller = useCropperState( savedCropState );
132
+ const output = applyToCanvas(
133
+ processedCanvas,
134
+ { width: processedCanvas.width, height: processedCanvas.height },
135
+ controller.state
136
+ );
499
137
  ```
500
138
 
501
- ### Undo/redo with gesture support
139
+ Canvas export is browser-only. Cross-origin images need valid CORS headers or the canvas will be tainted.
502
140
 
503
- The `Cropper` component fires `onGestureStart` and `onGestureEnd` callbacks at the boundaries of continuous interactions (pan drags, handle resizes, wheel/pinch zoom). These let you snapshot state before and after each gesture, treating the entire drag as a single undo step.
141
+ ## Programmatic Edits
504
142
 
505
- **Two kinds of undo entries:**
143
+ `TransformOperation` values are plain JSON. Apply them one at a time or replay them from scratch.
506
144
 
507
- 1. **Toolbar operations** (rotate, flip, zoom buttons) — snapshot state before calling a setter, then apply the `TransformOperation`.
508
- 2. **Gestures** (drag, resize, wheel zoom) — snapshot state in `onGestureStart`, compare with the current state in `onGestureEnd`, and push the before-state onto the undo stack.
145
+ ```ts
146
+ import { stateFromPipeline, type TransformOperation } from '../image-editor';
509
147
 
510
- See the `UndoRedo` story for a complete working example. Here is the core pattern:
148
+ const operations: TransformOperation[] = [
149
+ { type: 'crop', rect: { x: 0.1, y: 0.1, width: 0.8, height: 0.8 } },
150
+ { type: 'rotate', degrees: 5 },
151
+ { type: 'flip', direction: 'horizontal' },
152
+ ];
511
153
 
512
- ```tsx
513
- import { Cropper, useCropperState } from '../image-editor';
514
- import type { CropperState, TransformOperation } from '../image-editor';
515
- import { useState, useCallback, useRef, useEffect } from '@wordpress/element';
516
-
517
- function ImageEditorWithUndo( { src }: { src: string } ) {
518
- const controller = useCropperState();
519
- const { state, applyOperation, reset } = controller;
520
-
521
- // Keep a ref to the latest state so gesture callbacks never go stale.
522
- const stateRef = useRef( state );
523
- stateRef.current = state;
524
-
525
- // Undo/redo stacks store full CropperState snapshots.
526
- const [ past, setPast ] = useState< CropperState[] >( [] );
527
- const [ future, setFuture ] = useState< CropperState[] >( [] );
528
-
529
- // Ref to hold the state snapshot captured at gesture start.
530
- const snapshotRef = useRef< CropperState | null >( null );
531
-
532
- // --- Toolbar operations ---
533
-
534
- const applyToolbarOp = useCallback(
535
- ( op: TransformOperation ) => {
536
- // Snapshot current state before applying.
537
- setPast( ( prev ) => [ ...prev, { ...state } ] );
538
- setFuture( [] );
539
- applyOperation( op );
540
- },
541
- [ state, applyOperation ]
542
- );
543
-
544
- // --- Gesture-based undo ---
545
-
546
- const handleGestureStart = useCallback( () => {
547
- // Capture state at the start of the gesture (via ref to avoid stale closure).
548
- snapshotRef.current = { ...stateRef.current };
549
- }, [] );
550
-
551
- const handleGestureEnd = useCallback( () => {
552
- if ( ! snapshotRef.current ) {
553
- return;
554
- }
555
- const before = snapshotRef.current;
556
- snapshotRef.current = null;
557
-
558
- // Push the before-state as an undo entry.
559
- setPast( ( prev ) => [ ...prev, before ] );
560
- setFuture( [] );
561
- }, [] );
562
-
563
- // --- Undo / Redo ---
564
-
565
- const undo = useCallback( () => {
566
- if ( past.length === 0 ) {
567
- return;
568
- }
569
- const newPast = [ ...past ];
570
- const previous = newPast.pop()!;
571
- setPast( newPast );
572
- setFuture( ( prev ) => [ ...prev, { ...state } ] );
573
- reset( previous );
574
- }, [ past, state, reset ] );
575
-
576
- const redo = useCallback( () => {
577
- if ( future.length === 0 ) {
578
- return;
579
- }
580
- const newFuture = [ ...future ];
581
- const next = newFuture.pop()!;
582
- setPast( ( prev ) => [ ...prev, { ...state } ] );
583
- setFuture( newFuture );
584
- reset( next );
585
- }, [ future, state, reset ] );
586
-
587
- // --- Keyboard shortcuts (use refs to avoid stale closures) ---
588
-
589
- const undoRef = useRef( undo );
590
- const redoRef = useRef( redo );
591
- undoRef.current = undo;
592
- redoRef.current = redo;
593
-
594
- useEffect( () => {
595
- const handler = ( e: KeyboardEvent ) => {
596
- if ( ( e.metaKey || e.ctrlKey ) && e.key === 'z' ) {
597
- e.preventDefault();
598
- if ( e.shiftKey ) {
599
- redoRef.current();
600
- } else {
601
- undoRef.current();
602
- }
603
- }
604
- };
605
- document.addEventListener( 'keydown', handler );
606
- return () => document.removeEventListener( 'keydown', handler );
607
- }, [] );
608
-
609
- return (
610
- <div>
611
- <div>
612
- <button onClick={ undo } disabled={ past.length === 0 }>
613
- Undo ({ past.length })
614
- </button>
615
- <button onClick={ redo } disabled={ future.length === 0 }>
616
- Redo ({ future.length })
617
- </button>
618
- <button onClick={ () => applyToolbarOp( { type: 'rotate', degrees: 15 } ) }>
619
- Rotate +15
620
- </button>
621
- </div>
622
-
623
- <Cropper
624
- src={ src }
625
- controller={ controller }
626
- freeformCrop
627
- onGestureStart={ handleGestureStart }
628
- onGestureEnd={ handleGestureEnd }
629
- />
630
- </div>
631
- );
154
+ for ( const operation of operations ) {
155
+ controller.applyOperation( operation );
632
156
  }
633
- ```
634
-
635
- **Key implementation details:**
636
-
637
- | Concern | Solution |
638
- |---------|----------|
639
- | Stale closures in gesture callbacks | Use `useRef` for state (`stateRef`) and snapshot (`snapshotRef`). The callbacks are stable (`[]` deps) and always read the latest value. |
640
- | Stale closures in keyboard handler | Use `undoRef` / `redoRef` updated on every render, with the listener registered once (`[]` deps). |
641
- | Wheel zoom boundaries | The `useInteraction` hook debounces wheel events — it fires `onGestureStart` on the first scroll tick and `onGestureEnd` after 300ms of inactivity, grouping a burst of scroll events into one undo step. |
642
- | Handle resize settle | `onGestureEnd` fires after the settle animation (crop re-centers). The undo snapshot captures the final settled state. |
643
- | Pipeline display | For toolbar ops, log the `TransformOperation`. For gestures, compare before/after state and generate a descriptive label (e.g., "gesture: pan, zoom 1.5x"). |
644
-
645
- ## Accessibility
646
157
 
647
- The cropper is keyboard-accessible and screen-reader friendly:
648
-
649
- **Keyboard controls:**
650
- - **Arrow keys** on the container: pan the image (Shift for larger jumps)
651
- - **+/-** on the container: zoom in/out
652
- - **R** on the container: snap rotate 90°
653
- - **Tab** to crop handles, then **arrow keys** to resize (Shift for larger jumps)
654
- - Aspect ratio lock is respected during keyboard resize
655
-
656
- **Screen reader support:**
657
- - Container is a focusable `role="group"` with `aria-label="Image editor"`. We deliberately avoid `role="application"` because it disables the screen reader's default keybindings — too heavy for a single widget.
658
- - Resize handles are native `<button>` elements with descriptive `aria-label` (e.g., "Resize top-left corner"). Native buttons give correct focus behavior and announcements without extra ARIA.
659
- - An ARIA live region announces state changes (zoom, rotation, crop dimensions) with 300ms debounce.
660
-
661
- **For theme/plugin developers:**
662
- - Custom stencils should preserve `tabIndex`, `role`, and `aria-*` attributes on interactive elements
663
- - Use `aria-live="polite"` for any custom state announcements
664
- - Ensure custom overlays don't trap keyboard focus
665
-
666
- ## Testing
667
-
668
- ### Running unit tests
669
-
670
- ```bash
671
- # All media-editor/image-editor unit tests
672
- npx wp-scripts test-unit-js --testPathPattern="media-editor/image-editor"
673
-
674
- # Specific test file (e.g., camera tests only)
675
- npx wp-scripts test-unit-js --testPathPattern="media-editor/image-editor" --testNamePattern="camera"
676
-
677
- # TypeScript type checking (no emit)
678
- npx tsc --project packages/media-editor/src/image-editor/tsconfig.json --noEmit
158
+ const finalState = stateFromPipeline( operations );
679
159
  ```
680
160
 
681
- ### Running visual regression tests (storybook-playwright)
161
+ ## Accessibility Notes
682
162
 
683
- Visual regression tests use Playwright to screenshot Storybook stories and compare against baseline images. The spec is at `test/storybook-playwright/specs/image-editor.spec.ts`.
163
+ - The crop area is focusable and keyboard-operable.
164
+ - Resize handles are native buttons.
165
+ - Arrow keys pan the image or resize the focused handle.
166
+ - Shift increases keyboard pan/resize distance.
167
+ - `R` performs a 90 degree rotation.
168
+ - State changes are announced through an ARIA live region.
684
169
 
685
- ```bash
686
- # Start Storybook first (port 50241)
687
- npm run storybook
170
+ ## Tests
688
171
 
689
- # Run the visual regression tests
690
- npx playwright test test/storybook-playwright/specs/image-editor.spec.ts
172
+ Run focused unit tests with:
691
173
 
692
- # Update screenshots after intentional visual changes
693
- npx playwright test test/storybook-playwright/specs/image-editor.spec.ts --update-snapshots
174
+ ```bash
175
+ npm run test:unit packages/media-editor/src/image-editor -- --runInBand
694
176
  ```
695
177
 
696
- ### What the tests cover
697
-
698
- **Export matrix verification** (`core/export/test/canvas-renderer.ts`):
699
- - Identity state produces a 1:1 scale mapping with no rotation components
700
- - 90-degree rotation encodes rotation in the off-diagonal matrix values (a,d near zero; b,c non-zero with opposite signs)
701
- - Zoom 2x doubles the scale components relative to zoom 1x
702
- - Horizontal flip negates the x-scale component
703
- - `applyToCanvas` creates a canvas with correct dimensions and calls `setTransform`
704
-
705
- **Containment invariant** (`core/test/camera.ts`):
706
- - Verifies the image fully covers the crop area across multiple rotation and zoom combinations
707
- - Tests `restrictPanZoom` and `restrictCropRect` boundary enforcement
708
- - Run after any changes to camera restriction logic
709
-
710
- **Visual regression** (`test/storybook-playwright/specs/image-editor.spec.ts`):
711
- - Screenshots the Default and WithControls stories
712
- - Catches unintended visual changes to the cropper UI
713
-
714
- ### Adding new test cases
715
-
716
- 1. **New export transform tests**: Add to the `renderToCanvas -- export matrix verification` describe block in `core/export/test/canvas-renderer.ts`. Use `setupMockCanvas()` to initialize mocks, then call `renderToCanvas` and inspect `mockCtx.setTransform.mock.calls[0]` for the 6 matrix values `[a, b, c, d, e, f]`.
717
-
718
- 2. **New containment invariant cases**: Add rotation/zoom combinations to the parametric test in `core/test/camera.ts`.
178
+ Useful test areas:
719
179
 
720
- 3. **New visual regression stories**: Add a new test case in `test/storybook-playwright/specs/image-editor.spec.ts` using `gotoStoryId` with the Storybook story ID (format: `mediaeditor-imagecropper--story-name`).
180
+ - `core/test/camera.ts` for containment and camera invariants.
181
+ - `core/test/state.ts` for reducer behavior.
182
+ - `core/export/test/canvas-renderer.ts` for canvas export.
183
+ - `react/components/test/cropper.tsx` for React cropper behavior.
184
+ - `react/components/stencils/test/rectangle-stencil.tsx` for resize handles.