@wordpress/media-editor 0.20.0 → 0.21.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 (116) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +2 -1
  3. package/build/components/media-editor/index.cjs +7 -16
  4. package/build/components/media-editor/index.cjs.map +3 -3
  5. package/build/components/media-editor/use-crop-options.cjs +1 -2
  6. package/build/components/media-editor/use-crop-options.cjs.map +2 -2
  7. package/build/components/media-editor-canvas/index.cjs.map +3 -3
  8. package/build/components/media-editor-crop-panel/index.cjs +12 -8
  9. package/build/components/media-editor-crop-panel/index.cjs.map +3 -3
  10. package/build/components/media-editor-modal/index.cjs +2 -0
  11. package/build/components/media-editor-modal/index.cjs.map +2 -2
  12. package/build/components/media-editor-provider/index.cjs +2 -1
  13. package/build/components/media-editor-provider/index.cjs.map +2 -2
  14. package/build/components/media-form/index.cjs +28 -28
  15. package/build/components/media-form/index.cjs.map +3 -3
  16. package/build/components/media-preview/index.cjs.map +3 -3
  17. package/build/image-editor/react/components/cropper.cjs +1 -11
  18. package/build/image-editor/react/components/cropper.cjs.map +2 -2
  19. package/build/state/composite-reducer.cjs +33 -8
  20. package/build/state/composite-reducer.cjs.map +3 -3
  21. package/build/state/index.cjs.map +1 -1
  22. package/build/state/types.cjs.map +1 -1
  23. package/build/state/use-media-editor-state.cjs +20 -7
  24. package/build/state/use-media-editor-state.cjs.map +2 -2
  25. package/build-module/components/media-editor/index.mjs +9 -18
  26. package/build-module/components/media-editor/index.mjs.map +2 -2
  27. package/build-module/components/media-editor/use-crop-options.mjs +1 -2
  28. package/build-module/components/media-editor/use-crop-options.mjs.map +2 -2
  29. package/build-module/components/media-editor-canvas/index.mjs +2 -2
  30. package/build-module/components/media-editor-canvas/index.mjs.map +2 -2
  31. package/build-module/components/media-editor-crop-panel/index.mjs +13 -9
  32. package/build-module/components/media-editor-crop-panel/index.mjs.map +2 -2
  33. package/build-module/components/media-editor-modal/index.mjs +2 -0
  34. package/build-module/components/media-editor-modal/index.mjs.map +2 -2
  35. package/build-module/components/media-editor-provider/index.mjs +2 -1
  36. package/build-module/components/media-editor-provider/index.mjs.map +2 -2
  37. package/build-module/components/media-form/index.mjs +33 -30
  38. package/build-module/components/media-form/index.mjs.map +2 -2
  39. package/build-module/components/media-preview/index.mjs +2 -2
  40. package/build-module/components/media-preview/index.mjs.map +2 -2
  41. package/build-module/image-editor/react/components/cropper.mjs +1 -11
  42. package/build-module/image-editor/react/components/cropper.mjs.map +2 -2
  43. package/build-module/state/composite-reducer.mjs +23 -8
  44. package/build-module/state/composite-reducer.mjs.map +2 -2
  45. package/build-module/state/index.mjs.map +1 -1
  46. package/build-module/state/types.mjs.map +1 -1
  47. package/build-module/state/use-media-editor-state.mjs +20 -7
  48. package/build-module/state/use-media-editor-state.mjs.map +2 -2
  49. package/build-types/components/media-editor/index.d.ts +2 -1
  50. package/build-types/components/media-editor/index.d.ts.map +1 -1
  51. package/build-types/components/media-editor/use-crop-options.d.ts +0 -1
  52. package/build-types/components/media-editor/use-crop-options.d.ts.map +1 -1
  53. package/build-types/components/media-editor-crop-panel/index.d.ts.map +1 -1
  54. package/build-types/components/media-editor-modal/index.d.ts +7 -2
  55. package/build-types/components/media-editor-modal/index.d.ts.map +1 -1
  56. package/build-types/components/media-editor-provider/index.d.ts +7 -1
  57. package/build-types/components/media-editor-provider/index.d.ts.map +1 -1
  58. package/build-types/components/media-form/index.d.ts +5 -2
  59. package/build-types/components/media-form/index.d.ts.map +1 -1
  60. package/build-types/image-editor/react/components/cropper.d.ts.map +1 -1
  61. package/build-types/state/composite-reducer.d.ts +1 -1
  62. package/build-types/state/composite-reducer.d.ts.map +1 -1
  63. package/build-types/state/index.d.ts +1 -1
  64. package/build-types/state/index.d.ts.map +1 -1
  65. package/build-types/state/types.d.ts +34 -5
  66. package/build-types/state/types.d.ts.map +1 -1
  67. package/build-types/state/use-media-editor-state.d.ts +16 -5
  68. package/build-types/state/use-media-editor-state.d.ts.map +1 -1
  69. package/package.json +33 -22
  70. package/src/components/media-editor/index.tsx +12 -22
  71. package/src/components/media-editor/use-crop-options.ts +0 -2
  72. package/src/components/media-editor-canvas/index.tsx +2 -2
  73. package/src/components/media-editor-crop-panel/index.tsx +17 -9
  74. package/src/components/media-editor-image-controls/style.scss +1 -1
  75. package/src/components/media-editor-modal/index.tsx +8 -1
  76. package/src/components/media-editor-provider/index.tsx +8 -1
  77. package/src/components/media-form/index.tsx +48 -42
  78. package/src/components/media-preview/index.tsx +2 -2
  79. package/src/image-editor/docs/architecture.md +4 -0
  80. package/src/image-editor/react/components/cropper.tsx +1 -15
  81. package/src/state/composite-reducer.ts +24 -11
  82. package/src/state/index.ts +2 -0
  83. package/src/state/types.ts +37 -5
  84. package/src/state/use-media-editor-state.ts +46 -11
  85. package/global.d.ts +0 -5
  86. package/src/components/media-editor/test/restore-original.browser.test.tsx +0 -227
  87. package/src/components/media-editor/test/use-crop-options.jsdom.test.tsx +0 -106
  88. package/src/components/media-editor-crop-panel/test/index.jsdom.test.tsx +0 -72
  89. package/src/components/media-editor-image-controls/test/index.jsdom.test.tsx +0 -186
  90. package/src/components/media-editor-modal/test/build-modifiers.test.ts +0 -359
  91. package/src/components/media-editor-modal/test/index.jsdom.test.tsx +0 -182
  92. package/src/components/rotation-ruler/stories/index.story.tsx +0 -43
  93. package/src/components/rotation-ruler/test/index.jsdom.test.tsx +0 -140
  94. package/src/image-editor/core/export/test/canvas-renderer.jsdom.test.ts +0 -823
  95. package/src/image-editor/core/math/test/sanitize.ts +0 -242
  96. package/src/image-editor/core/test/camera.ts +0 -1218
  97. package/src/image-editor/core/test/interaction-controller.ts +0 -1299
  98. package/src/image-editor/core/test/preview-export-parity.ts +0 -249
  99. package/src/image-editor/core/test/render-camera-bridge.ts +0 -349
  100. package/src/image-editor/core/test/state.ts +0 -876
  101. package/src/image-editor/core/test/stencil-math.ts +0 -665
  102. package/src/image-editor/core/transforms/test/pipeline.ts +0 -267
  103. package/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx +0 -438
  104. package/src/image-editor/react/components/test/cropper.browser.test.tsx +0 -1462
  105. package/src/image-editor/react/hooks/test/use-aria-announcer.jsdom.test.ts +0 -491
  106. package/src/image-editor/react/hooks/test/use-cropper-reducer.jsdom.test.ts +0 -1049
  107. package/src/image-editor/react/hooks/test/use-interaction.jsdom.test.ts +0 -213
  108. package/src/image-editor/react/hooks/test/use-transform-style.jsdom.test.ts +0 -140
  109. package/src/image-editor/stories/rectangle-crop.story.tsx +0 -1073
  110. package/src/image-editor/stories/style.module.css +0 -65
  111. package/src/state/test/use-media-editor-state.browser.test.tsx +0 -79
  112. package/src/state/test/use-media-editor-state.jsdom.test.ts +0 -386
  113. package/src/store/test/reducer.ts +0 -64
  114. package/tsconfig.build.json +0 -26
  115. package/tsconfig.build.tsbuildinfo +0 -1
  116. package/tsconfig.json +0 -37
@@ -1,823 +0,0 @@
1
- import {
2
- afterEach,
3
- beforeEach,
4
- describe,
5
- expect,
6
- it,
7
- vi,
8
- type Mock,
9
- } from 'vitest';
10
- import type { CropperState } from '../../types';
11
- import { DEFAULT_STATE } from '../../constants';
12
- import {
13
- loadImage,
14
- renderToCanvas,
15
- applyToCanvas,
16
- canvasToBlob,
17
- canvasToDataURL,
18
- exportCroppedImage,
19
- } from '../canvas-renderer';
20
-
21
- /**
22
- * Mock context that records all calls for assertion.
23
- */
24
- function createMockContext() {
25
- return {
26
- setTransform: vi.fn(),
27
- translate: vi.fn(),
28
- rotate: vi.fn(),
29
- scale: vi.fn(),
30
- drawImage: vi.fn(),
31
- getImageData: vi.fn(),
32
- putImageData: vi.fn(),
33
- beginPath: vi.fn(),
34
- closePath: vi.fn(),
35
- moveTo: vi.fn(),
36
- lineTo: vi.fn(),
37
- clip: vi.fn(),
38
- };
39
- }
40
-
41
- /**
42
- * Create a mock canvas element with a spy-based 2D context.
43
- *
44
- * @param ctx The mock 2D context to attach to the canvas.
45
- */
46
- function createMockCanvas( ctx: ReturnType< typeof createMockContext > ) {
47
- const canvas = {
48
- width: 0,
49
- height: 0,
50
- getContext: vi.fn().mockReturnValue( ctx ),
51
- toBlob: vi.fn(),
52
- toDataURL: vi.fn().mockReturnValue( 'data:image/png;base64,abc' ),
53
- };
54
- return canvas as unknown as HTMLCanvasElement;
55
- }
56
-
57
- /**
58
- * A default test state with an image loaded and a partial crop.
59
- *
60
- * @param overrides Optional partial state to merge.
61
- */
62
- function createTestState( overrides?: Partial< CropperState > ): CropperState {
63
- return {
64
- ...DEFAULT_STATE,
65
- image: {
66
- src: 'https://example.com/photo.jpg',
67
- naturalWidth: 800,
68
- naturalHeight: 600,
69
- },
70
- pan: { ...DEFAULT_STATE.pan },
71
- flip: { ...DEFAULT_STATE.flip },
72
- cropRect: { x: 0.1, y: 0.2, width: 0.5, height: 0.5 },
73
- ...overrides,
74
- };
75
- }
76
-
77
- describe( 'loadImage', () => {
78
- it( 'should create an image element with crossOrigin set', async () => {
79
- const mockImage = {
80
- addEventListener: vi.fn(),
81
- set crossOrigin( value: string ) {
82
- this._crossOrigin = value;
83
- },
84
- get crossOrigin() {
85
- return this._crossOrigin;
86
- },
87
- _crossOrigin: '',
88
- set src( value: string ) {
89
- this._src = value;
90
- // Simulate successful load on next tick.
91
- const loadHandler = this.addEventListener.mock.calls.find(
92
- ( call: string[] ) => call[ 0 ] === 'load'
93
- );
94
- if ( loadHandler ) {
95
- loadHandler[ 1 ]();
96
- }
97
- },
98
- get src() {
99
- return this._src;
100
- },
101
- _src: '',
102
- };
103
-
104
- // Replace global Image constructor.
105
- const originalImage = global.Image;
106
- global.Image = vi.fn( function Image() {
107
- return mockImage;
108
- } ) as unknown as typeof Image;
109
-
110
- try {
111
- const result = await loadImage( 'https://example.com/test.jpg' );
112
- expect( result ).toBe( mockImage );
113
- expect( mockImage.crossOrigin ).toBe( 'anonymous' );
114
- expect( mockImage.src ).toBe( 'https://example.com/test.jpg' );
115
- expect( mockImage.addEventListener ).toHaveBeenCalledWith(
116
- 'load',
117
- expect.any( Function )
118
- );
119
- expect( mockImage.addEventListener ).toHaveBeenCalledWith(
120
- 'error',
121
- expect.any( Function )
122
- );
123
- } finally {
124
- global.Image = originalImage;
125
- }
126
- } );
127
-
128
- it( 'should reject when the image fails to load', async () => {
129
- const loadError = new Error( 'Network error' );
130
- const mockImage = {
131
- addEventListener: vi.fn(),
132
- set crossOrigin( _value: string ) {},
133
- set src( _value: string ) {
134
- // Simulate error on next tick.
135
- const errorHandler = this.addEventListener.mock.calls.find(
136
- ( call: string[] ) => call[ 0 ] === 'error'
137
- );
138
- if ( errorHandler ) {
139
- errorHandler[ 1 ]( loadError );
140
- }
141
- },
142
- };
143
-
144
- const originalImage = global.Image;
145
- global.Image = vi.fn( function Image() {
146
- return mockImage;
147
- } ) as unknown as typeof Image;
148
-
149
- try {
150
- await expect(
151
- loadImage( 'https://example.com/broken.jpg' )
152
- ).rejects.toBe( loadError );
153
- } finally {
154
- global.Image = originalImage;
155
- }
156
- } );
157
- } );
158
-
159
- describe( 'renderToCanvas', () => {
160
- let mockCtx: ReturnType< typeof createMockContext >;
161
- let canvasCount: number;
162
-
163
- beforeEach( () => {
164
- mockCtx = createMockContext();
165
- canvasCount = 0;
166
-
167
- // Mock document.createElement to return our mock canvases.
168
- vi.spyOn( document, 'createElement' ).mockImplementation(
169
- ( tag: string ) => {
170
- if ( tag === 'canvas' ) {
171
- canvasCount++;
172
- return createMockCanvas(
173
- mockCtx
174
- ) as unknown as HTMLElement;
175
- }
176
- return document.createElement( tag );
177
- }
178
- );
179
- } );
180
-
181
- afterEach( () => {
182
- vi.restoreAllMocks();
183
- } );
184
-
185
- it( 'should call setTransform and drawImage', () => {
186
- const state = createTestState();
187
- const mockImage = {
188
- naturalWidth: 800,
189
- naturalHeight: 600,
190
- } as HTMLImageElement;
191
-
192
- renderToCanvas( mockImage, state );
193
-
194
- // Single canvas for direct rendering.
195
- expect( canvasCount ).toBe( 1 );
196
-
197
- // New implementation uses setTransform (not translate/rotate/scale).
198
- expect( mockCtx.setTransform ).toHaveBeenCalledTimes( 1 );
199
- expect( mockCtx.setTransform ).toHaveBeenCalledWith(
200
- expect.any( Number ),
201
- expect.any( Number ),
202
- expect.any( Number ),
203
- expect.any( Number ),
204
- expect.any( Number ),
205
- expect.any( Number )
206
- );
207
-
208
- // drawImage called once — direct render into crop canvas.
209
- expect( mockCtx.drawImage ).toHaveBeenCalledTimes( 1 );
210
- } );
211
-
212
- it( 'should apply flip scale factors when flip is enabled', () => {
213
- const state = createTestState( {
214
- flip: { horizontal: true, vertical: true },
215
- } );
216
- const mockImage = {
217
- naturalWidth: 800,
218
- naturalHeight: 600,
219
- } as HTMLImageElement;
220
-
221
- // Render without flip for comparison.
222
- const stateNoFlip = createTestState( {
223
- flip: { horizontal: false, vertical: false },
224
- } );
225
- const mockCtxNoFlip = createMockContext();
226
- const canvasCountRef = { value: 0 };
227
- vi.restoreAllMocks();
228
- vi.spyOn( document, 'createElement' ).mockImplementation(
229
- ( tag: string ) => {
230
- if ( tag === 'canvas' ) {
231
- canvasCountRef.value++;
232
- // Alternate between flip and no-flip contexts.
233
- const ctx =
234
- canvasCountRef.value === 1 ? mockCtxNoFlip : mockCtx;
235
- return createMockCanvas( ctx ) as unknown as HTMLElement;
236
- }
237
- return document.createElement( tag );
238
- }
239
- );
240
-
241
- renderToCanvas( mockImage, stateNoFlip );
242
- renderToCanvas( mockImage, state );
243
-
244
- // Both should call setTransform once each.
245
- expect( mockCtxNoFlip.setTransform ).toHaveBeenCalledTimes( 1 );
246
- expect( mockCtx.setTransform ).toHaveBeenCalledTimes( 1 );
247
-
248
- // The a (scaleX) component of the matrix should differ between flip and no-flip.
249
- const noFlipArgs = mockCtxNoFlip.setTransform.mock.calls[ 0 ];
250
- const flipArgs = mockCtx.setTransform.mock.calls[ 0 ];
251
- // With horizontal+vertical flip, the sign of scale components should be negated.
252
- expect( Math.sign( noFlipArgs[ 0 ] ) ).not.toBe(
253
- Math.sign( flipArgs[ 0 ] )
254
- );
255
- } );
256
-
257
- it( 'should apply rotation — matrix differs for rotated vs non-rotated', () => {
258
- const stateRotated = createTestState( { rotation: 90 } );
259
- const stateNormal = createTestState( { rotation: 0 } );
260
- const mockImage = {
261
- naturalWidth: 800,
262
- naturalHeight: 600,
263
- } as HTMLImageElement;
264
-
265
- const mockCtxRotated = createMockContext();
266
- const mockCtxNormal = createMockContext();
267
- const canvasCountRef = { value: 0 };
268
- vi.restoreAllMocks();
269
- vi.spyOn( document, 'createElement' ).mockImplementation(
270
- ( tag: string ) => {
271
- if ( tag === 'canvas' ) {
272
- canvasCountRef.value++;
273
- const ctx =
274
- canvasCountRef.value === 1
275
- ? mockCtxNormal
276
- : mockCtxRotated;
277
- return createMockCanvas( ctx ) as unknown as HTMLElement;
278
- }
279
- return document.createElement( tag );
280
- }
281
- );
282
-
283
- renderToCanvas( mockImage, stateNormal );
284
- renderToCanvas( mockImage, stateRotated );
285
-
286
- expect( mockCtxNormal.setTransform ).toHaveBeenCalledTimes( 1 );
287
- expect( mockCtxRotated.setTransform ).toHaveBeenCalledTimes( 1 );
288
-
289
- const normalArgs = mockCtxNormal.setTransform.mock.calls[ 0 ];
290
- const rotatedArgs = mockCtxRotated.setTransform.mock.calls[ 0 ];
291
- // The matrix components should differ when rotation changes.
292
- const matricesDiffer = normalArgs.some(
293
- ( v: number, i: number ) => Math.abs( v - rotatedArgs[ i ] ) > 1e-9
294
- );
295
- expect( matricesDiffer ).toBe( true );
296
- } );
297
- } );
298
-
299
- describe( 'canvasToBlob', () => {
300
- it( 'should call canvas.toBlob with the correct arguments', async () => {
301
- const mockBlob = new Blob( [ 'test' ], { type: 'image/png' } );
302
- const mockCanvas = {
303
- toBlob: vi.fn( ( callback: BlobCallback ) => {
304
- callback( mockBlob );
305
- } ),
306
- } as unknown as HTMLCanvasElement;
307
-
308
- const result = await canvasToBlob( mockCanvas, 'image/webp', 0.8 );
309
-
310
- expect( mockCanvas.toBlob ).toHaveBeenCalledWith(
311
- expect.any( Function ),
312
- 'image/webp',
313
- 0.8
314
- );
315
- expect( result ).toBe( mockBlob );
316
- } );
317
-
318
- it( 'should use default mime type and quality when not specified', async () => {
319
- const mockBlob = new Blob( [ 'test' ], { type: 'image/png' } );
320
- const mockCanvas = {
321
- toBlob: vi.fn( ( callback: BlobCallback ) => {
322
- callback( mockBlob );
323
- } ),
324
- } as unknown as HTMLCanvasElement;
325
-
326
- await canvasToBlob( mockCanvas );
327
-
328
- expect( mockCanvas.toBlob ).toHaveBeenCalledWith(
329
- expect.any( Function ),
330
- 'image/png',
331
- 0.92
332
- );
333
- } );
334
-
335
- it( 'should reject when toBlob returns null', async () => {
336
- const mockCanvas = {
337
- toBlob: vi.fn( ( callback: BlobCallback ) => {
338
- callback( null );
339
- } ),
340
- } as unknown as HTMLCanvasElement;
341
-
342
- await expect( canvasToBlob( mockCanvas ) ).rejects.toThrow(
343
- 'Canvas toBlob returned null'
344
- );
345
- } );
346
- } );
347
-
348
- describe( 'canvasToDataURL', () => {
349
- it( 'should call canvas.toDataURL with correct arguments', () => {
350
- const mockCanvas = {
351
- toDataURL: vi.fn().mockReturnValue( 'data:image/jpeg;base64,abc' ),
352
- } as unknown as HTMLCanvasElement;
353
-
354
- const result = canvasToDataURL( mockCanvas, 'image/jpeg', 0.85 );
355
-
356
- expect( mockCanvas.toDataURL ).toHaveBeenCalledWith(
357
- 'image/jpeg',
358
- 0.85
359
- );
360
- expect( result ).toBe( 'data:image/jpeg;base64,abc' );
361
- } );
362
-
363
- it( 'should use default mime type and quality when not specified', () => {
364
- const mockCanvas = {
365
- toDataURL: vi.fn().mockReturnValue( 'data:image/png;base64,xyz' ),
366
- } as unknown as HTMLCanvasElement;
367
-
368
- canvasToDataURL( mockCanvas );
369
-
370
- expect( mockCanvas.toDataURL ).toHaveBeenCalledWith(
371
- 'image/png',
372
- 0.92
373
- );
374
- } );
375
- } );
376
-
377
- describe( 'exportCroppedImage', () => {
378
- let originalImage: typeof Image;
379
-
380
- beforeEach( () => {
381
- originalImage = global.Image;
382
-
383
- // Mock Image constructor for loadImage.
384
- const mockImage = {
385
- naturalWidth: 800,
386
- naturalHeight: 600,
387
- addEventListener: vi.fn(),
388
- _crossOrigin: '',
389
- set crossOrigin( value: string ) {
390
- this._crossOrigin = value;
391
- },
392
- get crossOrigin() {
393
- return this._crossOrigin;
394
- },
395
- _src: '',
396
- set src( value: string ) {
397
- this._src = value;
398
- const loadHandler = this.addEventListener.mock.calls.find(
399
- ( call: string[] ) => call[ 0 ] === 'load'
400
- );
401
- if ( loadHandler ) {
402
- loadHandler[ 1 ]();
403
- }
404
- },
405
- get src() {
406
- return this._src;
407
- },
408
- };
409
- global.Image = vi.fn( function Image() {
410
- return mockImage;
411
- } ) as unknown as typeof Image;
412
-
413
- // Mock document.createElement for renderToCanvas.
414
- const mockBlob = new Blob( [ 'test' ], { type: 'image/png' } );
415
- const mockCtx = createMockContext();
416
- vi.spyOn( document, 'createElement' ).mockImplementation(
417
- ( tag: string ) => {
418
- if ( tag === 'canvas' ) {
419
- const canvas = createMockCanvas( mockCtx );
420
- ( canvas as any ).toBlob = vi.fn(
421
- ( callback: BlobCallback ) => {
422
- callback( mockBlob );
423
- }
424
- );
425
- return canvas as unknown as HTMLElement;
426
- }
427
- return document.createElement( tag );
428
- }
429
- );
430
- } );
431
-
432
- afterEach( () => {
433
- global.Image = originalImage;
434
- vi.restoreAllMocks();
435
- } );
436
-
437
- it( 'should chain loadImage, renderToCanvas, and canvasToBlob', async () => {
438
- const state = createTestState();
439
- const result = await exportCroppedImage(
440
- 'https://example.com/photo.jpg',
441
- state,
442
- 'image/webp',
443
- 0.9
444
- );
445
-
446
- expect( result ).toBeInstanceOf( Blob );
447
- } );
448
-
449
- it( 'throws when image fails to load', async () => {
450
- // Override Image to simulate a load error.
451
- const errorImage = {
452
- addEventListener: vi.fn(),
453
- set crossOrigin( _value: string ) {},
454
- set src( _value: string ) {
455
- const errorHandler = this.addEventListener.mock.calls.find(
456
- ( call: string[] ) => call[ 0 ] === 'error'
457
- );
458
- if ( errorHandler ) {
459
- errorHandler[ 1 ]( new Error( 'Load failed' ) );
460
- }
461
- },
462
- };
463
- global.Image = vi.fn( function Image() {
464
- return errorImage;
465
- } ) as unknown as typeof Image;
466
-
467
- const state = createTestState();
468
- await expect(
469
- exportCroppedImage( 'https://example.com/broken.jpg', state )
470
- ).rejects.toBeDefined();
471
- } );
472
-
473
- it( 'propagates CORS-taint errors from canvasToBlob', async () => {
474
- // Mock Image to resolve (simulating a successful load even from
475
- // a tainted source — the browser doesn't flag the load itself,
476
- // only the later toBlob call).
477
- global.Image = vi.fn( function Image() {
478
- const img: {
479
- addEventListener: Mock;
480
- crossOrigin: string;
481
- src: string;
482
- naturalWidth: number;
483
- naturalHeight: number;
484
- } = {
485
- addEventListener: vi.fn( ( event: string, fn: () => void ) => {
486
- if ( event === 'load' ) {
487
- // Fire load synchronously after src is set.
488
- queueMicrotask( fn );
489
- }
490
- } ),
491
- crossOrigin: '',
492
- src: '',
493
- naturalWidth: 800,
494
- naturalHeight: 600,
495
- };
496
- return img;
497
- } ) as unknown as typeof Image;
498
-
499
- // Mock canvas to throw SecurityError from toBlob (CORS-taint).
500
- const corsCanvas = {
501
- width: 0,
502
- height: 0,
503
- getContext: vi.fn( () => ( {
504
- setTransform: vi.fn(),
505
- drawImage: vi.fn(),
506
- } ) ),
507
- toBlob: vi.fn( () => {
508
- throw new DOMException(
509
- 'Tainted canvases may not be exported',
510
- 'SecurityError'
511
- );
512
- } ),
513
- };
514
- vi.spyOn( document, 'createElement' ).mockImplementation( ( (
515
- tag: string
516
- ) => {
517
- if ( tag === 'canvas' ) {
518
- return corsCanvas as unknown as HTMLElement;
519
- }
520
- return document.createElement( tag );
521
- } ) as typeof document.createElement );
522
-
523
- const state = createTestState();
524
- await expect(
525
- exportCroppedImage(
526
- 'https://cross-origin.example/photo.jpg',
527
- state
528
- )
529
- ).rejects.toMatchObject( { name: 'SecurityError' } );
530
-
531
- vi.restoreAllMocks();
532
- } );
533
-
534
- it( 'throws descriptive error when canvas context is unavailable', () => {
535
- // Mock canvas.getContext to return null (no 2D context available).
536
- const noCtxCanvas = {
537
- width: 0,
538
- height: 0,
539
- getContext: vi.fn( () => null ),
540
- };
541
- vi.spyOn( document, 'createElement' ).mockImplementation( ( (
542
- tag: string
543
- ) => {
544
- if ( tag === 'canvas' ) {
545
- return noCtxCanvas as unknown as HTMLElement;
546
- }
547
- return document.createElement( tag );
548
- } ) as typeof document.createElement );
549
-
550
- const state = createTestState();
551
- const mockImage = {
552
- naturalWidth: 800,
553
- naturalHeight: 600,
554
- } as HTMLImageElement;
555
-
556
- expect( () => renderToCanvas( mockImage, state ) ).toThrow(
557
- /2D context/i
558
- );
559
-
560
- vi.restoreAllMocks();
561
- } );
562
- } );
563
-
564
- describe( 'renderToCanvas — export matrix verification', () => {
565
- let mockCtx: ReturnType< typeof createMockContext >;
566
-
567
- function setupMockCanvas() {
568
- mockCtx = createMockContext();
569
- vi.spyOn( document, 'createElement' ).mockImplementation(
570
- ( tag: string ) => {
571
- if ( tag === 'canvas' ) {
572
- return createMockCanvas(
573
- mockCtx
574
- ) as unknown as HTMLElement;
575
- }
576
- return document.createElement( tag );
577
- }
578
- );
579
- }
580
-
581
- afterEach( () => {
582
- vi.restoreAllMocks();
583
- } );
584
-
585
- it( 'identity state (no rotation, no zoom, full crop) should produce a 1:1 mapping', () => {
586
- setupMockCanvas();
587
- const state = createTestState( {
588
- rotation: 0,
589
- zoom: 1,
590
- flip: { horizontal: false, vertical: false },
591
- pan: { x: 0, y: 0 },
592
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
593
- } );
594
- const mockImage = {
595
- naturalWidth: 800,
596
- naturalHeight: 600,
597
- } as HTMLImageElement;
598
-
599
- renderToCanvas( mockImage, state );
600
-
601
- expect( mockCtx.setTransform ).toHaveBeenCalledTimes( 1 );
602
- const [ a, b, c, d, e, f ] = mockCtx.setTransform.mock.calls[ 0 ];
603
-
604
- // For identity: a and d should be positive scale factors (output/input),
605
- // b and c should be ~0 (no skew/rotation).
606
- expect( b ).toBeCloseTo( 0, 5 );
607
- expect( c ).toBeCloseTo( 0, 5 );
608
- expect( a ).toBeGreaterThan( 0 );
609
- expect( d ).toBeGreaterThan( 0 );
610
- // a and d should be approximately equal (uniform scale for 800x600 full crop).
611
- expect( a ).toBeCloseTo( d, 5 );
612
-
613
- // Translation e,f should position the image so that pixel (0,0) maps
614
- // to a consistent output location.
615
- expect( typeof e ).toBe( 'number' );
616
- expect( typeof f ).toBe( 'number' );
617
- } );
618
-
619
- it( '90-degree rotation should encode rotation in the matrix a,b,c,d values', () => {
620
- setupMockCanvas();
621
- const state = createTestState( {
622
- rotation: 90,
623
- zoom: 1,
624
- flip: { horizontal: false, vertical: false },
625
- pan: { x: 0, y: 0 },
626
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
627
- } );
628
- const mockImage = {
629
- naturalWidth: 800,
630
- naturalHeight: 600,
631
- } as HTMLImageElement;
632
-
633
- renderToCanvas( mockImage, state );
634
-
635
- expect( mockCtx.setTransform ).toHaveBeenCalledTimes( 1 );
636
- const [ a, b, c, d ] = mockCtx.setTransform.mock.calls[ 0 ];
637
-
638
- // For a 90° rotation, cos(90°)=0, sin(90°)=1.
639
- // The diagonal (a, d) should be ~0 and the off-diagonal (b, c) should
640
- // be non-zero, encoding the rotation.
641
- expect( a ).toBeCloseTo( 0, 3 );
642
- expect( d ).toBeCloseTo( 0, 3 );
643
- expect( Math.abs( b ) ).toBeGreaterThan( 0.1 );
644
- expect( Math.abs( c ) ).toBeGreaterThan( 0.1 );
645
- // b and c should have opposite signs for a proper rotation matrix.
646
- expect( Math.sign( b ) ).not.toBe( Math.sign( c ) );
647
- } );
648
-
649
- it( 'zoom 2x should double the scale components', () => {
650
- setupMockCanvas();
651
-
652
- // Render at zoom=1.
653
- const stateZ1 = createTestState( {
654
- rotation: 0,
655
- zoom: 1,
656
- flip: { horizontal: false, vertical: false },
657
- pan: { x: 0, y: 0 },
658
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
659
- } );
660
- const mockImage = {
661
- naturalWidth: 800,
662
- naturalHeight: 600,
663
- } as HTMLImageElement;
664
- renderToCanvas( mockImage, stateZ1 );
665
- const [ a1, , , d1 ] = mockCtx.setTransform.mock.calls[ 0 ];
666
-
667
- // Reset for zoom=2.
668
- vi.restoreAllMocks();
669
- setupMockCanvas();
670
- const stateZ2 = createTestState( {
671
- rotation: 0,
672
- zoom: 2,
673
- flip: { horizontal: false, vertical: false },
674
- pan: { x: 0, y: 0 },
675
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
676
- } );
677
- renderToCanvas( mockImage, stateZ2 );
678
- const [ a2, , , d2 ] = mockCtx.setTransform.mock.calls[ 0 ];
679
-
680
- // The scale components should double.
681
- expect( a2 ).toBeCloseTo( a1 * 2, 5 );
682
- expect( d2 ).toBeCloseTo( d1 * 2, 5 );
683
- } );
684
-
685
- it( 'horizontal flip should negate the x-scale component', () => {
686
- setupMockCanvas();
687
-
688
- // No flip.
689
- const stateNoFlip = createTestState( {
690
- rotation: 0,
691
- zoom: 1,
692
- flip: { horizontal: false, vertical: false },
693
- pan: { x: 0, y: 0 },
694
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
695
- } );
696
- const mockImage = {
697
- naturalWidth: 800,
698
- naturalHeight: 600,
699
- } as HTMLImageElement;
700
- renderToCanvas( mockImage, stateNoFlip );
701
- const [ aNoFlip ] = mockCtx.setTransform.mock.calls[ 0 ];
702
-
703
- // Reset for horizontal flip.
704
- vi.restoreAllMocks();
705
- setupMockCanvas();
706
- const stateFlip = createTestState( {
707
- rotation: 0,
708
- zoom: 1,
709
- flip: { horizontal: true, vertical: false },
710
- pan: { x: 0, y: 0 },
711
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
712
- } );
713
- renderToCanvas( mockImage, stateFlip );
714
- const [ aFlip ] = mockCtx.setTransform.mock.calls[ 0 ];
715
-
716
- // The x-scale (a) should be negated.
717
- expect( aNoFlip ).toBeGreaterThan( 0 );
718
- expect( aFlip ).toBeLessThan( 0 );
719
- expect( aFlip ).toBeCloseTo( -aNoFlip, 5 );
720
- } );
721
- } );
722
-
723
- describe( 'applyToCanvas — export matrix verification', () => {
724
- let mockCtx: ReturnType< typeof createMockContext >;
725
- let canvasWidths: number[];
726
- let canvasHeights: number[];
727
-
728
- function setupMockCanvas() {
729
- mockCtx = createMockContext();
730
- canvasWidths = [];
731
- canvasHeights = [];
732
- vi.spyOn( document, 'createElement' ).mockImplementation(
733
- ( tag: string ) => {
734
- if ( tag === 'canvas' ) {
735
- const canvas = createMockCanvas( mockCtx );
736
- // Track canvas size assignments.
737
- const originalDescriptor = {
738
- width: 0,
739
- height: 0,
740
- };
741
- Object.defineProperty( canvas, 'width', {
742
- get: () => originalDescriptor.width,
743
- set: ( v: number ) => {
744
- originalDescriptor.width = v;
745
- canvasWidths.push( v );
746
- },
747
- } );
748
- Object.defineProperty( canvas, 'height', {
749
- get: () => originalDescriptor.height,
750
- set: ( v: number ) => {
751
- originalDescriptor.height = v;
752
- canvasHeights.push( v );
753
- },
754
- } );
755
- return canvas as unknown as HTMLElement;
756
- }
757
- return document.createElement( tag );
758
- }
759
- );
760
- }
761
-
762
- afterEach( () => {
763
- vi.restoreAllMocks();
764
- } );
765
-
766
- it( 'should create a canvas with correct dimensions and call setTransform', () => {
767
- setupMockCanvas();
768
-
769
- const state = createTestState( {
770
- rotation: 0,
771
- zoom: 1,
772
- flip: { horizontal: false, vertical: false },
773
- pan: { x: 0, y: 0 },
774
- cropRect: { x: 0.1, y: 0.2, width: 0.5, height: 0.5 },
775
- } );
776
- const sourceSize = { width: 800, height: 600 };
777
- const mockSource = {} as CanvasImageSource;
778
-
779
- applyToCanvas( mockSource, sourceSize, state );
780
-
781
- // Canvas dimensions should match the crop region in natural pixels.
782
- const expectedW = Math.round( 0.5 * 800 );
783
- const expectedH = Math.round( 0.5 * 600 );
784
- expect( canvasWidths ).toContain( expectedW );
785
- expect( canvasHeights ).toContain( expectedH );
786
-
787
- // setTransform should be called with 6 numeric matrix values.
788
- expect( mockCtx.setTransform ).toHaveBeenCalledTimes( 1 );
789
- expect( mockCtx.setTransform ).toHaveBeenCalledWith(
790
- expect.any( Number ),
791
- expect.any( Number ),
792
- expect.any( Number ),
793
- expect.any( Number ),
794
- expect.any( Number ),
795
- expect.any( Number )
796
- );
797
-
798
- // drawImage should be called with the source.
799
- expect( mockCtx.drawImage ).toHaveBeenCalledTimes( 1 );
800
- expect( mockCtx.drawImage ).toHaveBeenCalledWith( mockSource, 0, 0 );
801
- } );
802
-
803
- it( 'should use custom output size when provided', () => {
804
- setupMockCanvas();
805
-
806
- const state = createTestState( {
807
- rotation: 0,
808
- zoom: 1,
809
- flip: { horizontal: false, vertical: false },
810
- pan: { x: 0, y: 0 },
811
- cropRect: { x: 0, y: 0, width: 1, height: 1 },
812
- } );
813
- const sourceSize = { width: 800, height: 600 };
814
- const outputSize = { width: 200, height: 150 };
815
- const mockSource = {} as CanvasImageSource;
816
-
817
- applyToCanvas( mockSource, sourceSize, state, outputSize );
818
-
819
- expect( canvasWidths ).toContain( 200 );
820
- expect( canvasHeights ).toContain( 150 );
821
- expect( mockCtx.setTransform ).toHaveBeenCalledTimes( 1 );
822
- } );
823
- } );