-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
selectors.js
1736 lines (1550 loc) · 46.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 { find, get, has, map, pick, mapValues, includes } from 'lodash';
import createSelector from 'rememo';
/**
* WordPress dependencies
*/
import {
getFreeformContentHandlerName,
getDefaultBlockName,
isUnmodifiedDefaultBlock,
} from '@wordpress/blocks';
import { isInTheFuture, getDate } from '@wordpress/date';
import { addQueryArgs } from '@wordpress/url';
import { createRegistrySelector } from '@wordpress/data';
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import { PREFERENCES_DEFAULTS } from './defaults';
import {
EDIT_MERGE_PROPERTIES,
POST_UPDATE_TRANSACTION_ID,
PERMALINK_POSTNAME_REGEX,
ONE_MINUTE_IN_MS,
AUTOSAVE_PROPERTIES,
} from './constants';
import { getPostRawValue } from './reducer';
import serializeBlocks from './utils/serialize-blocks';
/**
* Shared reference to an empty object for cases where it is important to avoid
* returning a new object 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.
*/
const EMPTY_OBJECT = {};
/**
* 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.
*/
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 const hasEditorUndo = createRegistrySelector( ( select ) => () => {
return select( 'core' ).hasUndo();
} );
/**
* 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 const hasEditorRedo = createRegistrySelector( ( select ) => () => {
return select( 'core' ).hasRedo();
} );
/**
* 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 content includes unsaved changes, or false otherwise.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether content includes unsaved changes.
*/
export function hasChangedContent( state ) {
const edits = getPostEdits( state );
return (
'blocks' in edits ||
// `edits` is intended to contain only values which are different from
// the saved post, so the mere presence of a property is an indicator
// that the value is different than what is known to be saved. While
// content in Visual mode is represented by the blocks state, in Text
// mode it is tracked by `edits.content`.
'content' in edits
);
}
/**
* 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 const isEditedPostDirty = createRegistrySelector(
( select ) => ( state ) => {
// Edits should contain only fields which differ from the saved post (reset
// at initial load and save complete). Thus, a non-empty edits state can be
// inferred to contain unsaved values.
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
if (
select( 'core' ).hasEditsForEntityRecord(
'postType',
postType,
postId
)
) {
return true;
}
return false;
}
);
/**
* Returns true if there are unsaved edits for entities other than
* the editor's post, and false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether there are edits or not.
*/
export const hasNonPostEntityChanges = createRegistrySelector(
( select ) => ( state ) => {
const enableFullSiteEditing = getEditorSettings( state )
.__experimentalEnableFullSiteEditing;
if ( ! enableFullSiteEditing ) {
return false;
}
const entityRecordChangesByRecord = select(
'core'
).getEntityRecordChangesByRecord();
const changedKinds = Object.keys( entityRecordChangesByRecord );
if (
changedKinds.length > 1 ||
( changedKinds.length === 1 &&
! entityRecordChangesByRecord.postType )
) {
// Return true if there is more than one edited entity kind
// or the edited entity kind is not the editor's post's kind.
return true;
} else if ( ! entityRecordChangesByRecord.postType ) {
// Don't continue if there are no edited entity kinds.
return false;
}
const { type, id } = getCurrentPost( state );
const changedPostTypes = Object.keys(
entityRecordChangesByRecord.postType
);
if (
changedPostTypes.length > 1 ||
( changedPostTypes.length === 1 &&
! entityRecordChangesByRecord.postType[ type ] )
) {
// Return true if there is more than one edited post type
// or the edited entity's post type is not the editor's post's post type.
return true;
}
const changedPosts = Object.keys(
entityRecordChangesByRecord.postType[ type ]
);
if (
changedPosts.length > 1 ||
( changedPosts.length === 1 &&
! entityRecordChangesByRecord.postType[ type ][ id ] )
) {
// Return true if there is more than one edited post
// or the edited post is not the editor's post.
return true;
}
return false;
}
);
/**
* 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 const getCurrentPost = createRegistrySelector(
( select ) => ( state ) => {
const postId = getCurrentPostId( state );
const postType = getCurrentPostType( state );
const post = select( 'core' ).getRawEntityRecord(
'postType',
postType,
postId
);
if ( post ) {
return post;
}
// This exists for compatibility with the previous selector behavior
// which would guarantee an object return based on the editor reducer's
// default empty object state.
return EMPTY_OBJECT;
}
);
/**
* 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.postType;
}
/**
* 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 state.postId;
}
/**
* 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 const getPostEdits = createRegistrySelector( ( select ) => ( state ) => {
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
return (
select( 'core' ).getEntityRecordEdits( 'postType', postType, postId ) ||
EMPTY_OBJECT
);
} );
/**
* Returns a new reference when edited values have changed. This is useful in
* inferring where an edit has been made between states by comparison of the
* return values using strict equality.
*
* @deprecated since Gutenberg 6.5.0.
*
* @example
*
* ```
* const hasEditOccurred = (
* getReferenceByDistinctEdits( beforeState ) !==
* getReferenceByDistinctEdits( afterState )
* );
* ```
*
* @param {Object} state Editor state.
*
* @return {*} A value whose reference will change only when an edit occurs.
*/
export const getReferenceByDistinctEdits = createRegistrySelector(
( select ) => (/* state */) => {
deprecated(
"`wp.data.select( 'core/editor' ).getReferenceByDistinctEdits`",
{
alternative:
"`wp.data.select( 'core' ).getReferenceByDistinctEdits`",
}
);
return select( 'core' ).getReferenceByDistinctEdits();
}
);
/**
* 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 ) {
switch ( attributeName ) {
case 'type':
return getCurrentPostType( state );
case 'id':
return getCurrentPostId( state );
default:
const post = getCurrentPost( state );
if ( ! post.hasOwnProperty( attributeName ) ) {
break;
}
return getPostRawValue( post[ attributeName ] );
}
}
/**
* Returns a single attribute of the post being edited, preferring the unsaved
* edit if one exists, but merging with the attribute value for the last known
* saved state of the post (this is needed for some nested attributes like meta).
*
* @param {Object} state Global application state.
* @param {string} attributeName Post attribute name.
*
* @return {*} Post attribute value.
*/
const getNestedEditedPostProperty = ( state, attributeName ) => {
const edits = getPostEdits( state );
if ( ! edits.hasOwnProperty( attributeName ) ) {
return getCurrentPostAttribute( state, attributeName );
}
return {
...getCurrentPostAttribute( state, attributeName ),
...edits[ 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 ) {
// Special cases
switch ( attributeName ) {
case 'content':
return getEditedPostContent( state );
}
// Fall back to saved post value if not edited.
const edits = getPostEdits( state );
if ( ! edits.hasOwnProperty( attributeName ) ) {
return getCurrentPostAttribute( state, attributeName );
}
// Merge properties are objects which contain only the patch edit in state,
// and thus must be merged with the current post attribute.
if ( EDIT_MERGE_PROPERTIES.has( attributeName ) ) {
return getNestedEditedPostProperty( 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.
*
* @deprecated since 5.6. Callers should use the `getAutosave( postType, postId, userId )` selector
* from the '@wordpress/core-data' package and access properties on the returned
* autosave object using getPostRawValue.
*
* @param {Object} state Global application state.
* @param {string} attributeName Autosave attribute name.
*
* @return {*} Autosave attribute value.
*/
export const getAutosaveAttribute = createRegistrySelector(
( select ) => ( state, attributeName ) => {
if (
! includes( AUTOSAVE_PROPERTIES, attributeName ) &&
attributeName !== 'preview_link'
) {
return;
}
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
const currentUserId = get( select( 'core' ).getCurrentUser(), [
'id',
] );
const autosave = select( 'core' ).getAutosave(
postType,
postId,
currentUserId
);
if ( autosave ) {
return getPostRawValue( 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' );
if ( status === 'private' ) {
return 'private';
}
const password = getEditedPostAttribute( state, 'password' );
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.
* @param {Object?} currentPost Explicit current post for bypassing registry selector.
*
* @return {boolean} Whether the post has been published.
*/
export function isCurrentPostPublished( state, currentPost ) {
const post = currentPost || getCurrentPost( state );
return (
[ 'publish', 'private' ].indexOf( post.status ) !== -1 ||
( post.status === 'future' &&
! isInTheFuture(
new Date( Number( getDate( post.date ) ) - ONE_MINUTE_IN_MS )
) )
);
}
/**
* 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 is sufficient to determine
// emptiness, testing saveable blocks length is a trivial operation. Since
// this function can be called frequently, optimize for the fast case as a
// condition of the mere existence of blocks. Note that the value of edited
// content takes precedent over block content, and must fall through to the
// default logic.
const blocks = getEditorBlocks( state );
if ( blocks.length ) {
// Pierce the abstraction of the serializer in knowing that blocks are
// joined with with newlines such that even if every individual block
// produces an empty save result, the serialized content is non-empty.
if ( blocks.length > 1 ) {
return false;
}
// There are two conditions under which the optimization cannot be
// assumed, and a fallthrough to getEditedPostContent must occur:
//
// 1. getBlocksForSerialization has special treatment in omitting a
// single unmodified default block.
// 2. Comment delimiters are omitted for a freeform or unregistered
// block in its serialization. The freeform block specifically may
// produce an empty string in its saved output.
//
// For all other content, the single block is assumed to make a post
// non-empty, if only by virtue of its own comment delimiters.
const blockName = blocks[ 0 ].name;
if (
blockName !== getDefaultBlockName() &&
blockName !== getFreeformContentHandlerName()
) {
return false;
}
}
return ! getEditedPostContent( state );
}
/**
* Returns true if the post can be autosaved, or false otherwise.
*
* @param {Object} state Global application state.
* @param {Object} autosave A raw autosave object from the REST API.
*
* @return {boolean} Whether the post can be autosaved.
*/
export const isEditedPostAutosaveable = createRegistrySelector(
( select ) =>
function( state ) {
// A post must contain a title, an excerpt, or non-empty content to be valid for autosaving.
if ( ! isEditedPostSaveable( state ) ) {
return false;
}
// A post is not autosavable when there is a post autosave lock.
if ( isPostAutosavingLocked( state ) ) {
return false;
}
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
const hasFetchedAutosave = select( 'core' ).hasFetchedAutosaves(
postType,
postId
);
const currentUserId = get( select( 'core' ).getCurrentUser(), [
'id',
] );
// Disable reason - this line causes the side-effect of fetching the autosave
// via a resolver, moving below the return would result in the autosave never
// being fetched.
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const autosave = select( 'core' ).getAutosave(
postType,
postId,
currentUserId
);
// If any existing autosaves have not yet been fetched, this function is
// unable to determine if the post is autosaveable, so return false.
if ( ! hasFetchedAutosave ) {
return false;
}
// If we don't already have an autosave, the post is autosaveable.
if ( ! autosave ) {
return true;
}
// To avoid an expensive content serialization, use the content dirtiness
// flag in place of content field comparison against the known autosave.
// This is not strictly accurate, and relies on a tolerance toward autosave
// request failures for unnecessary saves.
if ( hasChangedContent( state ) ) {
return true;
}
// If the title or excerpt has changed, the post is autosaveable.
return [ 'title', 'excerpt' ].some(
( field ) =>
getPostRawValue( 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).
*
* @deprecated since 5.6. Callers should use the `getAutosave( postType, postId, userId )`
* selector from the '@wordpress/core-data' package.
*
* @param {Object} state Editor state.
*
* @return {?Object} Current autosave, if exists.
*/
export const getAutosave = createRegistrySelector( ( select ) => ( state ) => {
deprecated( "`wp.data.select( 'core/editor' ).getAutosave()`", {
alternative:
"`wp.data.select( 'core' ).getAutosave( postType, postId, userId )`",
plugin: 'Gutenberg',
} );
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
const currentUserId = get( select( 'core' ).getCurrentUser(), [ 'id' ] );
const autosave = select( 'core' ).getAutosave(
postType,
postId,
currentUserId
);
return mapValues( pick( autosave, AUTOSAVE_PROPERTIES ), getPostRawValue );
} );
/**
* Returns the true if there is an existing autosave, otherwise false.
*
* @deprecated since 5.6. Callers should use the `getAutosave( postType, postId, userId )` selector
* from the '@wordpress/core-data' package and check for a truthy value.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether there is an existing autosave.
*/
export const hasAutosave = createRegistrySelector( ( select ) => ( state ) => {
deprecated( "`wp.data.select( 'core/editor' ).hasAutosave()`", {
alternative:
"`!! wp.data.select( 'core' ).getAutosave( postType, postId, userId )`",
plugin: 'Gutenberg',
} );
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
const currentUserId = get( select( 'core' ).getCurrentUser(), [ 'id' ] );
return !! select( 'core' ).getAutosave( postType, postId, currentUserId );
} );
/**
* 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 = getEditedPostAttribute( state, 'date' );
// Offset the date by one minute (network latency)
const checkedDate = new Date(
Number( getDate( date ) ) - ONE_MINUTE_IN_MS
);
return isInTheFuture( checkedDate );
}
/**
* 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' ||
status === 'pending'
) {
return date === modified;
}
return false;
}
/**
* Returns true if the post is currently being saved, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether post is being saved.
*/
export const isSavingPost = createRegistrySelector( ( select ) => ( state ) => {
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
return select( 'core' ).isSavingEntityRecord(
'postType',
postType,
postId
);
} );
/**
* Returns true if a previous post save was attempted successfully, or false
* otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post was saved successfully.
*/
export const didPostSaveRequestSucceed = createRegistrySelector(
( select ) => ( state ) => {
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
return ! select( 'core' ).getLastEntitySaveError(
'postType',
postType,
postId
);
}
);
/**
* Returns true if a previous post save was attempted but failed, or false
* otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post save failed.
*/
export const didPostSaveRequestFail = createRegistrySelector(
( select ) => ( state ) => {
const postType = getCurrentPostType( state );
const postId = getCurrentPostId( state );
return !! select( 'core' ).getLastEntitySaveError(
'postType',
postType,
postId
);
}
);
/**
* Returns true if the post is autosaving, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post is autosaving.
*/
export function isAutosavingPost( state ) {
if ( ! isSavingPost( state ) ) {
return false;
}
return !! get( state.saving, [ 'options', 'isAutosave' ] );
}
/**
* Returns true if the post is being previewed, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post is being previewed.
*/
export function isPreviewingPost( state ) {
if ( ! isSavingPost( state ) ) {
return false;
}
return !! state.saving.options.isPreview;
}
/**
* Returns the post preview link
*
* @param {Object} state Global application state.
*
* @return {string?} Preview Link.
*/
export function getEditedPostPreviewLink( state ) {
if ( state.saving.pending || isSavingPost( state ) ) {
return;
}
let previewLink = getAutosaveAttribute( state, 'preview_link' );
if ( ! previewLink ) {
previewLink = getEditedPostAttribute( state, 'link' );
if ( previewLink ) {
previewLink = addQueryArgs( previewLink, { preview: true } );
}
}
const featuredImageId = getEditedPostAttribute( state, 'featured_media' );
if ( previewLink && featuredImageId ) {
return addQueryArgs( previewLink, { _thumbnail_id: featuredImageId } );
}
return previewLink;
}
/**
* Returns a suggested post format for the current post, inferred only if there
* is a single block within the post and it is of a type known to match a
* default post format. Returns null if the format cannot be determined.
*
* @param {Object} state Global application state.
*
* @return {?string} Suggested post format.
*/
export function getSuggestedPostFormat( state ) {
const blocks = getEditorBlocks( state );
let name;
// If there is only one block in the content of the post grab its name
// so we can derive a suitable post format from it.
if ( blocks.length === 1 ) {
name = blocks[ 0 ].name;
}
// If there are two blocks in the content and the last one is a text blocks
// grab the name of the first one to also suggest a post format from it.
if ( blocks.length === 2 ) {
if ( blocks[ 1 ].name === 'core/paragraph' ) {
name = blocks[ 0 ].name;
}
}
// We only convert to default post formats in core.
switch ( name ) {
case 'core/image':
return 'image';
case 'core/quote':
case 'core/pullquote':
return 'quote';
case 'core/gallery':
return 'gallery';
case 'core/video':
case 'core-embed/youtube':
case 'core-embed/vimeo':
return 'video';
case 'core/audio':
case 'core-embed/spotify':
case 'core-embed/soundcloud':
return 'audio';
}
return null;
}
/**
* Returns a set of blocks which are to be used in consideration of the post's
* generated save content.
*
* @deprecated since Gutenberg 6.2.0.
*
* @param {Object} state Editor state.
*
* @return {WPBlock[]} Filtered set of blocks for save.
*/
export function getBlocksForSerialization( state ) {
deprecated( '`core/editor` getBlocksForSerialization selector', {
plugin: 'Gutenberg',
alternative: 'getEditorBlocks',
hint: 'Blocks serialization pre-processing occurs at save time',
} );
const blocks = state.editor.present.blocks.value;
// WARNING: Any changes to the logic of this function should be verified
// against the implementation of isEditedPostEmpty, which bypasses this
// function for performance' sake, in an assumption of this current logic
// being irrelevant to the optimized condition of emptiness.
// A single unmodified default block is assumed to be equivalent to an
// empty post.
const isSingleUnmodifiedDefaultBlock =
blocks.length === 1 && isUnmodifiedDefaultBlock( blocks[ 0 ] );
if ( isSingleUnmodifiedDefaultBlock ) {
return [];
}
return blocks;
}
/**
* Returns the content of the post being edited.