plugin.es6.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /**
  2. * @file
  3. * Drupal Media embed plugin.
  4. */
  5. (function(jQuery, Drupal, CKEDITOR) {
  6. /**
  7. * Gets the focused widget, if of the type specific for this plugin.
  8. *
  9. * @param {CKEDITOR.editor} editor
  10. * A CKEditor instance.
  11. *
  12. * @return {?CKEDITOR.plugins.widget}
  13. * The focused drupalmedia widget instance, or null.
  14. */
  15. function getFocusedWidget(editor) {
  16. const widget = editor.widgets.focused;
  17. if (widget && widget.name === 'drupalmedia') {
  18. return widget;
  19. }
  20. return null;
  21. }
  22. /**
  23. * Makes embedded items linkable by integrating with the drupallink plugin.
  24. *
  25. * @param {CKEDITOR.editor} editor
  26. * A CKEditor instance.
  27. */
  28. function linkCommandIntegrator(editor) {
  29. if (!editor.plugins.drupallink) {
  30. return;
  31. }
  32. CKEDITOR.plugins.drupallink.registerLinkableWidget('drupalmedia');
  33. editor.getCommand('drupalunlink').on('exec', function(evt) {
  34. const widget = getFocusedWidget(editor);
  35. if (!widget) {
  36. return;
  37. }
  38. widget.setData('link', null);
  39. this.refresh(editor, editor.elementPath());
  40. evt.cancel();
  41. });
  42. editor.getCommand('drupalunlink').on('refresh', function(evt) {
  43. const widget = getFocusedWidget(editor);
  44. if (!widget) {
  45. return;
  46. }
  47. this.setState(
  48. widget.data.link ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
  49. );
  50. evt.cancel();
  51. });
  52. // Register context menu items for editing link.
  53. if (editor.contextMenu) {
  54. editor.contextMenu.addListener(() => {
  55. const widget = getFocusedWidget(editor);
  56. if (!widget) {
  57. return;
  58. }
  59. if (widget.data.link) {
  60. return {
  61. link: CKEDITOR.TRISTATE_OFF,
  62. unlink: CKEDITOR.TRISTATE_OFF,
  63. };
  64. }
  65. return {};
  66. });
  67. }
  68. }
  69. CKEDITOR.plugins.add('drupalmedia', {
  70. requires: 'widget',
  71. beforeInit(editor) {
  72. // Configure CKEditor DTD for custom drupal-media element.
  73. // @see https://www.drupal.org/node/2448449#comment-9717735
  74. const { dtd } = CKEDITOR;
  75. // Allow text within the drupal-media tag.
  76. dtd['drupal-media'] = { '#': 1 };
  77. // Register drupal-media element as an allowed child in each tag that can
  78. // contain a div element and as an allowed child of the a tag.
  79. Object.keys(dtd).forEach(tagName => {
  80. if (dtd[tagName].div) {
  81. dtd[tagName]['drupal-media'] = 1;
  82. }
  83. });
  84. dtd.a['drupal-media'] = 1;
  85. editor.widgets.add('drupalmedia', {
  86. allowedContent: {
  87. 'drupal-media': {
  88. attributes: {
  89. '!data-entity-type': true,
  90. '!data-entity-uuid': true,
  91. 'data-align': true,
  92. 'data-caption': true,
  93. alt: true,
  94. title: true,
  95. },
  96. classes: {},
  97. },
  98. },
  99. // Minimum HTML which is required by this widget to work.
  100. // This does not use the object format used above, but a
  101. // CKEDITOR.style instance, because requiredContent does not support
  102. // the object format.
  103. // @see https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_filter_contentRule.html
  104. requiredContent: new CKEDITOR.style({
  105. element: 'drupal-media',
  106. attributes: {
  107. 'data-entity-type': '',
  108. 'data-entity-uuid': '',
  109. },
  110. }),
  111. pathName: Drupal.t('Embedded media'),
  112. editables: {
  113. caption: {
  114. selector: 'figcaption',
  115. allowedContent: 'a[!href]; em strong cite code br',
  116. pathName: Drupal.t('Caption'),
  117. },
  118. },
  119. getLabel() {
  120. if (this.data.label) {
  121. return this.data.label;
  122. }
  123. return Drupal.t('Embedded media');
  124. },
  125. upcast(element, data) {
  126. const { attributes } = element;
  127. // This matches the behavior of the corresponding server-side text filter plugin.
  128. if (
  129. element.name !== 'drupal-media' ||
  130. attributes['data-entity-type'] !== 'media' ||
  131. attributes['data-entity-uuid'] === undefined
  132. ) {
  133. return;
  134. }
  135. data.attributes = CKEDITOR.tools.copy(attributes);
  136. data.hasCaption = data.attributes.hasOwnProperty('data-caption');
  137. // Add space to the empty caption to allow the server-side text
  138. // filter to render a caption, allowing the placeholder-rendering
  139. // CSS to work.
  140. if (data.hasCaption && data.attributes['data-caption'] === '') {
  141. data.attributes['data-caption'] = ' ';
  142. }
  143. data.label = null;
  144. data.link = null;
  145. if (element.parent.name === 'a') {
  146. data.link = CKEDITOR.tools.copy(element.parent.attributes);
  147. // Omit CKEditor-internal attributes.
  148. Object.keys(element.parent.attributes).forEach(attrName => {
  149. if (attrName.indexOf('data-cke-') !== -1) {
  150. delete data.link[attrName];
  151. }
  152. });
  153. }
  154. // @see media_field_widget_form_alter()
  155. const hostEntityLangcode = document
  156. .getElementById(editor.name)
  157. .getAttribute('data-media-embed-host-entity-langcode');
  158. if (hostEntityLangcode) {
  159. data.hostEntityLangcode = hostEntityLangcode;
  160. }
  161. return element;
  162. },
  163. destroy() {
  164. this._tearDownDynamicEditables();
  165. },
  166. data(event) {
  167. // Only run during changes.
  168. if (this.oldData) {
  169. // The server-side text filter plugin treats both an empty
  170. // `data-caption` attribute and a non-existing one the same: it
  171. // does not render a caption. But in the CKEditor Widget, we need
  172. // to be able to show an empty caption with placeholder text using
  173. // CSS even when technically there is no `data-caption` attribute
  174. // value yet. That's why this CKEditor Widget has an independent
  175. // `hasCaption` boolean (which is not an attribute) to know when
  176. // to generate a non-empty `data-caption` attribute when the
  177. // content creator has enabled caption: this makes the server-side
  178. // text filter render a caption, allowing the placeholder-rendering
  179. // CSS to work.
  180. // @see core/modules/filter/css/filter.caption.css
  181. // @see ckeditor_ckeditor_css_alter()
  182. if (!this.data.hasCaption && this.oldData.hasCaption) {
  183. delete this.data.attributes['data-caption'];
  184. } else if (
  185. this.data.hasCaption &&
  186. !this.data.attributes['data-caption']
  187. ) {
  188. this.data.attributes['data-caption'] = ' ';
  189. }
  190. }
  191. if (this._previewNeedsServerSideUpdate()) {
  192. editor.fire('lockSnapshot');
  193. this._tearDownDynamicEditables();
  194. this._loadPreview(widget => {
  195. widget._setUpDynamicEditables();
  196. widget._setUpEditButton();
  197. editor.fire('unlockSnapshot');
  198. });
  199. }
  200. // Remove old attributes from drupal-media element within the widget.
  201. if (this.oldData) {
  202. Object.keys(this.oldData.attributes).forEach(attrName => {
  203. this.element.removeAttribute(attrName);
  204. });
  205. }
  206. // Add attributes to drupal-media element within the widget.
  207. this.element.setAttributes(this.data.attributes);
  208. // Track the previous state to allow checking if preview needs
  209. // server side update.
  210. this.oldData = CKEDITOR.tools.clone(this.data);
  211. },
  212. downcast() {
  213. const downcastElement = new CKEDITOR.htmlParser.element(
  214. 'drupal-media',
  215. this.data.attributes,
  216. );
  217. if (this.data.link) {
  218. const link = new CKEDITOR.htmlParser.element('a', this.data.link);
  219. link.add(downcastElement);
  220. return link;
  221. }
  222. return downcastElement;
  223. },
  224. _setUpDynamicEditables() {
  225. // Now that the caption is available in the DOM, make it editable.
  226. if (this.initEditable('caption', this.definition.editables.caption)) {
  227. const captionEditable = this.editables.caption;
  228. // @see core/modules/filter/css/filter.caption.css
  229. // @see ckeditor_ckeditor_css_alter()
  230. captionEditable.setAttribute(
  231. 'data-placeholder',
  232. Drupal.t('Enter caption here'),
  233. );
  234. // Ensure that any changes made to the caption are persisted in the
  235. // widget's data-caption attribute.
  236. this.captionObserver = new MutationObserver(() => {
  237. const mediaAttributes = CKEDITOR.tools.clone(
  238. this.data.attributes,
  239. );
  240. mediaAttributes['data-caption'] = captionEditable.getData();
  241. this.setData('attributes', mediaAttributes);
  242. });
  243. this.captionObserver.observe(captionEditable.$, {
  244. characterData: true,
  245. attributes: true,
  246. childList: true,
  247. subtree: true,
  248. });
  249. // Some browsers will add a <br> tag to a newly created DOM element
  250. // with no content. Remove this <br> if it is the only thing in the
  251. // caption. Our placeholder support requires the element to be
  252. // entirely empty.
  253. // @see core/modules/filter/css/filter.caption.css
  254. // @see core/modules/ckeditor/js/plugins/drupalimagecaption/plugin.es6.js
  255. if (
  256. captionEditable.$.childNodes.length === 1 &&
  257. captionEditable.$.childNodes.item(0).nodeName === 'BR'
  258. ) {
  259. captionEditable.$.removeChild(
  260. captionEditable.$.childNodes.item(0),
  261. );
  262. }
  263. }
  264. },
  265. /**
  266. * Injects HTML for edit button into the preview that was just loaded.
  267. */
  268. _setUpEditButton() {
  269. // No buttons for missing media.
  270. if (this.element.findOne('.media-embed-error')) {
  271. return;
  272. }
  273. /**
  274. * Determines if a node is an element node.
  275. *
  276. * @param {CKEDITOR.dom.node} n
  277. * A DOM node to evaluate.
  278. *
  279. * @return {bool}
  280. * Returns true if node is an element node and not a non-element
  281. * node (such as NODE_TEXT, NODE_COMMENT, NODE_DOCUMENT or
  282. * NODE_DOCUMENT_FRAGMENT).
  283. *
  284. * @see https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#property-NODE_ELEMENT
  285. */
  286. const isElementNode = function(n) {
  287. return n.type === CKEDITOR.NODE_ELEMENT;
  288. };
  289. // Find the actual embedded media in the DOM.
  290. const embeddedMediaContainer = this.data.hasCaption
  291. ? this.element.findOne('figure')
  292. : this.element;
  293. let embeddedMedia = embeddedMediaContainer.getFirst(isElementNode);
  294. // If there is a link, the top-level element is the `a` tag, and the
  295. // embedded media will be within the `a` tag.
  296. if (this.data.link) {
  297. embeddedMedia = embeddedMedia.getFirst(isElementNode);
  298. }
  299. // To allow the edit button to be absolutely positioned, the parent
  300. // element must be positioned relative.
  301. embeddedMedia.setStyle('position', 'relative');
  302. const editButton = CKEDITOR.dom.element.createFromHtml(
  303. Drupal.theme('mediaEmbedEditButton'),
  304. );
  305. embeddedMedia.getFirst().insertBeforeMe(editButton);
  306. // Make the edit button do things.
  307. const widget = this;
  308. this.element
  309. .findOne('.media-library-item__edit')
  310. .on('click', event => {
  311. const saveCallback = function(values) {
  312. event.cancel();
  313. editor.fire('saveSnapshot');
  314. if (values.hasOwnProperty('attributes')) {
  315. // Combine the dialog attributes with the widget attributes.
  316. // This copies the properties from widget.data.attributes to
  317. // values.attributes. (Properties already present
  318. // in values.attributes are not overwritten.)
  319. CKEDITOR.tools.extend(
  320. values.attributes,
  321. widget.data.attributes,
  322. );
  323. // Allow the dialog to delete attributes by setting them
  324. // to `false` or `none`. For example: `alt`.
  325. Object.keys(values.attributes).forEach(prop => {
  326. if (
  327. values.attributes[prop] === false ||
  328. (prop === 'data-align' &&
  329. values.attributes[prop] === 'none')
  330. ) {
  331. delete values.attributes[prop];
  332. }
  333. });
  334. }
  335. widget.setData({
  336. attributes: values.attributes,
  337. hasCaption: !!values.hasCaption,
  338. });
  339. editor.fire('saveSnapshot');
  340. };
  341. Drupal.ckeditor.openDialog(
  342. editor,
  343. Drupal.url(
  344. `editor/dialog/media/${editor.config.drupal.format}`,
  345. ),
  346. widget.data,
  347. saveCallback,
  348. {},
  349. );
  350. });
  351. // Allow opening the dialog with the return key or the space bar
  352. // by triggering a click event when a keydown event occurs on
  353. // the edit button.
  354. this.element
  355. .findOne('.media-library-item__edit')
  356. .on('keydown', event => {
  357. // The character code for the return key.
  358. const returnKey = 13;
  359. // The character code for the space bar.
  360. const spaceBar = 32;
  361. if (typeof event.data !== 'undefined') {
  362. const keypress = event.data.getKey();
  363. if (keypress === returnKey || keypress === spaceBar) {
  364. // Clicks the edit button that triggered the 'keydown'
  365. // event.
  366. event.sender.$.click();
  367. }
  368. // Stop propagation to keep the return key from
  369. // adding a line break.
  370. event.data.$.stopPropagation();
  371. event.data.$.stopImmediatePropagation();
  372. }
  373. });
  374. },
  375. _tearDownDynamicEditables() {
  376. // If we are watching for changes to the caption, stop doing that.
  377. if (this.captionObserver) {
  378. this.captionObserver.disconnect();
  379. }
  380. },
  381. /**
  382. * Determines if the preview needs to be re-rendered by the server.
  383. *
  384. * @return {boolean}
  385. * Returns true if the data hashes differ.
  386. */
  387. _previewNeedsServerSideUpdate() {
  388. // When the widget is first loading, it of course needs to still get a preview!
  389. if (!this.ready) {
  390. return true;
  391. }
  392. return this._hashData(this.oldData) !== this._hashData(this.data);
  393. },
  394. /**
  395. * Computes a hash of the data that can only be previewed by the server.
  396. *
  397. * @return {string}
  398. */
  399. _hashData(data) {
  400. const dataToHash = CKEDITOR.tools.clone(data);
  401. // The caption does not need rendering.
  402. delete dataToHash.attributes['data-caption'];
  403. // The media entity's label is server-side data and cannot be
  404. // modified by the content author.
  405. delete dataToHash.label;
  406. // Changed link destinations do not affect the visual preview.
  407. if (dataToHash.link) {
  408. delete dataToHash.link.href;
  409. }
  410. return JSON.stringify(dataToHash);
  411. },
  412. /**
  413. * Loads an media embed preview and runs a callback after insertion.
  414. *
  415. * Note the absence of caching, that's because this uses a GET request (which is cacheable) and the server takes
  416. * special care to make the responses privately cacheable (i.e. per session) in the browser.
  417. *
  418. * @see \Drupal\media\Controller\MediaFilterController::preview()
  419. *
  420. * @param {function} callback
  421. * A callback function that will be called after the preview has
  422. * loaded. Receives the widget instance.
  423. */
  424. _loadPreview(callback) {
  425. jQuery.get({
  426. url: Drupal.url(`media/${editor.config.drupal.format}/preview`),
  427. data: {
  428. text: this.downcast().getOuterHtml(),
  429. uuid: this.data.attributes['data-entity-uuid'],
  430. },
  431. dataType: 'html',
  432. success: (previewHtml, textStatus, jqXhr) => {
  433. this.element.setHtml(previewHtml);
  434. this.setData(
  435. 'label',
  436. jqXhr.getResponseHeader('Drupal-Media-Label'),
  437. );
  438. callback(this);
  439. },
  440. error: () => {
  441. this.element.setHtml(Drupal.theme('mediaEmbedPreviewError'));
  442. },
  443. });
  444. },
  445. });
  446. },
  447. afterInit(editor) {
  448. linkCommandIntegrator(editor);
  449. },
  450. });
  451. })(jQuery, Drupal, CKEDITOR);