File size: 9,484 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { createRef, Component } from 'react';
import { connect } from 'react-redux';
import { getAtomicSiteMediaViaProxyRetry } from 'calypso/lib/get-atomic-site-media';
import { mediaURLToProxyConfig, canvasToBlob } from 'calypso/lib/media/utils';
import {
	setImageEditorCropBounds,
	setImageEditorImageHasLoaded,
} from 'calypso/state/editor/image-editor/actions';
import {
	getImageEditorTransform,
	getImageEditorFileInfo,
	getImageEditorCrop,
	isImageEditorImageLoaded,
} from 'calypso/state/editor/image-editor/selectors';
import getImageEditorIsGreaterThanMinimumDimensions from 'calypso/state/selectors/get-image-editor-is-greater-than-minimum-dimensions';
import isJetpackSite from 'calypso/state/sites/selectors/is-jetpack-site';
import getSelectedSiteId from 'calypso/state/ui/selectors/get-selected-site-id';
import getSelectedSiteSlug from 'calypso/state/ui/selectors/get-selected-site-slug';
import ImageEditorCrop from './image-editor-crop';

const noop = () => {};

export class ImageEditorCanvas extends Component {
	static propTypes = {
		src: PropTypes.string,
		mimeType: PropTypes.string,
		transform: PropTypes.shape( {
			degrees: PropTypes.number,
			scaleX: PropTypes.number,
			scaleY: PropTypes.number,
		} ),
		crop: PropTypes.shape( {
			topRatio: PropTypes.number,
			leftRatio: PropTypes.number,
			widthRatio: PropTypes.number,
			heightRatio: PropTypes.number,
		} ),
		setImageEditorCropBounds: PropTypes.func,
		setImageEditorImageHasLoaded: PropTypes.func,
		onLoadError: PropTypes.func,
		isImageLoaded: PropTypes.bool,
		showCrop: PropTypes.bool,
		widthLimit: PropTypes.number,
	};

	static defaultProps = {
		transform: {
			degrees: 0,
			scaleX: 1,
			scaleY: 1,
		},
		crop: {
			cropTopRatio: 0,
			cropLeftRatio: 0,
			cropWidthRatio: 1,
			cropHeightRatio: 1,
		},
		setImageEditorCropBounds: noop,
		setImageEditorImageHasLoaded: noop,
		onLoadError: noop,
		isImageLoaded: false,
		showCrop: true,
		widthLimit: Infinity,
	};

	// throttle the frame rate of window.resize() to circa 30fps
	frameRateInterval = 1000 / 30;
	requestAnimationFrameId = null;
	lastTimestamp = null;
	isMounted = false;
	canvasRef = createRef();

	onWindowResize = () => {
		this.requestAnimationFrameId = window.requestAnimationFrame( this.updateCanvasPosition );
	};

	componentDidMount() {
		this.isMounted = true;
	}

	componentDidUpdate( prevProps ) {
		if ( this.props.src !== prevProps.src || ! this.image ) {
			this.getImage( this.props.src );
		}

		this.drawImage();
		this.updateCanvasPosition();
	}

	componentWillUnmount() {
		if ( typeof window !== 'undefined' && this.onWindowResize ) {
			window.removeEventListener( 'resize', this.onWindowResize );
			window.cancelAnimationFrame( this.requestAnimationFrameId );
		}

		this.isMounted = false;
	}

	fetchImageBlob( src ) {
		const { siteSlug, isJetpackNonAtomic } = this.props;
		const { filePath, query, isRelativeToSiteRoot } = mediaURLToProxyConfig( src, siteSlug );
		const useProxy = ! isJetpackNonAtomic && !! filePath && isRelativeToSiteRoot;

		if ( useProxy ) {
			return getAtomicSiteMediaViaProxyRetry( siteSlug, filePath, { query } );
		}

		if ( ! src.startsWith( 'blob' ) && ! src.startsWith( 'data' ) ) {
			src = src + '?'; // Fix #7991 by forcing Safari to ignore cache and perform valid CORS request
		}

		return window.fetch( src ).then( ( response ) => response.blob() );
	}

	getImage( src ) {
		this.fetchImageBlob( src )
			.then( ( blob ) => {
				if ( this.isMounted ) {
					this.initImage( window.URL.createObjectURL( blob ) );
				}
			} )
			.catch( ( error ) => {
				if ( this.isMounted ) {
					this.props.onLoadError( error );
				}
			} );
	}

	initImage( src ) {
		this.image = new Image();
		this.image.src = src;
		this.image.onload = this.onLoadComplete;
		this.image.onerror = this.onLoadComplete;
	}

	onLoadComplete = ( event ) => {
		if ( event.type !== 'load' || ! this.isMounted ) {
			return;
		}

		this.drawImage();
		this.updateCanvasPosition();

		if ( typeof window !== 'undefined' ) {
			this.lastTimestamp = window.performance.now();
			window.addEventListener( 'resize', this.onWindowResize );
		}

		this.props.setImageEditorImageHasLoaded( this.image.width, this.image.height );
	};

	toBlob( callback ) {
		const { widthLimit } = this.props;
		const { leftRatio, topRatio, widthRatio, heightRatio } = this.props.crop;

		const { mimeType, transform } = this.props;

		const canvas = this.canvasRef.current;
		const context = canvas.getContext( '2d' );
		const rotated = transform.degrees % 180 !== 0;
		const imageWidth = rotated ? this.image.height : this.image.width;
		const imageHeight = rotated ? this.image.width : this.image.height;
		const croppedLeft = leftRatio * imageWidth;
		const croppedTop = topRatio * imageHeight;
		const croppedWidth = widthRatio * imageWidth;
		const croppedHeight = heightRatio * imageHeight;

		const imageData = context.getImageData( croppedLeft, croppedTop, croppedWidth, croppedHeight );

		const newCanvas = document.createElement( 'canvas' );

		newCanvas.width = croppedWidth;
		newCanvas.height = croppedHeight;

		const newContext = newCanvas.getContext( '2d' );
		newContext.putImageData( imageData, 0, 0 );

		if ( Number.isFinite( widthLimit ) && widthLimit < croppedWidth ) {
			const resizedCanvas = document.createElement( 'canvas' );
			const scale = widthLimit / croppedWidth;
			resizedCanvas.width = scale * croppedHeight;
			resizedCanvas.height = scale * croppedWidth;
			const resizedContext = resizedCanvas.getContext( '2d' );
			resizedContext.drawImage( newCanvas, 0, 0, scale * croppedWidth, scale * croppedHeight );
			canvasToBlob( resizedCanvas, callback, mimeType, 1 );
		} else {
			canvasToBlob( newCanvas, callback, mimeType, 1 );
		}
	}

	drawImage() {
		if ( ! this.image ) {
			return;
		}

		const canvas = this.canvasRef.current;
		const imageWidth = this.image.width;
		const imageHeight = this.image.height;
		const transform = this.props.transform;
		const rotated = transform.degrees % 180 !== 0;

		//make sure the canvas draw area is the same size as the image
		canvas.width = rotated ? imageHeight : imageWidth;
		canvas.height = rotated ? imageWidth : imageHeight;

		const context = canvas.getContext( '2d' );

		context.clearRect( 0, 0, canvas.width, canvas.height );
		context.save();

		// setTransform() could be replaced with translate(), but it leads to
		// a false positive warning from eslint rule wpcalypso/i18n-no-variables
		context.setTransform( 1, 0, 0, 1, canvas.width / 2, canvas.height / 2 );

		context.scale( transform.scaleX, transform.scaleY );
		context.rotate( ( transform.degrees * Math.PI ) / 180 );

		context.drawImage( this.image, -imageWidth / 2, -imageHeight / 2 );

		context.restore();
	}

	updateCanvasPosition = ( timestamp ) => {
		const now = timestamp;
		const elapsedTime = now - this.lastTimestamp;

		if ( elapsedTime < this.frameRateInterval ) {
			return;
		}

		// if enough time has passed to call the next frame
		// reset lastTimeStamp minus 1 frame in ms ( to adjust for frame rates other than 60fps )
		this.lastTimestamp = now - ( elapsedTime % this.frameRateInterval );

		const { leftRatio, topRatio, widthRatio, heightRatio } = this.props.crop;

		const canvas = this.canvasRef.current;
		const canvasX = -50 * widthRatio - 100 * leftRatio;
		const canvasY = -50 * heightRatio - 100 * topRatio;

		const { offsetTop, offsetLeft, offsetWidth, offsetHeight } = canvas;

		this.props.setImageEditorCropBounds(
			offsetTop - ( offsetHeight * -canvasY ) / 100,
			offsetLeft - ( offsetWidth * -canvasX ) / 100,
			offsetTop + offsetHeight * ( 1 + canvasY / 100 ),
			offsetLeft + offsetWidth * ( 1 + canvasX / 100 )
		);
	};

	preventDrag( event ) {
		event.preventDefault();

		return false;
	}

	render() {
		const { leftRatio, topRatio, widthRatio, heightRatio } = this.props.crop;

		const { isImageLoaded, showCrop } = this.props;

		const canvasX = -50 * widthRatio - 100 * leftRatio;
		const canvasY = -50 * heightRatio - 100 * topRatio;

		const canvasStyle = {
			transform: 'translate(' + canvasX + '%, ' + canvasY + '%)',
			maxWidth: 85 / widthRatio + '%',
			maxHeight: 85 / heightRatio + '%',
		};

		const canvasClasses = clsx( 'image-editor__canvas', {
			'is-placeholder': ! isImageLoaded,
		} );

		return (
			<div className="image-editor__canvas-container">
				<canvas
					ref={ this.canvasRef }
					style={ canvasStyle }
					onMouseDown={ this.preventDrag }
					className={ canvasClasses }
				/>
				{ showCrop && <ImageEditorCrop /> }
			</div>
		);
	}
}

export default connect(
	( state ) => {
		const siteId = getSelectedSiteId( state );
		const siteSlug = getSelectedSiteSlug( state );
		const isJetpackNonAtomic = isJetpackSite( state, siteId, { treatAtomicAsJetpackSite: false } );

		const transform = getImageEditorTransform( state );
		const { src, mimeType } = getImageEditorFileInfo( state );
		const crop = getImageEditorCrop( state );
		const isImageLoaded = isImageEditorImageLoaded( state );
		const isGreaterThanMinimumDimensions = getImageEditorIsGreaterThanMinimumDimensions( state );

		return {
			siteSlug,
			isJetpackNonAtomic,
			src,
			mimeType,
			transform,
			crop,
			isImageLoaded,
			showCrop: !! ( isImageLoaded && isGreaterThanMinimumDimensions ),
		};
	},
	{
		setImageEditorCropBounds,
		setImageEditorImageHasLoaded,
	},
	null,
	{ forwardRef: true }
)( ImageEditorCanvas );