-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
posts.js
318 lines (284 loc) · 9.24 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
/**
* External dependencies
*/
import { BEGIN, COMMIT, REVERT } from 'redux-optimist';
import { get, pick, includes } from 'lodash';
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
// TODO: Ideally this would be the only dispatch in scope. This requires either
// refactoring editor actions to yielded controls, or replacing direct dispatch
// on the editor store with action creators (e.g. `REQUEST_POST_UPDATE_START`).
import { dispatch as dataDispatch } from '@wordpress/data';
/**
* Internal dependencies
*/
import {
resetAutosave,
resetPost,
updatePost,
} from '../actions';
import {
getCurrentPost,
getPostEdits,
getEditedPostContent,
getAutosave,
getCurrentPostType,
isEditedPostSaveable,
isEditedPostNew,
POST_UPDATE_TRANSACTION_ID,
} from '../selectors';
import { resolveSelector } from './utils';
/**
* Module Constants
*/
export const SAVE_POST_NOTICE_ID = 'SAVE_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.isAutosave;
// Prevent save if not saveable.
// We don't check for dirtiness here as this can be overriden in the UI.
if ( ! isEditedPostSaveable( 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 },
options: action.options,
} );
// 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,
};
request = apiFetch( {
path: `/wp/v2/${ postType.rest_base }/${ post.id }/autosaves`,
method: 'POST',
data: toSend,
} );
} else {
dataDispatch( 'core/notices' ).removeNotice( SAVE_POST_NOTICE_ID );
dataDispatch( 'core/notices' ).removeNotice( 'autosave-exists' );
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,
},
options: action.options,
postType,
} );
} catch ( error ) {
dispatch( {
type: 'REQUEST_POST_UPDATE_FAILURE',
optimist: { type: REVERT, id: POST_UPDATE_TRANSACTION_ID },
post,
edits,
error,
options: action.options,
} );
}
};
/**
* Request Post Update Success Effect handler
*
* @param {Object} action action object.
* @param {Object} store Redux Store.
*/
export const requestPostUpdateSuccess = ( action ) => {
const { previousPost, post, postType } = action;
// Autosaves are neither shown a notice nor redirected.
if ( get( action.options, [ 'isAutosave' ] ) ) {
return;
}
const publishStatus = [ 'publish', 'private', 'future' ];
const isPublished = includes( publishStatus, previousPost.status );
const willPublish = includes( publishStatus, post.status );
let noticeMessage;
let shouldShowLink = get( postType, [ 'viewable' ], false );
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 = postType.labels.item_reverted_to_draft;
shouldShowLink = false;
} else if ( ! isPublished && willPublish ) {
// If publishing or scheduling a post, show the corresponding
// publish message
noticeMessage = {
publish: postType.labels.item_published,
private: postType.labels.item_published_privately,
future: postType.labels.item_scheduled,
}[ post.status ];
} else {
// Generic fallback notice
noticeMessage = postType.labels.item_updated;
}
if ( noticeMessage ) {
const actions = [];
if ( shouldShowLink ) {
actions.push( {
label: postType.labels.view_item,
url: post.link,
} );
}
dataDispatch( 'core/notices' ).createSuccessNotice(
noticeMessage,
{
id: SAVE_POST_NOTICE_ID,
actions,
}
);
}
};
/**
* Request Post Update Failure Effect handler
*
* @param {Object} action action object.
*/
export const requestPostUpdateFailure = ( action ) => {
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 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' );
dataDispatch( 'core/notices' ).createErrorNotice( noticeMessage, {
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 );
dataDispatch( 'core/notices' ).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 ) => {
const message = action.error.message && action.error.code !== 'unknown_error' ? action.error.message : __( 'Trashing failed' );
dataDispatch( 'core/notices' ).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( {
// Timestamp arg allows caller to bypass browser caching, which is expected for this specific function.
path: `/wp/v2/${ postType.rest_base }/${ post.id }?context=edit&_timestamp=${ Date.now() }`,
} );
dispatch( resetPost( newPost ) );
};