-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
entries.ts
661 lines (595 loc) · 19.5 KB
/
entries.ts
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
import { fromJS, List, Map, Set } from 'immutable';
import { isEqual } from 'lodash';
import { actions as notifActions } from 'redux-notifications';
import { serializeValues } from '../lib/serializeEntryValues';
import { currentBackend, Backend } from '../backend';
import { getIntegrationProvider } from '../integrations';
import { selectIntegration, selectPublishedSlugs } from '../reducers';
import { selectFields } from '../reducers/collections';
import { selectCollectionEntriesCursor } from '../reducers/cursors';
import { Cursor } from 'netlify-cms-lib-util';
import { createEntry, EntryValue } from '../valueObjects/Entry';
import AssetProxy, { createAssetProxy } from '../valueObjects/AssetProxy';
import ValidationErrorTypes from '../constants/validationErrorTypes';
import { addAssets, getAsset } from './media';
import {
Collection,
EntryMap,
MediaFile,
State,
EntryFields,
EntryField,
MediaFileMap,
} from '../types/redux';
import { ThunkDispatch } from 'redux-thunk';
import { AnyAction, Dispatch } from 'redux';
import { waitForMediaLibraryToLoad } from './mediaLibrary';
const { notifSend } = notifActions;
/*
* Constant Declarations
*/
export const ENTRY_REQUEST = 'ENTRY_REQUEST';
export const ENTRY_SUCCESS = 'ENTRY_SUCCESS';
export const ENTRY_FAILURE = 'ENTRY_FAILURE';
export const ENTRIES_REQUEST = 'ENTRIES_REQUEST';
export const ENTRIES_SUCCESS = 'ENTRIES_SUCCESS';
export const ENTRIES_FAILURE = 'ENTRIES_FAILURE';
export const DRAFT_CREATE_FROM_ENTRY = 'DRAFT_CREATE_FROM_ENTRY';
export const DRAFT_CREATE_EMPTY = 'DRAFT_CREATE_EMPTY';
export const DRAFT_DISCARD = 'DRAFT_DISCARD';
export const DRAFT_CHANGE_FIELD = 'DRAFT_CHANGE_FIELD';
export const DRAFT_VALIDATION_ERRORS = 'DRAFT_VALIDATION_ERRORS';
export const DRAFT_CLEAR_ERRORS = 'DRAFT_CLEAR_ERRORS';
export const DRAFT_LOCAL_BACKUP_RETRIEVED = 'DRAFT_LOCAL_BACKUP_RETRIEVED';
export const DRAFT_CREATE_FROM_LOCAL_BACKUP = 'DRAFT_CREATE_FROM_LOCAL_BACKUP';
export const DRAFT_CREATE_DUPLICATE_FROM_ENTRY = 'DRAFT_CREATE_DUPLICATE_FROM_ENTRY';
export const ENTRY_PERSIST_REQUEST = 'ENTRY_PERSIST_REQUEST';
export const ENTRY_PERSIST_SUCCESS = 'ENTRY_PERSIST_SUCCESS';
export const ENTRY_PERSIST_FAILURE = 'ENTRY_PERSIST_FAILURE';
export const ENTRY_DELETE_REQUEST = 'ENTRY_DELETE_REQUEST';
export const ENTRY_DELETE_SUCCESS = 'ENTRY_DELETE_SUCCESS';
export const ENTRY_DELETE_FAILURE = 'ENTRY_DELETE_FAILURE';
export const ADD_DRAFT_ENTRY_MEDIA_FILE = 'ADD_DRAFT_ENTRY_MEDIA_FILE';
export const REMOVE_DRAFT_ENTRY_MEDIA_FILE = 'REMOVE_DRAFT_ENTRY_MEDIA_FILE';
/*
* Simple Action Creators (Internal)
* We still need to export them for tests
*/
export function entryLoading(collection: Collection, slug: string) {
return {
type: ENTRY_REQUEST,
payload: {
collection: collection.get('name'),
slug,
},
};
}
export function entryLoaded(collection: Collection, entry: EntryValue) {
return {
type: ENTRY_SUCCESS,
payload: {
collection: collection.get('name'),
entry,
},
};
}
export function entryLoadError(error: Error, collection: Collection, slug: string) {
return {
type: ENTRY_FAILURE,
payload: {
error,
collection: collection.get('name'),
slug,
},
};
}
export function entriesLoading(collection: Collection) {
return {
type: ENTRIES_REQUEST,
payload: {
collection: collection.get('name'),
},
};
}
export function entriesLoaded(
collection: Collection,
entries: EntryValue[],
pagination: number | null,
cursor: typeof Cursor,
append = true,
) {
return {
type: ENTRIES_SUCCESS,
payload: {
collection: collection.get('name'),
entries,
page: pagination,
cursor: Cursor.create(cursor),
append,
},
};
}
export function entriesFailed(collection: Collection, error: Error) {
return {
type: ENTRIES_FAILURE,
error: 'Failed to load entries',
payload: error.toString(),
meta: { collection: collection.get('name') },
};
}
export function entryPersisting(collection: Collection, entry: EntryMap) {
return {
type: ENTRY_PERSIST_REQUEST,
payload: {
collectionName: collection.get('name'),
entrySlug: entry.get('slug'),
},
};
}
export function entryPersisted(collection: Collection, entry: EntryMap, slug: string) {
return {
type: ENTRY_PERSIST_SUCCESS,
payload: {
collectionName: collection.get('name'),
entrySlug: entry.get('slug'),
/**
* Pass slug from backend for newly created entries.
*/
slug,
},
};
}
export function entryPersistFail(collection: Collection, entry: EntryMap, error: Error) {
return {
type: ENTRY_PERSIST_FAILURE,
error: 'Failed to persist entry',
payload: {
collectionName: collection.get('name'),
entrySlug: entry.get('slug'),
error: error.toString(),
},
};
}
export function entryDeleting(collection: Collection, slug: string) {
return {
type: ENTRY_DELETE_REQUEST,
payload: {
collectionName: collection.get('name'),
entrySlug: slug,
},
};
}
export function entryDeleted(collection: Collection, slug: string) {
return {
type: ENTRY_DELETE_SUCCESS,
payload: {
collectionName: collection.get('name'),
entrySlug: slug,
},
};
}
export function entryDeleteFail(collection: Collection, slug: string, error: Error) {
return {
type: ENTRY_DELETE_FAILURE,
payload: {
collectionName: collection.get('name'),
entrySlug: slug,
error: error.toString(),
},
};
}
export function emptyDraftCreated(entry: EntryValue) {
return {
type: DRAFT_CREATE_EMPTY,
payload: entry,
};
}
/*
* Exported simple Action Creators
*/
export function createDraftFromEntry(entry: EntryMap, metadata?: Map<string, unknown>) {
return {
type: DRAFT_CREATE_FROM_ENTRY,
payload: { entry, metadata },
};
}
export function createDraftDuplicateFromEntry(entry: EntryMap) {
return {
type: DRAFT_CREATE_DUPLICATE_FROM_ENTRY,
payload: createEntry(entry.get('collection'), '', '', { data: entry.get('data') }),
};
}
export function discardDraft() {
return { type: DRAFT_DISCARD };
}
export function changeDraftField(field: string, value: string, metadata: Record<string, unknown>) {
return {
type: DRAFT_CHANGE_FIELD,
payload: { field, value, metadata },
};
}
export function changeDraftFieldValidation(
uniquefieldId: string,
errors: { type: string; message: string }[],
) {
return {
type: DRAFT_VALIDATION_ERRORS,
payload: { uniquefieldId, errors },
};
}
export function clearFieldErrors() {
return { type: DRAFT_CLEAR_ERRORS };
}
export function localBackupRetrieved(entry: EntryValue) {
return {
type: DRAFT_LOCAL_BACKUP_RETRIEVED,
payload: { entry },
};
}
export function loadLocalBackup() {
return {
type: DRAFT_CREATE_FROM_LOCAL_BACKUP,
};
}
export function addDraftEntryMediaFile(file: MediaFile) {
return { type: ADD_DRAFT_ENTRY_MEDIA_FILE, payload: file };
}
export function removeDraftEntryMediaFile({ id }: { id: string }) {
return { type: REMOVE_DRAFT_ENTRY_MEDIA_FILE, payload: { id } };
}
export function persistLocalBackup(entry: EntryMap, collection: Collection) {
return (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const backend = currentBackend(state.config);
return backend.persistLocalDraftBackup(entry, collection);
};
}
export function retrieveLocalBackup(collection: Collection, slug: string) {
return async (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const backend = currentBackend(state.config);
const { entry } = await backend.getLocalDraftBackup(collection, slug);
if (entry) {
// load assets from backup
const mediaFiles = entry.mediaFiles || [];
const assetProxies: AssetProxy[] = mediaFiles.map(file =>
createAssetProxy({ path: file.path, file: file.file, url: file.url }),
);
dispatch(addAssets(assetProxies));
return dispatch(localBackupRetrieved(entry));
}
};
}
export function deleteLocalBackup(collection: Collection, slug: string) {
return (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const backend = currentBackend(state.config);
return backend.deleteLocalDraftBackup(collection, slug);
};
}
/*
* Exported Thunk Action Creators
*/
export function loadEntry(collection: Collection, slug: string) {
return (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const backend = currentBackend(state.config);
dispatch(entryLoading(collection, slug));
return backend
.getEntry(state, collection, slug)
.then((loadedEntry: EntryValue) => {
return dispatch(entryLoaded(collection, loadedEntry));
})
.catch((error: Error) => {
console.error(error);
dispatch(
notifSend({
message: {
details: error.message,
key: 'ui.toast.onFailToLoadEntries',
},
kind: 'danger',
dismissAfter: 8000,
}),
);
dispatch(entryLoadError(error, collection, slug));
});
};
}
const appendActions = fromJS({
['append_next']: { action: 'next', append: true },
});
const addAppendActionsToCursor = (cursor: typeof Cursor) => {
return Cursor.create(cursor).updateStore('actions', (actions: Set<string>) => {
return actions.union(
appendActions
.filter((v: Map<string, string | boolean>) => actions.has(v.get('action') as string))
.keySeq(),
);
});
};
export function loadEntries(collection: Collection, page = 0) {
return (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
if (collection.get('isFetching')) {
return;
}
const state = getState();
const backend = currentBackend(state.config);
const integration = selectIntegration(state, collection.get('name'), 'listEntries');
const provider = integration
? getIntegrationProvider(state.integrations, backend.getToken, integration)
: backend;
const append = !!(page && !isNaN(page) && page > 0);
dispatch(entriesLoading(collection));
provider
.listEntries(collection, page)
.then((response: { cursor: typeof Cursor }) => ({
...response,
// The only existing backend using the pagination system is the
// Algolia integration, which is also the only integration used
// to list entries. Thus, this checking for an integration can
// determine whether or not this is using the old integer-based
// pagination API. Other backends will simply store an empty
// cursor, which behaves identically to no cursor at all.
cursor: integration
? Cursor.create({
actions: ['next'],
meta: { usingOldPaginationAPI: true },
data: { nextPage: page + 1 },
})
: Cursor.create(response.cursor),
}))
.then((response: { cursor: typeof Cursor; pagination: number; entries: EntryValue[] }) =>
dispatch(
entriesLoaded(
collection,
response.cursor.meta.get('usingOldPaginationAPI')
? response.entries.reverse()
: response.entries,
response.pagination,
addAppendActionsToCursor(response.cursor),
append,
),
),
)
.catch((err: Error) => {
dispatch(
notifSend({
message: {
details: err,
key: 'ui.toast.onFailToLoadEntries',
},
kind: 'danger',
dismissAfter: 8000,
}),
);
return Promise.reject(dispatch(entriesFailed(collection, err)));
});
};
}
function traverseCursor(backend: Backend, cursor: typeof Cursor, action: string) {
if (!cursor.actions.has(action)) {
throw new Error(`The current cursor does not support the pagination action "${action}".`);
}
return backend.traverseCursor(cursor, action);
}
export function traverseCollectionCursor(collection: Collection, action: string) {
return async (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const collectionName = collection.get('name');
if (state.entries.getIn(['pages', `${collectionName}`, 'isFetching'])) {
return;
}
const backend = currentBackend(state.config);
const { action: realAction, append } = appendActions.has(action)
? appendActions.get(action).toJS()
: { action, append: false };
const cursor = selectCollectionEntriesCursor(state.cursors, collection.get('name'));
// Handle cursors representing pages in the old, integer-based
// pagination API
if (cursor.meta.get('usingOldPaginationAPI', false)) {
return dispatch(loadEntries(collection, cursor.data.get('nextPage')));
}
try {
dispatch(entriesLoading(collection));
const { entries, cursor: newCursor } = await traverseCursor(backend, cursor, realAction);
// Pass null for the old pagination argument - this will
// eventually be removed.
return dispatch(
entriesLoaded(collection, entries, null, addAppendActionsToCursor(newCursor), append),
);
} catch (err) {
console.error(err);
dispatch(
notifSend({
message: {
details: err,
key: 'ui.toast.onFailToPersist',
},
kind: 'danger',
dismissAfter: 8000,
}),
);
return Promise.reject(dispatch(entriesFailed(collection, err)));
}
};
}
export function createEmptyDraft(collection: Collection) {
return async (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const dataFields = createEmptyDraftData(collection.get('fields', List()));
let mediaFiles = [] as MediaFile[];
if (!collection.has('media_folder')) {
await waitForMediaLibraryToLoad(dispatch, getState());
mediaFiles = getState().mediaLibrary.get('files');
}
const newEntry = createEntry(collection.get('name'), '', '', { data: dataFields, mediaFiles });
dispatch(emptyDraftCreated(newEntry));
};
}
interface DraftEntryData {
[name: string]: string | null | DraftEntryData | DraftEntryData[] | (string | DraftEntryData)[];
}
export function createEmptyDraftData(fields: EntryFields, withNameKey = true) {
return fields.reduce(
(reduction: DraftEntryData | string | undefined, value: EntryField | undefined) => {
const acc = reduction as DraftEntryData;
const item = value as EntryField;
const subfields = item.get('field') || item.get('fields');
const list = item.get('widget') == 'list';
const name = item.get('name');
const defaultValue = item.get('default', null);
const isEmptyDefaultValue = (val: unknown) => [[{}], {}].some(e => isEqual(val, e));
if (List.isList(subfields)) {
const subDefaultValue = list
? [createEmptyDraftData(subfields as EntryFields)]
: createEmptyDraftData(subfields as EntryFields);
if (!isEmptyDefaultValue(subDefaultValue)) {
acc[name] = subDefaultValue;
}
return acc;
}
if (Map.isMap(subfields)) {
const subDefaultValue = list
? [createEmptyDraftData(List([subfields as EntryField]), false)]
: createEmptyDraftData(List([subfields as EntryField]));
if (!isEmptyDefaultValue(subDefaultValue)) {
acc[name] = subDefaultValue;
}
return acc;
}
if (defaultValue !== null) {
if (!withNameKey) {
return defaultValue;
}
acc[name] = defaultValue;
}
return acc;
},
{} as DraftEntryData,
);
}
export async function getMediaAssets({
getState,
mediaFiles,
dispatch,
collection,
entryPath,
}: {
getState: () => State;
mediaFiles: List<MediaFileMap>;
collection: Collection;
entryPath: string;
dispatch: Dispatch;
}) {
const filesArray = mediaFiles.toJS() as MediaFile[];
const assets = await Promise.all(
filesArray
.filter(file => file.draft)
.map(file => getAsset({ collection, entryPath, path: file.path })(dispatch, getState)),
);
return assets;
}
export function persistEntry(collection: Collection) {
return async (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const entryDraft = state.entryDraft;
const fieldsErrors = entryDraft.get('fieldsErrors');
const usedSlugs = selectPublishedSlugs(state, collection.get('name'));
// Early return if draft contains validation errors
if (!fieldsErrors.isEmpty()) {
const hasPresenceErrors = fieldsErrors.some(errors =>
errors.some(error => error.type && error.type === ValidationErrorTypes.PRESENCE),
);
if (hasPresenceErrors) {
dispatch(
notifSend({
message: {
key: 'ui.toast.missingRequiredField',
},
kind: 'danger',
dismissAfter: 8000,
}),
);
}
return Promise.reject();
}
const backend = currentBackend(state.config);
const entry = entryDraft.get('entry');
const assetProxies = await getMediaAssets({
getState,
mediaFiles: entry.get('mediaFiles'),
dispatch,
collection,
entryPath: entry.get('path'),
});
/**
* Serialize the values of any fields with registered serializers, and
* update the entry and entryDraft with the serialized values.
*/
const fields = selectFields(collection, entry.get('slug'));
const serializedData = serializeValues(entryDraft.getIn(['entry', 'data']), fields);
const serializedEntry = entry.set('data', serializedData);
const serializedEntryDraft = entryDraft.set('entry', serializedEntry);
dispatch(entryPersisting(collection, serializedEntry));
return backend
.persistEntry({
config: state.config,
collection,
entryDraft: serializedEntryDraft,
assetProxies,
usedSlugs,
})
.then((slug: string) => {
dispatch(
notifSend({
message: {
key: 'ui.toast.entrySaved',
},
kind: 'success',
dismissAfter: 4000,
}),
);
dispatch(entryPersisted(collection, serializedEntry, slug));
})
.catch((error: Error) => {
console.error(error);
dispatch(
notifSend({
message: {
details: error,
key: 'ui.toast.onFailToPersist',
},
kind: 'danger',
dismissAfter: 8000,
}),
);
return Promise.reject(dispatch(entryPersistFail(collection, serializedEntry, error)));
});
};
}
export function deleteEntry(collection: Collection, slug: string) {
return (dispatch: ThunkDispatch<State, {}, AnyAction>, getState: () => State) => {
const state = getState();
const backend = currentBackend(state.config);
dispatch(entryDeleting(collection, slug));
return backend
.deleteEntry(state.config, collection, slug)
.then(() => {
return dispatch(entryDeleted(collection, slug));
})
.catch((error: Error) => {
dispatch(
notifSend({
message: {
details: error,
key: 'ui.toast.onFailToDelete',
},
kind: 'danger',
dismissAfter: 8000,
}),
);
console.error(error);
return Promise.reject(dispatch(entryDeleteFail(collection, slug, error)));
});
};
}