ControllerView.es6.js 16 KB

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