component_library-1.0.x-dev/js/component-library.js
js/component-library.js
/**
* @file
* Component Library behaviors.
*/
(function (Drupal, once) {
'use strict';
Drupal.behaviors.componentLibrary = {
attach: function (context) {
// Core ajax listener is also capturing click event. To get ahead of it
// the event is delegated to the form.
const SELECTOR = '[data-drupal-selector="component-library-variant-add-form"],[data-drupal-selector="component-library-variant-edit-form"]';
const form = once('componentLibrary.form', SELECTOR, context).shift();
if (!form) {
return;
}
form.addEventListener('click', (event) => {
if (event.target.dataset.drupalSelector === 'edit-preview') {
// CodeMirror saves data on form submit. So that for ajax submission
// we collect data manually.
const editors = context.querySelectorAll('.CodeMirror');
for (let i = 0; i < editors.length; i++) {
editors[i].CodeMirror.save();
}
}
}, true);
// The textarea gets updated via Drupal ajax command, so the editor
// instances needs to be updated manually.
const dataTextarea = context.querySelector('[data-drupal-selector="edit-data"]');
if (dataTextarea) {
const handler = () => dataTextarea.nextSibling.CodeMirror.setValue(dataTextarea.innerHTML);
(new MutationObserver(handler)).observe(dataTextarea, {childList: true});
}
}
};
} (Drupal, once));
