-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
actions.js
971 lines (917 loc) · 25.6 KB
/
actions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/**
* External dependencies
*/
import fastDeepEqual from 'fast-deep-equal/es6';
import { v4 as uuid } from 'uuid';
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import { getNestedValue, setNestedValue } from './utils';
import { receiveItems, removeItems, receiveQueriedItems } from './queried-data';
import { getOrLoadEntitiesConfig, DEFAULT_ENTITY_KEY } from './entities';
import { createBatch } from './batch';
import { STORE_NAME } from './name';
import { getSyncProvider } from './sync';
/**
* Returns an action object used in signalling that authors have been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {string} queryID Query ID.
* @param {Array|Object} users Users received.
*
* @return {Object} Action object.
*/
export function receiveUserQuery( queryID, users ) {
return {
type: 'RECEIVE_USER_QUERY',
users: Array.isArray( users ) ? users : [ users ],
queryID,
};
}
/**
* Returns an action used in signalling that the current user has been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {Object} currentUser Current user object.
*
* @return {Object} Action object.
*/
export function receiveCurrentUser( currentUser ) {
return {
type: 'RECEIVE_CURRENT_USER',
currentUser,
};
}
/**
* Returns an action object used in adding new entities.
*
* @param {Array} entities Entities received.
*
* @return {Object} Action object.
*/
export function addEntities( entities ) {
return {
type: 'ADD_ENTITIES',
entities,
};
}
/**
* Returns an action object used in signalling that entity records have been received.
*
* @param {string} kind Kind of the received entity record.
* @param {string} name Name of the received entity record.
* @param {Array|Object} records Records received.
* @param {?Object} query Query Object.
* @param {?boolean} invalidateCache Should invalidate query caches.
* @param {?Object} edits Edits to reset.
* @param {?Object} meta Meta information about pagination.
* @return {Object} Action object.
*/
export function receiveEntityRecords(
kind,
name,
records,
query,
invalidateCache = false,
edits,
meta
) {
// Auto drafts should not have titles, but some plugins rely on them so we can't filter this
// on the server.
if ( kind === 'postType' ) {
records = ( Array.isArray( records ) ? records : [ records ] ).map(
( record ) =>
record.status === 'auto-draft'
? { ...record, title: '' }
: record
);
}
let action;
if ( query ) {
action = receiveQueriedItems( records, query, edits, meta );
} else {
action = receiveItems( records, edits, meta );
}
return {
...action,
kind,
name,
invalidateCache,
};
}
/**
* Returns an action object used in signalling that the current theme has been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {Object} currentTheme The current theme.
*
* @return {Object} Action object.
*/
export function receiveCurrentTheme( currentTheme ) {
return {
type: 'RECEIVE_CURRENT_THEME',
currentTheme,
};
}
/**
* Returns an action object used in signalling that the current global styles id has been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {string} currentGlobalStylesId The current global styles id.
*
* @return {Object} Action object.
*/
export function __experimentalReceiveCurrentGlobalStylesId(
currentGlobalStylesId
) {
return {
type: 'RECEIVE_CURRENT_GLOBAL_STYLES_ID',
id: currentGlobalStylesId,
};
}
/**
* Returns an action object used in signalling that the theme base global styles have been received
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {string} stylesheet The theme's identifier
* @param {Object} globalStyles The global styles object.
*
* @return {Object} Action object.
*/
export function __experimentalReceiveThemeBaseGlobalStyles(
stylesheet,
globalStyles
) {
return {
type: 'RECEIVE_THEME_GLOBAL_STYLES',
stylesheet,
globalStyles,
};
}
/**
* Returns an action object used in signalling that the theme global styles variations have been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {string} stylesheet The theme's identifier
* @param {Array} variations The global styles variations.
*
* @return {Object} Action object.
*/
export function __experimentalReceiveThemeGlobalStyleVariations(
stylesheet,
variations
) {
return {
type: 'RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS',
stylesheet,
variations,
};
}
/**
* Returns an action object used in signalling that the index has been received.
*
* @deprecated since WP 5.9, this is not useful anymore, use the selector direclty.
*
* @return {Object} Action object.
*/
export function receiveThemeSupports() {
deprecated( "wp.data.dispatch( 'core' ).receiveThemeSupports", {
since: '5.9',
} );
return {
type: 'DO_NOTHING',
};
}
/**
* Returns an action object used in signalling that the theme global styles CPT post revisions have been received.
* Ignored from documentation as it's internal to the data store.
*
* @deprecated since WordPress 6.5.0. Callers should use `dispatch( 'core' ).receiveRevision` instead.
*
* @ignore
*
* @param {number} currentId The post id.
* @param {Array} revisions The global styles revisions.
*
* @return {Object} Action object.
*/
export function receiveThemeGlobalStyleRevisions( currentId, revisions ) {
deprecated(
"wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()",
{
since: '6.5.0',
alternative: "wp.data.dispatch( 'core' ).receiveRevisions",
}
);
return {
type: 'RECEIVE_THEME_GLOBAL_STYLE_REVISIONS',
currentId,
revisions,
};
}
/**
* Returns an action object used in signalling that the preview data for
* a given URl has been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {string} url URL to preview the embed for.
* @param {*} preview Preview data.
*
* @return {Object} Action object.
*/
export function receiveEmbedPreview( url, preview ) {
return {
type: 'RECEIVE_EMBED_PREVIEW',
url,
preview,
};
}
/**
* Action triggered to delete an entity record.
*
* @param {string} kind Kind of the deleted entity.
* @param {string} name Name of the deleted entity.
* @param {string} recordId Record ID of the deleted entity.
* @param {?Object} query Special query parameters for the
* DELETE API call.
* @param {Object} [options] Delete options.
* @param {Function} [options.__unstableFetch] Internal use only. Function to
* call instead of `apiFetch()`.
* Must return a promise.
* @param {boolean} [options.throwOnError=false] If false, this action suppresses all
* the exceptions. Defaults to false.
*/
export const deleteEntityRecord =
(
kind,
name,
recordId,
query,
{ __unstableFetch = apiFetch, throwOnError = false } = {}
) =>
async ( { dispatch } ) => {
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.kind === kind && config.name === name
);
let error;
let deletedRecord = false;
if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) {
return;
}
const lock = await dispatch.__unstableAcquireStoreLock(
STORE_NAME,
[ 'entities', 'records', kind, name, recordId ],
{ exclusive: true }
);
try {
dispatch( {
type: 'DELETE_ENTITY_RECORD_START',
kind,
name,
recordId,
} );
let hasError = false;
try {
let path = `${ entityConfig.baseURL }/${ recordId }`;
if ( query ) {
path = addQueryArgs( path, query );
}
deletedRecord = await __unstableFetch( {
path,
method: 'DELETE',
} );
await dispatch( removeItems( kind, name, recordId, true ) );
} catch ( _error ) {
hasError = true;
error = _error;
}
dispatch( {
type: 'DELETE_ENTITY_RECORD_FINISH',
kind,
name,
recordId,
error,
} );
if ( hasError && throwOnError ) {
throw error;
}
return deletedRecord;
} finally {
dispatch.__unstableReleaseStoreLock( lock );
}
};
/**
* Returns an action object that triggers an
* edit to an entity record.
*
* @param {string} kind Kind of the edited entity record.
* @param {string} name Name of the edited entity record.
* @param {number|string} recordId Record ID of the edited entity record.
* @param {Object} edits The edits.
* @param {Object} options Options for the edit.
* @param {boolean} [options.undoIgnore] Whether to ignore the edit in undo history or not.
*
* @return {Object} Action object.
*/
export const editEntityRecord =
( kind, name, recordId, edits, options = {} ) =>
( { select, dispatch } ) => {
const entityConfig = select.getEntityConfig( kind, name );
if ( ! entityConfig ) {
throw new Error(
`The entity being edited (${ kind }, ${ name }) does not have a loaded config.`
);
}
const { mergedEdits = {} } = entityConfig;
const record = select.getRawEntityRecord( kind, name, recordId );
const editedRecord = select.getEditedEntityRecord(
kind,
name,
recordId
);
const edit = {
kind,
name,
recordId,
// Clear edits when they are equal to their persisted counterparts
// so that the property is not considered dirty.
edits: Object.keys( edits ).reduce( ( acc, key ) => {
const recordValue = record[ key ];
const editedRecordValue = editedRecord[ key ];
const value = mergedEdits[ key ]
? { ...editedRecordValue, ...edits[ key ] }
: edits[ key ];
acc[ key ] = fastDeepEqual( recordValue, value )
? undefined
: value;
return acc;
}, {} ),
};
if ( window.__experimentalEnableSync && entityConfig.syncConfig ) {
if ( process.env.IS_GUTENBERG_PLUGIN ) {
const objectId = entityConfig.getSyncObjectId( recordId );
getSyncProvider().update(
entityConfig.syncObjectType + '--edit',
objectId,
edit.edits
);
}
} else {
if ( ! options.undoIgnore ) {
select.getUndoManager().addRecord(
[
{
id: { kind, name, recordId },
changes: Object.keys( edits ).reduce(
( acc, key ) => {
acc[ key ] = {
from: editedRecord[ key ],
to: edits[ key ],
};
return acc;
},
{}
),
},
],
options.isCached
);
}
dispatch( {
type: 'EDIT_ENTITY_RECORD',
...edit,
} );
}
};
/**
* Action triggered to undo the last edit to
* an entity record, if any.
*/
export const undo =
() =>
( { select, dispatch } ) => {
const undoRecord = select.getUndoManager().undo();
if ( ! undoRecord ) {
return;
}
dispatch( {
type: 'UNDO',
record: undoRecord,
} );
};
/**
* Action triggered to redo the last undoed
* edit to an entity record, if any.
*/
export const redo =
() =>
( { select, dispatch } ) => {
const redoRecord = select.getUndoManager().redo();
if ( ! redoRecord ) {
return;
}
dispatch( {
type: 'REDO',
record: redoRecord,
} );
};
/**
* Forces the creation of a new undo level.
*
* @return {Object} Action object.
*/
export const __unstableCreateUndoLevel =
() =>
( { select } ) => {
select.getUndoManager().addRecord();
};
/**
* Action triggered to save an entity record.
*
* @param {string} kind Kind of the received entity.
* @param {string} name Name of the received entity.
* @param {Object} record Record to be saved.
* @param {Object} options Saving options.
* @param {boolean} [options.isAutosave=false] Whether this is an autosave.
* @param {Function} [options.__unstableFetch] Internal use only. Function to
* call instead of `apiFetch()`.
* Must return a promise.
* @param {boolean} [options.throwOnError=false] If false, this action suppresses all
* the exceptions. Defaults to false.
*/
export const saveEntityRecord =
(
kind,
name,
record,
{
isAutosave = false,
__unstableFetch = apiFetch,
throwOnError = false,
} = {}
) =>
async ( { select, resolveSelect, dispatch } ) => {
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.kind === kind && config.name === name
);
if ( ! entityConfig || entityConfig?.__experimentalNoFetch ) {
return;
}
const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
const recordId = record[ entityIdKey ];
const lock = await dispatch.__unstableAcquireStoreLock(
STORE_NAME,
[ 'entities', 'records', kind, name, recordId || uuid() ],
{ exclusive: true }
);
try {
// Evaluate optimized edits.
// (Function edits that should be evaluated on save to avoid expensive computations on every edit.)
for ( const [ key, value ] of Object.entries( record ) ) {
if ( typeof value === 'function' ) {
const evaluatedValue = value(
select.getEditedEntityRecord( kind, name, recordId )
);
dispatch.editEntityRecord(
kind,
name,
recordId,
{
[ key ]: evaluatedValue,
},
{ undoIgnore: true }
);
record[ key ] = evaluatedValue;
}
}
dispatch( {
type: 'SAVE_ENTITY_RECORD_START',
kind,
name,
recordId,
isAutosave,
} );
let updatedRecord;
let error;
let hasError = false;
try {
const path = `${ entityConfig.baseURL }${
recordId ? '/' + recordId : ''
}`;
const persistedRecord = select.getRawEntityRecord(
kind,
name,
recordId
);
if ( isAutosave ) {
// Most of this autosave logic is very specific to posts.
// This is fine for now as it is the only supported autosave,
// but ideally this should all be handled in the back end,
// so the client just sends and receives objects.
const currentUser = select.getCurrentUser();
const currentUserId = currentUser
? currentUser.id
: undefined;
const autosavePost = await resolveSelect.getAutosave(
persistedRecord.type,
persistedRecord.id,
currentUserId
);
// Autosaves need all expected fields to be present.
// So we fallback to the previous autosave and then
// to the actual persisted entity if the edits don't
// have a value.
let data = {
...persistedRecord,
...autosavePost,
...record,
};
data = Object.keys( data ).reduce(
( acc, key ) => {
if (
[
'title',
'excerpt',
'content',
'meta',
].includes( key )
) {
acc[ key ] = data[ key ];
}
return acc;
},
{
status:
data.status === 'auto-draft'
? 'draft'
: data.status,
}
);
updatedRecord = await __unstableFetch( {
path: `${ path }/autosaves`,
method: 'POST',
data,
} );
// An autosave may be processed by the server as a regular save
// when its update is requested by the author and the post had
// draft or auto-draft status.
if ( persistedRecord.id === updatedRecord.id ) {
let newRecord = {
...persistedRecord,
...data,
...updatedRecord,
};
newRecord = Object.keys( newRecord ).reduce(
( acc, key ) => {
// These properties are persisted in autosaves.
if (
[ 'title', 'excerpt', 'content' ].includes(
key
)
) {
acc[ key ] = newRecord[ key ];
} else if ( key === 'status' ) {
// Status is only persisted in autosaves when going from
// "auto-draft" to "draft".
acc[ key ] =
persistedRecord.status ===
'auto-draft' &&
newRecord.status === 'draft'
? newRecord.status
: persistedRecord.status;
} else {
// These properties are not persisted in autosaves.
acc[ key ] = persistedRecord[ key ];
}
return acc;
},
{}
);
dispatch.receiveEntityRecords(
kind,
name,
newRecord,
undefined,
true
);
} else {
dispatch.receiveAutosaves(
persistedRecord.id,
updatedRecord
);
}
} else {
let edits = record;
if ( entityConfig.__unstablePrePersist ) {
edits = {
...edits,
...entityConfig.__unstablePrePersist(
persistedRecord,
edits
),
};
}
updatedRecord = await __unstableFetch( {
path,
method: recordId ? 'PUT' : 'POST',
data: edits,
} );
dispatch.receiveEntityRecords(
kind,
name,
updatedRecord,
undefined,
true,
edits
);
}
} catch ( _error ) {
hasError = true;
error = _error;
}
dispatch( {
type: 'SAVE_ENTITY_RECORD_FINISH',
kind,
name,
recordId,
error,
isAutosave,
} );
if ( hasError && throwOnError ) {
throw error;
}
return updatedRecord;
} finally {
dispatch.__unstableReleaseStoreLock( lock );
}
};
/**
* Runs multiple core-data actions at the same time using one API request.
*
* Example:
*
* ```
* const [ savedRecord, updatedRecord, deletedRecord ] =
* await dispatch( 'core' ).__experimentalBatch( [
* ( { saveEntityRecord } ) => saveEntityRecord( 'root', 'widget', widget ),
* ( { saveEditedEntityRecord } ) => saveEntityRecord( 'root', 'widget', 123 ),
* ( { deleteEntityRecord } ) => deleteEntityRecord( 'root', 'widget', 123, null ),
* ] );
* ```
*
* @param {Array} requests Array of functions which are invoked simultaneously.
* Each function is passed an object containing
* `saveEntityRecord`, `saveEditedEntityRecord`, and
* `deleteEntityRecord`.
*
* @return {(thunkArgs: Object) => Promise} A promise that resolves to an array containing the return
* values of each function given in `requests`.
*/
export const __experimentalBatch =
( requests ) =>
async ( { dispatch } ) => {
const batch = createBatch();
const api = {
saveEntityRecord( kind, name, record, options ) {
return batch.add( ( add ) =>
dispatch.saveEntityRecord( kind, name, record, {
...options,
__unstableFetch: add,
} )
);
},
saveEditedEntityRecord( kind, name, recordId, options ) {
return batch.add( ( add ) =>
dispatch.saveEditedEntityRecord( kind, name, recordId, {
...options,
__unstableFetch: add,
} )
);
},
deleteEntityRecord( kind, name, recordId, query, options ) {
return batch.add( ( add ) =>
dispatch.deleteEntityRecord( kind, name, recordId, query, {
...options,
__unstableFetch: add,
} )
);
},
};
const resultPromises = requests.map( ( request ) => request( api ) );
const [ , ...results ] = await Promise.all( [
batch.run(),
...resultPromises,
] );
return results;
};
/**
* Action triggered to save an entity record's edits.
*
* @param {string} kind Kind of the entity.
* @param {string} name Name of the entity.
* @param {Object} recordId ID of the record.
* @param {Object} options Saving options.
*/
export const saveEditedEntityRecord =
( kind, name, recordId, options ) =>
async ( { select, dispatch } ) => {
if ( ! select.hasEditsForEntityRecord( kind, name, recordId ) ) {
return;
}
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.kind === kind && config.name === name
);
if ( ! entityConfig ) {
return;
}
const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
const edits = select.getEntityRecordNonTransientEdits(
kind,
name,
recordId
);
const record = { [ entityIdKey ]: recordId, ...edits };
return await dispatch.saveEntityRecord( kind, name, record, options );
};
/**
* Action triggered to save only specified properties for the entity.
*
* @param {string} kind Kind of the entity.
* @param {string} name Name of the entity.
* @param {Object} recordId ID of the record.
* @param {Array} itemsToSave List of entity properties or property paths to save.
* @param {Object} options Saving options.
*/
export const __experimentalSaveSpecifiedEntityEdits =
( kind, name, recordId, itemsToSave, options ) =>
async ( { select, dispatch } ) => {
if ( ! select.hasEditsForEntityRecord( kind, name, recordId ) ) {
return;
}
const edits = select.getEntityRecordNonTransientEdits(
kind,
name,
recordId
);
const editsToSave = {};
for ( const item of itemsToSave ) {
setNestedValue( editsToSave, item, getNestedValue( edits, item ) );
}
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.kind === kind && config.name === name
);
const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY;
// If a record key is provided then update the existing record.
// This necessitates providing `recordKey` to saveEntityRecord as part of the
// `record` argument (here called `editsToSave`) to stop that action creating
// a new record and instead cause it to update the existing record.
if ( recordId ) {
editsToSave[ entityIdKey ] = recordId;
}
return await dispatch.saveEntityRecord(
kind,
name,
editsToSave,
options
);
};
/**
* Returns an action object used in signalling that Upload permissions have been received.
*
* @deprecated since WP 5.9, use receiveUserPermission instead.
*
* @param {boolean} hasUploadPermissions Does the user have permission to upload files?
*
* @return {Object} Action object.
*/
export function receiveUploadPermissions( hasUploadPermissions ) {
deprecated( "wp.data.dispatch( 'core' ).receiveUploadPermissions", {
since: '5.9',
alternative: 'receiveUserPermission',
} );
return receiveUserPermission( 'create/media', hasUploadPermissions );
}
/**
* Returns an action object used in signalling that the current user has
* permission to perform an action on a REST resource.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {string} key A key that represents the action and REST resource.
* @param {boolean} isAllowed Whether or not the user can perform the action.
*
* @return {Object} Action object.
*/
export function receiveUserPermission( key, isAllowed ) {
return {
type: 'RECEIVE_USER_PERMISSION',
key,
isAllowed,
};
}
/**
* Returns an action object used in signalling that the autosaves for a
* post have been received.
* Ignored from documentation as it's internal to the data store.
*
* @ignore
*
* @param {number} postId The id of the post that is parent to the autosave.
* @param {Array|Object} autosaves An array of autosaves or singular autosave object.
*
* @return {Object} Action object.
*/
export function receiveAutosaves( postId, autosaves ) {
return {
type: 'RECEIVE_AUTOSAVES',
postId,
autosaves: Array.isArray( autosaves ) ? autosaves : [ autosaves ],
};
}
/**
* Returns an action object signalling that the fallback Navigation
* Menu id has been received.
*
* @param {integer} fallbackId the id of the fallback Navigation Menu
* @return {Object} Action object.
*/
export function receiveNavigationFallbackId( fallbackId ) {
return {
type: 'RECEIVE_NAVIGATION_FALLBACK_ID',
fallbackId,
};
}
/**
* Returns an action object used to set the template for a given query.
*
* @param {Object} query The lookup query.
* @param {string} templateId The resolved template id.
*
* @return {Object} Action object.
*/
export function receiveDefaultTemplateId( query, templateId ) {
return {
type: 'RECEIVE_DEFAULT_TEMPLATE',
query,
templateId,
};
}
/**
* Action triggered to receive revision items.
*
* @param {string} kind Kind of the received entity record revisions.
* @param {string} name Name of the received entity record revisions.
* @param {number|string} recordKey The key of the entity record whose revisions you want to fetch.
* @param {Array|Object} records Revisions received.
* @param {?Object} query Query Object.
* @param {?boolean} invalidateCache Should invalidate query caches.
* @param {?Object} meta Meta information about pagination.
*/
export const receiveRevisions =
( kind, name, recordKey, records, query, invalidateCache = false, meta ) =>
async ( { dispatch } ) => {
const configs = await dispatch( getOrLoadEntitiesConfig( kind ) );
const entityConfig = configs.find(
( config ) => config.kind === kind && config.name === name
);
const key =
entityConfig && entityConfig?.revisionKey
? entityConfig.revisionKey
: DEFAULT_ENTITY_KEY;
dispatch( {
type: 'RECEIVE_ITEM_REVISIONS',
key,
items: Array.isArray( records ) ? records : [ records ],
recordKey,
meta,
query,
kind,
name,
invalidateCache,
} );
};