-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
block.js
782 lines (717 loc) · 24.1 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/**
* External dependencies
*/
import classnames from 'classnames';
import { get, reduce, size, first, last } from 'lodash';
/**
* WordPress dependencies
*/
import { Component, Fragment } from '@wordpress/element';
import {
focus,
isTextField,
placeCaretAtHorizontalEdge,
placeCaretAtVerticalEdge,
} from '@wordpress/dom';
import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes';
import {
getBlockType,
getSaveElement,
isReusableBlock,
isUnmodifiedDefaultBlock,
getUnregisteredTypeHandlerName,
} from '@wordpress/blocks';
import { KeyboardShortcuts, withFilters } from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
import { withDispatch, withSelect } from '@wordpress/data';
import { withViewportMatch } from '@wordpress/viewport';
import { compose, pure } from '@wordpress/compose';
/**
* Internal dependencies
*/
import BlockEdit from '../block-edit';
import BlockMover from '../block-mover';
import BlockDropZone from '../block-drop-zone';
import BlockInvalidWarning from './block-invalid-warning';
import BlockCrashWarning from './block-crash-warning';
import BlockCrashBoundary from './block-crash-boundary';
import BlockHtml from './block-html';
import BlockBreadcrumb from './breadcrumb';
import BlockContextualToolbar from './block-contextual-toolbar';
import BlockMultiControls from './multi-controls';
import BlockMobileToolbar from './block-mobile-toolbar';
import BlockInsertionPoint from './insertion-point';
import IgnoreNestedEvents from '../ignore-nested-events';
import InserterWithShortcuts from '../inserter-with-shortcuts';
import Inserter from '../inserter';
import HoverArea from './hover-area';
import { isInsideRootBlock } from '../../utils/dom';
export class BlockListBlock extends Component {
constructor() {
super( ...arguments );
this.setBlockListRef = this.setBlockListRef.bind( this );
this.bindBlockNode = this.bindBlockNode.bind( this );
this.setAttributes = this.setAttributes.bind( this );
this.maybeHover = this.maybeHover.bind( this );
this.forceFocusedContextualToolbar = this.forceFocusedContextualToolbar.bind( this );
this.hideHoverEffects = this.hideHoverEffects.bind( this );
this.onFocus = this.onFocus.bind( this );
this.preventDrag = this.preventDrag.bind( this );
this.onPointerDown = this.onPointerDown.bind( this );
this.deleteOrInsertAfterWrapper = this.deleteOrInsertAfterWrapper.bind( this );
this.onBlockError = this.onBlockError.bind( this );
this.onTouchStart = this.onTouchStart.bind( this );
this.onClick = this.onClick.bind( this );
this.onDragStart = this.onDragStart.bind( this );
this.onDragEnd = this.onDragEnd.bind( this );
this.selectOnOpen = this.selectOnOpen.bind( this );
this.hadTouchStart = false;
this.state = {
error: null,
dragging: false,
isHovered: false,
};
this.isForcingContextualToolbar = false;
}
componentDidMount() {
if ( this.props.isSelected ) {
this.focusTabbable();
}
}
componentDidUpdate( prevProps ) {
if ( this.isForcingContextualToolbar ) {
// The forcing of contextual toolbar should only be true during one update,
// after the first update normal conditions should apply.
this.isForcingContextualToolbar = false;
}
if ( this.props.isTypingWithinBlock || this.props.isSelected ) {
this.hideHoverEffects();
}
if ( this.props.isSelected && ! prevProps.isSelected ) {
this.focusTabbable( true );
}
// When triggering a multi-selection, move the focus to the wrapper of the first selected block.
// This ensures that it is not possible to continue editing the initially selected block
// when a multi-selection is triggered.
if ( this.props.isFirstMultiSelected && ! prevProps.isFirstMultiSelected ) {
this.wrapperNode.focus();
}
}
setBlockListRef( node ) {
this.wrapperNode = node;
this.props.blockRef( node, this.props.clientId );
// We need to rerender to trigger a rerendering of HoverArea
// it depents on this.wrapperNode but we can't keep this.wrapperNode in state
// Because we need it to be immediately availeble for `focusableTabbable` to work.
this.forceUpdate();
}
bindBlockNode( node ) {
this.node = node;
}
/**
* When a block becomes selected, transition focus to an inner tabbable.
*
* @param {boolean} ignoreInnerBlocks Should not focus inner blocks.
*/
focusTabbable( ignoreInnerBlocks ) {
const { initialPosition } = this.props;
// Focus is captured by the wrapper node, so while focus transition
// should only consider tabbables within editable display, since it
// may be the wrapper itself or a side control which triggered the
// focus event, don't unnecessary transition to an inner tabbable.
if ( this.wrapperNode.contains( document.activeElement ) ) {
return;
}
// Find all tabbables within node.
const textInputs = focus.tabbable
.find( this.node )
.filter( isTextField )
// Exclude inner blocks
.filter( ( node ) => ! ignoreInnerBlocks || isInsideRootBlock( this.node, node ) );
// If reversed (e.g. merge via backspace), use the last in the set of
// tabbables.
const isReverse = -1 === initialPosition;
const target = ( isReverse ? last : first )( textInputs );
if ( ! target ) {
this.wrapperNode.focus();
return;
}
target.focus();
// In reverse case, need to explicitly place caret position.
if ( isReverse ) {
placeCaretAtHorizontalEdge( target, true );
placeCaretAtVerticalEdge( target, true );
}
}
setAttributes( attributes ) {
const { clientId, name, onChange } = this.props;
const type = getBlockType( name );
onChange( clientId, attributes );
const metaAttributes = reduce(
attributes,
( result, value, key ) => {
if ( get( type, [ 'attributes', key, 'source' ] ) === 'meta' ) {
result[ type.attributes[ key ].meta ] = value;
}
return result;
},
{}
);
if ( size( metaAttributes ) ) {
this.props.onMetaChange( metaAttributes );
}
}
onTouchStart() {
// Detect touchstart to disable hover on iOS
this.hadTouchStart = true;
}
onClick() {
// Clear touchstart detection
// Browser will try to emulate mouse events also see https://www.html5rocks.com/en/mobile/touchandmouse/
this.hadTouchStart = false;
}
/**
* A mouseover event handler to apply hover effect when a pointer device is
* placed within the bounds of the block. The mouseover event is preferred
* over mouseenter because it may be the case that a previous mouseenter
* event was blocked from being handled by a IgnoreNestedEvents component,
* therefore transitioning out of a nested block to the bounds of the block
* would otherwise not trigger a hover effect.
*
* @see https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter
*/
maybeHover() {
const { isPartOfMultiSelection, isSelected } = this.props;
const { isHovered } = this.state;
if (
isHovered ||
isPartOfMultiSelection ||
isSelected ||
this.hadTouchStart
) {
return;
}
this.setState( { isHovered: true } );
}
/**
* Sets the block state as unhovered if currently hovering. There are cases
* where mouseleave may occur but the block is not hovered (multi-select),
* so to avoid unnecesary renders, the state is only set if hovered.
*/
hideHoverEffects() {
if ( this.state.isHovered ) {
this.setState( { isHovered: false } );
}
}
/**
* Marks the block as selected when focused and not already selected. This
* specifically handles the case where block does not set focus on its own
* (via `setFocus`), typically if there is no focusable input in the block.
*
* @return {void}
*/
onFocus() {
if ( ! this.props.isSelected && ! this.props.isPartOfMultiSelection ) {
this.props.onSelect();
}
}
/**
* Prevents default dragging behavior within a block to allow for multi-
* selection to take effect unhampered.
*
* @param {DragEvent} event Drag event.
*
* @return {void}
*/
preventDrag( event ) {
event.preventDefault();
}
/**
* Begins tracking cursor multi-selection when clicking down within block.
*
* @param {MouseEvent} event A mousedown event.
*
* @return {void}
*/
onPointerDown( event ) {
// Not the main button.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
if ( event.button !== 0 ) {
return;
}
if ( event.shiftKey ) {
if ( ! this.props.isSelected ) {
this.props.onShiftSelection();
event.preventDefault();
}
} else {
this.props.onSelectionStart( this.props.clientId );
// Allow user to escape out of a multi-selection to a singular
// selection of a block via click. This is handled here since
// onFocus excludes blocks involved in a multiselection, as
// focus can be incurred by starting a multiselection (focus
// moved to first block's multi-controls).
if ( this.props.isPartOfMultiSelection ) {
this.props.onSelect();
}
}
}
/**
* Interprets keydown event intent to remove or insert after block if key
* event occurs on wrapper node. This can occur when the block has no text
* fields of its own, particularly after initial insertion, to allow for
* easy deletion and continuous writing flow to add additional content.
*
* @param {KeyboardEvent} event Keydown event.
*/
deleteOrInsertAfterWrapper( event ) {
const { keyCode, target } = event;
// These block shortcuts should only trigger if the wrapper of the block is selected
// And when it's not a multi-selection to avoid conflicting with RichText/Inputs and multiselection.
if (
! this.props.isSelected ||
target !== this.wrapperNode ||
this.props.isLocked
) {
return;
}
switch ( keyCode ) {
case ENTER:
// Insert default block after current block if enter and event
// not already handled by descendant.
this.props.onInsertDefaultBlockAfter();
event.preventDefault();
break;
case BACKSPACE:
case DELETE:
// Remove block on backspace.
const { clientId, onRemove } = this.props;
onRemove( clientId );
event.preventDefault();
break;
}
}
onBlockError( error ) {
this.setState( { error } );
}
onDragStart() {
this.setState( { dragging: true } );
}
onDragEnd() {
this.setState( { dragging: false } );
}
selectOnOpen( open ) {
if ( open && ! this.props.isSelected ) {
this.props.onSelect();
}
}
forceFocusedContextualToolbar() {
this.isForcingContextualToolbar = true;
// trigger a re-render
this.setState( () => ( {} ) );
}
render() {
return (
<HoverArea container={ this.wrapperNode }>
{ ( { hoverArea } ) => {
const {
mode,
isFocusMode,
hasFixedToolbar,
isLocked,
isFirst,
isLast,
clientId,
rootClientId,
isSelected,
isPartOfMultiSelection,
isFirstMultiSelected,
isTypingWithinBlock,
isCaretWithinFormattedText,
isEmptyDefaultBlock,
isMovable,
isParentOfSelectedBlock,
isDraggable,
className,
name,
isValid,
attributes,
} = this.props;
const isHovered = this.state.isHovered && ! isPartOfMultiSelection;
const blockType = getBlockType( name );
// translators: %s: Type of block (i.e. Text, Image etc)
const blockLabel = sprintf( __( 'Block: %s' ), blockType.title );
// The block as rendered in the editor is composed of general block UI
// (mover, toolbar, wrapper) and the display of the block content.
const isUnregisteredBlock = name === getUnregisteredTypeHandlerName();
// If the block is selected and we're typing the block should not appear.
// Empty paragraph blocks should always show up as unselected.
const showEmptyBlockSideInserter =
( isSelected || isHovered ) && isEmptyDefaultBlock && isValid;
const shouldAppearSelected =
! isFocusMode &&
! showEmptyBlockSideInserter &&
isSelected &&
! isTypingWithinBlock;
const shouldAppearHovered =
! isFocusMode &&
! hasFixedToolbar &&
isHovered &&
! isEmptyDefaultBlock;
// We render block movers and block settings to keep them tabbale even if hidden
const shouldRenderMovers =
! isFocusMode &&
( isSelected || hoverArea === 'left' ) &&
! showEmptyBlockSideInserter &&
! isPartOfMultiSelection &&
! isTypingWithinBlock;
const shouldShowBreadcrumb =
! isFocusMode && isHovered && ! isEmptyDefaultBlock;
const shouldShowContextualToolbar =
! hasFixedToolbar &&
! showEmptyBlockSideInserter &&
( ( isSelected &&
( ! isTypingWithinBlock || isCaretWithinFormattedText ) ) ||
isFirstMultiSelected );
const shouldShowMobileToolbar = shouldAppearSelected;
const { error, dragging } = this.state;
// Insertion point can only be made visible if the block is at the
// the extent of a multi-selection, or not in a multi-selection.
const shouldShowInsertionPoint =
( isPartOfMultiSelection && isFirstMultiSelected ) ||
! isPartOfMultiSelection;
// The wp-block className is important for editor styles.
// Generate the wrapper class names handling the different states of the block.
const wrapperClassName = classnames(
'wp-block editor-block-list__block block-editor-block-list__block',
{
'has-warning': ! isValid || !! error || isUnregisteredBlock,
'is-selected': shouldAppearSelected,
'is-multi-selected': isPartOfMultiSelection,
'is-hovered': shouldAppearHovered,
'is-reusable': isReusableBlock( blockType ),
'is-dragging': dragging,
'is-typing': isTypingWithinBlock,
'is-focused':
isFocusMode && ( isSelected || isParentOfSelectedBlock ),
'is-focus-mode': isFocusMode,
},
className
);
const { onReplace } = this.props;
// Determine whether the block has props to apply to the wrapper.
let wrapperProps = this.props.wrapperProps;
if ( blockType.getEditWrapperProps ) {
wrapperProps = {
...wrapperProps,
...blockType.getEditWrapperProps( attributes ),
};
}
const blockElementId = `block-${ clientId }`;
// We wrap the BlockEdit component in a div that hides it when editing in
// HTML mode. This allows us to render all of the ancillary pieces
// (InspectorControls, etc.) which are inside `BlockEdit` but not
// `BlockHTML`, even in HTML mode.
let blockEdit = (
<BlockEdit
name={ name }
isSelected={ isSelected }
attributes={ attributes }
setAttributes={ this.setAttributes }
insertBlocksAfter={ isLocked ? undefined : this.props.onInsertBlocksAfter }
onReplace={ isLocked ? undefined : onReplace }
mergeBlocks={ isLocked ? undefined : this.props.onMerge }
clientId={ clientId }
isSelectionEnabled={ this.props.isSelectionEnabled }
toggleSelection={ this.props.toggleSelection }
/>
);
if ( mode !== 'visual' ) {
blockEdit = <div style={ { display: 'none' } }>{ blockEdit }</div>;
}
// Disable reasons:
//
// jsx-a11y/mouse-events-have-key-events:
// - onMouseOver is explicitly handling hover effects
//
// jsx-a11y/no-static-element-interactions:
// - Each block can be selected by clicking on it
/* eslint-disable jsx-a11y/mouse-events-have-key-events, jsx-a11y/no-static-element-interactions, jsx-a11y/onclick-has-role, jsx-a11y/click-events-have-key-events */
return (
<IgnoreNestedEvents
id={ blockElementId }
ref={ this.setBlockListRef }
onMouseOver={ this.maybeHover }
onMouseOverHandled={ this.hideHoverEffects }
onMouseLeave={ this.hideHoverEffects }
className={ wrapperClassName }
data-type={ name }
onTouchStart={ this.onTouchStart }
onFocus={ this.onFocus }
onClick={ this.onClick }
onKeyDown={ this.deleteOrInsertAfterWrapper }
tabIndex="0"
aria-label={ blockLabel }
childHandledEvents={ [ 'onDragStart', 'onMouseDown' ] }
{ ...wrapperProps }
>
{ shouldShowInsertionPoint && (
<BlockInsertionPoint
clientId={ clientId }
rootClientId={ rootClientId }
/>
) }
<BlockDropZone
clientId={ clientId }
rootClientId={ rootClientId }
/>
{ isFirstMultiSelected && (
<BlockMultiControls rootClientId={ rootClientId } />
) }
<div className="editor-block-list__block-edit block-editor-block-list__block-edit">
{ shouldRenderMovers && (
<BlockMover
clientIds={ clientId }
blockElementId={ blockElementId }
isFirst={ isFirst }
isLast={ isLast }
isHidden={ ! ( isHovered || isSelected ) || hoverArea !== 'left' }
isDraggable={
isDraggable !== false &&
( ! isPartOfMultiSelection && isMovable )
}
onDragStart={ this.onDragStart }
onDragEnd={ this.onDragEnd }
/>
) }
{ shouldShowBreadcrumb && (
<BlockBreadcrumb
clientId={ clientId }
isHidden={
! ( isHovered || isSelected ) || hoverArea !== 'left'
}
/>
) }
{ ( shouldShowContextualToolbar ||
this.isForcingContextualToolbar ) && (
<BlockContextualToolbar
// If the toolbar is being shown because of being forced
// it should focus the toolbar right after the mount.
focusOnMount={ this.isForcingContextualToolbar }
/>
) }
{ ! shouldShowContextualToolbar &&
isSelected &&
! hasFixedToolbar &&
! isEmptyDefaultBlock && (
<KeyboardShortcuts
bindGlobal
eventName="keydown"
shortcuts={ {
'alt+f10': this.forceFocusedContextualToolbar,
} }
/>
) }
<IgnoreNestedEvents
ref={ this.bindBlockNode }
onDragStart={ this.preventDrag }
onMouseDown={ this.onPointerDown }
data-block={ clientId }
>
<BlockCrashBoundary onError={ this.onBlockError }>
{ isValid && blockEdit }
{ isValid && mode === 'html' && (
<BlockHtml clientId={ clientId } />
) }
{ ! isValid && [
<BlockInvalidWarning
key="invalid-warning"
clientId={ clientId }
/>,
<div key="invalid-preview">
{ getSaveElement( blockType, attributes ) }
</div>,
] }
</BlockCrashBoundary>
{ shouldShowMobileToolbar && (
<BlockMobileToolbar clientId={ clientId } />
) }
{ !! error && <BlockCrashWarning /> }
</IgnoreNestedEvents>
</div>
{ showEmptyBlockSideInserter && (
<Fragment>
<div className="editor-block-list__side-inserter block-editor-block-list__side-inserter">
<InserterWithShortcuts
clientId={ clientId }
rootClientId={ rootClientId }
onToggle={ this.selectOnOpen }
/>
</div>
<div className="editor-block-list__empty-block-inserter block-editor-block-list__empty-block-inserter">
<Inserter
position="top right"
onToggle={ this.selectOnOpen }
rootClientId={ rootClientId }
clientId={ clientId }
/>
</div>
</Fragment>
) }
</IgnoreNestedEvents>
);
/* eslint-enable jsx-a11y/no-static-element-interactions, jsx-a11y/onclick-has-role, jsx-a11y/click-events-have-key-events */
} }
</HoverArea>
);
}
}
const applyWithSelect = withSelect(
( select, { clientId, rootClientId, isLargeViewport } ) => {
const {
isBlockSelected,
isAncestorMultiSelected,
isBlockMultiSelected,
isFirstMultiSelectedBlock,
isTyping,
isCaretWithinFormattedText,
getBlockMode,
isSelectionEnabled,
getSelectedBlocksInitialCaretPosition,
getSettings,
hasSelectedInnerBlock,
getTemplateLock,
__unstableGetBlockWithoutInnerBlocks,
} = select( 'core/block-editor' );
const block = __unstableGetBlockWithoutInnerBlocks( clientId );
const isSelected = isBlockSelected( clientId );
const { hasFixedToolbar, focusMode } = getSettings();
const templateLock = getTemplateLock( rootClientId );
const isParentOfSelectedBlock = hasSelectedInnerBlock( clientId, true );
// The fallback to `{}` is a temporary fix.
// This function should never be called when a block is not present in the state.
// It happens now because the order in withSelect rendering is not correct.
const { name, attributes, isValid } = block || {};
return {
isPartOfMultiSelection:
isBlockMultiSelected( clientId ) || isAncestorMultiSelected( clientId ),
isFirstMultiSelected: isFirstMultiSelectedBlock( clientId ),
// We only care about this prop when the block is selected
// Thus to avoid unnecessary rerenders we avoid updating the prop if the block is not selected.
isTypingWithinBlock:
( isSelected || isParentOfSelectedBlock ) && isTyping(),
isCaretWithinFormattedText: isCaretWithinFormattedText(),
mode: getBlockMode( clientId ),
isSelectionEnabled: isSelectionEnabled(),
initialPosition: isSelected ? getSelectedBlocksInitialCaretPosition() : null,
isEmptyDefaultBlock:
name && isUnmodifiedDefaultBlock( { name, attributes } ),
isMovable: 'all' !== templateLock,
isLocked: !! templateLock,
isFocusMode: focusMode && isLargeViewport,
hasFixedToolbar: hasFixedToolbar && isLargeViewport,
// Users of the editor.BlockListBlock filter used to be able to access the block prop
// Ideally these blocks would rely on the clientId prop only.
// This is kept for backward compatibility reasons.
block,
name,
attributes,
isValid,
isSelected,
isParentOfSelectedBlock,
};
}
);
const applyWithDispatch = withDispatch( ( dispatch, ownProps, { select } ) => {
const {
updateBlockAttributes,
selectBlock,
multiSelect,
insertBlocks,
insertDefaultBlock,
removeBlock,
mergeBlocks,
replaceBlocks,
toggleSelection,
} = dispatch( 'core/block-editor' );
return {
onChange( clientId, attributes ) {
updateBlockAttributes( clientId, attributes );
},
onSelect( clientId = ownProps.clientId, initialPosition ) {
selectBlock( clientId, initialPosition );
},
onInsertBlocks( blocks, index ) {
const { rootClientId } = ownProps;
insertBlocks( blocks, index, rootClientId );
},
onInsertDefaultBlockAfter() {
const { clientId, rootClientId } = ownProps;
const {
getBlockIndex,
} = select( 'core/block-editor' );
const index = getBlockIndex( clientId, rootClientId );
insertDefaultBlock( {}, rootClientId, index + 1 );
},
onInsertBlocksAfter( blocks ) {
const { clientId, rootClientId } = ownProps;
const {
getBlockIndex,
} = select( 'core/block-editor' );
const index = getBlockIndex( clientId, rootClientId );
insertBlocks( blocks, index + 1, rootClientId );
},
onRemove( clientId ) {
removeBlock( clientId );
},
onMerge( forward ) {
const { clientId } = ownProps;
const {
getPreviousBlockClientId,
getNextBlockClientId,
} = select( 'core/block-editor' );
if ( forward ) {
const nextBlockClientId = getNextBlockClientId( clientId );
if ( nextBlockClientId ) {
mergeBlocks( clientId, nextBlockClientId );
}
} else {
const previousBlockClientId = getPreviousBlockClientId( clientId );
if ( previousBlockClientId ) {
mergeBlocks( previousBlockClientId, clientId );
}
}
},
onReplace( blocks ) {
replaceBlocks( [ ownProps.clientId ], blocks );
},
onMetaChange( updatedMeta ) {
const { getSettings } = select( 'core/block-editor' );
const onChangeMeta = getSettings().__experimentalMetaSource.onChange;
onChangeMeta( updatedMeta );
},
onShiftSelection() {
if ( ! ownProps.isSelectionEnabled ) {
return;
}
const {
getBlockSelectionStart,
} = select( 'core/block-editor' );
if ( getBlockSelectionStart() ) {
multiSelect( getBlockSelectionStart(), ownProps.clientId );
} else {
selectBlock( ownProps.clientId );
}
},
toggleSelection( selectionEnabled ) {
toggleSelection( selectionEnabled );
},
};
} );
export default compose(
pure,
withViewportMatch( { isLargeViewport: 'medium' } ),
applyWithSelect,
applyWithDispatch,
withFilters( 'editor.BlockListBlock' )
)( BlockListBlock );