annotate core/modules/ckeditor/js/views/ControllerView.es6.js @ 19:fa3358dc1485 tip

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