-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
block.js
485 lines (426 loc) · 13 KB
/
block.js
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/**
* External dependencies
*/
import { connect } from 'react-redux';
import classnames from 'classnames';
import { Slot } from 'react-slot-fill';
import { partial } from 'lodash';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
/**
* WordPress dependencies
*/
import { Children, Component } from 'element';
import { IconButton, Toolbar } from 'components';
import { BACKSPACE, ESCAPE, DELETE, UP, DOWN, LEFT, RIGHT } from 'utils/keycodes';
import { getBlockType, getBlockDefaultClassname } from 'blocks';
import { __, sprintf } from 'i18n';
/**
* Internal dependencies
*/
import BlockMover from '../../block-mover';
import BlockRightMenu from '../../block-settings-menu';
import BlockSwitcher from '../../block-switcher';
import {
updateBlockAttributes,
focusBlock,
mergeBlocks,
insertBlocks,
removeBlocks,
clearSelectedBlock,
startTyping,
stopTyping,
} from '../../actions';
import {
getPreviousBlock,
getNextBlock,
getBlock,
getBlockFocus,
getBlockIndex,
isBlockHovered,
isBlockSelected,
isBlockMultiSelected,
isFirstMultiSelectedBlock,
isTyping,
} from '../../selectors';
function FirstChild( { children } ) {
const childrenArray = Children.toArray( children );
return childrenArray[ 0 ] || null;
}
class VisualEditorBlock extends Component {
constructor() {
super( ...arguments );
this.state = {
showMobileControls: false,
};
this.bindBlockNode = this.bindBlockNode.bind( this );
this.setAttributes = this.setAttributes.bind( this );
this.maybeHover = this.maybeHover.bind( this );
this.maybeStartTyping = this.maybeStartTyping.bind( this );
this.stopTypingOnMouseMove = this.stopTypingOnMouseMove.bind( this );
this.removeOrDeselect = this.removeOrDeselect.bind( this );
this.mergeBlocks = this.mergeBlocks.bind( this );
this.onFocus = this.onFocus.bind( this );
this.onPointerDown = this.onPointerDown.bind( this );
this.onKeyDown = this.onKeyDown.bind( this );
this.onKeyUp = this.onKeyUp.bind( this );
this.handleArrowKey = this.handleArrowKey.bind( this );
this.toggleMobileControls = this.toggleMobileControls.bind( this );
this.previousOffset = null;
}
componentDidMount() {
if ( this.props.focus ) {
this.node.focus();
}
}
componentWillReceiveProps( newProps ) {
if (
this.props.order !== newProps.order &&
( ( this.props.isSelected && newProps.isSelected ) ||
( this.props.isFirstMultiSelected && newProps.isFirstMultiSelected ) )
) {
this.previousOffset = this.node.getBoundingClientRect().top;
}
}
componentDidUpdate( prevProps ) {
// Preserve scroll prosition when block rearranged
if ( this.previousOffset ) {
window.scrollTo(
window.scrollX,
window.scrollY + this.node.getBoundingClientRect().top - this.previousOffset
);
this.previousOffset = null;
}
// Focus node when focus state is programmatically transferred.
if ( this.props.focus && ! prevProps.focus ) {
this.node.focus();
}
// Bind or unbind mousemove from page when user starts or stops typing
if ( this.props.isTyping !== prevProps.isTyping ) {
if ( this.props.isTyping ) {
document.addEventListener( 'mousemove', this.stopTypingOnMouseMove );
} else {
this.removeStopTypingListener();
}
}
}
componentWillUnmount() {
this.removeStopTypingListener();
}
removeStopTypingListener() {
document.removeEventListener( 'mousemove', this.stopTypingOnMouseMove );
}
bindBlockNode( node ) {
this.node = node;
this.props.blockRef( node );
}
setAttributes( attributes ) {
const { block, onChange } = this.props;
onChange( block.uid, attributes );
}
maybeHover() {
const { isHovered, isSelected, isMultiSelected, onHover } = this.props;
if ( isHovered || isSelected || isMultiSelected ) {
return;
}
onHover();
}
maybeStartTyping() {
// We do not want to dispatch start typing if...
// - State value already reflects that we're typing (dispatch noise)
// - The current block is not selected (e.g. after a split occurs,
// we'll still receive the keyDown event, but the focus has since
// shifted to the newly created block)
if ( ! this.props.isTyping && this.props.isSelected ) {
this.props.onStartTyping();
}
}
stopTypingOnMouseMove( { clientX, clientY } ) {
const { lastClientX, lastClientY } = this;
// We need to check that the mouse really moved
// Because Safari trigger mousemove event when we press shift, ctrl...
if (
lastClientX &&
lastClientY &&
( lastClientX !== clientX || lastClientY !== clientY )
) {
this.props.onStopTyping();
}
this.lastClientX = clientX;
this.lastClientY = clientY;
}
removeOrDeselect( event ) {
const { keyCode, target } = event;
const {
uid,
multiSelectedBlockUids,
previousBlock,
onRemove,
onFocus,
onDeselect,
} = this.props;
// Remove block on backspace.
if ( BACKSPACE === keyCode || DELETE === keyCode ) {
if ( target === this.node ) {
event.preventDefault();
onRemove( [ uid ] );
if ( previousBlock ) {
onFocus( previousBlock.uid, { offset: -1 } );
}
}
if ( multiSelectedBlockUids.length ) {
event.preventDefault();
onRemove( multiSelectedBlockUids );
}
}
// Deselect on escape.
if ( ESCAPE === keyCode ) {
onDeselect();
}
}
mergeBlocks( forward = false ) {
const { block, previousBlock, nextBlock, onMerge } = this.props;
// Do nothing when it's the first block.
if (
( ! forward && ! previousBlock ) ||
( forward && ! nextBlock )
) {
return;
}
if ( forward ) {
onMerge( block, nextBlock );
} else {
onMerge( previousBlock, block );
}
}
onFocus( event ) {
if ( event.target === this.node ) {
this.props.onSelect();
}
}
onPointerDown( event ) {
// Not the main button (usually the left button on pointer device).
if ( event.buttons !== 1 ) {
return;
}
this.props.onSelectionStart();
this.props.onSelect();
}
onKeyDown( event ) {
const { keyCode } = event;
this.handleArrowKey( event );
if ( keyCode === UP || keyCode === LEFT || keyCode === DOWN || keyCode === RIGHT ) {
const selection = window.getSelection();
this.lastRange = selection.rangeCount ? selection.getRangeAt( 0 ) : null;
}
}
onKeyUp( event ) {
this.removeOrDeselect( event );
this.handleArrowKey( event );
}
handleArrowKey( event ) {
const { keyCode, target } = event;
const moveUp = ( keyCode === UP || keyCode === LEFT );
const moveDown = ( keyCode === DOWN || keyCode === RIGHT );
const selectors = [
'*[contenteditable="true"]',
'*[tabindex]',
'textarea',
'input',
].join( ',' );
if ( moveUp || moveDown ) {
const selection = window.getSelection();
const range = selection.rangeCount ? selection.getRangeAt( 0 ) : null;
// If there's no movement, so we're either at the end of start, or
// no text input at all.
if ( range !== this.lastRange ) {
return;
}
const focusableNodes = Array.from( document.querySelectorAll( selectors ) );
if ( moveUp ) {
focusableNodes.reverse();
}
const targetNode = focusableNodes
.slice( focusableNodes.indexOf( target ) )
.reduce( ( result, node ) => {
return result || ( node.contains( target ) ? null : node );
}, null );
if ( targetNode ) {
targetNode.focus();
}
}
delete this.lastRange;
}
toggleMobileControls() {
this.setState( {
showMobileControls: ! this.state.showMobileControls,
} );
}
render() {
const { block, multiSelectedBlockUids } = this.props;
const blockType = getBlockType( block.name );
// translators: %s: Type of block (i.e. Text, Image etc)
const blockLabel = sprintf( __( 'Block: %s' ), blockType.title );
const { className = getBlockDefaultClassname( block.name ) } = blockType;
// The block as rendered in the editor is composed of general block UI
// (mover, toolbar, wrapper) and the display of the block content, which
// is referred to as <BlockEdit />.
let BlockEdit;
// `edit` and `save` are functions or components describing the markup
// with which a block is displayed. If `blockType` is valid, assign
// them preferencially as the render value for the block.
if ( blockType ) {
BlockEdit = blockType.edit || blockType.save;
}
// Should `BlockEdit` return as null, we have nothing to display for the block.
if ( ! BlockEdit ) {
return null;
}
// Generate the wrapper class names handling the different states of the block.
const { isHovered, isSelected, isMultiSelected, isFirstMultiSelected, focus } = this.props;
const showUI = isSelected && ( ! this.props.isTyping || focus.collapsed === false );
const { showMobileControls } = this.state;
const wrapperClassname = classnames( 'editor-visual-editor__block', {
'is-selected': showUI,
'is-multi-selected': isMultiSelected,
'is-hovered': isHovered,
'is-showing-mobile-controls': showMobileControls,
} );
const { onMouseLeave, onFocus, onInsertBlocksAfter } = this.props;
// Determine whether the block has props to apply to the wrapper.
let wrapperProps;
if ( blockType.getEditWrapperProps ) {
wrapperProps = blockType.getEditWrapperProps( block.attributes );
}
// Disable reason: Each block can be selected by clicking on it
/* eslint-disable jsx-a11y/no-static-element-interactions, jsx-a11y/onclick-has-role, jsx-a11y/click-events-have-key-events */
return (
<div
ref={ this.bindBlockNode }
onKeyDown={ this.onKeyDown }
onKeyUp={ this.onKeyUp }
onFocus={ this.onFocus }
onMouseMove={ this.maybeHover }
onMouseEnter={ this.maybeHover }
onMouseLeave={ onMouseLeave }
className={ wrapperClassname }
data-type={ block.name }
tabIndex="0"
aria-label={ blockLabel }
{ ...wrapperProps }
>
{ ( showUI || isHovered ) && <BlockMover uids={ [ block.uid ] } /> }
{ ( showUI || isHovered ) && <BlockRightMenu uid={ block.uid } /> }
{ showUI &&
<CSSTransitionGroup
transitionName={ { appear: 'is-appearing', appearActive: 'is-appearing-active' } }
transitionAppear={ true }
transitionAppearTimeout={ 100 }
transitionEnter={ false }
transitionLeave={ false }
component={ FirstChild }
>
<div className="editor-visual-editor__block-controls">
<BlockSwitcher uid={ block.uid } />
<Slot name="Formatting.Toolbar" />
<Toolbar className="editor-visual-editor__mobile-tools">
{ ( showUI || isHovered ) && <BlockMover uids={ [ block.uid ] } /> }
{ ( showUI || isHovered ) && <BlockRightMenu uid={ block.uid } /> }
<IconButton
className="editor-visual-editor__mobile-toggle"
onClick={ this.toggleMobileControls }
aria-expanded={ showMobileControls }
label={ __( 'Toggle extra controls' ) }
icon="ellipsis"
/>
</Toolbar>
</div>
</CSSTransitionGroup>
}
{ isFirstMultiSelected && (
<BlockMover uids={ multiSelectedBlockUids } />
) }
<div
onKeyPress={ this.maybeStartTyping }
onDragStart={ ( event ) => event.preventDefault() }
onMouseDown={ this.onPointerDown }
onTouchStart={ this.onPointerDown }
>
<BlockEdit
focus={ focus }
attributes={ block.attributes }
setAttributes={ this.setAttributes }
insertBlocksAfter={ onInsertBlocksAfter }
setFocus={ partial( onFocus, block.uid ) }
mergeBlocks={ this.mergeBlocks }
className={ classnames( className, block.attributes.className ) }
id={ block.uid }
/>
</div>
</div>
);
/* eslint-enable jsx-a11y/no-static-element-interactions, jsx-a11y/onclick-has-role, jsx-a11y/click-events-have-key-events */
}
}
export default connect(
( state, ownProps ) => {
return {
previousBlock: getPreviousBlock( state, ownProps.uid ),
nextBlock: getNextBlock( state, ownProps.uid ),
block: getBlock( state, ownProps.uid ),
isSelected: isBlockSelected( state, ownProps.uid ),
isMultiSelected: isBlockMultiSelected( state, ownProps.uid ),
isFirstMultiSelected: isFirstMultiSelectedBlock( state, ownProps.uid ),
isHovered: isBlockHovered( state, ownProps.uid ),
focus: getBlockFocus( state, ownProps.uid ),
isTyping: isTyping( state ),
order: getBlockIndex( state, ownProps.uid ),
};
},
( dispatch, ownProps ) => ( {
onChange( uid, attributes ) {
dispatch( updateBlockAttributes( uid, attributes ) );
},
onSelect() {
dispatch( {
type: 'TOGGLE_BLOCK_SELECTED',
selected: true,
uid: ownProps.uid,
} );
},
onDeselect() {
dispatch( clearSelectedBlock() );
},
onStartTyping() {
dispatch( startTyping() );
},
onStopTyping() {
dispatch( stopTyping() );
},
onHover() {
dispatch( {
type: 'TOGGLE_BLOCK_HOVERED',
hovered: true,
uid: ownProps.uid,
} );
},
onMouseLeave() {
dispatch( {
type: 'TOGGLE_BLOCK_HOVERED',
hovered: false,
uid: ownProps.uid,
} );
},
onInsertBlocksAfter( blocks ) {
dispatch( insertBlocks( blocks, ownProps.uid ) );
},
onFocus( ...args ) {
dispatch( focusBlock( ...args ) );
},
onRemove( uids ) {
dispatch( removeBlocks( uids ) );
},
onMerge( ...args ) {
dispatch( mergeBlocks( ...args ) );
},
} )
)( VisualEditorBlock );