mercury_editor-2.0.x-dev/source/js/post-messages-listener.js
source/js/post-messages-listener.js
((Drupal, drupalSettings, once) => {
/**
* Collection of functions to respond to postMessage events.
*/
const iFrameActions = {
/**
* Runs a set of ajax commands.
* @param {Object} data The ajax commands.
*/
ajaxCommands(data) {
const { commands, status } = data;
const ajaxObj = Drupal.ajax({ url: '' });
const ajaxCommands = new Drupal.AjaxCommands();
Object.keys(commands || {}).reduce((executionQueue, key) => {
return executionQueue
.then(() => {
const { command } = commands[key];
if (command && ajaxCommands[command]) {
return ajaxCommands[command](ajaxObj, commands[key], status);
}
})
.catch(console.error);
}, Promise.resolve());
},
/**
* Saves the preview's page state for use in ajax requests.
* @param {Object} pageState
*/
ajaxPreviewPageState(pageState) {
drupalSettings.ajaxPreviewPageState = pageState;
},
/**
* Closes the modal for a component.
* @param {Object} settings The settings for the modal.
*/
closeModal(settings) {
const componentType = settings.componentType.replace(/_/g, '-');
const dialogElement = document.querySelector(
`mercury-dialog:has([data-drupal-selector="edit-layout-paragraphs-component-form-${componentType}"])`,
);
if (!dialogElement) {
return;
}
dialogElement.close();
},
/**
* Ajax click handler for Layout Paragraphs UI elements in iframe.
* @param {Object} settings The ajax settings.
*/
drupalAjax(settings) {
Drupal.ajax(settings).execute();
},
/**
* Used to share Layout Paragraphs settings to the parent window.
* @param {Object} data
*/
layoutParagraphsSettings(data) {
drupalSettings.lpBuilder = data || {};
},
/**
* Respond to mercury editor state updates.
* @param {Object} data
*/
mercuryEditorUpdateState(data) {
const event = new CustomEvent('mercuryEditorUpdateState', {
bubbles: true,
detail: {
stateIndex: data.stateIndex,
stateCount: data.stateCount,
},
});
document.dispatchEvent(event);
},
/**
* Respond to preview updates.
* @param {*} data
*/
previewUpdated(data) {
const eventObject = new CustomEvent(`mercuryEditorPreviewUpdated`, {
bubbles: true,
detail: data,
});
document.dispatchEvent(eventObject);
},
/**
* Selects a component in the preview.
* @param {Object} data The data containing the uuid of the component to select.
*/
componentSelected(data) {
const { uuid } = data;
const component = document.querySelector(`[data-uuid="${uuid}"]`);
if (component) {
component.scrollIntoView({ behavior: 'smooth', block: 'center' });
const event = new CustomEvent('lpb-component:focus', {
bubbles: true,
cancelable: true,
detail: { uuid },
});
component.dispatchEvent(event);
}
},
};
Drupal.behaviors.mercuryEditorPostMessagesListener = {
attach() {
// Listen for window.postMessage() to handle iFrame behavior.
if (once('me-msg-listener', 'html').length) {
window.addEventListener('message', (e) => {
if (iFrameActions[e.data.type]) {
iFrameActions[e.data.type](e.data.settings);
}
});
}
},
};
})(Drupal, drupalSettings, once);
