/
index.tsx
288 lines (262 loc) · 8.14 KB
/
index.tsx
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
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useEffect, useRef, useState } from '@wordpress/element';
import {
__experimentalUseDragging as useDragging,
useInstanceId,
useIsomorphicLayoutEffect,
} from '@wordpress/compose';
/**
* Internal dependencies
*/
import BaseControl from '../base-control';
import Controls from './controls';
import FocalPoint from './focal-point';
import Grid from './grid';
import Media from './media';
import {
MediaWrapper,
MediaContainer,
} from './styles/focal-point-picker-style';
import { INITIAL_BOUNDS } from './utils';
import { useUpdateEffect } from '../utils/hooks';
import type { WordPressComponentProps } from '../context/wordpress-component';
import type {
FocalPoint as FocalPointType,
FocalPointPickerProps,
} from './types';
import type { KeyboardEventHandler } from 'react';
const GRID_OVERLAY_TIMEOUT = 600;
/**
* Focal Point Picker is a component which creates a UI for identifying the most important visual point of an image.
*
* This component addresses a specific problem: with large background images it is common to see undesirable crops,
* especially when viewing on smaller viewports such as mobile phones. This component allows the selection of
* the point with the most important visual information and returns it as a pair of numbers between 0 and 1.
* This value can be easily converted into the CSS `background-position` attribute, and will ensure that the
* focal point is never cropped out, regardless of viewport.
*
* - Example focal point picker value: `{ x: 0.5, y: 0.1 }`
* - Corresponding CSS: `background-position: 50% 10%;`
*
* ```jsx
* import { FocalPointPicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ focalPoint, setFocalPoint ] = useState( {
* x: 0.5,
* y: 0.5,
* } );
*
* const url = '/path/to/image';
*
* // Example function to render the CSS styles based on Focal Point Picker value
* const style = {
* backgroundImage: `url(${ url })`,
* backgroundPosition: `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`,
* };
*
* return (
* <>
* <FocalPointPicker
* url={ url }
* value={ focalPoint }
* onDragStart={ setFocalPoint }
* onDrag={ setFocalPoint }
* onChange={ setFocalPoint }
* />
* <div style={ style } />
* </>
* );
* };
* ```
*/
export function FocalPointPicker( {
__nextHasNoMarginBottom,
__next40pxDefaultSize = false,
autoPlay = true,
className,
help,
label,
onChange,
onDrag,
onDragEnd,
onDragStart,
resolvePoint,
url,
value: valueProp = {
x: 0.5,
y: 0.5,
},
...restProps
}: WordPressComponentProps< FocalPointPickerProps, 'div', false > ) {
const [ point, setPoint ] = useState( valueProp );
const [ showGridOverlay, setShowGridOverlay ] = useState( false );
const { startDrag, endDrag, isDragging } = useDragging( {
onDragStart: ( event ) => {
dragAreaRef.current?.focus();
const value = getValueWithinDragArea( event );
// `value` can technically be undefined if getValueWithinDragArea() is
// called before dragAreaRef is set, but this shouldn't happen in reality.
if ( ! value ) return;
onDragStart?.( value, event );
setPoint( value );
},
onDragMove: ( event ) => {
// Prevents text-selection when dragging.
event.preventDefault();
const value = getValueWithinDragArea( event );
if ( ! value ) return;
onDrag?.( value, event );
setPoint( value );
},
onDragEnd: () => {
onDragEnd?.();
onChange?.( point );
},
} );
// Uses the internal point while dragging or else the value from props.
const { x, y } = isDragging ? point : valueProp;
const dragAreaRef = useRef< HTMLDivElement >( null );
const [ bounds, setBounds ] = useState( INITIAL_BOUNDS );
const refUpdateBounds = useRef( () => {
if ( ! dragAreaRef.current ) return;
const { clientWidth: width, clientHeight: height } =
dragAreaRef.current;
// Falls back to initial bounds if the ref has no size. Since styles
// give the drag area dimensions even when the media has not loaded
// this should only happen in unit tests (jsdom).
setBounds(
width > 0 && height > 0 ? { width, height } : { ...INITIAL_BOUNDS }
);
} );
useEffect( () => {
const updateBounds = refUpdateBounds.current;
if ( ! dragAreaRef.current ) return;
const { defaultView } = dragAreaRef.current.ownerDocument;
defaultView?.addEventListener( 'resize', updateBounds );
return () => defaultView?.removeEventListener( 'resize', updateBounds );
}, [] );
// Updates the bounds to cover cases of unspecified media or load failures.
useIsomorphicLayoutEffect( () => void refUpdateBounds.current(), [] );
// TODO: Consider refactoring getValueWithinDragArea() into a pure function.
// https://github.com/WordPress/gutenberg/pull/43872#discussion_r963455173
const getValueWithinDragArea = ( {
clientX,
clientY,
shiftKey,
}: {
clientX: number;
clientY: number;
shiftKey: boolean;
} ) => {
if ( ! dragAreaRef.current ) return;
const { top, left } = dragAreaRef.current.getBoundingClientRect();
let nextX = ( clientX - left ) / bounds.width;
let nextY = ( clientY - top ) / bounds.height;
// Enables holding shift to jump values by 10%.
if ( shiftKey ) {
nextX = Math.round( nextX / 0.1 ) * 0.1;
nextY = Math.round( nextY / 0.1 ) * 0.1;
}
return getFinalValue( { x: nextX, y: nextY } );
};
const getFinalValue = ( value: FocalPointType ): FocalPointType => {
const resolvedValue = resolvePoint?.( value ) ?? value;
resolvedValue.x = Math.max( 0, Math.min( resolvedValue.x, 1 ) );
resolvedValue.y = Math.max( 0, Math.min( resolvedValue.y, 1 ) );
const roundToTwoDecimalPlaces = ( n: number ) =>
Math.round( n * 1e2 ) / 1e2;
return {
x: roundToTwoDecimalPlaces( resolvedValue.x ),
y: roundToTwoDecimalPlaces( resolvedValue.y ),
};
};
const arrowKeyStep: KeyboardEventHandler< HTMLDivElement > = ( event ) => {
const { code, shiftKey } = event;
if (
! [ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight' ].includes(
code
)
)
return;
event.preventDefault();
const value = { x, y };
const step = shiftKey ? 0.1 : 0.01;
const delta =
code === 'ArrowUp' || code === 'ArrowLeft' ? -1 * step : step;
const axis = code === 'ArrowUp' || code === 'ArrowDown' ? 'y' : 'x';
value[ axis ] = value[ axis ] + delta;
onChange?.( getFinalValue( value ) );
};
const focalPointPosition = {
left: x !== undefined ? x * bounds.width : 0.5 * bounds.width,
top: y !== undefined ? y * bounds.height : 0.5 * bounds.height,
};
const classes = classnames(
'components-focal-point-picker-control',
className
);
const instanceId = useInstanceId( FocalPointPicker );
const id = `inspector-focal-point-picker-control-${ instanceId }`;
useUpdateEffect( () => {
setShowGridOverlay( true );
const timeout = window.setTimeout( () => {
setShowGridOverlay( false );
}, GRID_OVERLAY_TIMEOUT );
return () => window.clearTimeout( timeout );
}, [ x, y ] );
return (
<BaseControl
{ ...restProps }
__nextHasNoMarginBottom={ __nextHasNoMarginBottom }
label={ label }
id={ id }
help={ help }
className={ classes }
>
<MediaWrapper className="components-focal-point-picker-wrapper">
<MediaContainer
className="components-focal-point-picker"
onKeyDown={ arrowKeyStep }
onMouseDown={ startDrag }
onBlur={ () => {
if ( isDragging ) endDrag();
} }
ref={ dragAreaRef }
role="button"
tabIndex={ -1 }
>
<Grid bounds={ bounds } showOverlay={ showGridOverlay } />
<Media
alt={ __( 'Media preview' ) }
autoPlay={ autoPlay }
onLoad={ refUpdateBounds.current }
src={ url }
/>
<FocalPoint
{ ...focalPointPosition }
isDragging={ isDragging }
/>
</MediaContainer>
</MediaWrapper>
<Controls
__nextHasNoMarginBottom={ __nextHasNoMarginBottom }
__next40pxDefaultSize={ __next40pxDefaultSize }
hasHelpText={ !! help }
point={ { x, y } }
onChange={ ( value ) => {
onChange?.( getFinalValue( value ) );
} }
/>
</BaseControl>
);
}
export default FocalPointPicker;