Skip to content

Commit

Permalink
API Standardise endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Jul 17, 2024
1 parent 94193a5 commit aaec782
Show file tree
Hide file tree
Showing 22 changed files with 1,580 additions and 986 deletions.
33 changes: 6 additions & 27 deletions client/dist/js/bundle.js

Large diffs are not rendered by default.

34 changes: 4 additions & 30 deletions client/src/boot/registerTransforms.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import Injector from 'lib/Injector';
import readOneBlockQuery from 'state/history/readOneBlockQuery';
import HistoricElementViewFactory from 'components/HistoricElementView/HistoricElementView';
import revertToBlockVersionMutation from 'state/history/revertToBlockVersionMutation';
import readBlocksForAreaQuery from 'state/editor/readBlocksForAreaQuery';
import addElementToArea from 'state/editor/addElementMutation';
import revertToBlockVersionRequest from 'state/history/revertToBlockVersionRequest';
import ArchiveAction from 'components/ElementActions/ArchiveAction';
import DuplicateAction from 'components/ElementActions/DuplicateAction';
import SaveAction from 'components/ElementActions/SaveAction';
Expand Down Expand Up @@ -40,35 +38,11 @@ export default () => {
Injector.transform(
'blocks-history-revert',
(updater) => {
// Add block element revert GraphQL mutation to the HistoryViewerToolbar
// Add revertToVersion() to props.actions on HistoryViewerToolbar
updater.component(
'HistoryViewerToolbar.VersionedAdmin.HistoryViewer.Element.HistoryViewerVersionDetail',
revertToBlockVersionMutation,
'BlockRevertMutation'
);
}
);

Injector.transform(
'cms-element-editor',
(updater) => {
// Add GraphQL query for reading elements on a page for the ElementEditor
updater.component(
'ElementList',
readBlocksForAreaQuery,
'PageElements'
);
}
);

Injector.transform(
'cms-element-adder',
(updater) => {
// Add GraphQL query for adding elements to an ElementEditor (ElementalArea)
updater.component(
'AddElementPopover',
addElementToArea,
'ElementAddButton'
revertToBlockVersionRequest,
'BlockRevertRequest'
);
}
);
Expand Down
29 changes: 15 additions & 14 deletions client/src/components/ElementActions/ArchiveAction.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
/* global window */
import React from 'react';
import React, { useContext } from 'react';
import { compose } from 'redux';
import AbstractAction from 'components/ElementActions/AbstractAction';
import archiveBlockMutation from 'state/editor/archiveBlockMutation';
import i18n from 'i18n';
import { ElementEditorContext } from 'components/ElementEditor/ElementEditor';
import backend from 'lib/Backend';
import { getConfig } from 'state/editor/elementConfig';

/**
* Adds the elemental menu action to archive a block of any state
*/
const ArchiveAction = (MenuComponent) => (props) => {
const { fetchBlocks } = useContext(ElementEditorContext);

const handleClick = (event) => {
event.stopPropagation();

const { element: { id }, isPublished, actions: { handleArchiveBlock } } = props;

const isPublished = props.element.isPublished;
let archiveMessage = i18n._t(
'ElementArchiveAction.CONFIRM_DELETE',
'Are you sure you want to send this block to the archive?'
);

if (isPublished) {
archiveMessage = i18n._t(
'ElementArchiveAction.CONFIRM_DELETE_AND_UNPUBLISH',
'Warning: This block will be unpublished before being sent to the archive. Are you sure you want to proceed?'
);
}

// eslint-disable-next-line no-alert
if (handleArchiveBlock && window.confirm(archiveMessage)) {
handleArchiveBlock(id).then(() => {
const preview = window.jQuery('.cms-preview');
if (preview && typeof preview.entwine === 'function') {
preview.entwine('ss.preview')._loadUrl(preview.find('iframe').attr('src'));
}
});
if (!window.confirm(archiveMessage)) {
return;
}
const id = props.element.id;
const url = `${getConfig().controllerLink.replace(/\/$/, '')}/archive`;
backend.post(url, {
ID: id,
})
.then(() => fetchBlocks());
};

const disabled = props.element.canDelete !== undefined && !props.element.canDelete;
Expand Down
22 changes: 12 additions & 10 deletions client/src/components/ElementActions/DuplicateAction.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
/* global window */
import React from 'react';
import React, { useContext } from 'react';
import { compose } from 'redux';
import AbstractAction from 'components/ElementActions/AbstractAction';
import duplicateBlockMutation from 'state/editor/duplicateBlockMutation';
import i18n from 'i18n';
import { ElementEditorContext } from 'components/ElementEditor/ElementEditor';
import backend from 'lib/Backend';
import { getConfig } from 'state/editor/elementConfig';

/**
* Adds the elemental menu action to duplicate a block
*/
const DuplicateAction = (MenuComponent) => (props) => {
const { fetchBlocks } = useContext(ElementEditorContext);

if (props.type.broken) {
// Don't allow this action for a broken element.
return (
Expand All @@ -18,15 +23,12 @@ const DuplicateAction = (MenuComponent) => (props) => {

const handleClick = (event) => {
event.stopPropagation();

const { element: { id }, actions: { handleDuplicateBlock } } = props;

if (handleDuplicateBlock) {
handleDuplicateBlock(id).then(() => {
const preview = window.jQuery('.cms-preview');
preview.entwine('ss.preview')._loadUrl(preview.find('iframe').attr('src'));
});
}
const id = props.element.id;
const url = `${getConfig().controllerLink.replace(/\/$/, '')}/duplicate`;
backend.post(url, {
ID: id,
})
.then(() => fetchBlocks());
};

const disabled = props.element.canCreate !== undefined && !props.element.canCreate;
Expand Down
111 changes: 111 additions & 0 deletions client/src/components/ElementActions/PublishAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,72 @@ import React, { useContext } from 'react';
import AbstractAction from 'components/ElementActions/AbstractAction';
import i18n from 'i18n';
import { ElementContext } from 'components/ElementEditor/Element';
import backend from 'lib/Backend';
import { loadElementSchemaValue } from 'state/editor/loadElementSchemaValue';
import { ElementEditorContext } from 'components/ElementEditor/ElementEditor';
import { getConfig } from 'state/editor/elementConfig';

/**
* Show a toast message reporting whether publication of Element was successful
*
* @param {string} type E.g. "Content" - human friendly element type (not PHP FQCN)
* @param {string} title Title of the element, or a false value if unset (e.g. undefined)
* @param {boolean} success Show a success message (true), or an error message (false)
*/
const reportPublicationStatus = (type, title, success) => {
const noTitle = i18n.inject(
i18n._t('ElementHeader.NOTITLE', 'Untitled {type} block'),
{ type }
);
const successMessage = i18n.inject(
i18n._t('ElementPublishAction.SUCCESS_NOTIFICATION', 'Published \'{title}\' successfully'),
{ title: title || noTitle }
);
const errorMessage = i18n.inject(
i18n._t('ElementPublishAction.ERROR_NOTIFICATION', 'Error publishing \'{title}\''),
{ title: title || noTitle }
);
window.jQuery.noticeAdd({
text: success ? successMessage : errorMessage,
stay: false,
type: success ? 'success' : 'error',
});
};

/**
* Post updated Element data to save it
*
* @param {number} id Element ID
* @param {object} formData Information to be saved
* @param {string} securityId Security ID for form submission
*/
const performSaveForElementWithFormData = (id, formData, securityId) => {
const saveEndpoint = backend.createEndpointFetcher({
url: loadElementSchemaValue('saveUrl', id),
method: loadElementSchemaValue('saveMethod'),
payloadFormat: loadElementSchemaValue('payloadFormat'),
defaultData: {
SecurityID: securityId
},
});

// Perform save & get new version number to publish
return saveEndpoint(formData)
.then(() => window.ss.apolloClient.queryManager.reFetchObservableQueries())
.then((input) => {
const preview = window.jQuery('.cms-preview');
preview.entwine('ss.preview')._loadUrl(preview.find('iframe').attr('src'));
return input;
})
.then((newPageData) => {
const newElementData = newPageData[0] && newPageData[0]
.data
.readOneElementalArea
.elements
.find((elementData) => elementData.id === id);
return newElementData && newElementData.version;
});
};

/**
* Adds the elemental menu action to publish a draft/modified block
Expand All @@ -12,12 +78,57 @@ const PublishAction = (MenuComponent) => (props) => {
formDirty,
onPublishButtonClick,
} = useContext(ElementContext);
const { fetchBlocks } = useContext(ElementEditorContext);

if (props.type.broken) {
// Don't allow this action for a broken element.
return (
<MenuComponent {...props} />
);
}

const { element } = props;

const publishElement = () => {
const id = props.element.id;
const url = `${getConfig().controllerLink.replace(/\/$/, '')}/publish`;
return backend.post(url, {
ID: id,
})
.then(() => fetchBlocks());
};

const handleClick = (event) => {
event.stopPropagation();
onPublishButtonClick();

const {
element: {
id,
title,
},
type,
securityId,
formData,
reinitialiseForm,
} = props;

let actionFlow = new Promise((resolve) => resolve());

// Edits have been made to the form. Peform a "Save & Publish"
if (formDirty) {
actionFlow = performSaveForElementWithFormData(id, formData, securityId)
.then((passthrough) => {
reinitialiseForm(formData);
return passthrough;
});
}

// Perform publish. Data is assumed to be up to date
actionFlow
.then(() => publishElement())
.then(() => reportPublicationStatus(type.title, title, true))
.catch(() => reportPublicationStatus(type.title, title, false));
};

const disabled = props.element.canPublish !== undefined && !props.element.canPublish;
Expand Down
80 changes: 72 additions & 8 deletions client/src/components/ElementActions/SaveAction.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,89 @@
/* global window */
import React, { useContext } from 'react';
import AbstractAction from 'components/ElementActions/AbstractAction';
import i18n from 'i18n';
import { ElementContext } from 'components/ElementEditor/Element';
import { loadElementSchemaValue } from 'state/editor/loadElementSchemaValue';
import { ElementEditorContext } from 'components/ElementEditor/ElementEditor';
import backend from 'lib/Backend';

const SaveAction = (MenuComponent) => (props) => {
const {
onSaveButtonClick,
formDirty,
} = useContext(ElementContext);

const { fetchBlocks } = useContext(ElementEditorContext);

if (!props.expandable || props.type.broken) {
// Some elemental blocks can not be edited inline (e.g. User form blocks)
// We don't want to add a "Save" action for those blocks.
return (
<MenuComponent {...props} />
);
}

const handleClick = (event) => {
event.stopPropagation();
onSaveButtonClick();

const { element, type, securityId, formData, reinitialiseForm } = props;
const { jQuery: $ } = window;
const noTitle = i18n.inject(
i18n._t(
'ElementHeader.NOTITLE',
'Untitled {type} block'
),
{ type: type.title }
);

const endpointSpec = {
url: loadElementSchemaValue('saveUrl', element.id),
method: loadElementSchemaValue('saveMethod'),
payloadFormat: loadElementSchemaValue('payloadFormat'),
defaultData: {
SecurityID: securityId
},
};

const endpoint = backend.createEndpointFetcher(endpointSpec);
endpoint(formData)
.then(() => {
// Update the Apollo query cache with the new form data
const { apolloClient } = window.ss;
// @todo optimistically update the data for the current element instead of
// rerunning the whole query
apolloClient.queryManager.reFetchObservableQueries();
reinitialiseForm(formData);

fetchBlocks();

const newTitle = formData ? formData[`PageElements_${element.id}_Title`] : null;
$.noticeAdd({
text: i18n.inject(
i18n._t(
'ElementSaveAction.SUCCESS_NOTIFICATION',
'Saved \'{title}\' successfully'
),
{ title: newTitle || noTitle }
),
stay: false,
type: 'success'
});
})
.catch(() => {
$.noticeAdd({
text: i18n.inject(
i18n._t(
'ElementSaveAction.ERROR_NOTIFICATION',
'Error saving \'{title}\''
),
{ title: element.Title || noTitle }
),
stay: false,
type: 'error'
});
});
};

const newProps = {
Expand All @@ -21,14 +93,6 @@ const SaveAction = (MenuComponent) => (props) => {
toggle: props.toggle,
};

if (!props.expandable || props.type.broken) {
// Some elemental blocks can not be edited inline (e.g. User form blocks)
// We don't want to add a "Save" action for those blocks.
return (
<MenuComponent {...props} />
);
}

return (
<MenuComponent {...props}>
{props.children}
Expand Down
Loading

0 comments on commit aaec782

Please sign in to comment.