-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
actions.js
2192 lines (2009 loc) · 62.3 KB
/
actions.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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint no-console: [ 'error', { allow: [ 'error', 'warn' ] } ] */
/**
* WordPress dependencies
*/
import {
cloneBlock,
__experimentalCloneSanitizedBlock,
createBlock,
doBlocksMatchTemplate,
getBlockType,
getDefaultBlockName,
hasBlockSupport,
switchToBlockType,
synchronizeBlocksWithTemplate,
getBlockSupport,
isUnmodifiedDefaultBlock,
isUnmodifiedBlock,
} from '@wordpress/blocks';
import { speak } from '@wordpress/a11y';
import { __, _n, sprintf } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
import { create, insert, remove, toHTMLString } from '@wordpress/rich-text';
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import {
retrieveSelectedAttribute,
findRichTextAttributeKey,
START_OF_SELECTED_AREA,
} from '../utils/selection';
import {
__experimentalUpdateSettings,
privateRemoveBlocks,
} from './private-actions';
/** @typedef {import('../components/use-on-block-drop/types').WPDropOperation} WPDropOperation */
const castArray = ( maybeArray ) =>
Array.isArray( maybeArray ) ? maybeArray : [ maybeArray ];
/**
* Action that resets blocks state to the specified array of blocks, taking precedence
* over any other content reflected as an edit in state.
*
* @param {Array} blocks Array of blocks.
*/
export const resetBlocks =
( blocks ) =>
( { dispatch } ) => {
dispatch( { type: 'RESET_BLOCKS', blocks } );
dispatch( validateBlocksToTemplate( blocks ) );
};
/**
* Block validity is a function of blocks state (at the point of a
* reset) and the template setting. As a compromise to its placement
* across distinct parts of state, it is implemented here as a side
* effect of the block reset action.
*
* @param {Array} blocks Array of blocks.
*/
export const validateBlocksToTemplate =
( blocks ) =>
( { select, dispatch } ) => {
const template = select.getTemplate();
const templateLock = select.getTemplateLock();
// Unlocked templates are considered always valid because they act
// as default values only.
const isBlocksValidToTemplate =
! template ||
templateLock !== 'all' ||
doBlocksMatchTemplate( blocks, template );
// Update if validity has changed.
const isValidTemplate = select.isValidTemplate();
if ( isBlocksValidToTemplate !== isValidTemplate ) {
dispatch.setTemplateValidity( isBlocksValidToTemplate );
return isBlocksValidToTemplate;
}
};
/**
* A block selection object.
*
* @typedef {Object} WPBlockSelection
*
* @property {string} clientId A block client ID.
* @property {string} attributeKey A block attribute key.
* @property {number} offset An attribute value offset, based on the rich
* text value. See `wp.richText.create`.
*/
/**
* A selection object.
*
* @typedef {Object} WPSelection
*
* @property {WPBlockSelection} start The selection start.
* @property {WPBlockSelection} end The selection end.
*/
/* eslint-disable jsdoc/valid-types */
/**
* Returns an action object used in signalling that selection state should be
* reset to the specified selection.
*
* @param {WPBlockSelection} selectionStart The selection start.
* @param {WPBlockSelection} selectionEnd The selection end.
* @param {0|-1|null} initialPosition Initial block position.
*
* @return {Object} Action object.
*/
export function resetSelection(
selectionStart,
selectionEnd,
initialPosition
) {
/* eslint-enable jsdoc/valid-types */
return {
type: 'RESET_SELECTION',
selectionStart,
selectionEnd,
initialPosition,
};
}
/**
* Returns an action object used in signalling that blocks have been received.
* Unlike resetBlocks, these should be appended to the existing known set, not
* replacing.
*
* @deprecated
*
* @param {Object[]} blocks Array of block objects.
*
* @return {Object} Action object.
*/
export function receiveBlocks( blocks ) {
deprecated( 'wp.data.dispatch( "core/block-editor" ).receiveBlocks', {
since: '5.9',
alternative: 'resetBlocks or insertBlocks',
} );
return {
type: 'RECEIVE_BLOCKS',
blocks,
};
}
/**
* Action that updates attributes of multiple blocks with the specified client IDs.
*
* @param {string|string[]} clientIds Block client IDs.
* @param {Object} attributes Block attributes to be merged. Should be keyed by clientIds if
* uniqueByBlock is true.
* @param {boolean} uniqueByBlock true if each block in clientIds array has a unique set of attributes
* @return {Object} Action object.
*/
export function updateBlockAttributes(
clientIds,
attributes,
uniqueByBlock = false
) {
return {
type: 'UPDATE_BLOCK_ATTRIBUTES',
clientIds: castArray( clientIds ),
attributes,
uniqueByBlock,
};
}
/**
* Action that updates the block with the specified client ID.
*
* @param {string} clientId Block client ID.
* @param {Object} updates Block attributes to be merged.
*
* @return {Object} Action object.
*/
export function updateBlock( clientId, updates ) {
return {
type: 'UPDATE_BLOCK',
clientId,
updates,
};
}
/* eslint-disable jsdoc/valid-types */
/**
* Returns an action object used in signalling that the block with the
* specified client ID has been selected, optionally accepting a position
* value reflecting its selection directionality. An initialPosition of -1
* reflects a reverse selection.
*
* @param {string} clientId Block client ID.
* @param {0|-1|null} initialPosition Optional initial position. Pass as -1 to
* reflect reverse selection.
*
* @return {Object} Action object.
*/
export function selectBlock( clientId, initialPosition = 0 ) {
/* eslint-enable jsdoc/valid-types */
return {
type: 'SELECT_BLOCK',
initialPosition,
clientId,
};
}
/**
* Returns an action object used in signalling that the block with the
* specified client ID has been hovered.
*
* @param {string} clientId Block client ID.
*
* @return {Object} Action object.
*/
export function hoverBlock( clientId ) {
return {
type: 'HOVER_BLOCK',
clientId,
};
}
/**
* Yields action objects used in signalling that the block preceding the given
* clientId (or optionally, its first parent from bottom to top)
* should be selected.
*
* @param {string} clientId Block client ID.
* @param {boolean} fallbackToParent If true, select the first parent if there is no previous block.
*/
export const selectPreviousBlock =
( clientId, fallbackToParent = false ) =>
( { select, dispatch } ) => {
const previousBlockClientId =
select.getPreviousBlockClientId( clientId );
if ( previousBlockClientId ) {
dispatch.selectBlock( previousBlockClientId, -1 );
} else if ( fallbackToParent ) {
const firstParentClientId = select.getBlockRootClientId( clientId );
if ( firstParentClientId ) {
dispatch.selectBlock( firstParentClientId, -1 );
}
}
};
/**
* Yields action objects used in signalling that the block following the given
* clientId should be selected.
*
* @param {string} clientId Block client ID.
*/
export const selectNextBlock =
( clientId ) =>
( { select, dispatch } ) => {
const nextBlockClientId = select.getNextBlockClientId( clientId );
if ( nextBlockClientId ) {
dispatch.selectBlock( nextBlockClientId );
}
};
/**
* Action that starts block multi-selection.
*
* @return {Object} Action object.
*/
export function startMultiSelect() {
return {
type: 'START_MULTI_SELECT',
};
}
/**
* Action that stops block multi-selection.
*
* @return {Object} Action object.
*/
export function stopMultiSelect() {
return {
type: 'STOP_MULTI_SELECT',
};
}
/**
* Action that changes block multi-selection.
*
* @param {string} start First block of the multi selection.
* @param {string} end Last block of the multiselection.
* @param {number|null} __experimentalInitialPosition Optional initial position. Pass as null to skip focus within editor canvas.
*/
export const multiSelect =
( start, end, __experimentalInitialPosition = 0 ) =>
( { select, dispatch } ) => {
const startBlockRootClientId = select.getBlockRootClientId( start );
const endBlockRootClientId = select.getBlockRootClientId( end );
// Only allow block multi-selections at the same level.
if ( startBlockRootClientId !== endBlockRootClientId ) {
return;
}
dispatch( {
type: 'MULTI_SELECT',
start,
end,
initialPosition: __experimentalInitialPosition,
} );
const blockCount = select.getSelectedBlockCount();
speak(
sprintf(
/* translators: %s: number of selected blocks */
_n( '%s block selected.', '%s blocks selected.', blockCount ),
blockCount
),
'assertive'
);
};
/**
* Action that clears the block selection.
*
* @return {Object} Action object.
*/
export function clearSelectedBlock() {
return {
type: 'CLEAR_SELECTED_BLOCK',
};
}
/**
* Action that enables or disables block selection.
*
* @param {boolean} [isSelectionEnabled=true] Whether block selection should
* be enabled.
*
* @return {Object} Action object.
*/
export function toggleSelection( isSelectionEnabled = true ) {
return {
type: 'TOGGLE_SELECTION',
isSelectionEnabled,
};
}
/* eslint-disable jsdoc/valid-types */
/**
* Action that replaces given blocks with one or more replacement blocks.
*
* @param {(string|string[])} clientIds Block client ID(s) to replace.
* @param {(Object|Object[])} blocks Replacement block(s).
* @param {number} indexToSelect Index of replacement block to select.
* @param {0|-1|null} initialPosition Index of caret after in the selected block after the operation.
* @param {?Object} meta Optional Meta values to be passed to the action object.
*
* @return {Object} Action object.
*/
export const replaceBlocks =
( clientIds, blocks, indexToSelect, initialPosition = 0, meta ) =>
( { select, dispatch, registry } ) => {
/* eslint-enable jsdoc/valid-types */
clientIds = castArray( clientIds );
blocks = castArray( blocks );
const rootClientId = select.getBlockRootClientId( clientIds[ 0 ] );
// Replace is valid if the new blocks can be inserted in the root block.
for ( let index = 0; index < blocks.length; index++ ) {
const block = blocks[ index ];
const canInsertBlock = select.canInsertBlockType(
block.name,
rootClientId
);
if ( ! canInsertBlock ) {
return;
}
}
// We're batching these two actions because an extra `undo/redo` step can
// be created, based on whether we insert a default block or not.
registry.batch( () => {
dispatch( {
type: 'REPLACE_BLOCKS',
clientIds,
blocks,
time: Date.now(),
indexToSelect,
initialPosition,
meta,
} );
// To avoid a focus loss when removing the last block, assure there is
// always a default block if the last of the blocks have been removed.
dispatch.ensureDefaultBlock();
} );
};
/**
* Action that replaces a single block with one or more replacement blocks.
*
* @param {(string|string[])} clientId Block client ID to replace.
* @param {(Object|Object[])} block Replacement block(s).
*
* @return {Object} Action object.
*/
export function replaceBlock( clientId, block ) {
return replaceBlocks( clientId, block );
}
/**
* Higher-order action creator which, given the action type to dispatch creates
* an action creator for managing block movement.
*
* @param {string} type Action type to dispatch.
*
* @return {Function} Action creator.
*/
const createOnMove =
( type ) =>
( clientIds, rootClientId ) =>
( { select, dispatch } ) => {
// If one of the blocks is locked or the parent is locked, we cannot move any block.
const canMoveBlocks = select.canMoveBlocks( clientIds );
if ( ! canMoveBlocks ) {
return;
}
dispatch( { type, clientIds: castArray( clientIds ), rootClientId } );
};
export const moveBlocksDown = createOnMove( 'MOVE_BLOCKS_DOWN' );
export const moveBlocksUp = createOnMove( 'MOVE_BLOCKS_UP' );
/**
* Action that moves given blocks to a new position.
*
* @param {?string} clientIds The client IDs of the blocks.
* @param {?string} fromRootClientId Root client ID source.
* @param {?string} toRootClientId Root client ID destination.
* @param {number} index The index to move the blocks to.
*/
export const moveBlocksToPosition =
( clientIds, fromRootClientId = '', toRootClientId = '', index ) =>
( { select, dispatch } ) => {
const canMoveBlocks = select.canMoveBlocks( clientIds );
// If one of the blocks is locked or the parent is locked, we cannot move any block.
if ( ! canMoveBlocks ) {
return;
}
// If moving inside the same root block the move is always possible.
if ( fromRootClientId !== toRootClientId ) {
const canRemoveBlocks = select.canRemoveBlocks( clientIds );
// If we're moving to another block, it means we're deleting blocks from
// the original block, so we need to check if removing is possible.
if ( ! canRemoveBlocks ) {
return;
}
const canInsertBlocks = select.canInsertBlocks(
clientIds,
toRootClientId
);
// If moving to other parent block, the move is possible if we can insert a block of the same type inside the new parent block.
if ( ! canInsertBlocks ) {
return;
}
}
dispatch( {
type: 'MOVE_BLOCKS_TO_POSITION',
fromRootClientId,
toRootClientId,
clientIds,
index,
} );
};
/**
* Action that moves given block to a new position.
*
* @param {?string} clientId The client ID of the block.
* @param {?string} fromRootClientId Root client ID source.
* @param {?string} toRootClientId Root client ID destination.
* @param {number} index The index to move the block to.
*/
export function moveBlockToPosition(
clientId,
fromRootClientId = '',
toRootClientId = '',
index
) {
return moveBlocksToPosition(
[ clientId ],
fromRootClientId,
toRootClientId,
index
);
}
/**
* Action that inserts a single block, optionally at a specific index respective a root block list.
*
* Only allowed blocks are inserted. The action may fail silently for blocks that are not allowed or if
* a templateLock is active on the block list.
*
* @param {Object} block Block object to insert.
* @param {?number} index Index at which block should be inserted.
* @param {?string} rootClientId Optional root client ID of block list on which to insert.
* @param {?boolean} updateSelection If true block selection will be updated. If false, block selection will not change. Defaults to true.
* @param {?Object} meta Optional Meta values to be passed to the action object.
*
* @return {Object} Action object.
*/
export function insertBlock(
block,
index,
rootClientId,
updateSelection,
meta
) {
return insertBlocks(
[ block ],
index,
rootClientId,
updateSelection,
0,
meta
);
}
/* eslint-disable jsdoc/valid-types */
/**
* Action that inserts an array of blocks, optionally at a specific index respective a root block list.
*
* Only allowed blocks are inserted. The action may fail silently for blocks that are not allowed or if
* a templateLock is active on the block list.
*
* @param {Object[]} blocks Block objects to insert.
* @param {?number} index Index at which block should be inserted.
* @param {?string} rootClientId Optional root client ID of block list on which to insert.
* @param {?boolean} updateSelection If true block selection will be updated. If false, block selection will not change. Defaults to true.
* @param {0|-1|null} initialPosition Initial focus position. Setting it to null prevent focusing the inserted block.
* @param {?Object} meta Optional Meta values to be passed to the action object.
*
* @return {Object} Action object.
*/
export const insertBlocks =
(
blocks,
index,
rootClientId,
updateSelection = true,
initialPosition = 0,
meta
) =>
( { select, dispatch } ) => {
/* eslint-enable jsdoc/valid-types */
if ( initialPosition !== null && typeof initialPosition === 'object' ) {
meta = initialPosition;
initialPosition = 0;
deprecated(
"meta argument in wp.data.dispatch('core/block-editor')",
{
since: '5.8',
hint: 'The meta argument is now the 6th argument of the function',
}
);
}
blocks = castArray( blocks );
const allowedBlocks = [];
for ( const block of blocks ) {
const isValid = select.canInsertBlockType(
block.name,
rootClientId
);
if ( isValid ) {
allowedBlocks.push( block );
}
}
if ( allowedBlocks.length ) {
dispatch( {
type: 'INSERT_BLOCKS',
blocks: allowedBlocks,
index,
rootClientId,
time: Date.now(),
updateSelection,
initialPosition: updateSelection ? initialPosition : null,
meta,
} );
}
};
/**
* Action that shows the insertion point.
*
* @param {?string} rootClientId Optional root client ID of block list on
* which to insert.
* @param {?number} index Index at which block should be inserted.
* @param {?Object} __unstableOptions Additional options.
* @property {boolean} __unstableWithInserter Whether or not to show an inserter button.
* @property {WPDropOperation} operation The operation to perform when applied,
* either 'insert' or 'replace' for now.
*
* @return {Object} Action object.
*/
export function showInsertionPoint(
rootClientId,
index,
__unstableOptions = {}
) {
const { __unstableWithInserter, operation, nearestSide } =
__unstableOptions;
return {
type: 'SHOW_INSERTION_POINT',
rootClientId,
index,
__unstableWithInserter,
operation,
nearestSide,
};
}
/**
* Action that hides the insertion point.
*/
export const hideInsertionPoint =
() =>
( { select, dispatch } ) => {
if ( ! select.isBlockInsertionPointVisible() ) {
return;
}
dispatch( {
type: 'HIDE_INSERTION_POINT',
} );
};
/**
* Action that resets the template validity.
*
* @param {boolean} isValid template validity flag.
*
* @return {Object} Action object.
*/
export function setTemplateValidity( isValid ) {
return {
type: 'SET_TEMPLATE_VALIDITY',
isValid,
};
}
/**
* Action that synchronizes the template with the list of blocks.
*
* @return {Object} Action object.
*/
export const synchronizeTemplate =
() =>
( { select, dispatch } ) => {
dispatch( { type: 'SYNCHRONIZE_TEMPLATE' } );
const blocks = select.getBlocks();
const template = select.getTemplate();
const updatedBlockList = synchronizeBlocksWithTemplate(
blocks,
template
);
dispatch.resetBlocks( updatedBlockList );
};
/**
* Delete the current selection.
*
* @param {boolean} isForward
*/
export const __unstableDeleteSelection =
( isForward ) =>
( { registry, select, dispatch } ) => {
const selectionAnchor = select.getSelectionStart();
const selectionFocus = select.getSelectionEnd();
if ( selectionAnchor.clientId === selectionFocus.clientId ) {
return;
}
// It's not mergeable if there's no rich text selection.
if (
! selectionAnchor.attributeKey ||
! selectionFocus.attributeKey ||
typeof selectionAnchor.offset === 'undefined' ||
typeof selectionFocus.offset === 'undefined'
) {
return false;
}
const anchorRootClientId = select.getBlockRootClientId(
selectionAnchor.clientId
);
const focusRootClientId = select.getBlockRootClientId(
selectionFocus.clientId
);
// It's not mergeable if the selection doesn't start and end in the same
// block list. Maybe in the future it should be allowed.
if ( anchorRootClientId !== focusRootClientId ) {
return;
}
const blockOrder = select.getBlockOrder( anchorRootClientId );
const anchorIndex = blockOrder.indexOf( selectionAnchor.clientId );
const focusIndex = blockOrder.indexOf( selectionFocus.clientId );
// Reassign selection start and end based on order.
let selectionStart, selectionEnd;
if ( anchorIndex > focusIndex ) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const targetSelection = isForward ? selectionEnd : selectionStart;
const targetBlock = select.getBlock( targetSelection.clientId );
const targetBlockType = getBlockType( targetBlock.name );
if ( ! targetBlockType.merge ) {
return;
}
const selectionA = selectionStart;
const selectionB = selectionEnd;
const blockA = select.getBlock( selectionA.clientId );
const blockB = select.getBlock( selectionB.clientId );
const htmlA = blockA.attributes[ selectionA.attributeKey ];
const htmlB = blockB.attributes[ selectionB.attributeKey ];
let valueA = create( { html: htmlA } );
let valueB = create( { html: htmlB } );
valueA = remove( valueA, selectionA.offset, valueA.text.length );
valueB = insert( valueB, START_OF_SELECTED_AREA, 0, selectionB.offset );
// Clone the blocks so we don't manipulate the original.
const cloneA = cloneBlock( blockA, {
[ selectionA.attributeKey ]: toHTMLString( { value: valueA } ),
} );
const cloneB = cloneBlock( blockB, {
[ selectionB.attributeKey ]: toHTMLString( { value: valueB } ),
} );
const followingBlock = isForward ? cloneA : cloneB;
// We can only merge blocks with similar types
// thus, we transform the block to merge first
const blocksWithTheSameType =
blockA.name === blockB.name
? [ followingBlock ]
: switchToBlockType( followingBlock, targetBlockType.name );
// If the block types can not match, do nothing
if ( ! blocksWithTheSameType || ! blocksWithTheSameType.length ) {
return;
}
let updatedAttributes;
if ( isForward ) {
const blockToMerge = blocksWithTheSameType.pop();
updatedAttributes = targetBlockType.merge(
blockToMerge.attributes,
cloneB.attributes
);
} else {
const blockToMerge = blocksWithTheSameType.shift();
updatedAttributes = targetBlockType.merge(
cloneA.attributes,
blockToMerge.attributes
);
}
const newAttributeKey = retrieveSelectedAttribute( updatedAttributes );
const convertedHtml = updatedAttributes[ newAttributeKey ];
const convertedValue = create( { html: convertedHtml } );
const newOffset = convertedValue.text.indexOf( START_OF_SELECTED_AREA );
const newValue = remove( convertedValue, newOffset, newOffset + 1 );
const newHtml = toHTMLString( { value: newValue } );
updatedAttributes[ newAttributeKey ] = newHtml;
const selectedBlockClientIds = select.getSelectedBlockClientIds();
const replacement = [
...( isForward ? blocksWithTheSameType : [] ),
{
// Preserve the original client ID.
...targetBlock,
attributes: {
...targetBlock.attributes,
...updatedAttributes,
},
},
...( isForward ? [] : blocksWithTheSameType ),
];
registry.batch( () => {
dispatch.selectionChange(
targetBlock.clientId,
newAttributeKey,
newOffset,
newOffset
);
dispatch.replaceBlocks(
selectedBlockClientIds,
replacement,
0, // If we don't pass the `indexToSelect` it will default to the last block.
select.getSelectedBlocksInitialCaretPosition()
);
} );
};
/**
* Split the current selection.
* @param {?Array} blocks
*/
export const __unstableSplitSelection =
( blocks = [] ) =>
( { registry, select, dispatch } ) => {
const selectionAnchor = select.getSelectionStart();
const selectionFocus = select.getSelectionEnd();
const anchorRootClientId = select.getBlockRootClientId(
selectionAnchor.clientId
);
const focusRootClientId = select.getBlockRootClientId(
selectionFocus.clientId
);
// It's not splittable if the selection doesn't start and end in the same
// block list. Maybe in the future it should be allowed.
if ( anchorRootClientId !== focusRootClientId ) {
return;
}
const blockOrder = select.getBlockOrder( anchorRootClientId );
const anchorIndex = blockOrder.indexOf( selectionAnchor.clientId );
const focusIndex = blockOrder.indexOf( selectionFocus.clientId );
// Reassign selection start and end based on order.
let selectionStart, selectionEnd;
if ( anchorIndex > focusIndex ) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const selectionA = selectionStart;
const selectionB = selectionEnd;
const blockA = select.getBlock( selectionA.clientId );
const blockB = select.getBlock( selectionB.clientId );
const blockAType = getBlockType( blockA.name );
const blockBType = getBlockType( blockB.name );
const attributeKeyA =
typeof selectionA.attributeKey === 'string'
? selectionA.attributeKey
: findRichTextAttributeKey( blockAType );
const attributeKeyB =
typeof selectionB.attributeKey === 'string'
? selectionB.attributeKey
: findRichTextAttributeKey( blockBType );
const blockAttributes = select.getBlockAttributes(
selectionA.clientId
);
const bindings = blockAttributes?.metadata?.bindings;
// If the attribute is bound, don't split the selection and insert a new block instead.
if ( bindings?.[ attributeKeyA ] ) {
// Show warning if user tries to insert a block into another block with bindings.
if ( blocks.length ) {
const { createWarningNotice } =
registry.dispatch( noticesStore );
createWarningNotice(
__(
"Blocks can't be inserted into other blocks with bindings"
),
{
type: 'snackbar',
}
);
return;
}
dispatch.insertAfterBlock( selectionA.clientId );
return;
}
// Can't split if the selection is not set.
if (
! attributeKeyA ||
! attributeKeyB ||
typeof selectionAnchor.offset === 'undefined' ||
typeof selectionFocus.offset === 'undefined'
) {
return;
}
// We can do some short-circuiting if the selection is collapsed.
if (
selectionA.clientId === selectionB.clientId &&
attributeKeyA === attributeKeyB &&
selectionA.offset === selectionB.offset
) {
// If an unmodified default block is selected, replace it. We don't
// want to be converting into a default block.
if ( blocks.length ) {
if ( isUnmodifiedDefaultBlock( blockA ) ) {
dispatch.replaceBlocks(
[ selectionA.clientId ],
blocks,
blocks.length - 1,
-1
);
return;
}
}
// If selection is at the start or end, we can simply insert an
// empty block, provided this block has no inner blocks.
else if ( ! select.getBlockOrder( selectionA.clientId ).length ) {
function createEmpty() {
const defaultBlockName = getDefaultBlockName();
return select.canInsertBlockType(
defaultBlockName,
anchorRootClientId
)
? createBlock( defaultBlockName )
: createBlock(
select.getBlockName( selectionA.clientId )
);
}
const length = blockAttributes[ attributeKeyA ].length;
if ( selectionA.offset === 0 && length ) {
dispatch.insertBlocks(
[ createEmpty() ],
select.getBlockIndex( selectionA.clientId ),
anchorRootClientId,
false
);
return;
}
if ( selectionA.offset === length ) {
dispatch.insertBlocks(
[ createEmpty() ],
select.getBlockIndex( selectionA.clientId ) + 1,
anchorRootClientId
);
return;
}
}
}
const htmlA = blockA.attributes[ attributeKeyA ];
const htmlB = blockB.attributes[ attributeKeyB ];
let valueA = create( { html: htmlA } );
let valueB = create( { html: htmlB } );
valueA = remove( valueA, selectionA.offset, valueA.text.length );
valueB = remove( valueB, 0, selectionB.offset );
let head = {
// Preserve the original client ID.
...blockA,
// If both start and end are the same, should only copy innerBlocks
// once.
innerBlocks:
blockA.clientId === blockB.clientId ? [] : blockA.innerBlocks,
attributes: {
...blockA.attributes,
[ attributeKeyA ]: toHTMLString( { value: valueA } ),
},
};
let tail = {
...blockB,
// Only preserve the original client ID if the end is different.