annotate core/modules/ckeditor/js/views/ControllerView.es6.js @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents a9cd425dd02b
children
rev   line source
Chris@0 1 /**
Chris@0 2 * @file
Chris@0 3 * A Backbone View acting as a controller for CKEditor toolbar configuration.
Chris@0 4 */
Chris@0 5
Chris@4 6 (function($, Drupal, Backbone, CKEDITOR, _) {
Chris@4 7 Drupal.ckeditor.ControllerView = Backbone.View.extend(
Chris@4 8 /** @lends Drupal.ckeditor.ControllerView# */ {
Chris@4 9 /**
Chris@4 10 * @type {object}
Chris@4 11 */
Chris@4 12 events: {},
Chris@0 13
Chris@4 14 /**
Chris@4 15 * Backbone View acting as a controller for CKEditor toolbar configuration.
Chris@4 16 *
Chris@4 17 * @constructs
Chris@4 18 *
Chris@4 19 * @augments Backbone.View
Chris@4 20 */
Chris@4 21 initialize() {
Chris@4 22 this.getCKEditorFeatures(
Chris@4 23 this.model.get('hiddenEditorConfig'),
Chris@4 24 this.disableFeaturesDisallowedByFilters.bind(this),
Chris@4 25 );
Chris@0 26
Chris@4 27 // Push the active editor configuration to the textarea.
Chris@4 28 this.model.listenTo(
Chris@4 29 this.model,
Chris@4 30 'change:activeEditorConfig',
Chris@4 31 this.model.sync,
Chris@4 32 );
Chris@4 33 this.listenTo(this.model, 'change:isDirty', this.parseEditorDOM);
Chris@4 34 },
Chris@0 35
Chris@4 36 /**
Chris@4 37 * Converts the active toolbar DOM structure to an object representation.
Chris@4 38 *
Chris@4 39 * @param {Drupal.ckeditor.ConfigurationModel} model
Chris@4 40 * The state model for the CKEditor configuration.
Chris@4 41 * @param {bool} isDirty
Chris@4 42 * Tracks whether the active toolbar DOM structure has been changed.
Chris@4 43 * isDirty is toggled back to false in this method.
Chris@4 44 * @param {object} options
Chris@4 45 * An object that includes:
Chris@4 46 * @param {bool} [options.broadcast]
Chris@4 47 * A flag that controls whether a CKEditorToolbarChanged event should be
Chris@4 48 * fired for configuration changes.
Chris@4 49 *
Chris@4 50 * @fires event:CKEditorToolbarChanged
Chris@4 51 */
Chris@4 52 parseEditorDOM(model, isDirty, options) {
Chris@4 53 if (isDirty) {
Chris@4 54 const currentConfig = this.model.get('activeEditorConfig');
Chris@0 55
Chris@4 56 // Process the rows.
Chris@4 57 const rows = [];
Chris@4 58 this.$el
Chris@4 59 .find('.ckeditor-active-toolbar-configuration')
Chris@4 60 .children('.ckeditor-row')
Chris@4 61 .each(function() {
Chris@4 62 const groups = [];
Chris@4 63 // Process the button groups.
Chris@4 64 $(this)
Chris@4 65 .find('.ckeditor-toolbar-group')
Chris@4 66 .each(function() {
Chris@4 67 const $group = $(this);
Chris@4 68 const $buttons = $group.find('.ckeditor-button');
Chris@4 69 if ($buttons.length) {
Chris@4 70 const group = {
Chris@4 71 name: $group.attr(
Chris@4 72 'data-drupal-ckeditor-toolbar-group-name',
Chris@4 73 ),
Chris@4 74 items: [],
Chris@4 75 };
Chris@4 76 $group
Chris@4 77 .find('.ckeditor-button, .ckeditor-multiple-button')
Chris@4 78 .each(function() {
Chris@4 79 group.items.push(
Chris@4 80 $(this).attr('data-drupal-ckeditor-button-name'),
Chris@4 81 );
Chris@4 82 });
Chris@4 83 groups.push(group);
Chris@4 84 }
Chris@0 85 });
Chris@4 86 if (groups.length) {
Chris@4 87 rows.push(groups);
Chris@0 88 }
Chris@0 89 });
Chris@4 90 this.model.set('activeEditorConfig', rows);
Chris@4 91 // Mark the model as clean. Whether or not the sync to the textfield
Chris@4 92 // occurs depends on the activeEditorConfig attribute firing a change
Chris@4 93 // event. The DOM has at least been processed and posted, so as far as
Chris@4 94 // the model is concerned, it is clean.
Chris@4 95 this.model.set('isDirty', false);
Chris@4 96
Chris@4 97 // Determine whether we should trigger an event.
Chris@4 98 if (options.broadcast !== false) {
Chris@4 99 const prev = this.getButtonList(currentConfig);
Chris@4 100 const next = this.getButtonList(rows);
Chris@4 101 if (prev.length !== next.length) {
Chris@4 102 this.$el
Chris@4 103 .find('.ckeditor-toolbar-active')
Chris@4 104 .trigger('CKEditorToolbarChanged', [
Chris@4 105 prev.length < next.length ? 'added' : 'removed',
Chris@4 106 _.difference(
Chris@4 107 _.union(prev, next),
Chris@4 108 _.intersection(prev, next),
Chris@4 109 )[0],
Chris@4 110 ]);
Chris@0 111 }
Chris@4 112 }
Chris@4 113 }
Chris@4 114 },
Chris@4 115
Chris@4 116 /**
Chris@4 117 * Asynchronously retrieve the metadata for all available CKEditor features.
Chris@4 118 *
Chris@4 119 * In order to get a list of all features needed by CKEditor, we create a
Chris@4 120 * hidden CKEditor instance, then check the CKEditor's "allowedContent"
Chris@4 121 * filter settings. Because creating an instance is expensive, a callback
Chris@4 122 * must be provided that will receive a hash of {@link Drupal.EditorFeature}
Chris@4 123 * features keyed by feature (button) name.
Chris@4 124 *
Chris@4 125 * @param {object} CKEditorConfig
Chris@4 126 * An object that represents the configuration settings for a CKEditor
Chris@4 127 * editor component.
Chris@4 128 * @param {function} callback
Chris@4 129 * A function to invoke when the instanceReady event is fired by the
Chris@4 130 * CKEditor object.
Chris@4 131 */
Chris@4 132 getCKEditorFeatures(CKEditorConfig, callback) {
Chris@4 133 const getProperties = function(CKEPropertiesList) {
Chris@4 134 return _.isObject(CKEPropertiesList) ? _.keys(CKEPropertiesList) : [];
Chris@4 135 };
Chris@4 136
Chris@4 137 const convertCKERulesToEditorFeature = function(
Chris@4 138 feature,
Chris@4 139 CKEFeatureRules,
Chris@4 140 ) {
Chris@4 141 for (let i = 0; i < CKEFeatureRules.length; i++) {
Chris@4 142 const CKERule = CKEFeatureRules[i];
Chris@4 143 const rule = new Drupal.EditorFeatureHTMLRule();
Chris@4 144
Chris@4 145 // Tags.
Chris@4 146 const tags = getProperties(CKERule.elements);
Chris@4 147 rule.required.tags = CKERule.propertiesOnly ? [] : tags;
Chris@4 148 rule.allowed.tags = tags;
Chris@4 149 // Attributes.
Chris@4 150 rule.required.attributes = getProperties(
Chris@4 151 CKERule.requiredAttributes,
Chris@4 152 );
Chris@4 153 rule.allowed.attributes = getProperties(CKERule.attributes);
Chris@4 154 // Styles.
Chris@4 155 rule.required.styles = getProperties(CKERule.requiredStyles);
Chris@4 156 rule.allowed.styles = getProperties(CKERule.styles);
Chris@4 157 // Classes.
Chris@4 158 rule.required.classes = getProperties(CKERule.requiredClasses);
Chris@4 159 rule.allowed.classes = getProperties(CKERule.classes);
Chris@4 160 // Raw.
Chris@4 161 rule.raw = CKERule;
Chris@4 162
Chris@4 163 feature.addHTMLRule(rule);
Chris@4 164 }
Chris@4 165 };
Chris@4 166
Chris@4 167 // Create hidden CKEditor with all features enabled, retrieve metadata.
Chris@4 168 // @see \Drupal\ckeditor\Plugin\Editor\CKEditor::buildConfigurationForm().
Chris@4 169 const hiddenCKEditorID = 'ckeditor-hidden';
Chris@4 170 if (CKEDITOR.instances[hiddenCKEditorID]) {
Chris@4 171 CKEDITOR.instances[hiddenCKEditorID].destroy(true);
Chris@4 172 }
Chris@4 173 // Load external plugins, if any.
Chris@4 174 const hiddenEditorConfig = this.model.get('hiddenEditorConfig');
Chris@4 175 if (hiddenEditorConfig.drupalExternalPlugins) {
Chris@4 176 const externalPlugins = hiddenEditorConfig.drupalExternalPlugins;
Chris@4 177 Object.keys(externalPlugins || {}).forEach(pluginName => {
Chris@4 178 CKEDITOR.plugins.addExternal(
Chris@4 179 pluginName,
Chris@4 180 externalPlugins[pluginName],
Chris@4 181 '',
Chris@4 182 );
Chris@0 183 });
Chris@4 184 }
Chris@4 185 CKEDITOR.inline($(`#${hiddenCKEditorID}`).get(0), CKEditorConfig);
Chris@0 186
Chris@4 187 // Once the instance is ready, retrieve the allowedContent filter rules
Chris@4 188 // and convert them to Drupal.EditorFeature objects.
Chris@4 189 CKEDITOR.once('instanceReady', e => {
Chris@4 190 if (e.editor.name === hiddenCKEditorID) {
Chris@4 191 // First collect all CKEditor allowedContent rules.
Chris@4 192 const CKEFeatureRulesMap = {};
Chris@4 193 const rules = e.editor.filter.allowedContent;
Chris@4 194 let rule;
Chris@4 195 let name;
Chris@4 196 for (let i = 0; i < rules.length; i++) {
Chris@4 197 rule = rules[i];
Chris@4 198 name = rule.featureName || ':(';
Chris@4 199 if (!CKEFeatureRulesMap[name]) {
Chris@4 200 CKEFeatureRulesMap[name] = [];
Chris@4 201 }
Chris@4 202 CKEFeatureRulesMap[name].push(rule);
Chris@4 203 }
Chris@4 204
Chris@4 205 // Now convert these to Drupal.EditorFeature objects. And track which
Chris@4 206 // buttons are mapped to which features.
Chris@4 207 // @see getFeatureForButton()
Chris@4 208 const features = {};
Chris@4 209 const buttonsToFeatures = {};
Chris@4 210 Object.keys(CKEFeatureRulesMap).forEach(featureName => {
Chris@4 211 const feature = new Drupal.EditorFeature(featureName);
Chris@4 212 convertCKERulesToEditorFeature(
Chris@4 213 feature,
Chris@4 214 CKEFeatureRulesMap[featureName],
Chris@4 215 );
Chris@4 216 features[featureName] = feature;
Chris@4 217 const command = e.editor.getCommand(featureName);
Chris@4 218 if (command) {
Chris@4 219 buttonsToFeatures[command.uiItems[0].name] = featureName;
Chris@4 220 }
Chris@4 221 });
Chris@4 222
Chris@4 223 callback(features, buttonsToFeatures);
Chris@4 224 }
Chris@4 225 });
Chris@4 226 },
Chris@4 227
Chris@4 228 /**
Chris@4 229 * Retrieves the feature for a given button from featuresMetadata. Returns
Chris@4 230 * false if the given button is in fact a divider.
Chris@4 231 *
Chris@4 232 * @param {string} button
Chris@4 233 * The name of a CKEditor button.
Chris@4 234 *
Chris@4 235 * @return {object}
Chris@4 236 * The feature metadata object for a button.
Chris@4 237 */
Chris@4 238 getFeatureForButton(button) {
Chris@4 239 // Return false if the button being added is a divider.
Chris@4 240 if (button === '-') {
Chris@4 241 return false;
Chris@4 242 }
Chris@4 243
Chris@4 244 // Get a Drupal.editorFeature object that contains all metadata for
Chris@4 245 // the feature that was just added or removed. Not every feature has
Chris@4 246 // such metadata.
Chris@4 247 let featureName = this.model.get('buttonsToFeatures')[
Chris@4 248 button.toLowerCase()
Chris@4 249 ];
Chris@4 250 // Features without an associated command do not have a 'feature name' by
Chris@4 251 // default, so we use the lowercased button name instead.
Chris@4 252 if (!featureName) {
Chris@4 253 featureName = button.toLowerCase();
Chris@4 254 }
Chris@4 255 const featuresMetadata = this.model.get('featuresMetadata');
Chris@4 256 if (!featuresMetadata[featureName]) {
Chris@4 257 featuresMetadata[featureName] = new Drupal.EditorFeature(featureName);
Chris@4 258 this.model.set('featuresMetadata', featuresMetadata);
Chris@4 259 }
Chris@4 260 return featuresMetadata[featureName];
Chris@4 261 },
Chris@4 262
Chris@4 263 /**
Chris@4 264 * Checks buttons against filter settings; disables disallowed buttons.
Chris@4 265 *
Chris@4 266 * @param {object} features
Chris@4 267 * A map of {@link Drupal.EditorFeature} objects.
Chris@4 268 * @param {object} buttonsToFeatures
Chris@4 269 * Object containing the button-to-feature mapping.
Chris@4 270 *
Chris@4 271 * @see Drupal.ckeditor.ControllerView#getFeatureForButton
Chris@4 272 */
Chris@4 273 disableFeaturesDisallowedByFilters(features, buttonsToFeatures) {
Chris@4 274 this.model.set('featuresMetadata', features);
Chris@4 275 // Store the button-to-feature mapping. Needs to happen only once, because
Chris@4 276 // the same buttons continue to have the same features; only the rules for
Chris@4 277 // specific features may change.
Chris@4 278 // @see getFeatureForButton()
Chris@4 279 this.model.set('buttonsToFeatures', buttonsToFeatures);
Chris@4 280
Chris@4 281 // Ensure that toolbar configuration changes are broadcast.
Chris@4 282 this.broadcastConfigurationChanges(this.$el);
Chris@4 283
Chris@4 284 // Initialization: not all of the default toolbar buttons may be allowed
Chris@4 285 // by the current filter settings. Remove any of the default toolbar
Chris@4 286 // buttons that require more permissive filter settings. The remaining
Chris@4 287 // default toolbar buttons are marked as "added".
Chris@4 288 let existingButtons = [];
Chris@4 289 // Loop through each button group after flattening the groups from the
Chris@4 290 // toolbar row arrays.
Chris@4 291 const buttonGroups = _.flatten(this.model.get('activeEditorConfig'));
Chris@4 292 for (let i = 0; i < buttonGroups.length; i++) {
Chris@4 293 // Pull the button names from each toolbar button group.
Chris@4 294 const buttons = buttonGroups[i].items;
Chris@4 295 for (let k = 0; k < buttons.length; k++) {
Chris@4 296 existingButtons.push(buttons[k]);
Chris@4 297 }
Chris@4 298 }
Chris@4 299 // Remove duplicate buttons.
Chris@4 300 existingButtons = _.unique(existingButtons);
Chris@4 301 // Prepare the active toolbar and available-button toolbars.
Chris@4 302 for (let n = 0; n < existingButtons.length; n++) {
Chris@4 303 const button = existingButtons[n];
Chris@4 304 const feature = this.getFeatureForButton(button);
Chris@4 305 // Skip dividers.
Chris@4 306 if (feature === false) {
Chris@4 307 continue;
Chris@4 308 }
Chris@4 309
Chris@4 310 if (Drupal.editorConfiguration.featureIsAllowedByFilters(feature)) {
Chris@4 311 // Existing toolbar buttons are in fact "added features".
Chris@0 312 this.$el
Chris@0 313 .find('.ckeditor-toolbar-active')
Chris@4 314 .trigger('CKEditorToolbarChanged', ['added', existingButtons[n]]);
Chris@4 315 } else {
Chris@4 316 // Move the button element from the active the active toolbar to the
Chris@4 317 // list of available buttons.
Chris@4 318 $(
Chris@4 319 `.ckeditor-toolbar-active li[data-drupal-ckeditor-button-name="${button}"]`,
Chris@4 320 )
Chris@4 321 .detach()
Chris@4 322 .appendTo(
Chris@4 323 '.ckeditor-toolbar-disabled > .ckeditor-toolbar-available > ul',
Chris@4 324 );
Chris@4 325 // Update the toolbar value field.
Chris@4 326 this.model.set({ isDirty: true }, { broadcast: false });
Chris@0 327 }
Chris@0 328 }
Chris@4 329 },
Chris@0 330
Chris@4 331 /**
Chris@4 332 * Sets up broadcasting of CKEditor toolbar configuration changes.
Chris@4 333 *
Chris@4 334 * @param {jQuery} $ckeditorToolbar
Chris@4 335 * The active toolbar DOM element wrapped in jQuery.
Chris@4 336 */
Chris@4 337 broadcastConfigurationChanges($ckeditorToolbar) {
Chris@4 338 const view = this;
Chris@4 339 const hiddenEditorConfig = this.model.get('hiddenEditorConfig');
Chris@4 340 const getFeatureForButton = this.getFeatureForButton.bind(this);
Chris@4 341 const getCKEditorFeatures = this.getCKEditorFeatures.bind(this);
Chris@4 342 $ckeditorToolbar
Chris@4 343 .find('.ckeditor-toolbar-active')
Chris@4 344 // Listen for CKEditor toolbar configuration changes. When a button is
Chris@4 345 // added/removed, call an appropriate Drupal.editorConfiguration method.
Chris@4 346 .on(
Chris@4 347 'CKEditorToolbarChanged.ckeditorAdmin',
Chris@4 348 (event, action, button) => {
Chris@4 349 const feature = getFeatureForButton(button);
Chris@0 350
Chris@4 351 // Early-return if the button being added is a divider.
Chris@4 352 if (feature === false) {
Chris@4 353 return;
Chris@4 354 }
Chris@0 355
Chris@4 356 // Trigger a standardized text editor configuration event to indicate
Chris@4 357 // whether a feature was added or removed, so that filters can react.
Chris@4 358 const configEvent =
Chris@4 359 action === 'added' ? 'addedFeature' : 'removedFeature';
Chris@4 360 Drupal.editorConfiguration[configEvent](feature);
Chris@4 361 },
Chris@4 362 )
Chris@4 363 // Listen for CKEditor plugin settings changes. When a plugin setting is
Chris@4 364 // changed, rebuild the CKEditor features metadata.
Chris@4 365 .on(
Chris@4 366 'CKEditorPluginSettingsChanged.ckeditorAdmin',
Chris@4 367 (event, settingsChanges) => {
Chris@4 368 // Update hidden CKEditor configuration.
Chris@4 369 Object.keys(settingsChanges || {}).forEach(key => {
Chris@4 370 hiddenEditorConfig[key] = settingsChanges[key];
Chris@4 371 });
Chris@0 372
Chris@4 373 // Retrieve features for the updated hidden CKEditor configuration.
Chris@4 374 getCKEditorFeatures(hiddenEditorConfig, features => {
Chris@4 375 // Trigger a standardized text editor configuration event for each
Chris@4 376 // feature that was modified by the configuration changes.
Chris@4 377 const featuresMetadata = view.model.get('featuresMetadata');
Chris@4 378 Object.keys(features || {}).forEach(name => {
Chris@4 379 const feature = features[name];
Chris@4 380 if (
Chris@4 381 featuresMetadata.hasOwnProperty(name) &&
Chris@4 382 !_.isEqual(featuresMetadata[name], feature)
Chris@4 383 ) {
Chris@4 384 Drupal.editorConfiguration.modifiedFeature(feature);
Chris@4 385 }
Chris@4 386 });
Chris@4 387 // Update the CKEditor features metadata.
Chris@4 388 view.model.set('featuresMetadata', features);
Chris@4 389 });
Chris@4 390 },
Chris@4 391 );
Chris@4 392 },
Chris@0 393
Chris@4 394 /**
Chris@4 395 * Returns the list of buttons from an editor configuration.
Chris@4 396 *
Chris@4 397 * @param {object} config
Chris@4 398 * A CKEditor configuration object.
Chris@4 399 *
Chris@4 400 * @return {Array}
Chris@4 401 * A list of buttons in the CKEditor configuration.
Chris@4 402 */
Chris@4 403 getButtonList(config) {
Chris@4 404 const buttons = [];
Chris@4 405 // Remove the rows.
Chris@4 406 config = _.flatten(config);
Chris@0 407
Chris@4 408 // Loop through the button groups and pull out the buttons.
Chris@4 409 config.forEach(group => {
Chris@4 410 group.items.forEach(button => {
Chris@4 411 buttons.push(button);
Chris@0 412 });
Chris@0 413 });
Chris@4 414
Chris@4 415 // Remove the dividing elements if any.
Chris@4 416 return _.without(buttons, '-');
Chris@4 417 },
Chris@0 418 },
Chris@4 419 );
Chris@4 420 })(jQuery, Drupal, Backbone, CKEDITOR, _);