-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
selectors.js
2025 lines (1824 loc) · 57.3 KB
/
selectors.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 {
castArray,
flatMap,
find,
first,
get,
has,
includes,
isArray,
isBoolean,
last,
map,
orderBy,
reduce,
size,
some,
} from 'lodash';
import createSelector from 'rememo';
/**
* WordPress dependencies
*/
import {
serialize,
getBlockType,
getBlockTypes,
hasBlockSupport,
hasChildBlocksWithInserterSupport,
getUnknownTypeHandlerName,
isUnmodifiedDefaultBlock,
} from '@wordpress/blocks';
import { moment } from '@wordpress/date';
import { removep } from '@wordpress/autop';
/**
* Dependencies
*/
import { PREFERENCES_DEFAULTS } from './defaults';
/***
* Module constants
*/
export const POST_UPDATE_TRANSACTION_ID = 'post-update';
const PERMALINK_POSTNAME_REGEX = /%(?:postname|pagename)%/;
export const INSERTER_UTILITY_HIGH = 3;
export const INSERTER_UTILITY_MEDIUM = 2;
export const INSERTER_UTILITY_LOW = 1;
export const INSERTER_UTILITY_NONE = 0;
const MILLISECONDS_PER_HOUR = 3600 * 1000;
const MILLISECONDS_PER_DAY = 24 * 3600 * 1000;
const MILLISECONDS_PER_WEEK = 7 * 24 * 3600 * 1000;
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation, as in a connected or
* other pure component which performs `shouldComponentUpdate` check on props.
* This should be used as a last resort, since the normalized data should be
* maintained by the reducer result in state.
*
* @type {Array}
*/
const EMPTY_ARRAY = [];
/**
* Returns true if any past editor history snapshots exist, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether undo history exists.
*/
export function hasEditorUndo( state ) {
return state.editor.past.length > 0;
}
/**
* Returns true if any future editor history snapshots exist, or false
* otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether redo history exists.
*/
export function hasEditorRedo( state ) {
return state.editor.future.length > 0;
}
/**
* Returns true if the currently edited post is yet to be saved, or false if
* the post has been saved.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post is new.
*/
export function isEditedPostNew( state ) {
return getCurrentPost( state ).status === 'auto-draft';
}
/**
* Returns true if there are unsaved values for the current edit session, or
* false if the editing state matches the saved or new post.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether unsaved values exist.
*/
export function isEditedPostDirty( state ) {
return state.editor.isDirty || inSomeHistory( state, isEditedPostDirty );
}
/**
* Returns true if there are no unsaved values for the current edit session and
* if the currently edited post is new (has never been saved before).
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether new post and unsaved values exist.
*/
export function isCleanNewPost( state ) {
return ! isEditedPostDirty( state ) && isEditedPostNew( state );
}
/**
* Returns the post currently being edited in its last known saved state, not
* including unsaved edits. Returns an object containing relevant default post
* values if the post has not yet been saved.
*
* @param {Object} state Global application state.
*
* @return {Object} Post object.
*/
export function getCurrentPost( state ) {
return state.currentPost;
}
/**
* Returns the post type of the post currently being edited.
*
* @param {Object} state Global application state.
*
* @return {string} Post type.
*/
export function getCurrentPostType( state ) {
return state.currentPost.type;
}
/**
* Returns the ID of the post currently being edited, or null if the post has
* not yet been saved.
*
* @param {Object} state Global application state.
*
* @return {?number} ID of current post.
*/
export function getCurrentPostId( state ) {
return getCurrentPost( state ).id || null;
}
/**
* Returns the number of revisions of the post currently being edited.
*
* @param {Object} state Global application state.
*
* @return {number} Number of revisions.
*/
export function getCurrentPostRevisionsCount( state ) {
return get( getCurrentPost( state ), [ '_links', 'version-history', 0, 'count' ], 0 );
}
/**
* Returns the last revision ID of the post currently being edited,
* or null if the post has no revisions.
*
* @param {Object} state Global application state.
*
* @return {?number} ID of the last revision.
*/
export function getCurrentPostLastRevisionId( state ) {
return get( getCurrentPost( state ), [ '_links', 'predecessor-version', 0, 'id' ], null );
}
/**
* Returns any post values which have been changed in the editor but not yet
* been saved.
*
* @param {Object} state Global application state.
*
* @return {Object} Object of key value pairs comprising unsaved edits.
*/
export function getPostEdits( state ) {
return state.editor.present.edits;
}
/**
* Returns an attribute value of the saved post.
*
* @param {Object} state Global application state.
* @param {string} attributeName Post attribute name.
*
* @return {*} Post attribute value.
*/
export function getCurrentPostAttribute( state, attributeName ) {
const post = getCurrentPost( state );
if ( post.hasOwnProperty( attributeName ) ) {
return post[ attributeName ];
}
}
/**
* Returns a single attribute of the post being edited, preferring the unsaved
* edit if one exists, but falling back to the attribute for the last known
* saved state of the post.
*
* @param {Object} state Global application state.
* @param {string} attributeName Post attribute name.
*
* @return {*} Post attribute value.
*/
export function getEditedPostAttribute( state, attributeName ) {
const edits = getPostEdits( state );
// Special cases
switch ( attributeName ) {
case 'content':
return getEditedPostContent( state );
}
if ( ! edits.hasOwnProperty( attributeName ) ) {
return getCurrentPostAttribute( state, attributeName );
}
return edits[ attributeName ];
}
/**
* Returns an attribute value of the current autosave revision for a post, or
* null if there is no autosave for the post.
*
* @param {Object} state Global application state.
* @param {string} attributeName Autosave attribute name.
*
* @return {*} Autosave attribute value.
*/
export function getAutosaveAttribute( state, attributeName ) {
if ( ! hasAutosave( state ) ) {
return null;
}
const autosave = getAutosave( state );
if ( autosave.hasOwnProperty( attributeName ) ) {
return autosave[ attributeName ];
}
}
/**
* Returns the current visibility of the post being edited, preferring the
* unsaved value if different than the saved post. The return value is one of
* "private", "password", or "public".
*
* @param {Object} state Global application state.
*
* @return {string} Post visibility.
*/
export function getEditedPostVisibility( state ) {
const status = getEditedPostAttribute( state, 'status' );
const password = getEditedPostAttribute( state, 'password' );
if ( status === 'private' ) {
return 'private';
} else if ( password ) {
return 'password';
}
return 'public';
}
/**
* Returns true if post is pending review.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether current post is pending review.
*/
export function isCurrentPostPending( state ) {
return getCurrentPost( state ).status === 'pending';
}
/**
* Return true if the current post has already been published.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post has been published.
*/
export function isCurrentPostPublished( state ) {
const post = getCurrentPost( state );
return [ 'publish', 'private' ].indexOf( post.status ) !== -1 ||
( post.status === 'future' && moment( post.date ).isBefore( moment() ) );
}
/**
* Returns true if post is already scheduled.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether current post is scheduled to be posted.
*/
export function isCurrentPostScheduled( state ) {
return getCurrentPost( state ).status === 'future' && ! isCurrentPostPublished( state );
}
/**
* Return true if the post being edited can be published.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post can been published.
*/
export function isEditedPostPublishable( state ) {
const post = getCurrentPost( state );
// TODO: Post being publishable should be superset of condition of post
// being saveable. Currently this restriction is imposed at UI.
//
// See: <PostPublishButton /> (`isButtonEnabled` assigned by `isSaveable`)
return isEditedPostDirty( state ) || [ 'publish', 'private', 'future' ].indexOf( post.status ) === -1;
}
/**
* Returns true if the post can be saved, or false otherwise. A post must
* contain a title, an excerpt, or non-empty content to be valid for save.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post can be saved.
*/
export function isEditedPostSaveable( state ) {
if ( isSavingPost( state ) ) {
return false;
}
// TODO: Post should not be saveable if not dirty. Cannot be added here at
// this time since posts where meta boxes are present can be saved even if
// the post is not dirty. Currently this restriction is imposed at UI, but
// should be moved here.
//
// See: `isEditedPostPublishable` (includes `isEditedPostDirty` condition)
// See: <PostSavedState /> (`forceIsDirty` prop)
// See: <PostPublishButton /> (`forceIsDirty` prop)
// See: https://github.com/WordPress/gutenberg/pull/4184
return (
!! getEditedPostAttribute( state, 'title' ) ||
!! getEditedPostAttribute( state, 'excerpt' ) ||
! isEditedPostEmpty( state )
);
}
/**
* Returns true if the edited post has content. A post has content if it has at
* least one saveable block or otherwise has a non-empty content property
* assigned.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether post has content.
*/
export function isEditedPostEmpty( state ) {
// While the condition of truthy content string would be sufficient for
// determining emptiness, testing saveable blocks length is a trivial
// operation by comparison. Since this function can be called frequently,
// optimize for the fast case where saveable blocks are non-empty.
return (
! getBlocksForSerialization( state ).length &&
! getEditedPostAttribute( state, 'content' )
);
}
/**
* Returns true if the post can be autosaved, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post can be autosaved.
*/
export function isEditedPostAutosaveable( state ) {
// A post must contain a title, an excerpt, or non-empty content to be valid for autosaving.
if ( ! isEditedPostSaveable( state ) ) {
return false;
}
// If we don't already have an autosave, the post is autosaveable.
if ( ! hasAutosave( state ) ) {
return true;
}
// If the title, excerpt or content has changed, the post is autosaveable.
const autosave = getAutosave( state );
return [ 'title', 'excerpt', 'content' ].some( ( field ) => (
autosave[ field ] !== getEditedPostAttribute( state, field )
) );
}
/**
* Returns the current autosave, or null if one is not set (i.e. if the post
* has yet to be autosaved, or has been saved or published since the last
* autosave).
*
* @param {Object} state Editor state.
*
* @return {?Object} Current autosave, if exists.
*/
export function getAutosave( state ) {
return state.autosave;
}
/**
* Returns the true if there is an existing autosave, otherwise false.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether there is an existing autosave.
*/
export function hasAutosave( state ) {
return !! getAutosave( state );
}
/**
* Return true if the post being edited is being scheduled. Preferring the
* unsaved status values.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post has been published.
*/
export function isEditedPostBeingScheduled( state ) {
const date = moment( getEditedPostAttribute( state, 'date' ) );
// Adding 1 minute as an error threshold between the server and the client dates.
const now = moment().add( 1, 'minute' );
return date.isAfter( now );
}
/**
* Returns whether the current post should be considered to have a "floating"
* date (i.e. that it would publish "Immediately" rather than at a set time).
*
* Unlike in the PHP backend, the REST API returns a full date string for posts
* where the 0000-00-00T00:00:00 placeholder is present in the database. To
* infer that a post is set to publish "Immediately" we check whether the date
* and modified date are the same.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether the edited post has a floating date value.
*/
export function isEditedPostDateFloating( state ) {
const date = getEditedPostAttribute( state, 'date' );
const modified = getEditedPostAttribute( state, 'modified' );
const status = getEditedPostAttribute( state, 'status' );
if ( status === 'draft' || status === 'auto-draft' ) {
return date === modified;
}
return false;
}
/**
* Returns a new reference when the inner blocks of a given block client ID
* change. This is used exclusively as a memoized selector dependant, relying
* on this selector's shared return value and recursively those of its inner
* blocks defined as dependencies. This abuses mechanics of the selector
* memoization to return from the original selector function only when
* dependants change.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {*} A value whose reference will change only when inner blocks of
* the given block client ID change.
*/
export const getBlockDependantsCacheBust = createSelector(
() => [],
( state, clientId ) => map(
getBlockOrder( state, clientId ),
( innerBlockClientId ) => getBlock( state, innerBlockClientId ),
),
);
/**
* Returns a block's name given its client ID, or null if no block exists with
* the client ID.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {string} Block name.
*/
export function getBlockName( state, clientId ) {
const block = state.editor.present.blocksByClientId[ clientId ];
return block ? block.name : null;
}
/**
* Returns a block given its client ID. This is a parsed copy of the block,
* containing its `blockName`, `clientId`, and current `attributes` state. This
* is not the block's registration settings, which must be retrieved from the
* blocks module registration store.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {Object} Parsed block object.
*/
export const getBlock = createSelector(
( state, clientId ) => {
const block = state.editor.present.blocksByClientId[ clientId ];
if ( ! block ) {
return null;
}
let { attributes } = block;
// Inject custom source attribute values.
//
// TODO: Create generic external sourcing pattern, not explicitly
// targeting meta attributes.
const type = getBlockType( block.name );
if ( type ) {
attributes = reduce( type.attributes, ( result, value, key ) => {
if ( value.source === 'meta' ) {
if ( result === attributes ) {
result = { ...result };
}
result[ key ] = getPostMeta( state, value.meta );
}
return result;
}, attributes );
}
return {
...block,
attributes,
innerBlocks: getBlocks( state, clientId ),
};
},
( state, clientId ) => [
state.editor.present.blocksByClientId[ clientId ],
getBlockDependantsCacheBust( state, clientId ),
state.editor.present.edits.meta,
state.currentPost.meta,
]
);
function getPostMeta( state, key ) {
return has( state, [ 'editor', 'present', 'edits', 'meta', key ] ) ?
get( state, [ 'editor', 'present', 'edits', 'meta', key ] ) :
get( state, [ 'currentPost', 'meta', key ] );
}
/**
* Returns all block objects for the current post being edited as an array in
* the order they appear in the post.
*
* Note: It's important to memoize this selector to avoid return a new instance
* on each call
*
* @param {Object} state Editor state.
* @param {?String} rootClientId Optional root client ID of block list.
*
* @return {Object[]} Post blocks.
*/
export const getBlocks = createSelector(
( state, rootClientId ) => {
return map(
getBlockOrder( state, rootClientId ),
( clientId ) => getBlock( state, clientId )
);
},
( state ) => [
state.editor.present.blockOrder,
state.editor.present.blocksByClientId,
]
);
/**
* Returns an array containing the clientIds of all descendants
* of the blocks given.
*
* @param {Object} state Global application state.
* @param {Array} clientIds Array of blocks to inspect.
*
* @return {Array} ids of descendants.
*/
export const getClientIdsOfDescendants = ( state, clientIds ) => flatMap( clientIds, ( clientId ) => {
const descendants = getBlockOrder( state, clientId );
return [ ...descendants, ...getClientIdsOfDescendants( state, descendants ) ];
} );
/**
* Returns an array containing the clientIds of the top-level blocks
* and their descendants of any depth (for nested blocks).
*
* @param {Object} state Global application state.
*
* @return {Array} ids of top-level and descendant blocks.
*/
export const getClientIdsWithDescendants = createSelector(
( state ) => {
const topLevelIds = getBlockOrder( state );
return [ ...topLevelIds, ...getClientIdsOfDescendants( state, topLevelIds ) ];
},
( state ) => [
state.editor.present.blockOrder,
]
);
/**
* Returns the total number of blocks, or the total number of blocks with a specific name in a post.
* The number returned includes nested blocks.
*
* @param {Object} state Global application state.
* @param {?String} blockName Optional block name, if specified only blocks of that type will be counted.
*
* @return {number} Number of blocks in the post, or number of blocks with name equal to blockName.
*/
export const getGlobalBlockCount = createSelector(
( state, blockName ) => {
if ( ! blockName ) {
return size( state.editor.present.blocksByClientId );
}
return reduce(
state.editor.present.blocksByClientId,
( count, block ) => block.name === blockName ? count + 1 : count,
0
);
},
( state ) => [
state.editor.present.blocksByClientId,
]
);
/**
* Given an array of block client IDs, returns the corresponding array of block
* objects.
*
* @param {Object} state Editor state.
* @param {string[]} clientIds Client IDs for which blocks are to be returned.
*
* @return {WPBlock[]} Block objects.
*/
export const getBlocksByClientId = createSelector(
( state, clientIds ) => map(
castArray( clientIds ),
( clientId ) => getBlock( state, clientId )
),
( state ) => [
state.editor.present.blocksByClientId,
state.editor.present.blockOrder,
state.editor.present.edits.meta,
state.currentPost.meta,
state.editor.present.blocksByClientId,
]
);
/**
* Returns the number of blocks currently present in the post.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {number} Number of blocks in the post.
*/
export function getBlockCount( state, rootClientId ) {
return getBlockOrder( state, rootClientId ).length;
}
/**
* Returns the current block selection start. This value may be null, and it
* may represent either a singular block selection or multi-selection start.
* A selection is singular if its start and end match.
*
* @param {Object} state Global application state.
*
* @return {?string} Client ID of block selection start.
*/
export function getBlockSelectionStart( state ) {
return state.blockSelection.start;
}
/**
* Returns the current block selection end. This value may be null, and it
* may represent either a singular block selection or multi-selection end.
* A selection is singular if its start and end match.
*
* @param {Object} state Global application state.
*
* @return {?string} Client ID of block selection end.
*/
export function getBlockSelectionEnd( state ) {
return state.blockSelection.end;
}
/**
* Returns the number of blocks currently selected in the post.
*
* @param {Object} state Global application state.
*
* @return {number} Number of blocks selected in the post.
*/
export function getSelectedBlockCount( state ) {
const multiSelectedBlockCount = getMultiSelectedBlockClientIds( state ).length;
if ( multiSelectedBlockCount ) {
return multiSelectedBlockCount;
}
return state.blockSelection.start ? 1 : 0;
}
/**
* Returns true if there is a single selected block, or false otherwise.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether a single block is selected.
*/
export function hasSelectedBlock( state ) {
const { start, end } = state.blockSelection;
return !! start && start === end;
}
/**
* Returns the currently selected block client ID, or null if there is no
* selected block.
*
* @param {Object} state Editor state.
*
* @return {?string} Selected block client ID.
*/
export function getSelectedBlockClientId( state ) {
const { start, end } = state.blockSelection;
return start === end && start ? start : null;
}
/**
* Returns the currently selected block, or null if there is no selected block.
*
* @param {Object} state Global application state.
*
* @return {?Object} Selected block.
*/
export function getSelectedBlock( state ) {
const clientId = getSelectedBlockClientId( state );
return clientId ? getBlock( state, clientId ) : null;
}
/**
* Given a block client ID, returns the root block from which the block is
* nested, an empty string for top-level blocks, or null if the block does not
* exist.
*
* @param {Object} state Editor state.
* @param {string} clientId Block from which to find root client ID.
*
* @return {?string} Root client ID, if exists
*/
export function getBlockRootClientId( state, clientId ) {
const { blockOrder } = state.editor.present;
for ( const rootClientId in blockOrder ) {
if ( includes( blockOrder[ rootClientId ], clientId ) ) {
return rootClientId;
}
}
return null;
}
/**
* Returns the client ID of the block adjacent one at the given reference
* startClientId and modifier directionality. Defaults start startClientId to
* the selected block, and direction as next block. Returns null if there is no
* adjacent block.
*
* @param {Object} state Editor state.
* @param {?string} startClientId Optional client ID of block from which to
* search.
* @param {?number} modifier Directionality multiplier (1 next, -1
* previous).
*
* @return {?string} Return the client ID of the block, or null if none exists.
*/
export function getAdjacentBlockClientId( state, startClientId, modifier = 1 ) {
// Default to selected block.
if ( startClientId === undefined ) {
startClientId = getSelectedBlockClientId( state );
}
// Try multi-selection starting at extent based on modifier.
if ( startClientId === undefined ) {
if ( modifier < 0 ) {
startClientId = getFirstMultiSelectedBlockClientId( state );
} else {
startClientId = getLastMultiSelectedBlockClientId( state );
}
}
// Validate working start client ID.
if ( ! startClientId ) {
return null;
}
// Retrieve start block root client ID, being careful to allow the falsey
// empty string top-level root by explicitly testing against null.
const rootClientId = getBlockRootClientId( state, startClientId );
if ( rootClientId === null ) {
return null;
}
const { blockOrder } = state.editor.present;
const orderSet = blockOrder[ rootClientId ];
const index = orderSet.indexOf( startClientId );
const nextIndex = ( index + ( 1 * modifier ) );
// Block was first in set and we're attempting to get previous.
if ( nextIndex < 0 ) {
return null;
}
// Block was last in set and we're attempting to get next.
if ( nextIndex === orderSet.length ) {
return null;
}
// Assume incremented index is within the set.
return orderSet[ nextIndex ];
}
/**
* Returns the previous block's client ID from the given reference start ID.
* Defaults start to the selected block. Returns null if there is no previous
* block.
*
* @param {Object} state Editor state.
* @param {?string} startClientId Optional client ID of block from which to
* search.
*
* @return {?string} Adjacent block's client ID, or null if none exists.
*/
export function getPreviousBlockClientId( state, startClientId ) {
return getAdjacentBlockClientId( state, startClientId, -1 );
}
/**
* Returns the next block's client ID from the given reference start ID.
* Defaults start to the selected block. Returns null if there is no next
* block.
*
* @param {Object} state Editor state.
* @param {?string} startClientId Optional client ID of block from which to
* search.
*
* @return {?string} Adjacent block's client ID, or null if none exists.
*/
export function getNextBlockClientId( state, startClientId ) {
return getAdjacentBlockClientId( state, startClientId, 1 );
}
/**
* Returns the initial caret position for the selected block.
* This position is to used to position the caret properly when the selected block changes.
*
* @param {Object} state Global application state.
*
* @return {?Object} Selected block.
*/
export function getSelectedBlocksInitialCaretPosition( state ) {
const { start, end } = state.blockSelection;
if ( start !== end || ! start ) {
return null;
}
return state.blockSelection.initialPosition;
}
/**
* Returns the current multi-selection set of block client IDs, or an empty
* array if there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {Array} Multi-selected block client IDs.
*/
export const getMultiSelectedBlockClientIds = createSelector(
( state ) => {
const { start, end } = state.blockSelection;
if ( start === end ) {
return [];
}
// Retrieve root client ID to aid in retrieving relevant nested block
// order, being careful to allow the falsey empty string top-level root
// by explicitly testing against null.
const rootClientId = getBlockRootClientId( state, start );
if ( rootClientId === null ) {
return [];
}
const blockOrder = getBlockOrder( state, rootClientId );
const startIndex = blockOrder.indexOf( start );
const endIndex = blockOrder.indexOf( end );
if ( startIndex > endIndex ) {
return blockOrder.slice( endIndex, startIndex + 1 );
}
return blockOrder.slice( startIndex, endIndex + 1 );
},
( state ) => [
state.editor.present.blockOrder,
state.blockSelection.start,
state.blockSelection.end,
],
);
/**
* Returns the current multi-selection set of blocks, or an empty array if
* there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {Array} Multi-selected block objects.
*/
export const getMultiSelectedBlocks = createSelector(
( state ) => {
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds( state );
if ( ! multiSelectedBlockClientIds.length ) {
return EMPTY_ARRAY;
}
return multiSelectedBlockClientIds.map( ( clientId ) => getBlock( state, clientId ) );
},
( state ) => [
state.editor.present.blockOrder,
state.blockSelection.start,
state.blockSelection.end,
state.editor.present.blocksByClientId,
state.editor.present.edits.meta,
state.currentPost.meta,
]
);
/**
* Returns the client ID of the first block in the multi-selection set, or null
* if there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {?string} First block client ID in the multi-selection set.
*/
export function getFirstMultiSelectedBlockClientId( state ) {
return first( getMultiSelectedBlockClientIds( state ) ) || null;
}
/**
* Returns the client ID of the last block in the multi-selection set, or null
* if there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {?string} Last block client ID in the multi-selection set.
*/
export function getLastMultiSelectedBlockClientId( state ) {
return last( getMultiSelectedBlockClientIds( state ) ) || null;
}
/**
* Returns true if a multi-selection exists, and the block corresponding to the
* specified client ID is the first block of the multi-selection set, or false
* otherwise.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Whether block is first in mult-selection.
*/
export function isFirstMultiSelectedBlock( state, clientId ) {
return getFirstMultiSelectedBlockClientId( state ) === clientId;
}
/**
* Returns true if the client ID occurs within the block multi-selection, or
* false otherwise.
*