static-cms/src/backends/backend.js

368 lines
11 KiB
JavaScript
Raw Normal View History

import { attempt, isError } from 'lodash';
WIP - Global UI (#785) * update top bar and collections sidebar UI * update collection entries UI * improve global layout * merge search page into collection page * enable new entry button * search fixup * wip -initial editor update * update editor scrolling and markdown toolbar position * wip * editor toolbar progress * editor toolbar wip * finished basic editor toolbar * add standalone toggle component * improve markdown toolbar spacing * add user avatar placeholder * finish markdown toggle styling * refactor icon setup, add new icons * add new icons to markdown editor toolbar * remove extra app container * add markdown active mark style * relation and text widget styling * widget design updates, basic list/object design update * widget style updates, image widget improvements * refactor widget directory, fix file removal * widget focus styles * finish editor widget focus styles * migrate media library modal to react-modal * wip - migrate editor component form to modal * wip - move editor component form to modal * wip - embed plugin forms in the editor * inline shortcode forms working * disable react hot loading, its breaking things * improve shortcode form styles * make shortcode form collapsible, improve styling * add close functionality to shortcode blocks * improve base media library styling * fix shortcode label * migrate unstyled workflow to new UI * wip - reorganizing everything * more work moving everything * finish more moving and eliminating stuff * restructure, remove react-toolbox * wip - removing old stuff, more restructure * finish restructure * wip - css arch * switch back to test repo * update react-datetime to ^2.11.0 * remove leftover react-toolbox button * more restructuring clean-up * fix UI component directory case * wip -css editor control style * wip - consolidate widget styles * wip - use a single control renderer * fixed object values breaking * wip - editor control active styles * pass control wrapper to widgets * ensure branch name is trimmed * wip - improve widget authoring support * import Map to Widget component * refactor toolbar buttons * wip - more widget active styles * break out editor toggle component * add local scroll sync back * update editor toggle icons * limit editor control pane content width * fix editor control spacing * migrate markdown toolbar stickiness to css * fix markdown toolbar border radius * temporarily use test backend * stop markdown toolbar from going to bottom * restore disabled markdown toolbar buttons for raw * test markdown widget without focus styles * more widget updates * remove card visuals from editor * disable dragging editor split off screen * use editorControl component for shortcode fields * make header site link configurable * add configurable collection descriptions * temporarily add example assets * add basic list view * remove outdated css mixins * add and implement search icon * activate quick add menu * visualize usable space in editor view * fix entry close, other improvements * wip - editorial workflow updates * some dropshadow and other CSS tweaks * workflow ui updates * add worfklow card buttons * fix workflow card button handlers * some dropshadow and other CSS tweaks * make workflow board wider * center workflow and collection views * add basic responsiveness * a bunch of fun UI fixes! a BUNCH! (#875) * give `.nc-entryEditor-toolbar-mainSection` left and right child divs * a bunch of fun UI fixes! a BUNCH! * remove obscure --buttonShadow * revert to test repo * fix not found page styling * allow workflow publishing from any column * disallow publishing from all columns, with feedback * fix new entry button * fix markdown state persisting across entries * enable simple workflow save and new from editor * update slug in address bar when saving new entry * wip - workflow updates, deletion working * add status change functionality to editor * wip - improving status change from editor * editor toolbar back button improvements, loading improvements, cleanup * progress on the media library UI cleanup * remove font smothing css * a quick fix for these buttons * tweaks * progress on media library modal— broken FYI * fix media library functionality, finish migrating footer * remove media library footer files * remove leftover css import * fix media library * editor publishing functionality complete (unstyled) * remove leftover loader var from media library * wip - editor publishing styles * add status dropdown styling * editor toolbar style updates * editor toolbar state improvements * progress on the media library UI cleanup, style improvements * finish editorial workflow editor styling * finish media library styling * fix config * add what-input to optimize focus styling * fix button * fix navigation blocking for simple workflow * improve simple workflow publishing * add avatar dropdown to editor top bar * style github and test-repo auth pages * add git gateway auth page styles * improve editor error styling
2017-12-07 12:37:10 -05:00
import { resolveFormat } from "Formats/formats";
import { selectIntegration } from 'Reducers/integrations';
import {
selectListMethod,
selectEntrySlug,
selectEntryPath,
selectAllowNewEntries,
selectAllowDeletion,
selectFolderEntryExtension
} from "Reducers/collections";
import { createEntry } from "ValueObjects/Entry";
import { sanitizeSlug } from "Lib/urlHelper";
2016-12-23 16:59:48 -02:00
import TestRepoBackend from "./test-repo/implementation";
import GitHubBackend from "./github/implementation";
import GitGatewayBackend from "./git-gateway/implementation";
import { registerBackend, getBackend } from 'Lib/registry';
/**
* Register internal backends
*/
registerBackend('git-gateway', GitGatewayBackend);
registerBackend('github', GitHubBackend);
registerBackend('test-repo', TestRepoBackend);
2016-05-30 16:55:32 -07:00
class LocalStorageAuthStore {
2016-12-23 17:30:27 -02:00
storageKey = "netlify-cms-user";
2016-05-30 16:55:32 -07:00
retrieve() {
const data = window.localStorage.getItem(this.storageKey);
return data && JSON.parse(data);
}
2016-05-30 16:55:32 -07:00
store(userData) {
window.localStorage.setItem(this.storageKey, JSON.stringify(userData));
}
logout() {
window.localStorage.removeItem(this.storageKey);
}
}
2016-12-23 16:59:48 -02:00
const slugFormatter = (template = "{{slug}}", entryData) => {
const date = new Date();
const getIdentifier = (entryData) => {
2017-06-22 21:39:32 +01:00
const validIdentifierFields = ["title", "path"];
const identifiers = validIdentifierFields.map((field) =>
entryData.find((_, key) => key.toLowerCase().trim() === field)
2017-06-22 21:39:32 +01:00
);
const identifier = identifiers.find(ident => ident !== undefined);
if (identifier === undefined) {
throw new Error("Collection must have a field name that is a valid entry identifier");
2017-06-22 21:39:32 +01:00
}
return identifier;
};
const slug = template.replace(/\{\{([^\}]+)\}\}/g, (_, field) => {
2016-10-28 11:42:31 -02:00
switch (field) {
2016-12-23 16:59:48 -02:00
case "year":
return date.getFullYear();
2016-12-23 16:59:48 -02:00
case "month":
return (`0${ date.getMonth() + 1 }`).slice(-2);
2016-12-23 16:59:48 -02:00
case "day":
return (`0${ date.getDate() }`).slice(-2);
2016-12-23 16:59:48 -02:00
case "slug":
return getIdentifier(entryData).trim();
default:
return entryData.get(field, "").trim();
}
})
// Convert slug to lower-case
.toLocaleLowerCase()
// Replace periods and spaces with dashes.
.replace(/[.\s]/g, '-');
return sanitizeSlug(slug);
};
class Backend {
constructor(implementation, backendName, authStore = null) {
this.implementation = implementation;
this.backendName = backendName;
this.authStore = authStore;
if (this.implementation === null) {
2016-12-23 16:59:48 -02:00
throw new Error("Cannot instantiate a Backend with no implementation");
}
}
currentUser() {
if (this.user) { return this.user; }
const stored = this.authStore && this.authStore.retrieve();
if (stored && stored.backendName === this.backendName) {
2017-08-29 13:45:05 -06:00
return Promise.resolve(this.implementation.restoreUser(stored)).then((user) => {
const newUser = {...user, backendName: this.backendName};
// return confirmed/rehydrated user object instead of stored
this.authStore.store(newUser);
return newUser;
});
}
2016-12-23 16:59:48 -02:00
return Promise.resolve(null);
}
authComponent() {
return this.implementation.authComponent();
}
authenticate(credentials) {
2016-05-30 16:55:32 -07:00
return this.implementation.authenticate(credentials).then((user) => {
const newUser = {...user, backendName: this.backendName};
if (this.authStore) { this.authStore.store(newUser); }
return newUser;
2016-05-30 16:55:32 -07:00
});
}
logout() {
return Promise.resolve(this.implementation.logout()).then(() => {
if (this.authStore) {
this.authStore.logout();
}
});
}
2017-01-10 22:23:22 -02:00
getToken = () => this.implementation.getToken();
listEntries(collection) {
const listMethod = this.implementation[selectListMethod(collection)];
2017-04-14 19:19:45 +01:00
const extension = selectFolderEntryExtension(collection);
const collectionFilter = collection.get('filter');
2017-04-14 19:19:45 +01:00
return listMethod.call(this.implementation, collection, extension)
.then(loadedEntries => (
loadedEntries.map(loadedEntry => createEntry(
2016-12-23 16:59:48 -02:00
collection.get("name"),
selectEntrySlug(collection, loadedEntry.file.path),
loadedEntry.file.path,
{ raw: loadedEntry.data || '', label: loadedEntry.file.label }
))
))
.then(entries => (
{
entries: entries.map(this.entryWithFormat(collection)),
}
))
// If this collection has a "filter" property, filter entries accordingly
.then(loadedCollection => (
{
entries: collectionFilter ? this.filterEntries(loadedCollection, collectionFilter) : loadedCollection.entries
}
));
}
2016-10-27 13:12:18 -02:00
getEntry(collection, slug) {
return this.implementation.getEntry(collection, slug, selectEntryPath(collection, slug))
2016-10-27 15:33:15 +02:00
.then(loadedEntry => this.entryWithFormat(collection, slug)(createEntry(
2016-12-23 16:59:48 -02:00
collection.get("name"),
slug,
loadedEntry.file.path,
{ raw: loadedEntry.data, label: loadedEntry.file.label }
2016-10-27 14:45:32 +02:00
))
);
}
getMedia() {
return this.implementation.getMedia();
}
2016-09-06 13:04:17 -03:00
entryWithFormat(collectionOrEntity) {
return (entry) => {
2016-09-06 13:04:17 -03:00
const format = resolveFormat(collectionOrEntity, entry);
if (entry && entry.raw !== undefined) {
const data = (format && attempt(format.fromFile.bind(null, entry.raw))) || {};
2017-06-07 12:47:57 -04:00
if (isError(data)) console.error(data);
return Object.assign(entry, { data: isError(data) ? {} : data });
}
2016-10-27 14:45:32 +02:00
return format.fromFile(entry);
};
}
unpublishedEntries(collections) {
return this.implementation.unpublishedEntries()
2016-10-28 11:42:31 -02:00
.then(loadedEntries => loadedEntries.filter(entry => entry !== null))
.then(entries => (
entries.map((loadedEntry) => {
2017-03-15 18:47:18 -07:00
const entry = createEntry(
loadedEntry.metaData.collection,
loadedEntry.slug,
loadedEntry.file.path,
{
raw: loadedEntry.data,
isModification: loadedEntry.isModification,
}
);
entry.metaData = loadedEntry.metaData;
return entry;
})
))
2016-10-28 11:42:31 -02:00
.then(entries => ({
pagination: 0,
entries: entries.map(entry => {
const collection = collections.get(entry.collection);
return this.entryWithFormat(collection)(entry);
}),
2016-10-28 11:42:31 -02:00
}));
2016-09-06 13:04:17 -03:00
}
unpublishedEntry(collection, slug) {
return this.implementation.unpublishedEntry(collection, slug)
2016-10-28 11:42:31 -02:00
.then((loadedEntry) => {
2017-03-15 18:47:18 -07:00
const entry = createEntry(
"draft",
loadedEntry.slug,
loadedEntry.file.path,
{
raw: loadedEntry.data,
isModification: loadedEntry.isModification,
});
2016-10-28 11:42:31 -02:00
entry.metaData = loadedEntry.metaData;
return entry;
})
.then(this.entryWithFormat(collection, slug));
}
persistEntry(config, collection, entryDraft, MediaFiles, integrations, options = {}) {
2016-12-23 16:59:48 -02:00
const newEntry = entryDraft.getIn(["entry", "newRecord"]) || false;
const parsedData = {
2016-12-23 16:59:48 -02:00
title: entryDraft.getIn(["entry", "data", "title"], "No Title"),
description: entryDraft.getIn(["entry", "data", "description"], "No Description!"),
};
2016-12-23 16:59:48 -02:00
const entryData = entryDraft.getIn(["entry", "data"]).toJS();
let entryObj;
if (newEntry) {
if (!selectAllowNewEntries(collection)) {
2016-12-23 16:59:48 -02:00
throw (new Error("Not allowed to create new entries in this collection"));
}
2016-12-23 16:59:48 -02:00
const slug = slugFormatter(collection.get("slug"), entryDraft.getIn(["entry", "data"]));
const path = selectEntryPath(collection, slug);
entryObj = {
2016-10-28 04:51:37 +02:00
path,
slug,
raw: this.entryToRaw(collection, entryDraft.get("entry")),
};
} else {
2016-12-23 16:59:48 -02:00
const path = entryDraft.getIn(["entry", "path"]);
const slug = entryDraft.getIn(["entry", "slug"]);
entryObj = {
2016-10-28 04:51:37 +02:00
path,
slug,
raw: this.entryToRaw(collection, entryDraft.get("entry")),
};
}
2016-07-19 17:11:22 -03:00
2017-03-17 01:09:52 +00:00
const commitMessage = `${ (newEntry ? "Create " : "Update ") +
2016-12-23 16:59:48 -02:00
collection.get("label") } ${ entryObj.slug }`;
2016-07-19 17:11:22 -03:00
2016-12-23 16:59:48 -02:00
const mode = config.get("publish_mode");
2016-12-23 16:59:48 -02:00
const collectionName = collection.get("name");
/**
* Determine whether an asset store integration is in use.
*/
const hasAssetStore = integrations && !!selectIntegration(integrations, null, 'assetStore');
const updatedOptions = { ...options, hasAssetStore };
WIP - Global UI (#785) * update top bar and collections sidebar UI * update collection entries UI * improve global layout * merge search page into collection page * enable new entry button * search fixup * wip -initial editor update * update editor scrolling and markdown toolbar position * wip * editor toolbar progress * editor toolbar wip * finished basic editor toolbar * add standalone toggle component * improve markdown toolbar spacing * add user avatar placeholder * finish markdown toggle styling * refactor icon setup, add new icons * add new icons to markdown editor toolbar * remove extra app container * add markdown active mark style * relation and text widget styling * widget design updates, basic list/object design update * widget style updates, image widget improvements * refactor widget directory, fix file removal * widget focus styles * finish editor widget focus styles * migrate media library modal to react-modal * wip - migrate editor component form to modal * wip - move editor component form to modal * wip - embed plugin forms in the editor * inline shortcode forms working * disable react hot loading, its breaking things * improve shortcode form styles * make shortcode form collapsible, improve styling * add close functionality to shortcode blocks * improve base media library styling * fix shortcode label * migrate unstyled workflow to new UI * wip - reorganizing everything * more work moving everything * finish more moving and eliminating stuff * restructure, remove react-toolbox * wip - removing old stuff, more restructure * finish restructure * wip - css arch * switch back to test repo * update react-datetime to ^2.11.0 * remove leftover react-toolbox button * more restructuring clean-up * fix UI component directory case * wip -css editor control style * wip - consolidate widget styles * wip - use a single control renderer * fixed object values breaking * wip - editor control active styles * pass control wrapper to widgets * ensure branch name is trimmed * wip - improve widget authoring support * import Map to Widget component * refactor toolbar buttons * wip - more widget active styles * break out editor toggle component * add local scroll sync back * update editor toggle icons * limit editor control pane content width * fix editor control spacing * migrate markdown toolbar stickiness to css * fix markdown toolbar border radius * temporarily use test backend * stop markdown toolbar from going to bottom * restore disabled markdown toolbar buttons for raw * test markdown widget without focus styles * more widget updates * remove card visuals from editor * disable dragging editor split off screen * use editorControl component for shortcode fields * make header site link configurable * add configurable collection descriptions * temporarily add example assets * add basic list view * remove outdated css mixins * add and implement search icon * activate quick add menu * visualize usable space in editor view * fix entry close, other improvements * wip - editorial workflow updates * some dropshadow and other CSS tweaks * workflow ui updates * add worfklow card buttons * fix workflow card button handlers * some dropshadow and other CSS tweaks * make workflow board wider * center workflow and collection views * add basic responsiveness * a bunch of fun UI fixes! a BUNCH! (#875) * give `.nc-entryEditor-toolbar-mainSection` left and right child divs * a bunch of fun UI fixes! a BUNCH! * remove obscure --buttonShadow * revert to test repo * fix not found page styling * allow workflow publishing from any column * disallow publishing from all columns, with feedback * fix new entry button * fix markdown state persisting across entries * enable simple workflow save and new from editor * update slug in address bar when saving new entry * wip - workflow updates, deletion working * add status change functionality to editor * wip - improving status change from editor * editor toolbar back button improvements, loading improvements, cleanup * progress on the media library UI cleanup * remove font smothing css * a quick fix for these buttons * tweaks * progress on media library modal— broken FYI * fix media library functionality, finish migrating footer * remove media library footer files * remove leftover css import * fix media library * editor publishing functionality complete (unstyled) * remove leftover loader var from media library * wip - editor publishing styles * add status dropdown styling * editor toolbar style updates * editor toolbar state improvements * progress on the media library UI cleanup, style improvements * finish editorial workflow editor styling * finish media library styling * fix config * add what-input to optimize focus styling * fix button * fix navigation blocking for simple workflow * improve simple workflow publishing * add avatar dropdown to editor top bar * style github and test-repo auth pages * add git gateway auth page styles * improve editor error styling
2017-12-07 12:37:10 -05:00
const opts = { newEntry, parsedData, commitMessage, collectionName, mode, ...updatedOptions };
WIP - Global UI (#785) * update top bar and collections sidebar UI * update collection entries UI * improve global layout * merge search page into collection page * enable new entry button * search fixup * wip -initial editor update * update editor scrolling and markdown toolbar position * wip * editor toolbar progress * editor toolbar wip * finished basic editor toolbar * add standalone toggle component * improve markdown toolbar spacing * add user avatar placeholder * finish markdown toggle styling * refactor icon setup, add new icons * add new icons to markdown editor toolbar * remove extra app container * add markdown active mark style * relation and text widget styling * widget design updates, basic list/object design update * widget style updates, image widget improvements * refactor widget directory, fix file removal * widget focus styles * finish editor widget focus styles * migrate media library modal to react-modal * wip - migrate editor component form to modal * wip - move editor component form to modal * wip - embed plugin forms in the editor * inline shortcode forms working * disable react hot loading, its breaking things * improve shortcode form styles * make shortcode form collapsible, improve styling * add close functionality to shortcode blocks * improve base media library styling * fix shortcode label * migrate unstyled workflow to new UI * wip - reorganizing everything * more work moving everything * finish more moving and eliminating stuff * restructure, remove react-toolbox * wip - removing old stuff, more restructure * finish restructure * wip - css arch * switch back to test repo * update react-datetime to ^2.11.0 * remove leftover react-toolbox button * more restructuring clean-up * fix UI component directory case * wip -css editor control style * wip - consolidate widget styles * wip - use a single control renderer * fixed object values breaking * wip - editor control active styles * pass control wrapper to widgets * ensure branch name is trimmed * wip - improve widget authoring support * import Map to Widget component * refactor toolbar buttons * wip - more widget active styles * break out editor toggle component * add local scroll sync back * update editor toggle icons * limit editor control pane content width * fix editor control spacing * migrate markdown toolbar stickiness to css * fix markdown toolbar border radius * temporarily use test backend * stop markdown toolbar from going to bottom * restore disabled markdown toolbar buttons for raw * test markdown widget without focus styles * more widget updates * remove card visuals from editor * disable dragging editor split off screen * use editorControl component for shortcode fields * make header site link configurable * add configurable collection descriptions * temporarily add example assets * add basic list view * remove outdated css mixins * add and implement search icon * activate quick add menu * visualize usable space in editor view * fix entry close, other improvements * wip - editorial workflow updates * some dropshadow and other CSS tweaks * workflow ui updates * add worfklow card buttons * fix workflow card button handlers * some dropshadow and other CSS tweaks * make workflow board wider * center workflow and collection views * add basic responsiveness * a bunch of fun UI fixes! a BUNCH! (#875) * give `.nc-entryEditor-toolbar-mainSection` left and right child divs * a bunch of fun UI fixes! a BUNCH! * remove obscure --buttonShadow * revert to test repo * fix not found page styling * allow workflow publishing from any column * disallow publishing from all columns, with feedback * fix new entry button * fix markdown state persisting across entries * enable simple workflow save and new from editor * update slug in address bar when saving new entry * wip - workflow updates, deletion working * add status change functionality to editor * wip - improving status change from editor * editor toolbar back button improvements, loading improvements, cleanup * progress on the media library UI cleanup * remove font smothing css * a quick fix for these buttons * tweaks * progress on media library modal— broken FYI * fix media library functionality, finish migrating footer * remove media library footer files * remove leftover css import * fix media library * editor publishing functionality complete (unstyled) * remove leftover loader var from media library * wip - editor publishing styles * add status dropdown styling * editor toolbar style updates * editor toolbar state improvements * progress on the media library UI cleanup, style improvements * finish editorial workflow editor styling * finish media library styling * fix config * add what-input to optimize focus styling * fix button * fix navigation blocking for simple workflow * improve simple workflow publishing * add avatar dropdown to editor top bar * style github and test-repo auth pages * add git gateway auth page styles * improve editor error styling
2017-12-07 12:37:10 -05:00
return this.implementation.persistEntry(entryObj, MediaFiles, opts)
.then(() => entryObj.slug);
}
persistMedia(file) {
const options = {
commitMessage: `Upload ${file.path}`,
};
return this.implementation.persistMedia(file, options);
}
deleteEntry(config, collection, slug) {
const path = selectEntryPath(collection, slug);
if (!selectAllowDeletion(collection)) {
throw (new Error("Not allowed to delete entries in this collection"));
}
const commitMessage = `Delete ${ collection.get('label') }${ slug }`;
return this.implementation.deleteFile(path, commitMessage);
}
deleteMedia(path) {
const commitMessage = `Delete ${path}`;
return this.implementation.deleteFile(path, commitMessage);
}
persistUnpublishedEntry(...args) {
return this.persistEntry(...args, { unpublished: true });
2016-09-13 16:00:24 -03:00
}
updateUnpublishedEntryStatus(collection, slug, newStatus) {
return this.implementation.updateUnpublishedEntryStatus(collection, slug, newStatus);
}
publishUnpublishedEntry(collection, slug) {
return this.implementation.publishUnpublishedEntry(collection, slug);
2016-09-14 18:25:45 -03:00
}
deleteUnpublishedEntry(collection, slug) {
return this.implementation.deleteUnpublishedEntry(collection, slug);
}
entryToRaw(collection, entry) {
const format = resolveFormat(collection, entry.toJS());
const fieldsOrder = this.fieldsOrder(collection, entry);
return format && format.toFile(entry.get("data").toJS(), fieldsOrder);
}
fieldsOrder(collection, entry) {
const fields = collection.get('fields');
if (fields) {
return collection.get('fields').map(f => f.get('name')).toArray();
}
const files = collection.get('files');
const file = (files || []).filter(f => f.get("name") === entry.get("slug")).get(0);
if (file == null) {
throw new Error(`No file found for ${ entry.get("slug") } in ${ collection.get('name') }`);
}
return file.get('fields').map(f => f.get('name')).toArray();
}
filterEntries(collection, filterRule) {
return collection.entries.filter(entry => (
entry.data[filterRule.get('field')] === filterRule.get('value')
));
}
}
2016-05-30 16:55:32 -07:00
export function resolveBackend(config) {
2016-12-23 16:59:48 -02:00
const name = config.getIn(["backend", "name"]);
2016-05-30 16:55:32 -07:00
if (name == null) {
2016-12-23 16:59:48 -02:00
throw new Error("No backend defined in configuration");
2016-05-30 16:55:32 -07:00
}
const authStore = new LocalStorageAuthStore();
if (!getBackend(name)) {
throw new Error(`Backend not found: ${ name }`);
} else {
return new Backend(getBackend(name).init(config), name, authStore);
2016-05-30 16:55:32 -07:00
}
}
export const currentBackend = (function () {
let backend = null;
return (config) => {
if (backend) { return backend; }
2016-12-23 16:59:48 -02:00
if (config.get("backend")) {
return backend = resolveBackend(config);
}
};
}());