-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathactions.js
774 lines (740 loc) · 18.9 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
/**
* External dependencies
*/
import { castArray, get, isEqual, find } from 'lodash';
import { v4 as uuid } from 'uuid';
/**
* WordPress dependencies
*/
import { controls } from '@wordpress/data';
import { apiFetch, __unstableAwaitPromise } from '@wordpress/data-controls';
import { addQueryArgs } from '@wordpress/url';
/**
* Internal dependencies
*/
import { receiveItems, removeItems, receiveQueriedItems } from './queried-data';
import { getKindEntities, DEFAULT_ENTITY_KEY } from './entities';
import {
__unstableAcquireStoreLock,
__unstableReleaseStoreLock,
} from './locks';
import { createBatch } from './batch';
import { getDispatch } from './controls';
import { STORE_NAME } from './name';
/**
* Returns an action object used in signalling that authors have been received.
*
* @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: castArray( users ),
queryID,
};
}
/**
* Returns an action used in signalling that the current user has been received.
*
* @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.
* @param {string} name Name of the received entity.
* @param {Array|Object} records Records received.
* @param {?Object} query Query Object.
* @param {?boolean} invalidateCache Should invalidate query caches.
* @param {?Object} edits Edits to reset.
* @return {Object} Action object.
*/
export function receiveEntityRecords(
kind,
name,
records,
query,
invalidateCache = false,
edits
) {
// 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 = castArray( records ).map( ( record ) =>
record.status === 'auto-draft' ? { ...record, title: '' } : record
);
}
let action;
if ( query ) {
action = receiveQueriedItems( records, query, edits );
} else {
action = receiveItems( records, edits );
}
return {
...action,
kind,
name,
invalidateCache,
};
}
/**
* Returns an action object used in signalling that the current theme has been received.
*
* @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 index has been received.
*
* @param {Object} themeSupports Theme support for the current theme.
*
* @return {Object} Action object.
*/
export function receiveThemeSupports( themeSupports ) {
return {
type: 'RECEIVE_THEME_SUPPORTS',
themeSupports,
};
}
/**
* Returns an action object used in signalling that the preview data for
* a given URl has been received.
*
* @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 control descriptor.
*/
export function* deleteEntityRecord(
kind,
name,
recordId,
query,
{ __unstableFetch = null } = {}
) {
const entities = yield getKindEntities( kind );
const entity = find( entities, { kind, name } );
let error;
let deletedRecord = false;
if ( ! entity ) {
return;
}
const lock = yield* __unstableAcquireStoreLock(
STORE_NAME,
[ 'entities', 'data', kind, name, recordId ],
{ exclusive: true }
);
try {
yield {
type: 'DELETE_ENTITY_RECORD_START',
kind,
name,
recordId,
};
try {
let path = `${ entity.baseURL }/${ recordId }`;
if ( query ) {
path = addQueryArgs( path, query );
}
const options = {
path,
method: 'DELETE',
};
if ( __unstableFetch ) {
deletedRecord = yield __unstableAwaitPromise(
__unstableFetch( options )
);
} else {
deletedRecord = yield apiFetch( options );
}
yield removeItems( kind, name, recordId, true );
} catch ( _error ) {
error = _error;
}
yield {
type: 'DELETE_ENTITY_RECORD_FINISH',
kind,
name,
recordId,
error,
};
return deletedRecord;
} finally {
yield* __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} 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 function* editEntityRecord( kind, name, recordId, edits, options = {} ) {
const entity = yield controls.select( STORE_NAME, 'getEntity', kind, name );
if ( ! entity ) {
throw new Error(
`The entity being edited (${ kind }, ${ name }) does not have a loaded config.`
);
}
const { transientEdits = {}, mergedEdits = {} } = entity;
const record = yield controls.select(
STORE_NAME,
'getRawEntityRecord',
kind,
name,
recordId
);
const editedRecord = yield controls.select(
STORE_NAME,
'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 ] = isEqual( recordValue, value ) ? undefined : value;
return acc;
}, {} ),
transientEdits,
};
return {
type: 'EDIT_ENTITY_RECORD',
...edit,
meta: {
undo: ! options.undoIgnore && {
...edit,
// Send the current values for things like the first undo stack entry.
edits: Object.keys( edits ).reduce( ( acc, key ) => {
acc[ key ] = editedRecord[ key ];
return acc;
}, {} ),
},
},
};
}
/**
* Action triggered to undo the last edit to
* an entity record, if any.
*/
export function* undo() {
const undoEdit = yield controls.select( STORE_NAME, 'getUndoEdit' );
if ( ! undoEdit ) {
return;
}
yield {
type: 'EDIT_ENTITY_RECORD',
...undoEdit,
meta: {
isUndo: true,
},
};
}
/**
* Action triggered to redo the last undoed
* edit to an entity record, if any.
*/
export function* redo() {
const redoEdit = yield controls.select( STORE_NAME, 'getRedoEdit' );
if ( ! redoEdit ) {
return;
}
yield {
type: 'EDIT_ENTITY_RECORD',
...redoEdit,
meta: {
isRedo: true,
},
};
}
/**
* Forces the creation of a new undo level.
*
* @return {Object} Action object.
*/
export function __unstableCreateUndoLevel() {
return { type: 'CREATE_UNDO_LEVEL' };
}
/**
* 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 control
* descriptor.
*/
export function* saveEntityRecord(
kind,
name,
record,
{ isAutosave = false, __unstableFetch = null } = {}
) {
const entities = yield getKindEntities( kind );
const entity = find( entities, { kind, name } );
if ( ! entity ) {
return;
}
const entityIdKey = entity.key || DEFAULT_ENTITY_KEY;
const recordId = record[ entityIdKey ];
const lock = yield* __unstableAcquireStoreLock(
STORE_NAME,
[ 'entities', 'data', 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(
yield controls.select(
STORE_NAME,
'getEditedEntityRecord',
kind,
name,
recordId
)
);
yield editEntityRecord(
kind,
name,
recordId,
{
[ key ]: evaluatedValue,
},
{ undoIgnore: true }
);
record[ key ] = evaluatedValue;
}
}
yield {
type: 'SAVE_ENTITY_RECORD_START',
kind,
name,
recordId,
isAutosave,
};
let updatedRecord;
let error;
try {
const path = `${ entity.baseURL }${
recordId ? '/' + recordId : ''
}`;
const persistedRecord = yield controls.select(
STORE_NAME,
'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 = yield controls.select(
STORE_NAME,
'getCurrentUser'
);
const currentUserId = currentUser ? currentUser.id : undefined;
const autosavePost = yield controls.select(
STORE_NAME,
'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' ].includes( key )
) {
// Edits should be the "raw" attribute values.
acc[ key ] = get( data[ key ], 'raw', data[ key ] );
}
return acc;
},
{
status:
data.status === 'auto-draft'
? 'draft'
: data.status,
}
);
const options = {
path: `${ path }/autosaves`,
method: 'POST',
data,
};
if ( __unstableFetch ) {
updatedRecord = yield __unstableAwaitPromise(
__unstableFetch( options )
);
} else {
updatedRecord = yield apiFetch( options );
}
// 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
)
) {
// Edits should be the "raw" attribute values.
acc[ key ] = get(
newRecord[ key ],
'raw',
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 ] = get(
persistedRecord[ key ],
'raw',
persistedRecord[ key ]
);
}
return acc;
},
{}
);
yield receiveEntityRecords(
kind,
name,
newRecord,
undefined,
true
);
} else {
yield receiveAutosaves( persistedRecord.id, updatedRecord );
}
} else {
let edits = record;
if ( entity.__unstablePrePersist ) {
edits = {
...edits,
...entity.__unstablePrePersist(
persistedRecord,
edits
),
};
}
const options = {
path,
method: recordId ? 'PUT' : 'POST',
data: edits,
};
if ( __unstableFetch ) {
updatedRecord = yield __unstableAwaitPromise(
__unstableFetch( options )
);
} else {
updatedRecord = yield apiFetch( options );
}
yield receiveEntityRecords(
kind,
name,
updatedRecord,
undefined,
true,
edits
);
}
} catch ( _error ) {
error = _error;
}
yield {
type: 'SAVE_ENTITY_RECORD_FINISH',
kind,
name,
recordId,
error,
isAutosave,
};
return updatedRecord;
} finally {
yield* __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 {Promise} A promise that resolves to an array containing the return
* values of each function given in `requests`.
*/
export function* __experimentalBatch( requests ) {
const batch = createBatch();
const dispatch = yield getDispatch();
const api = {
saveEntityRecord( kind, name, record, options ) {
return batch.add( ( add ) =>
dispatch( STORE_NAME ).saveEntityRecord( kind, name, record, {
...options,
__unstableFetch: add,
} )
);
},
saveEditedEntityRecord( kind, name, recordId, options ) {
return batch.add( ( add ) =>
dispatch( STORE_NAME ).saveEditedEntityRecord(
kind,
name,
recordId,
{
...options,
__unstableFetch: add,
}
)
);
},
deleteEntityRecord( kind, name, recordId, query, options ) {
return batch.add( ( add ) =>
dispatch( STORE_NAME ).deleteEntityRecord(
kind,
name,
recordId,
query,
{
...options,
__unstableFetch: add,
}
)
);
},
};
const resultPromises = requests.map( ( request ) => request( api ) );
const [ , ...results ] = yield __unstableAwaitPromise(
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 function* saveEditedEntityRecord( kind, name, recordId, options ) {
if (
! ( yield controls.select(
STORE_NAME,
'hasEditsForEntityRecord',
kind,
name,
recordId
) )
) {
return;
}
const edits = yield controls.select(
STORE_NAME,
'getEntityRecordNonTransientEdits',
kind,
name,
recordId
);
const record = { id: recordId, ...edits };
return yield* 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 to save.
* @param {Object} options Saving options.
*/
export function* __experimentalSaveSpecifiedEntityEdits(
kind,
name,
recordId,
itemsToSave,
options
) {
if (
! ( yield controls.select(
STORE_NAME,
'hasEditsForEntityRecord',
kind,
name,
recordId
) )
) {
return;
}
const edits = yield controls.select(
STORE_NAME,
'getEntityRecordNonTransientEdits',
kind,
name,
recordId
);
const editsToSave = {};
for ( const edit in edits ) {
if ( itemsToSave.some( ( item ) => item === edit ) ) {
editsToSave[ edit ] = edits[ edit ];
}
}
return yield* saveEntityRecord( kind, name, editsToSave, options );
}
/**
* Returns an action object used in signalling that Upload permissions have been received.
*
* @param {boolean} hasUploadPermissions Does the user have permission to upload files?
*
* @return {Object} Action object.
*/
export function receiveUploadPermissions( hasUploadPermissions ) {
return {
type: 'RECEIVE_USER_PERMISSION',
key: 'create/media',
isAllowed: hasUploadPermissions,
};
}
/**
* Returns an action object used in signalling that the current user has
* permission to perform an action on a REST resource.
*
* @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.
*
* @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: castArray( autosaves ),
};
}