3 * A Backbone View acting as a controller for CKEditor toolbar configuration.
6 (function($, Drupal, Backbone, CKEDITOR, _) {
7 Drupal.ckeditor.ControllerView = Backbone.View.extend(
8 /** @lends Drupal.ckeditor.ControllerView# */ {
15 * Backbone View acting as a controller for CKEditor toolbar configuration.
19 * @augments Backbone.View
22 this.getCKEditorFeatures(
23 this.model.get('hiddenEditorConfig'),
24 this.disableFeaturesDisallowedByFilters.bind(this),
27 // Push the active editor configuration to the textarea.
30 'change:activeEditorConfig',
33 this.listenTo(this.model, 'change:isDirty', this.parseEditorDOM);
37 * Converts the active toolbar DOM structure to an object representation.
39 * @param {Drupal.ckeditor.ConfigurationModel} model
40 * The state model for the CKEditor configuration.
41 * @param {bool} isDirty
42 * Tracks whether the active toolbar DOM structure has been changed.
43 * isDirty is toggled back to false in this method.
44 * @param {object} options
45 * An object that includes:
46 * @param {bool} [options.broadcast]
47 * A flag that controls whether a CKEditorToolbarChanged event should be
48 * fired for configuration changes.
50 * @fires event:CKEditorToolbarChanged
52 parseEditorDOM(model, isDirty, options) {
54 const currentConfig = this.model.get('activeEditorConfig');
59 .find('.ckeditor-active-toolbar-configuration')
60 .children('.ckeditor-row')
63 // Process the button groups.
65 .find('.ckeditor-toolbar-group')
67 const $group = $(this);
68 const $buttons = $group.find('.ckeditor-button');
69 if ($buttons.length) {
72 'data-drupal-ckeditor-toolbar-group-name',
77 .find('.ckeditor-button, .ckeditor-multiple-button')
80 $(this).attr('data-drupal-ckeditor-button-name'),
90 this.model.set('activeEditorConfig', rows);
91 // Mark the model as clean. Whether or not the sync to the textfield
92 // occurs depends on the activeEditorConfig attribute firing a change
93 // event. The DOM has at least been processed and posted, so as far as
94 // the model is concerned, it is clean.
95 this.model.set('isDirty', false);
97 // Determine whether we should trigger an event.
98 if (options.broadcast !== false) {
99 const prev = this.getButtonList(currentConfig);
100 const next = this.getButtonList(rows);
101 if (prev.length !== next.length) {
103 .find('.ckeditor-toolbar-active')
104 .trigger('CKEditorToolbarChanged', [
105 prev.length < next.length ? 'added' : 'removed',
108 _.intersection(prev, next),
117 * Asynchronously retrieve the metadata for all available CKEditor features.
119 * In order to get a list of all features needed by CKEditor, we create a
120 * hidden CKEditor instance, then check the CKEditor's "allowedContent"
121 * filter settings. Because creating an instance is expensive, a callback
122 * must be provided that will receive a hash of {@link Drupal.EditorFeature}
123 * features keyed by feature (button) name.
125 * @param {object} CKEditorConfig
126 * An object that represents the configuration settings for a CKEditor
128 * @param {function} callback
129 * A function to invoke when the instanceReady event is fired by the
132 getCKEditorFeatures(CKEditorConfig, callback) {
133 const getProperties = function(CKEPropertiesList) {
134 return _.isObject(CKEPropertiesList) ? _.keys(CKEPropertiesList) : [];
137 const convertCKERulesToEditorFeature = function(
141 for (let i = 0; i < CKEFeatureRules.length; i++) {
142 const CKERule = CKEFeatureRules[i];
143 const rule = new Drupal.EditorFeatureHTMLRule();
146 const tags = getProperties(CKERule.elements);
147 rule.required.tags = CKERule.propertiesOnly ? [] : tags;
148 rule.allowed.tags = tags;
150 rule.required.attributes = getProperties(
151 CKERule.requiredAttributes,
153 rule.allowed.attributes = getProperties(CKERule.attributes);
155 rule.required.styles = getProperties(CKERule.requiredStyles);
156 rule.allowed.styles = getProperties(CKERule.styles);
158 rule.required.classes = getProperties(CKERule.requiredClasses);
159 rule.allowed.classes = getProperties(CKERule.classes);
163 feature.addHTMLRule(rule);
167 // Create hidden CKEditor with all features enabled, retrieve metadata.
168 // @see \Drupal\ckeditor\Plugin\Editor\CKEditor::buildConfigurationForm().
169 const hiddenCKEditorID = 'ckeditor-hidden';
170 if (CKEDITOR.instances[hiddenCKEditorID]) {
171 CKEDITOR.instances[hiddenCKEditorID].destroy(true);
173 // Load external plugins, if any.
174 const hiddenEditorConfig = this.model.get('hiddenEditorConfig');
175 if (hiddenEditorConfig.drupalExternalPlugins) {
176 const externalPlugins = hiddenEditorConfig.drupalExternalPlugins;
177 Object.keys(externalPlugins || {}).forEach(pluginName => {
178 CKEDITOR.plugins.addExternal(
180 externalPlugins[pluginName],
185 CKEDITOR.inline($(`#${hiddenCKEditorID}`).get(0), CKEditorConfig);
187 // Once the instance is ready, retrieve the allowedContent filter rules
188 // and convert them to Drupal.EditorFeature objects.
189 CKEDITOR.once('instanceReady', e => {
190 if (e.editor.name === hiddenCKEditorID) {
191 // First collect all CKEditor allowedContent rules.
192 const CKEFeatureRulesMap = {};
193 const rules = e.editor.filter.allowedContent;
196 for (let i = 0; i < rules.length; i++) {
198 name = rule.featureName || ':(';
199 if (!CKEFeatureRulesMap[name]) {
200 CKEFeatureRulesMap[name] = [];
202 CKEFeatureRulesMap[name].push(rule);
205 // Now convert these to Drupal.EditorFeature objects. And track which
206 // buttons are mapped to which features.
207 // @see getFeatureForButton()
209 const buttonsToFeatures = {};
210 Object.keys(CKEFeatureRulesMap).forEach(featureName => {
211 const feature = new Drupal.EditorFeature(featureName);
212 convertCKERulesToEditorFeature(
214 CKEFeatureRulesMap[featureName],
216 features[featureName] = feature;
217 const command = e.editor.getCommand(featureName);
219 buttonsToFeatures[command.uiItems[0].name] = featureName;
223 callback(features, buttonsToFeatures);
229 * Retrieves the feature for a given button from featuresMetadata. Returns
230 * false if the given button is in fact a divider.
232 * @param {string} button
233 * The name of a CKEditor button.
236 * The feature metadata object for a button.
238 getFeatureForButton(button) {
239 // Return false if the button being added is a divider.
240 if (button === '-') {
244 // Get a Drupal.editorFeature object that contains all metadata for
245 // the feature that was just added or removed. Not every feature has
247 let featureName = this.model.get('buttonsToFeatures')[
250 // Features without an associated command do not have a 'feature name' by
251 // default, so we use the lowercased button name instead.
253 featureName = button.toLowerCase();
255 const featuresMetadata = this.model.get('featuresMetadata');
256 if (!featuresMetadata[featureName]) {
257 featuresMetadata[featureName] = new Drupal.EditorFeature(featureName);
258 this.model.set('featuresMetadata', featuresMetadata);
260 return featuresMetadata[featureName];
264 * Checks buttons against filter settings; disables disallowed buttons.
266 * @param {object} features
267 * A map of {@link Drupal.EditorFeature} objects.
268 * @param {object} buttonsToFeatures
269 * Object containing the button-to-feature mapping.
271 * @see Drupal.ckeditor.ControllerView#getFeatureForButton
273 disableFeaturesDisallowedByFilters(features, buttonsToFeatures) {
274 this.model.set('featuresMetadata', features);
275 // Store the button-to-feature mapping. Needs to happen only once, because
276 // the same buttons continue to have the same features; only the rules for
277 // specific features may change.
278 // @see getFeatureForButton()
279 this.model.set('buttonsToFeatures', buttonsToFeatures);
281 // Ensure that toolbar configuration changes are broadcast.
282 this.broadcastConfigurationChanges(this.$el);
284 // Initialization: not all of the default toolbar buttons may be allowed
285 // by the current filter settings. Remove any of the default toolbar
286 // buttons that require more permissive filter settings. The remaining
287 // default toolbar buttons are marked as "added".
288 let existingButtons = [];
289 // Loop through each button group after flattening the groups from the
290 // toolbar row arrays.
291 const buttonGroups = _.flatten(this.model.get('activeEditorConfig'));
292 for (let i = 0; i < buttonGroups.length; i++) {
293 // Pull the button names from each toolbar button group.
294 const buttons = buttonGroups[i].items;
295 for (let k = 0; k < buttons.length; k++) {
296 existingButtons.push(buttons[k]);
299 // Remove duplicate buttons.
300 existingButtons = _.unique(existingButtons);
301 // Prepare the active toolbar and available-button toolbars.
302 for (let n = 0; n < existingButtons.length; n++) {
303 const button = existingButtons[n];
304 const feature = this.getFeatureForButton(button);
306 if (feature === false) {
310 if (Drupal.editorConfiguration.featureIsAllowedByFilters(feature)) {
311 // Existing toolbar buttons are in fact "added features".
313 .find('.ckeditor-toolbar-active')
314 .trigger('CKEditorToolbarChanged', ['added', existingButtons[n]]);
316 // Move the button element from the active the active toolbar to the
317 // list of available buttons.
319 `.ckeditor-toolbar-active li[data-drupal-ckeditor-button-name="${button}"]`,
323 '.ckeditor-toolbar-disabled > .ckeditor-toolbar-available > ul',
325 // Update the toolbar value field.
326 this.model.set({ isDirty: true }, { broadcast: false });
332 * Sets up broadcasting of CKEditor toolbar configuration changes.
334 * @param {jQuery} $ckeditorToolbar
335 * The active toolbar DOM element wrapped in jQuery.
337 broadcastConfigurationChanges($ckeditorToolbar) {
339 const hiddenEditorConfig = this.model.get('hiddenEditorConfig');
340 const getFeatureForButton = this.getFeatureForButton.bind(this);
341 const getCKEditorFeatures = this.getCKEditorFeatures.bind(this);
343 .find('.ckeditor-toolbar-active')
344 // Listen for CKEditor toolbar configuration changes. When a button is
345 // added/removed, call an appropriate Drupal.editorConfiguration method.
347 'CKEditorToolbarChanged.ckeditorAdmin',
348 (event, action, button) => {
349 const feature = getFeatureForButton(button);
351 // Early-return if the button being added is a divider.
352 if (feature === false) {
356 // Trigger a standardized text editor configuration event to indicate
357 // whether a feature was added or removed, so that filters can react.
359 action === 'added' ? 'addedFeature' : 'removedFeature';
360 Drupal.editorConfiguration[configEvent](feature);
363 // Listen for CKEditor plugin settings changes. When a plugin setting is
364 // changed, rebuild the CKEditor features metadata.
366 'CKEditorPluginSettingsChanged.ckeditorAdmin',
367 (event, settingsChanges) => {
368 // Update hidden CKEditor configuration.
369 Object.keys(settingsChanges || {}).forEach(key => {
370 hiddenEditorConfig[key] = settingsChanges[key];
373 // Retrieve features for the updated hidden CKEditor configuration.
374 getCKEditorFeatures(hiddenEditorConfig, features => {
375 // Trigger a standardized text editor configuration event for each
376 // feature that was modified by the configuration changes.
377 const featuresMetadata = view.model.get('featuresMetadata');
378 Object.keys(features || {}).forEach(name => {
379 const feature = features[name];
381 featuresMetadata.hasOwnProperty(name) &&
382 !_.isEqual(featuresMetadata[name], feature)
384 Drupal.editorConfiguration.modifiedFeature(feature);
387 // Update the CKEditor features metadata.
388 view.model.set('featuresMetadata', features);
395 * Returns the list of buttons from an editor configuration.
397 * @param {object} config
398 * A CKEditor configuration object.
401 * A list of buttons in the CKEditor configuration.
403 getButtonList(config) {
406 config = _.flatten(config);
408 // Loop through the button groups and pull out the buttons.
409 config.forEach(group => {
410 group.items.forEach(button => {
411 buttons.push(button);
415 // Remove the dividing elements if any.
416 return _.without(buttons, '-');
420 })(jQuery, Drupal, Backbone, CKEDITOR, _);