-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathposts.js
341 lines (303 loc) · 9.65 KB
/
posts.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
/**
* External dependencies
*/
import { BEGIN, COMMIT, REVERT } from 'redux-optimist';
import { pick, includes } from 'lodash';
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
/**
* Internal dependencies
*/
import {
resetAutosave,
resetPost,
updatePost,
removeNotice,
createSuccessNotice,
createErrorNotice,
} from '../actions';
import {
getCurrentPost,
getPostEdits,
getEditedPostContent,
getAutosave,
getCurrentPostType,
isEditedPostAutosaveable,
isEditedPostSaveable,
isEditedPostNew,
POST_UPDATE_TRANSACTION_ID,
} from '../selectors';
import { resolveSelector } from './utils';
/**
* Module Constants
*/
const SAVE_POST_NOTICE_ID = 'SAVE_POST_NOTICE_ID';
export const AUTOSAVE_POST_NOTICE_ID = 'AUTOSAVE_POST_NOTICE_ID';
const TRASH_POST_NOTICE_ID = 'TRASH_POST_NOTICE_ID';
/**
* Request Post Update Effect handler
*
* @param {Object} action the fetchReusableBlocks action object.
* @param {Object} store Redux Store.
*/
export const requestPostUpdate = async ( action, store ) => {
const { dispatch, getState } = store;
const state = getState();
const post = getCurrentPost( state );
const isAutosave = !! action.options.autosave;
// Prevent save if not saveable.
const isSaveable = isAutosave ? isEditedPostAutosaveable : isEditedPostSaveable;
if ( ! isSaveable( state ) ) {
return;
}
let edits = getPostEdits( state );
if ( isAutosave ) {
edits = pick( edits, [ 'title', 'content', 'excerpt' ] );
}
// New posts (with auto-draft status) must be explicitly assigned draft
// status if there is not already a status assigned in edits (publish).
// Otherwise, they are wrongly left as auto-draft. Status is not always
// respected for autosaves, so it cannot simply be included in the pick
// above. This behavior relies on an assumption that an auto-draft post
// would never be saved by anyone other than the owner of the post, per
// logic within autosaves REST controller to save status field only for
// draft/auto-draft by current user.
//
// See: https://core.trac.wordpress.org/ticket/43316#comment:88
// See: https://core.trac.wordpress.org/ticket/43316#comment:89
if ( isEditedPostNew( state ) ) {
edits = { status: 'draft', ...edits };
}
let toSend = {
...edits,
content: getEditedPostContent( state ),
id: post.id,
};
const postType = await resolveSelector( 'core', 'getPostType', getCurrentPostType( state ) );
dispatch( {
type: 'REQUEST_POST_UPDATE_START',
optimist: { type: BEGIN, id: POST_UPDATE_TRANSACTION_ID },
isAutosave,
} );
// Optimistically apply updates under the assumption that the post
// will be updated. See below logic in success resolution for revert
// if the autosave is applied as a revision.
dispatch( {
...updatePost( toSend ),
optimist: { id: POST_UPDATE_TRANSACTION_ID },
} );
let request;
if ( isAutosave ) {
// Ensure autosaves contain all expected fields, using autosave or
// post values as fallback if not otherwise included in edits.
toSend = {
...pick( post, [ 'title', 'content', 'excerpt' ] ),
...getAutosave( state ),
...toSend,
parent: post.id,
};
request = apiFetch( {
path: `/wp/v2/${ postType.rest_base }/${ post.id }/autosaves`,
method: 'POST',
data: toSend,
} );
} else {
dispatch( removeNotice( SAVE_POST_NOTICE_ID ) );
dispatch( removeNotice( AUTOSAVE_POST_NOTICE_ID ) );
request = apiFetch( {
path: `/wp/v2/${ postType.rest_base }/${ post.id }`,
method: 'PUT',
data: toSend,
} );
}
try {
const newPost = await request;
const reset = isAutosave ? resetAutosave : resetPost;
dispatch( reset( newPost ) );
// An autosave may be processed by the server as a regular save
// when its update is requested by the author and the post was
// draft or auto-draft.
const isRevision = newPost.id !== post.id;
dispatch( {
type: 'REQUEST_POST_UPDATE_SUCCESS',
previousPost: post,
post: newPost,
optimist: {
// Note: REVERT is not a failure case here. Rather, it
// is simply reversing the assumption that the updates
// were applied to the post proper, such that the post
// treated as having unsaved changes.
type: isRevision ? REVERT : COMMIT,
id: POST_UPDATE_TRANSACTION_ID,
},
isAutosave,
} );
} catch ( error ) {
dispatch( {
type: 'REQUEST_POST_UPDATE_FAILURE',
optimist: { type: REVERT, id: POST_UPDATE_TRANSACTION_ID },
post,
edits,
error,
} );
}
};
/**
* Request Post Update Success Effect handler
*
* @param {Object} action action object.
* @param {Object} store Redux Store.
*/
export const requestPostUpdateSuccess = ( action, store ) => {
const { previousPost, post, isAutosave } = action;
const { dispatch, getState } = store;
// TEMPORARY: If edits remain after a save completes, the user must be
// prompted about unsaved changes. This should be refactored as part of
// the `isEditedPostDirty` selector instead.
//
// See: https://github.com/WordPress/gutenberg/issues/7409
if ( Object.keys( getPostEdits( getState() ) ).length ) {
dispatch( { type: 'DIRTY_ARTIFICIALLY' } );
}
// Autosaves are neither shown a notice nor redirected.
if ( isAutosave ) {
return;
}
const publishStatus = [ 'publish', 'private', 'future' ];
const isPublished = includes( publishStatus, previousPost.status );
const willPublish = includes( publishStatus, post.status );
let noticeMessage;
let shouldShowLink = true;
if ( ! isPublished && ! willPublish ) {
// If saving a non-published post, don't show notice.
noticeMessage = null;
} else if ( isPublished && ! willPublish ) {
// If undoing publish status, show specific notice
noticeMessage = __( 'Post reverted to draft.' );
shouldShowLink = false;
} else if ( ! isPublished && willPublish ) {
// If publishing or scheduling a post, show the corresponding
// publish message
noticeMessage = {
publish: __( 'Post published!' ),
private: __( 'Post published privately!' ),
future: __( 'Post scheduled!' ),
}[ post.status ];
} else {
// Generic fallback notice
noticeMessage = __( 'Post updated!' );
}
if ( noticeMessage ) {
dispatch( createSuccessNotice(
<p>
{ noticeMessage }
{ ' ' }
{ shouldShowLink && <a href={ post.link }>{ __( 'View post' ) }</a> }
</p>,
{ id: SAVE_POST_NOTICE_ID, spokenMessage: noticeMessage }
) );
}
};
/**
* Request Post Update Failure Effect handler
*
* @param {Object} action action object.
* @param {Object} store Redux Store.
*/
export const requestPostUpdateFailure = ( action, store ) => {
const { post, edits, error } = action;
if ( error && 'rest_autosave_no_changes' === error.code ) {
// Autosave requested a new autosave, but there were no changes. This shouldn't
// result in an error notice for the user.
return;
}
const { dispatch } = store;
const publishStatus = [ 'publish', 'private', 'future' ];
const isPublished = publishStatus.indexOf( post.status ) !== -1;
// If the post was being published, we show the corresponding publish error message
// Unless we publish an "updating failed" message
const messages = {
publish: __( 'Publishing failed' ),
private: __( 'Publishing failed' ),
future: __( 'Scheduling failed' ),
};
const noticeMessage = ! isPublished && publishStatus.indexOf( edits.status ) !== -1 ?
messages[ edits.status ] :
__( 'Updating failed' );
const cloudflareDetailsLink = addQueryArgs(
'post.php',
{
post: post.id,
action: 'edit',
'classic-editor': '',
'cloudflare-error': '',
} );
const cloudflaredMessage = error && 'cloudflare_error' === error.code ?
<p>
{ noticeMessage }
<br />
{ __( 'Cloudflare is blocking REST API requests.' ) }
{ ' ' }
<a href={ cloudflareDetailsLink }>{ __( 'Learn More' ) } </a>
</p> :
noticeMessage;
dispatch( createErrorNotice( cloudflaredMessage, { id: SAVE_POST_NOTICE_ID } ) );
};
/**
* Trash Post Effect handler
*
* @param {Object} action action object.
* @param {Object} store Redux Store.
*/
export const trashPost = async ( action, store ) => {
const { dispatch, getState } = store;
const { postId } = action;
const postTypeSlug = getCurrentPostType( getState() );
const postType = await resolveSelector( 'core', 'getPostType', postTypeSlug );
dispatch( removeNotice( TRASH_POST_NOTICE_ID ) );
try {
await apiFetch( { path: `/wp/v2/${ postType.rest_base }/${ postId }`, method: 'DELETE' } );
const post = getCurrentPost( getState() );
// TODO: This should be an updatePost action (updating subsets of post properties),
// But right now editPost is tied with change detection.
dispatch( resetPost( { ...post, status: 'trash' } ) );
} catch ( error ) {
dispatch( {
...action,
type: 'TRASH_POST_FAILURE',
error,
} );
}
};
/**
* Trash Post Failure Effect handler
*
* @param {Object} action action object.
* @param {Object} store Redux Store.
*/
export const trashPostFailure = ( action, store ) => {
const message = action.error.message && action.error.code !== 'unknown_error' ? action.error.message : __( 'Trashing failed' );
store.dispatch( createErrorNotice( message, { id: TRASH_POST_NOTICE_ID } ) );
};
/**
* Refresh Post Effect handler
*
* @param {Object} action action object.
* @param {Object} store Redux Store.
*/
export const refreshPost = async ( action, store ) => {
const { dispatch, getState } = store;
const state = getState();
const post = getCurrentPost( state );
const postTypeSlug = getCurrentPostType( getState() );
const postType = await resolveSelector( 'core', 'getPostType', postTypeSlug );
const newPost = await apiFetch( {
path: `/wp/v2/${ postType.rest_base }/${ post.id }`,
data: { context: 'edit' },
} );
dispatch( resetPost( newPost ) );
};