-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
implementation.js
302 lines (259 loc) · 8.32 KB
/
implementation.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
import { attempt, isError, take, unset } from 'lodash';
import uuid from 'uuid/v4';
import {
EditorialWorkflowError,
Cursor,
CURSOR_COMPATIBILITY_SYMBOL,
basename,
getCollectionDepth,
} from 'netlify-cms-lib-util';
import AuthenticationPage from './AuthenticationPage';
window.repoFiles = window.repoFiles || {};
window.repoFilesUnpublished = window.repoFilesUnpublished || [];
function getFile(path) {
const segments = path.split('/');
let obj = window.repoFiles;
while (obj && segments.length) {
obj = obj[segments.shift()];
}
return obj || {};
}
const pageSize = 10;
const getCursor = (collection, extension, entries, index) => {
const count = entries.length;
const pageCount = Math.floor(count / pageSize);
return Cursor.create({
actions: [
...(index < pageCount ? ['next', 'last'] : []),
...(index > 0 ? ['prev', 'first'] : []),
],
meta: { index, count, pageSize, pageCount },
data: { collection, extension, index, pageCount },
});
};
export const getFolderEntries = (tree, folder, extension, depth, files = [], path = folder) => {
if (depth <= 0) {
return files;
}
Object.keys(tree[folder] || {}).forEach(key => {
if (key.endsWith(`.${extension}`)) {
const file = tree[folder][key];
files.unshift({
file: { path: `${path}/${key}` },
data: file.content,
});
} else {
const subTree = tree[folder];
return getFolderEntries(subTree, key, extension, depth - 1, files, `${path}/${key}`);
}
});
return files;
};
export default class TestBackend {
constructor(config, options = {}) {
this.config = config;
this.assets = [];
this.options = options;
}
authComponent() {
return AuthenticationPage;
}
restoreUser(user) {
return this.authenticate(user);
}
authenticate() {
return Promise.resolve();
}
logout() {
return null;
}
getToken() {
return Promise.resolve('');
}
traverseCursor(cursor, action) {
const { collection, extension, index, pageCount } = cursor.data.toObject();
const newIndex = (() => {
if (action === 'next') {
return index + 1;
}
if (action === 'prev') {
return index - 1;
}
if (action === 'first') {
return 0;
}
if (action === 'last') {
return pageCount;
}
})();
// TODO: stop assuming cursors are for collections
const depth = getCollectionDepth(collection);
const allEntries = getFolderEntries(
window.repoFiles,
collection.get('folder'),
extension,
depth,
);
const entries = allEntries.slice(newIndex * pageSize, newIndex * pageSize + pageSize);
const newCursor = getCursor(collection, extension, allEntries, newIndex);
return Promise.resolve({ entries, cursor: newCursor });
}
entriesByFolder(collection, extension) {
const folder = collection.get('folder');
const depth = getCollectionDepth(collection);
const entries = folder ? getFolderEntries(window.repoFiles, folder, extension, depth) : [];
const cursor = getCursor(collection, extension, entries, 0);
const ret = take(entries, pageSize);
ret[CURSOR_COMPATIBILITY_SYMBOL] = cursor;
return Promise.resolve(ret);
}
entriesByFiles(collection) {
const files = collection.get('files').map(collectionFile => ({
path: collectionFile.get('file'),
label: collectionFile.get('label'),
}));
return Promise.all(
files.map(file => ({
file,
data: getFile(file.path).content,
})),
);
}
getEntry(collection, slug, path) {
return Promise.resolve({
file: { path },
data: getFile(path).content,
});
}
unpublishedEntries() {
return Promise.resolve(window.repoFilesUnpublished);
}
getMediaFiles(entry) {
const mediaFiles = entry.mediaFiles.map(file => ({
...file,
...this.mediaFileToAsset(file),
file: file.fileObj,
}));
return mediaFiles;
}
unpublishedEntry(collection, slug) {
const entry = window.repoFilesUnpublished.find(
e => e.metaData.collection === collection.get('name') && e.slug === slug,
);
if (!entry) {
return Promise.reject(
new EditorialWorkflowError('content is not under editorial workflow', true),
);
}
entry.mediaFiles = this.getMediaFiles(entry);
return Promise.resolve(entry);
}
deleteUnpublishedEntry(collection, slug) {
const unpubStore = window.repoFilesUnpublished;
const existingEntryIndex = unpubStore.findIndex(
e => e.metaData.collection === collection && e.slug === slug,
);
unpubStore.splice(existingEntryIndex, 1);
return Promise.resolve();
}
async persistEntry({ path, raw, slug }, mediaFiles, options = {}) {
if (options.useWorkflow) {
const unpubStore = window.repoFilesUnpublished;
const existingEntryIndex = unpubStore.findIndex(e => e.file.path === path);
if (existingEntryIndex >= 0) {
const unpubEntry = { ...unpubStore[existingEntryIndex], data: raw };
unpubEntry.title = options.parsedData && options.parsedData.title;
unpubEntry.description = options.parsedData && options.parsedData.description;
unpubEntry.mediaFiles = mediaFiles;
unpubStore.splice(existingEntryIndex, 1, unpubEntry);
} else {
const unpubEntry = {
data: raw,
file: {
path,
},
metaData: {
collection: options.collectionName,
status: options.status || this.options.initialWorkflowStatus,
title: options.parsedData && options.parsedData.title,
description: options.parsedData && options.parsedData.description,
},
slug,
mediaFiles,
};
unpubStore.push(unpubEntry);
}
return Promise.resolve();
}
const newEntry = options.newEntry || false;
const segments = path.split('/');
const entry = newEntry ? { content: raw } : { ...getFile(path), content: raw };
let obj = window.repoFiles;
while (segments.length > 1) {
const segment = segments.shift();
obj[segment] = obj[segment] || {};
obj = obj[segment];
}
obj[segments.shift()] = entry;
await Promise.all(mediaFiles.map(file => this.persistMedia(file)));
return Promise.resolve();
}
updateUnpublishedEntryStatus(collection, slug, newStatus) {
const unpubStore = window.repoFilesUnpublished;
const entryIndex = unpubStore.findIndex(
e => e.metaData.collection === collection && e.slug === slug,
);
unpubStore[entryIndex].metaData.status = newStatus;
return Promise.resolve();
}
async publishUnpublishedEntry(collection, slug) {
const unpubStore = window.repoFilesUnpublished;
const unpubEntryIndex = unpubStore.findIndex(
e => e.metaData.collection === collection && e.slug === slug,
);
const unpubEntry = unpubStore[unpubEntryIndex];
const entry = { raw: unpubEntry.data, slug: unpubEntry.slug, path: unpubEntry.file.path };
unpubStore.splice(unpubEntryIndex, 1);
await this.persistEntry(entry, unpubEntry.mediaFiles);
return { mediaFiles: this.getMediaFiles(unpubEntry) };
}
getMedia() {
return Promise.resolve(this.assets);
}
async getMediaFile(path) {
const asset = this.assets.find(asset => asset.path === path);
const name = basename(path);
const blob = await fetch(asset.url).then(res => res.blob());
const fileObj = new File([blob], name);
return {
displayURL: asset.url,
path,
name,
size: fileObj.size,
file: fileObj,
url: asset.url,
};
}
mediaFileToAsset(mediaFile) {
const { fileObj } = mediaFile;
const { name, size } = fileObj;
const objectUrl = attempt(window.URL.createObjectURL, fileObj);
const url = isError(objectUrl) ? '' : objectUrl;
const normalizedAsset = { id: uuid(), name, size, path: mediaFile.path, url, displayURL: url };
return normalizedAsset;
}
persistMedia(mediaFile) {
const normalizedAsset = this.mediaFileToAsset(mediaFile);
this.assets.push(normalizedAsset);
return Promise.resolve(normalizedAsset);
}
deleteFile(path) {
const assetIndex = this.assets.findIndex(asset => asset.path === path);
if (assetIndex > -1) {
this.assets.splice(assetIndex, 1);
} else {
unset(window.repoFiles, path.split('/'));
}
return Promise.resolve();
}
}