-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
reducer.js
1368 lines (1207 loc) · 34.6 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 {
flow,
reduce,
first,
last,
omit,
without,
mapValues,
keys,
isEqual,
isEmpty,
get,
identity,
difference,
omitBy,
} from 'lodash';
/**
* WordPress dependencies
*/
import { combineReducers } from '@wordpress/data';
import { isReusableBlock } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import {
PREFERENCES_DEFAULTS,
SETTINGS_DEFAULTS,
} from './defaults';
import { insertAt, moveTo } from './array';
/**
* 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 = { [ rootClientId ]: [] };
blocks.forEach( ( block ) => {
const { clientId, innerBlocks } = block;
result[ rootClientId ].push( clientId );
Object.assign( result, mapBlockOrder( innerBlocks, clientId ) );
} );
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 = '' ) {
return blocks.reduce( ( result, block ) => Object.assign(
result,
{ [ block.clientId ]: rootClientId },
mapBlockParents( block.innerBlocks, block.clientId )
), {} );
}
/**
* 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 {Object} Flattened object.
*/
function flattenBlocks( blocks, transform = identity ) {
const result = {};
const stack = [ ...blocks ];
while ( stack.length ) {
const { innerBlocks, ...block } = stack.shift();
stack.push( ...innerBlocks );
result[ block.clientId ] = transform( block );
}
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 {Object} Flattened block attributes object.
*/
function getFlattenedBlocksWithoutAttributes( blocks ) {
return flattenBlocks( blocks, ( block ) => omit( block, 'attributes' ) );
}
/**
* 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 {Object} Flattened block attributes object.
*/
function getFlattenedBlockAttributes( blocks ) {
return flattenBlocks( blocks, ( block ) => block.attributes );
}
/**
* Given a block order map object, returns *all* of the block client IDs that are
* a descendant of the given root client ID.
*
* Calling this with `rootClientId` set to `''` results in a list of client IDs
* that are in the post. That is, it excludes blocks like fetched reusable
* blocks which are stored into state but not visible.
*
* @param {Object} blocksOrder Object that maps block client IDs to a list of
* nested block client IDs.
* @param {?string} rootClientId The root client ID to search. Defaults to ''.
*
* @return {Array} List of descendant client IDs.
*/
function getNestedBlockClientIds( blocksOrder, rootClientId = '' ) {
return reduce( blocksOrder[ rootClientId ], ( result, clientId ) => [
...result,
clientId,
...getNestedBlockClientIds( blocksOrder, clientId ),
], [] );
}
/**
* Returns an object against which it is safe to perform mutating operations,
* given the original object and its current working copy.
*
* @param {Object} original Original object.
* @param {Object} working Working object.
*
* @return {Object} Mutation-safe object.
*/
function getMutateSafeObject( original, working ) {
if ( original === working ) {
return { ...original };
}
return working;
}
/**
* 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 isEqual( keys( a ), 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' &&
action.clientId === lastAction.clientId &&
hasSameKeys( action.attributes, lastAction.attributes )
);
}
/**
* Utility returning an object with an empty object value for each key.
*
* @param {Array} objectKeys Keys to fill.
* @return {Object} Object filled with empty object as values for each clientId.
*/
const fillKeysWithEmptyObject = ( objectKeys ) => {
return objectKeys.reduce( ( result, key ) => {
result[ key ] = {};
return result;
}, {} );
};
/**
* Higher-order reducer intended to compute a cache key for each block in the post.
* A new instance of the cache key (empty object) is created each time the block object
* needs to be refreshed (for any change in the block or its children).
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withBlockCache = ( reducer ) => ( state = {}, action ) => {
const newState = reducer( state, action );
if ( newState === state ) {
return state;
}
newState.cache = state.cache ? state.cache : {};
/**
* For each clientId provided, traverses up parents, adding the provided clientIds
* and each parent's clientId to the returned array.
*
* When calling this function consider that it uses the old state, so any state
* modifications made by the `reducer` will not be present.
*
* @param {Array} clientIds an Array of block clientIds.
*
* @return {Array} The provided clientIds and all of their parent clientIds.
*/
const getBlocksWithParentsClientIds = ( clientIds ) => {
return clientIds.reduce( ( result, clientId ) => {
let current = clientId;
do {
result.push( current );
current = state.parents[ current ];
} while ( current );
return result;
}, [] );
};
switch ( action.type ) {
case 'RESET_BLOCKS':
newState.cache = mapValues( flattenBlocks( action.blocks ), () => ( {} ) );
break;
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS': {
const updatedBlockUids = keys( flattenBlocks( action.blocks ) );
if ( action.rootClientId ) {
updatedBlockUids.push( action.rootClientId );
}
newState.cache = {
...newState.cache,
...fillKeysWithEmptyObject(
getBlocksWithParentsClientIds( updatedBlockUids ),
),
};
break;
}
case 'UPDATE_BLOCK':
case 'UPDATE_BLOCK_ATTRIBUTES':
newState.cache = {
...newState.cache,
...fillKeysWithEmptyObject(
getBlocksWithParentsClientIds( [ action.clientId ] ),
),
};
break;
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
const parentClientIds = fillKeysWithEmptyObject( getBlocksWithParentsClientIds( action.replacedClientIds ) );
newState.cache = {
...omit( newState.cache, action.replacedClientIds ),
...omit( parentClientIds, action.replacedClientIds ),
...fillKeysWithEmptyObject( keys( flattenBlocks( action.blocks ) ) ),
};
break;
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
newState.cache = {
...omit( newState.cache, action.removedClientIds ),
...fillKeysWithEmptyObject(
difference( getBlocksWithParentsClientIds( action.clientIds ), action.clientIds ),
),
};
break;
case 'MOVE_BLOCK_TO_POSITION': {
const updatedBlockUids = [ action.clientId ];
if ( action.fromRootClientId ) {
updatedBlockUids.push( action.fromRootClientId );
}
if ( action.toRootClientId ) {
updatedBlockUids.push( action.toRootClientId );
}
newState.cache = {
...newState.cache,
...fillKeysWithEmptyObject(
getBlocksWithParentsClientIds( updatedBlockUids )
),
};
break;
}
case 'MOVE_BLOCKS_UP':
case 'MOVE_BLOCKS_DOWN': {
const updatedBlockUids = [];
if ( action.rootClientId ) {
updatedBlockUids.push( action.rootClientId );
}
newState.cache = {
...newState.cache,
...fillKeysWithEmptyObject(
getBlocksWithParentsClientIds( updatedBlockUids )
),
};
break;
}
case 'SAVE_REUSABLE_BLOCK_SUCCESS': {
const updatedBlockUids = keys( omitBy( newState.attributes, ( attributes, clientId ) => {
return newState.byClientId[ clientId ].name !== 'core/block' || attributes.ref !== action.updatedId;
} ) );
newState.cache = {
...newState.cache,
...fillKeysWithEmptyObject(
getBlocksWithParentsClientIds( updatedBlockUids )
),
};
}
}
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;
return ( state, action ) => {
let nextState = reducer( state, action );
const isExplicitPersistentChange = action.type === 'MARK_LAST_CHANGE_AS_PERSISTENT';
// Defer to previous state value (or default) unless changing or
// explicitly marking as persistent.
if ( state === nextState && ! isExplicitPersistentChange ) {
const nextIsPersistentChange = get( state, [ 'isPersistentChange' ], true );
if ( state.isPersistentChange === nextIsPersistentChange ) {
return state;
}
return {
...nextState,
isPersistentChange: nextIsPersistentChange,
};
}
nextState = {
...nextState,
isPersistentChange: (
isExplicitPersistentChange ||
! 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;
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 ) => {
const getAllChildren = ( clientIds ) => {
let result = clientIds;
for ( let i = 0; i < result.length; i++ ) {
if ( ! state.order[ result[ i ] ] ) {
continue;
}
if ( result === clientIds ) {
result = [ ...result ];
}
result.push( ...state.order[ 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) alone.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withBlockReset = ( reducer ) => ( state, action ) => {
if ( state && action.type === 'RESET_BLOCKS' ) {
const visibleClientIds = getNestedBlockClientIds( state.order );
return {
...state,
byClientId: {
...omit( state.byClientId, visibleClientIds ),
...getFlattenedBlocksWithoutAttributes( action.blocks ),
},
attributes: {
...omit( state.attributes, visibleClientIds ),
...getFlattenedBlockAttributes( action.blocks ),
},
order: {
...omit( state.order, visibleClientIds ),
...mapBlockOrder( action.blocks ),
},
parents: {
...omit( state.parents, visibleClientIds ),
...mapBlockParents( action.blocks ),
},
cache: {
...omit( state.cache, visibleClientIds ),
...mapValues( flattenBlocks( action.blocks ), () => ( {} ) ),
},
};
}
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 );
}
let stateAfterBlocksRemoval = state;
if ( state.order[ action.rootClientId ] ) {
stateAfterBlocksRemoval = reducer( stateAfterBlocksRemoval, {
type: 'REMOVE_BLOCKS',
clientIds: state.order[ action.rootClientId ],
} );
}
let stateAfterInsert = stateAfterBlocksRemoval;
if ( action.blocks.length ) {
stateAfterInsert = reducer( stateAfterInsert, {
...action,
type: 'INSERT_BLOCKS',
index: 0,
} );
}
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 = mapValues( state.attributes, ( attributes, clientId ) => {
const { name } = state.byClientId[ clientId ];
if ( name === 'core/block' && attributes.ref === id ) {
return {
...attributes,
ref: updatedId,
};
}
return attributes;
} );
}
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 = flow(
combineReducers,
withSaveReusableBlock, // needs to be before withBlockCache
withBlockCache, // needs to be before withInnerBlocksRemoveCascade
withInnerBlocksRemoveCascade,
withReplaceInnerBlocks, // needs to be after withInnerBlocksRemoveCascade
withBlockReset,
withPersistentBlockChange,
withIgnoredBlockChange,
)( {
byClientId( state = {}, action ) {
switch ( action.type ) {
case 'RESET_BLOCKS':
return getFlattenedBlocksWithoutAttributes( action.blocks );
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS':
return {
...state,
...getFlattenedBlocksWithoutAttributes( action.blocks ),
};
case 'UPDATE_BLOCK':
// Ignore updates if block isn't known
if ( ! state[ action.clientId ] ) {
return state;
}
// Do nothing if only attributes change.
const changes = omit( action.updates, 'attributes' );
if ( isEmpty( changes ) ) {
return state;
}
return {
...state,
[ action.clientId ]: {
...state[ action.clientId ],
...changes,
},
};
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
if ( ! action.blocks ) {
return state;
}
return {
...omit( state, action.replacedClientIds ),
...getFlattenedBlocksWithoutAttributes( action.blocks ),
};
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
return omit( state, action.removedClientIds );
}
return state;
},
attributes( state = {}, action ) {
switch ( action.type ) {
case 'RESET_BLOCKS':
return getFlattenedBlockAttributes( action.blocks );
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS':
return {
...state,
...getFlattenedBlockAttributes( action.blocks ),
};
case 'UPDATE_BLOCK':
// Ignore updates if block isn't known or there are no attribute changes.
if ( ! state[ action.clientId ] || ! action.updates.attributes ) {
return state;
}
return {
...state,
[ action.clientId ]: {
...state[ action.clientId ],
...action.updates.attributes,
},
};
case 'UPDATE_BLOCK_ATTRIBUTES':
// Ignore updates if block isn't known
if ( ! state[ action.clientId ] ) {
return state;
}
// Consider as updates only changed values
const nextAttributes = reduce( action.attributes, ( result, value, key ) => {
if ( value !== result[ key ] ) {
result = getMutateSafeObject( state[ action.clientId ], result );
result[ key ] = value;
}
return result;
}, state[ action.clientId ] );
// Skip update if nothing has been changed. The reference will
// match the original block if `reduce` had no changed values.
if ( nextAttributes === state[ action.clientId ] ) {
return state;
}
// Otherwise replace attributes in state
return {
...state,
[ action.clientId ]: nextAttributes,
};
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
if ( ! action.blocks ) {
return state;
}
return {
...omit( state, action.replacedClientIds ),
...getFlattenedBlockAttributes( action.blocks ),
};
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
return omit( state, action.removedClientIds );
}
return state;
},
order( state = {}, action ) {
switch ( action.type ) {
case 'RESET_BLOCKS':
return mapBlockOrder( action.blocks );
case 'RECEIVE_BLOCKS':
return {
...state,
...omit( mapBlockOrder( action.blocks ), '' ),
};
case 'INSERT_BLOCKS': {
const { rootClientId = '' } = action;
const subState = state[ rootClientId ] || [];
const mappedBlocks = mapBlockOrder( action.blocks, rootClientId );
const { index = subState.length } = action;
return {
...state,
...mappedBlocks,
[ rootClientId ]: insertAt( subState, mappedBlocks[ rootClientId ], index ),
};
}
case 'MOVE_BLOCK_TO_POSITION': {
const { fromRootClientId = '', toRootClientId = '', clientId } = action;
const { index = state[ toRootClientId ].length } = action;
// Moving inside the same parent block
if ( fromRootClientId === toRootClientId ) {
const subState = state[ toRootClientId ];
const fromIndex = subState.indexOf( clientId );
return {
...state,
[ toRootClientId ]: moveTo( state[ toRootClientId ], fromIndex, index ),
};
}
// Moving from a parent block to another
return {
...state,
[ fromRootClientId ]: without( state[ fromRootClientId ], clientId ),
[ toRootClientId ]: insertAt( state[ toRootClientId ], clientId, index ),
};
}
case 'MOVE_BLOCKS_UP': {
const { clientIds, rootClientId = '' } = action;
const firstClientId = first( clientIds );
const subState = state[ rootClientId ];
if ( ! subState.length || firstClientId === first( subState ) ) {
return state;
}
const firstIndex = subState.indexOf( firstClientId );
return {
...state,
[ rootClientId ]: moveTo( subState, firstIndex, firstIndex - 1, clientIds.length ),
};
}
case 'MOVE_BLOCKS_DOWN': {
const { clientIds, rootClientId = '' } = action;
const firstClientId = first( clientIds );
const lastClientId = last( clientIds );
const subState = state[ rootClientId ];
if ( ! subState.length || lastClientId === last( subState ) ) {
return state;
}
const firstIndex = subState.indexOf( firstClientId );
return {
...state,
[ rootClientId ]: moveTo( subState, firstIndex, firstIndex + 1, clientIds.length ),
};
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN': {
const { clientIds } = action;
if ( ! action.blocks ) {
return state;
}
const mappedBlocks = mapBlockOrder( action.blocks );
return flow( [
( nextState ) => omit( nextState, action.replacedClientIds ),
( nextState ) => ( {
...nextState,
...omit( mappedBlocks, '' ),
} ),
( nextState ) => mapValues( nextState, ( subState ) => (
reduce( subState, ( result, clientId ) => {
if ( clientId === clientIds[ 0 ] ) {
return [
...result,
...mappedBlocks[ '' ],
];
}
if ( clientIds.indexOf( clientId ) === -1 ) {
result.push( clientId );
}
return result;
}, [] )
) ),
] )( state );
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
return flow( [
// Remove inner block ordering for removed blocks
( nextState ) => omit( nextState, action.removedClientIds ),
// Remove deleted blocks from other blocks' orderings
( nextState ) => mapValues( nextState, ( subState ) => (
without( subState, ...action.removedClientIds )
) ),
] )( state );
}
return state;
},
// While technically redundant data as the inverse of `order`, it serves as
// an optimization for the selectors which derive the ancestry of a block.
parents( state = {}, action ) {
switch ( action.type ) {
case 'RESET_BLOCKS':
return mapBlockParents( action.blocks );
case 'RECEIVE_BLOCKS':
return {
...state,
...mapBlockParents( action.blocks ),
};
case 'INSERT_BLOCKS':
return {
...state,
...mapBlockParents( action.blocks, action.rootClientId || '' ),
};
case 'MOVE_BLOCK_TO_POSITION': {
return {
...state,
[ action.clientId ]: action.toRootClientId || '',
};
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
return {
...omit( state, action.replacedClientIds ),
...mapBlockParents( action.blocks, state[ action.clientIds[ 0 ] ] ),
};
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
return omit( state, action.removedClientIds );
}
return state;
},
} );
/**
* Reducer returning typing state.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
export function isTyping( state = false, action ) {
switch ( action.type ) {
case 'START_TYPING':
return true;
case 'STOP_TYPING':
return false;
}
return state;
}
/**
* Reducer returning dragging state.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
export function isDraggingBlocks( state = false, action ) {
switch ( action.type ) {
case 'START_DRAGGING_BLOCKS':
return true;
case 'STOP_DRAGGING_BLOCKS':
return false;
}
return state;
}
/**
* Reducer returning whether the caret is within formatted text.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
export function isCaretWithinFormattedText( state = false, action ) {
switch ( action.type ) {
case 'ENTER_FORMATTED_TEXT':
return true;
case 'EXIT_FORMATTED_TEXT':
return false;
}
return state;
}
/**
* Internal helper reducer for selectionStart and selectionEnd. Can hold a block
* selection, represented by an object with property clientId.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function selection( state = {}, action ) {
switch ( action.type ) {
case 'CLEAR_SELECTED_BLOCK': {
if ( state.clientId ) {
return {};
}
return state;
}
case 'SELECT_BLOCK':
if ( action.clientId === state.clientId ) {
return state;
}
return { clientId: action.clientId };
case 'REPLACE_INNER_BLOCKS': // REPLACE_INNER_BLOCKS and INSERT_BLOCKS should follow the same logic.
case 'INSERT_BLOCKS': {
if ( ! action.updateSelection ) {
return state;
}
return { clientId: action.blocks[ 0 ].clientId };
}
case 'REMOVE_BLOCKS':
if (
! action.clientIds ||
! action.clientIds.length ||
action.clientIds.indexOf( state.clientId ) === -1
) {
return state;
}
return {};
case 'REPLACE_BLOCKS': {
if ( action.clientIds.indexOf( state.clientId ) === -1 ) {
return state;
}
const indexToSelect = action.indexToSelect || action.blocks.length - 1;
const blockToSelect = action.blocks[ indexToSelect ];
if ( ! blockToSelect ) {
return {};
}
if ( blockToSelect.clientId === state.clientId ) {
return state;