-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
reducer.js
2824 lines (2574 loc) · 73.9 KB
/
reducer.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
/**
* External dependencies
*/
import fastDeepEqual from 'fast-deep-equal/es6';
/**
* WordPress dependencies
*/
import { pipe } from '@wordpress/compose';
import { combineReducers, select } from '@wordpress/data';
import deprecated from '@wordpress/deprecated';
import {
store as blocksStore,
privateApis as blocksPrivateApis,
} from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { PREFERENCES_DEFAULTS, SETTINGS_DEFAULTS } from './defaults';
import { insertAt, moveTo } from './array';
import { sectionRootClientIdKey } from './private-keys';
import { unlock } from '../lock-unlock';
const { isContentBlock } = unlock( blocksPrivateApis );
const identity = ( x ) => x;
/**
* Given an array of blocks, returns an object where each key is a nesting
* context, the value of which is an array of block client IDs existing within
* that nesting context.
*
* @param {Array} blocks Blocks to map.
* @param {?string} rootClientId Assumed root client ID.
*
* @return {Object} Block order map object.
*/
function mapBlockOrder( blocks, rootClientId = '' ) {
const result = new Map();
const current = [];
result.set( rootClientId, current );
blocks.forEach( ( block ) => {
const { clientId, innerBlocks } = block;
current.push( clientId );
mapBlockOrder( innerBlocks, clientId ).forEach(
( order, subClientId ) => {
result.set( subClientId, order );
}
);
} );
return result;
}
/**
* Given an array of blocks, returns an object where each key contains
* the clientId of the block and the value is the parent of the block.
*
* @param {Array} blocks Blocks to map.
* @param {?string} rootClientId Assumed root client ID.
*
* @return {Object} Block order map object.
*/
function mapBlockParents( blocks, rootClientId = '' ) {
const result = [];
const stack = [ [ rootClientId, blocks ] ];
while ( stack.length ) {
const [ parent, currentBlocks ] = stack.shift();
currentBlocks.forEach( ( { innerBlocks, ...block } ) => {
result.push( [ block.clientId, parent ] );
if ( innerBlocks?.length ) {
stack.push( [ block.clientId, innerBlocks ] );
}
} );
}
return result;
}
/**
* Helper method to iterate through all blocks, recursing into inner blocks,
* applying a transformation function to each one.
* Returns a flattened object with the transformed blocks.
*
* @param {Array} blocks Blocks to flatten.
* @param {Function} transform Transforming function to be applied to each block.
*
* @return {Array} Flattened object.
*/
function flattenBlocks( blocks, transform = identity ) {
const result = [];
const stack = [ ...blocks ];
while ( stack.length ) {
const { innerBlocks, ...block } = stack.shift();
stack.push( ...innerBlocks );
result.push( [ block.clientId, transform( block ) ] );
}
return result;
}
function getFlattenedClientIds( blocks ) {
const result = {};
const stack = [ ...blocks ];
while ( stack.length ) {
const { innerBlocks, ...block } = stack.shift();
stack.push( ...innerBlocks );
result[ block.clientId ] = true;
}
return result;
}
/**
* Given an array of blocks, returns an object containing all blocks, without
* attributes, recursing into inner blocks. Keys correspond to the block client
* ID, the value of which is the attributes object.
*
* @param {Array} blocks Blocks to flatten.
*
* @return {Array} Flattened block attributes object.
*/
function getFlattenedBlocksWithoutAttributes( blocks ) {
return flattenBlocks( blocks, ( block ) => {
const { attributes, ...restBlock } = block;
return restBlock;
} );
}
/**
* Given an array of blocks, returns an object containing all block attributes,
* recursing into inner blocks. Keys correspond to the block client ID, the
* value of which is the attributes object.
*
* @param {Array} blocks Blocks to flatten.
*
* @return {Array} Flattened block attributes object.
*/
function getFlattenedBlockAttributes( blocks ) {
return flattenBlocks( blocks, ( block ) => block.attributes );
}
/**
* Returns true if the two object arguments have the same keys, or false
* otherwise.
*
* @param {Object} a First object.
* @param {Object} b Second object.
*
* @return {boolean} Whether the two objects have the same keys.
*/
export function hasSameKeys( a, b ) {
return fastDeepEqual( Object.keys( a ), Object.keys( b ) );
}
/**
* Returns true if, given the currently dispatching action and the previously
* dispatched action, the two actions are updating the same block attribute, or
* false otherwise.
*
* @param {Object} action Currently dispatching action.
* @param {Object} lastAction Previously dispatched action.
*
* @return {boolean} Whether actions are updating the same block attribute.
*/
export function isUpdatingSameBlockAttribute( action, lastAction ) {
return (
action.type === 'UPDATE_BLOCK_ATTRIBUTES' &&
lastAction !== undefined &&
lastAction.type === 'UPDATE_BLOCK_ATTRIBUTES' &&
fastDeepEqual( action.clientIds, lastAction.clientIds ) &&
hasSameKeys( action.attributes, lastAction.attributes )
);
}
function updateBlockTreeForBlocks( state, blocks ) {
const treeToUpdate = state.tree;
const stack = [ ...blocks ];
const flattenedBlocks = [ ...blocks ];
while ( stack.length ) {
const block = stack.shift();
stack.push( ...block.innerBlocks );
flattenedBlocks.push( ...block.innerBlocks );
}
// Create objects before mutating them, that way it's always defined.
for ( const block of flattenedBlocks ) {
treeToUpdate.set( block.clientId, {} );
}
for ( const block of flattenedBlocks ) {
treeToUpdate.set(
block.clientId,
Object.assign( treeToUpdate.get( block.clientId ), {
...state.byClientId.get( block.clientId ),
attributes: state.attributes.get( block.clientId ),
innerBlocks: block.innerBlocks.map( ( subBlock ) =>
treeToUpdate.get( subBlock.clientId )
),
} )
);
}
}
function updateParentInnerBlocksInTree(
state,
updatedClientIds,
updateChildrenOfUpdatedClientIds = false
) {
const treeToUpdate = state.tree;
const uncontrolledParents = new Set( [] );
const controlledParents = new Set();
for ( const clientId of updatedClientIds ) {
let current = updateChildrenOfUpdatedClientIds
? clientId
: state.parents.get( clientId );
do {
if ( state.controlledInnerBlocks[ current ] ) {
// Should stop on controlled blocks.
// If we reach a controlled parent, break out of the loop.
controlledParents.add( current );
break;
} else {
// Else continue traversing up through parents.
uncontrolledParents.add( current );
current = state.parents.get( current );
}
} while ( current !== undefined );
}
// To make sure the order of assignments doesn't matter,
// we first create empty objects and mutates the inner blocks later.
for ( const clientId of uncontrolledParents ) {
treeToUpdate.set( clientId, { ...treeToUpdate.get( clientId ) } );
}
for ( const clientId of uncontrolledParents ) {
treeToUpdate.get( clientId ).innerBlocks = (
state.order.get( clientId ) || []
).map( ( subClientId ) => treeToUpdate.get( subClientId ) );
}
// Controlled parent blocks, need a dedicated key for their inner blocks
// to be used when doing getBlocks( controlledBlockClientId ).
for ( const clientId of controlledParents ) {
treeToUpdate.set( 'controlled||' + clientId, {
innerBlocks: ( state.order.get( clientId ) || [] ).map(
( subClientId ) => treeToUpdate.get( subClientId )
),
} );
}
}
/**
* Higher-order reducer intended to compute full block objects key for each block in the post.
* This is a denormalization to optimize the performance of the getBlock selectors and avoid
* recomputing the block objects and avoid heavy memoization.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withBlockTree =
( reducer ) =>
( state = {}, action ) => {
const newState = reducer( state, action );
if ( newState === state ) {
return state;
}
newState.tree = state.tree ? state.tree : new Map();
switch ( action.type ) {
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS': {
newState.tree = new Map( newState.tree );
updateBlockTreeForBlocks( newState, action.blocks );
updateParentInnerBlocksInTree(
newState,
action.rootClientId ? [ action.rootClientId ] : [ '' ],
true
);
break;
}
case 'UPDATE_BLOCK':
newState.tree = new Map( newState.tree );
newState.tree.set( action.clientId, {
...newState.tree.get( action.clientId ),
...newState.byClientId.get( action.clientId ),
attributes: newState.attributes.get( action.clientId ),
} );
updateParentInnerBlocksInTree(
newState,
[ action.clientId ],
false
);
break;
case 'SYNC_DERIVED_BLOCK_ATTRIBUTES':
case 'UPDATE_BLOCK_ATTRIBUTES': {
newState.tree = new Map( newState.tree );
action.clientIds.forEach( ( clientId ) => {
newState.tree.set( clientId, {
...newState.tree.get( clientId ),
attributes: newState.attributes.get( clientId ),
} );
} );
updateParentInnerBlocksInTree(
newState,
action.clientIds,
false
);
break;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': {
const inserterClientIds = getFlattenedClientIds(
action.blocks
);
newState.tree = new Map( newState.tree );
action.replacedClientIds.forEach( ( clientId ) => {
newState.tree.delete( clientId );
// Controlled inner blocks are only removed
// if the block doesn't move to another position
// otherwise their content will be lost.
if ( ! inserterClientIds[ clientId ] ) {
newState.tree.delete( 'controlled||' + clientId );
}
} );
updateBlockTreeForBlocks( newState, action.blocks );
updateParentInnerBlocksInTree(
newState,
action.blocks.map( ( b ) => b.clientId ),
false
);
// If there are no replaced blocks, it means we're removing blocks so we need to update their parent.
const parentsOfRemovedBlocks = [];
for ( const clientId of action.clientIds ) {
const parentId = state.parents.get( clientId );
if (
parentId !== undefined &&
( parentId === '' ||
newState.byClientId.get( parentId ) )
) {
parentsOfRemovedBlocks.push( parentId );
}
}
updateParentInnerBlocksInTree(
newState,
parentsOfRemovedBlocks,
true
);
break;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
const parentsOfRemovedBlocks = [];
for ( const clientId of action.clientIds ) {
const parentId = state.parents.get( clientId );
if (
parentId !== undefined &&
( parentId === '' ||
newState.byClientId.get( parentId ) )
) {
parentsOfRemovedBlocks.push( parentId );
}
}
newState.tree = new Map( newState.tree );
action.removedClientIds.forEach( ( clientId ) => {
newState.tree.delete( clientId );
newState.tree.delete( 'controlled||' + clientId );
} );
updateParentInnerBlocksInTree(
newState,
parentsOfRemovedBlocks,
true
);
break;
case 'MOVE_BLOCKS_TO_POSITION': {
const updatedBlockUids = [];
if ( action.fromRootClientId ) {
updatedBlockUids.push( action.fromRootClientId );
} else {
updatedBlockUids.push( '' );
}
if ( action.toRootClientId ) {
updatedBlockUids.push( action.toRootClientId );
}
newState.tree = new Map( newState.tree );
updateParentInnerBlocksInTree(
newState,
updatedBlockUids,
true
);
break;
}
case 'MOVE_BLOCKS_UP':
case 'MOVE_BLOCKS_DOWN': {
const updatedBlockUids = [
action.rootClientId ? action.rootClientId : '',
];
newState.tree = new Map( newState.tree );
updateParentInnerBlocksInTree(
newState,
updatedBlockUids,
true
);
break;
}
case 'SAVE_REUSABLE_BLOCK_SUCCESS': {
const updatedBlockUids = [];
newState.attributes.forEach( ( attributes, clientId ) => {
if (
newState.byClientId.get( clientId ).name ===
'core/block' &&
attributes.ref === action.updatedId
) {
updatedBlockUids.push( clientId );
}
} );
newState.tree = new Map( newState.tree );
updatedBlockUids.forEach( ( clientId ) => {
newState.tree.set( clientId, {
...newState.byClientId.get( clientId ),
attributes: newState.attributes.get( clientId ),
innerBlocks: newState.tree.get( clientId ).innerBlocks,
} );
} );
updateParentInnerBlocksInTree(
newState,
updatedBlockUids,
false
);
}
}
return newState;
};
/**
* Higher-order reducer intended to augment the blocks reducer, assigning an
* `isPersistentChange` property value corresponding to whether a change in
* state can be considered as persistent. All changes are considered persistent
* except when updating the same block attribute as in the previous action.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
function withPersistentBlockChange( reducer ) {
let lastAction;
let markNextChangeAsNotPersistent = false;
let explicitPersistent;
return ( state, action ) => {
let nextState = reducer( state, action );
let nextIsPersistentChange;
if ( action.type === 'SET_EXPLICIT_PERSISTENT' ) {
explicitPersistent = action.isPersistentChange;
nextIsPersistentChange = state.isPersistentChange ?? true;
}
if ( explicitPersistent !== undefined ) {
nextIsPersistentChange = explicitPersistent;
return nextIsPersistentChange === nextState.isPersistentChange
? nextState
: {
...nextState,
isPersistentChange: nextIsPersistentChange,
};
}
const isExplicitPersistentChange =
action.type === 'MARK_LAST_CHANGE_AS_PERSISTENT' ||
markNextChangeAsNotPersistent;
// Defer to previous state value (or default) unless changing or
// explicitly marking as persistent.
if ( state === nextState && ! isExplicitPersistentChange ) {
markNextChangeAsNotPersistent =
action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT';
nextIsPersistentChange = state?.isPersistentChange ?? true;
if ( state.isPersistentChange === nextIsPersistentChange ) {
return state;
}
return {
...nextState,
isPersistentChange: nextIsPersistentChange,
};
}
nextState = {
...nextState,
isPersistentChange: isExplicitPersistentChange
? ! markNextChangeAsNotPersistent
: ! isUpdatingSameBlockAttribute( action, lastAction ),
};
// In comparing against the previous action, consider only those which
// would have qualified as one which would have been ignored or not
// have resulted in a changed state.
lastAction = action;
markNextChangeAsNotPersistent =
action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT';
return nextState;
};
}
/**
* Higher-order reducer intended to augment the blocks reducer, assigning an
* `isIgnoredChange` property value corresponding to whether a change in state
* can be considered as ignored. A change is considered ignored when the result
* of an action not incurred by direct user interaction.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
function withIgnoredBlockChange( reducer ) {
/**
* Set of action types for which a blocks state change should be ignored.
*
* @type {Set}
*/
const IGNORED_ACTION_TYPES = new Set( [ 'RECEIVE_BLOCKS' ] );
return ( state, action ) => {
const nextState = reducer( state, action );
if ( nextState !== state ) {
nextState.isIgnoredChange = IGNORED_ACTION_TYPES.has( action.type );
}
return nextState;
};
}
/**
* Higher-order reducer targeting the combined blocks reducer, augmenting
* block client IDs in remove action to include cascade of inner blocks.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withInnerBlocksRemoveCascade = ( reducer ) => ( state, action ) => {
// Gets all children which need to be removed.
const getAllChildren = ( clientIds ) => {
let result = clientIds;
for ( let i = 0; i < result.length; i++ ) {
if (
! state.order.get( result[ i ] ) ||
( action.keepControlledInnerBlocks &&
action.keepControlledInnerBlocks[ result[ i ] ] )
) {
continue;
}
if ( result === clientIds ) {
result = [ ...result ];
}
result.push( ...state.order.get( result[ i ] ) );
}
return result;
};
if ( state ) {
switch ( action.type ) {
case 'REMOVE_BLOCKS':
action = {
...action,
type: 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN',
removedClientIds: getAllChildren( action.clientIds ),
};
break;
case 'REPLACE_BLOCKS':
action = {
...action,
type: 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN',
replacedClientIds: getAllChildren( action.clientIds ),
};
break;
}
}
return reducer( state, action );
};
/**
* Higher-order reducer which targets the combined blocks reducer and handles
* the `RESET_BLOCKS` action. When dispatched, this action will replace all
* blocks that exist in the post, leaving blocks that exist only in state (e.g.
* reusable blocks and blocks controlled by inner blocks controllers) alone.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withBlockReset = ( reducer ) => ( state, action ) => {
if ( action.type === 'RESET_BLOCKS' ) {
const newState = {
...state,
byClientId: new Map(
getFlattenedBlocksWithoutAttributes( action.blocks )
),
attributes: new Map( getFlattenedBlockAttributes( action.blocks ) ),
order: mapBlockOrder( action.blocks ),
parents: new Map( mapBlockParents( action.blocks ) ),
controlledInnerBlocks: {},
};
newState.tree = new Map( state?.tree );
updateBlockTreeForBlocks( newState, action.blocks );
newState.tree.set( '', {
innerBlocks: action.blocks.map( ( subBlock ) =>
newState.tree.get( subBlock.clientId )
),
} );
return newState;
}
return reducer( state, action );
};
/**
* Higher-order reducer which targets the combined blocks reducer and handles
* the `REPLACE_INNER_BLOCKS` action. When dispatched, this action the state
* should become equivalent to the execution of a `REMOVE_BLOCKS` action
* containing all the child's of the root block followed by the execution of
* `INSERT_BLOCKS` with the new blocks.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withReplaceInnerBlocks = ( reducer ) => ( state, action ) => {
if ( action.type !== 'REPLACE_INNER_BLOCKS' ) {
return reducer( state, action );
}
// Finds every nested inner block controller. We must check the action blocks
// and not just the block parent state because some inner block controllers
// should be deleted if specified, whereas others should not be deleted. If
// a controlled should not be deleted, then we need to avoid deleting its
// inner blocks from the block state because its inner blocks will not be
// attached to the block in the action.
const nestedControllers = {};
if ( Object.keys( state.controlledInnerBlocks ).length ) {
const stack = [ ...action.blocks ];
while ( stack.length ) {
const { innerBlocks, ...block } = stack.shift();
stack.push( ...innerBlocks );
if ( !! state.controlledInnerBlocks[ block.clientId ] ) {
nestedControllers[ block.clientId ] = true;
}
}
}
// The `keepControlledInnerBlocks` prop will keep the inner blocks of the
// marked block in the block state so that they can be reattached to the
// marked block when we re-insert everything a few lines below.
let stateAfterBlocksRemoval = state;
if ( state.order.get( action.rootClientId ) ) {
stateAfterBlocksRemoval = reducer( stateAfterBlocksRemoval, {
type: 'REMOVE_BLOCKS',
keepControlledInnerBlocks: nestedControllers,
clientIds: state.order.get( action.rootClientId ),
} );
}
let stateAfterInsert = stateAfterBlocksRemoval;
if ( action.blocks.length ) {
stateAfterInsert = reducer( stateAfterInsert, {
...action,
type: 'INSERT_BLOCKS',
index: 0,
} );
// We need to re-attach the controlled inner blocks to the blocks tree and
// preserve their block order. Otherwise, an inner block controller's blocks
// will be deleted entirely from its entity.
const stateAfterInsertOrder = new Map( stateAfterInsert.order );
Object.keys( nestedControllers ).forEach( ( key ) => {
if ( state.order.get( key ) ) {
stateAfterInsertOrder.set( key, state.order.get( key ) );
}
} );
stateAfterInsert.order = stateAfterInsertOrder;
stateAfterInsert.tree = new Map( stateAfterInsert.tree );
Object.keys( nestedControllers ).forEach( ( _key ) => {
const key = `controlled||${ _key }`;
if ( state.tree.has( key ) ) {
stateAfterInsert.tree.set( key, state.tree.get( key ) );
}
} );
}
return stateAfterInsert;
};
/**
* Higher-order reducer which targets the combined blocks reducer and handles
* the `SAVE_REUSABLE_BLOCK_SUCCESS` action. This action can't be handled by
* regular reducers and needs a higher-order reducer since it needs access to
* both `byClientId` and `attributes` simultaneously.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withSaveReusableBlock = ( reducer ) => ( state, action ) => {
if ( state && action.type === 'SAVE_REUSABLE_BLOCK_SUCCESS' ) {
const { id, updatedId } = action;
// If a temporary reusable block is saved, we swap the temporary id with the final one.
if ( id === updatedId ) {
return state;
}
state = { ...state };
state.attributes = new Map( state.attributes );
state.attributes.forEach( ( attributes, clientId ) => {
const { name } = state.byClientId.get( clientId );
if ( name === 'core/block' && attributes.ref === id ) {
state.attributes.set( clientId, {
...attributes,
ref: updatedId,
} );
}
} );
}
return reducer( state, action );
};
/**
* Higher-order reducer which removes blocks from state when switching parent block controlled state.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withResetControlledBlocks = ( reducer ) => ( state, action ) => {
if ( action.type === 'SET_HAS_CONTROLLED_INNER_BLOCKS' ) {
// when switching a block from controlled to uncontrolled or inverse,
// we need to remove its content first.
const tempState = reducer( state, {
type: 'REPLACE_INNER_BLOCKS',
rootClientId: action.clientId,
blocks: [],
} );
return reducer( tempState, action );
}
return reducer( state, action );
};
/**
* Reducer returning the blocks state.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
export const blocks = pipe(
combineReducers,
withSaveReusableBlock, // Needs to be before withBlockCache.
withBlockTree, // Needs to be before withInnerBlocksRemoveCascade.
withInnerBlocksRemoveCascade,
withReplaceInnerBlocks, // Needs to be after withInnerBlocksRemoveCascade.
withBlockReset,
withPersistentBlockChange,
withIgnoredBlockChange,
withResetControlledBlocks
)( {
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
byClientId( state = new Map(), action ) {
switch ( action.type ) {
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS': {
const newState = new Map( state );
getFlattenedBlocksWithoutAttributes( action.blocks ).forEach(
( [ key, value ] ) => {
newState.set( key, value );
}
);
return newState;
}
case 'UPDATE_BLOCK': {
// Ignore updates if block isn't known.
if ( ! state.has( action.clientId ) ) {
return state;
}
// Do nothing if only attributes change.
const { attributes, ...changes } = action.updates;
if ( Object.values( changes ).length === 0 ) {
return state;
}
const newState = new Map( state );
newState.set( action.clientId, {
...state.get( action.clientId ),
...changes,
} );
return newState;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': {
if ( ! action.blocks ) {
return state;
}
const newState = new Map( state );
action.replacedClientIds.forEach( ( clientId ) => {
newState.delete( clientId );
} );
getFlattenedBlocksWithoutAttributes( action.blocks ).forEach(
( [ key, value ] ) => {
newState.set( key, value );
}
);
return newState;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN': {
const newState = new Map( state );
action.removedClientIds.forEach( ( clientId ) => {
newState.delete( clientId );
} );
return newState;
}
}
return state;
},
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
attributes( state = new Map(), action ) {
switch ( action.type ) {
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS': {
const newState = new Map( state );
getFlattenedBlockAttributes( action.blocks ).forEach(
( [ key, value ] ) => {
newState.set( key, value );
}
);
return newState;
}
case 'UPDATE_BLOCK': {
// Ignore updates if block isn't known or there are no attribute changes.
if (
! state.get( action.clientId ) ||
! action.updates.attributes
) {
return state;
}
const newState = new Map( state );
newState.set( action.clientId, {
...state.get( action.clientId ),
...action.updates.attributes,
} );
return newState;
}
case 'SYNC_DERIVED_BLOCK_ATTRIBUTES':
case 'UPDATE_BLOCK_ATTRIBUTES': {
// Avoid a state change if none of the block IDs are known.
if ( action.clientIds.every( ( id ) => ! state.get( id ) ) ) {
return state;
}
let hasChange = false;
const newState = new Map( state );
for ( const clientId of action.clientIds ) {
const updatedAttributeEntries = Object.entries(
action.uniqueByBlock
? action.attributes[ clientId ]
: action.attributes ?? {}
);
if ( updatedAttributeEntries.length === 0 ) {
continue;
}
let hasUpdatedAttributes = false;
const existingAttributes = state.get( clientId );
const newAttributes = {};
updatedAttributeEntries.forEach( ( [ key, value ] ) => {
if ( existingAttributes[ key ] !== value ) {
hasUpdatedAttributes = true;
newAttributes[ key ] = value;
}
} );
hasChange = hasChange || hasUpdatedAttributes;
if ( hasUpdatedAttributes ) {
newState.set( clientId, {
...existingAttributes,
...newAttributes,
} );
}
}
return hasChange ? newState : state;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': {
if ( ! action.blocks ) {
return state;
}
const newState = new Map( state );
action.replacedClientIds.forEach( ( clientId ) => {
newState.delete( clientId );
} );
getFlattenedBlockAttributes( action.blocks ).forEach(
( [ key, value ] ) => {
newState.set( key, value );
}
);
return newState;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN': {
const newState = new Map( state );
action.removedClientIds.forEach( ( clientId ) => {
newState.delete( clientId );
} );
return newState;
}
}
return state;
},
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
order( state = new Map(), action ) {
switch ( action.type ) {
case 'RECEIVE_BLOCKS': {
const blockOrder = mapBlockOrder( action.blocks );
const newState = new Map( state );
blockOrder.forEach( ( order, clientId ) => {
if ( clientId !== '' ) {
newState.set( clientId, order );
}
} );
newState.set(
'',
( state.get( '' ) ?? [] ).concat( blockOrder[ '' ] )
);
return newState;
}
case 'INSERT_BLOCKS': {
const { rootClientId = '' } = action;
const subState = state.get( rootClientId ) || [];
const mappedBlocks = mapBlockOrder(
action.blocks,
rootClientId
);
const { index = subState.length } = action;
const newState = new Map( state );
mappedBlocks.forEach( ( order, clientId ) => {
newState.set( clientId, order );
} );
newState.set(
rootClientId,
insertAt(
subState,
mappedBlocks.get( rootClientId ),
index
)
);
return newState;
}
case 'MOVE_BLOCKS_TO_POSITION': {
const {
fromRootClientId = '',
toRootClientId = '',
clientIds,
} = action;
const { index = state.get( toRootClientId ).length } = action;
// Moving inside the same parent block.
if ( fromRootClientId === toRootClientId ) {
const subState = state.get( toRootClientId );
const fromIndex = subState.indexOf( clientIds[ 0 ] );
const newState = new Map( state );
newState.set(
toRootClientId,
moveTo(
state.get( toRootClientId ),