plugin.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. /* global tinymce */
  2. tinymce.PluginManager.add( 'wpeditimage', function( editor ) {
  3. var toolbar, serializer, touchOnImage, pasteInCaption,
  4. each = tinymce.each,
  5. trim = tinymce.trim,
  6. iOS = tinymce.Env.iOS;
  7. function isPlaceholder( node ) {
  8. return !! ( editor.dom.getAttrib( node, 'data-mce-placeholder' ) || editor.dom.getAttrib( node, 'data-mce-object' ) );
  9. }
  10. editor.addButton( 'wp_img_remove', {
  11. tooltip: 'Remove',
  12. icon: 'dashicon dashicons-no',
  13. onclick: function() {
  14. removeImage( editor.selection.getNode() );
  15. }
  16. } );
  17. editor.addButton( 'wp_img_edit', {
  18. tooltip: 'Edit|button', // '|button' is not displayed, only used for context
  19. icon: 'dashicon dashicons-edit',
  20. onclick: function() {
  21. editImage( editor.selection.getNode() );
  22. }
  23. } );
  24. each( {
  25. alignleft: 'Align left',
  26. aligncenter: 'Align center',
  27. alignright: 'Align right',
  28. alignnone: 'No alignment'
  29. }, function( tooltip, name ) {
  30. var direction = name.slice( 5 );
  31. editor.addButton( 'wp_img_' + name, {
  32. tooltip: tooltip,
  33. icon: 'dashicon dashicons-align-' + direction,
  34. cmd: 'alignnone' === name ? 'wpAlignNone' : 'Justify' + direction.slice( 0, 1 ).toUpperCase() + direction.slice( 1 ),
  35. onPostRender: function() {
  36. var self = this;
  37. editor.on( 'NodeChange', function( event ) {
  38. var node;
  39. // Don't bother.
  40. if ( event.element.nodeName !== 'IMG' ) {
  41. return;
  42. }
  43. node = editor.dom.getParent( event.element, '.wp-caption' ) || event.element;
  44. if ( 'alignnone' === name ) {
  45. self.active( ! /\balign(left|center|right)\b/.test( node.className ) );
  46. } else {
  47. self.active( editor.dom.hasClass( node, name ) );
  48. }
  49. } );
  50. }
  51. } );
  52. } );
  53. editor.once( 'preinit', function() {
  54. if ( editor.wp && editor.wp._createToolbar ) {
  55. toolbar = editor.wp._createToolbar( [
  56. 'wp_img_alignleft',
  57. 'wp_img_aligncenter',
  58. 'wp_img_alignright',
  59. 'wp_img_alignnone',
  60. 'wp_img_edit',
  61. 'wp_img_remove'
  62. ] );
  63. }
  64. } );
  65. editor.on( 'wptoolbar', function( event ) {
  66. if ( event.element.nodeName === 'IMG' && ! isPlaceholder( event.element ) ) {
  67. event.toolbar = toolbar;
  68. }
  69. } );
  70. function isNonEditable( node ) {
  71. var parent = editor.$( node ).parents( '[contenteditable]' );
  72. return parent && parent.attr( 'contenteditable' ) === 'false';
  73. }
  74. // Safari on iOS fails to select images in contentEditoble mode on touch.
  75. // Select them again.
  76. if ( iOS ) {
  77. editor.on( 'init', function() {
  78. editor.on( 'touchstart', function( event ) {
  79. if ( event.target.nodeName === 'IMG' && ! isNonEditable( event.target ) ) {
  80. touchOnImage = true;
  81. }
  82. });
  83. editor.dom.bind( editor.getDoc(), 'touchmove', function() {
  84. touchOnImage = false;
  85. });
  86. editor.on( 'touchend', function( event ) {
  87. if ( touchOnImage && event.target.nodeName === 'IMG' && ! isNonEditable( event.target ) ) {
  88. var node = event.target;
  89. touchOnImage = false;
  90. window.setTimeout( function() {
  91. editor.selection.select( node );
  92. editor.nodeChanged();
  93. }, 100 );
  94. } else if ( toolbar ) {
  95. toolbar.hide();
  96. }
  97. });
  98. });
  99. }
  100. function parseShortcode( content ) {
  101. return content.replace( /(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function( a, b, c ) {
  102. var id, align, classes, caption, img, width;
  103. id = b.match( /id=['"]([^'"]*)['"] ?/ );
  104. if ( id ) {
  105. b = b.replace( id[0], '' );
  106. }
  107. align = b.match( /align=['"]([^'"]*)['"] ?/ );
  108. if ( align ) {
  109. b = b.replace( align[0], '' );
  110. }
  111. classes = b.match( /class=['"]([^'"]*)['"] ?/ );
  112. if ( classes ) {
  113. b = b.replace( classes[0], '' );
  114. }
  115. width = b.match( /width=['"]([0-9]*)['"] ?/ );
  116. if ( width ) {
  117. b = b.replace( width[0], '' );
  118. }
  119. c = trim( c );
  120. img = c.match( /((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i );
  121. if ( img && img[2] ) {
  122. caption = trim( img[2] );
  123. img = trim( img[1] );
  124. } else {
  125. // old captions shortcode style
  126. caption = trim( b ).replace( /caption=['"]/, '' ).replace( /['"]$/, '' );
  127. img = c;
  128. }
  129. id = ( id && id[1] ) ? id[1].replace( /[<>&]+/g, '' ) : '';
  130. align = ( align && align[1] ) ? align[1] : 'alignnone';
  131. classes = ( classes && classes[1] ) ? ' ' + classes[1].replace( /[<>&]+/g, '' ) : '';
  132. if ( ! width && img ) {
  133. width = img.match( /width=['"]([0-9]*)['"]/ );
  134. }
  135. if ( width && width[1] ) {
  136. width = width[1];
  137. }
  138. if ( ! width || ! caption ) {
  139. return c;
  140. }
  141. width = parseInt( width, 10 );
  142. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  143. width += 10;
  144. }
  145. return '<div class="mceTemp"><dl id="' + id + '" class="wp-caption ' + align + classes + '" style="width: ' + width + 'px">' +
  146. '<dt class="wp-caption-dt">'+ img +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl></div>';
  147. });
  148. }
  149. function getShortcode( content ) {
  150. return content.replace( /(?:<div [^>]+mceTemp[^>]+>)?\s*(<dl [^>]+wp-caption[^>]+>[\s\S]+?<\/dl>)\s*(?:<\/div>)?/g, function( all, dl ) {
  151. var out = '';
  152. if ( dl.indexOf('<img ') === -1 || dl.indexOf('</p>') !== -1 ) {
  153. // Broken caption. The user managed to drag the image out or type in the wrapper div?
  154. // Remove the <dl>, <dd> and <dt> and return the remaining text.
  155. return dl.replace( /<d[ldt]( [^>]+)?>/g, '' ).replace( /<\/d[ldt]>/g, '' );
  156. }
  157. out = dl.replace( /\s*<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>\s*/gi, function( a, b, c, caption ) {
  158. var id, classes, align, width;
  159. width = c.match( /width="([0-9]*)"/ );
  160. width = ( width && width[1] ) ? width[1] : '';
  161. classes = b.match( /class="([^"]*)"/ );
  162. classes = ( classes && classes[1] ) ? classes[1] : '';
  163. align = classes.match( /align[a-z]+/i ) || 'alignnone';
  164. if ( ! width || ! caption ) {
  165. if ( 'alignnone' !== align[0] ) {
  166. c = c.replace( /><img/, ' class="' + align[0] + '"><img' );
  167. }
  168. return c;
  169. }
  170. id = b.match( /id="([^"]*)"/ );
  171. id = ( id && id[1] ) ? id[1] : '';
  172. classes = classes.replace( /wp-caption ?|align[a-z]+ ?/gi, '' );
  173. if ( classes ) {
  174. classes = ' class="' + classes + '"';
  175. }
  176. caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
  177. // no line breaks inside HTML tags
  178. return a.replace( /[\r\n\t]+/, ' ' );
  179. });
  180. // convert remaining line breaks to <br>
  181. caption = caption.replace( /\s*\n\s*/g, '<br />' );
  182. return '[caption id="' + id + '" align="' + align + '" width="' + width + '"' + classes + ']' + c + ' ' + caption + '[/caption]';
  183. });
  184. if ( out.indexOf('[caption') === -1 ) {
  185. // the caption html seems broken, try to find the image that may be wrapped in a link
  186. // and may be followed by <p> with the caption text.
  187. out = dl.replace( /[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2' );
  188. }
  189. return out;
  190. });
  191. }
  192. function extractImageData( imageNode ) {
  193. var classes, extraClasses, metadata, captionBlock, caption, link, width, height,
  194. captionClassName = [],
  195. dom = editor.dom,
  196. isIntRegExp = /^\d+$/;
  197. // default attributes
  198. metadata = {
  199. attachment_id: false,
  200. size: 'custom',
  201. caption: '',
  202. align: 'none',
  203. extraClasses: '',
  204. link: false,
  205. linkUrl: '',
  206. linkClassName: '',
  207. linkTargetBlank: false,
  208. linkRel: '',
  209. title: ''
  210. };
  211. metadata.url = dom.getAttrib( imageNode, 'src' );
  212. metadata.alt = dom.getAttrib( imageNode, 'alt' );
  213. metadata.title = dom.getAttrib( imageNode, 'title' );
  214. width = dom.getAttrib( imageNode, 'width' );
  215. height = dom.getAttrib( imageNode, 'height' );
  216. if ( ! isIntRegExp.test( width ) || parseInt( width, 10 ) < 1 ) {
  217. width = imageNode.naturalWidth || imageNode.width;
  218. }
  219. if ( ! isIntRegExp.test( height ) || parseInt( height, 10 ) < 1 ) {
  220. height = imageNode.naturalHeight || imageNode.height;
  221. }
  222. metadata.customWidth = metadata.width = width;
  223. metadata.customHeight = metadata.height = height;
  224. classes = tinymce.explode( imageNode.className, ' ' );
  225. extraClasses = [];
  226. tinymce.each( classes, function( name ) {
  227. if ( /^wp-image/.test( name ) ) {
  228. metadata.attachment_id = parseInt( name.replace( 'wp-image-', '' ), 10 );
  229. } else if ( /^align/.test( name ) ) {
  230. metadata.align = name.replace( 'align', '' );
  231. } else if ( /^size/.test( name ) ) {
  232. metadata.size = name.replace( 'size-', '' );
  233. } else {
  234. extraClasses.push( name );
  235. }
  236. } );
  237. metadata.extraClasses = extraClasses.join( ' ' );
  238. // Extract caption
  239. captionBlock = dom.getParents( imageNode, '.wp-caption' );
  240. if ( captionBlock.length ) {
  241. captionBlock = captionBlock[0];
  242. classes = captionBlock.className.split( ' ' );
  243. tinymce.each( classes, function( name ) {
  244. if ( /^align/.test( name ) ) {
  245. metadata.align = name.replace( 'align', '' );
  246. } else if ( name && name !== 'wp-caption' ) {
  247. captionClassName.push( name );
  248. }
  249. } );
  250. metadata.captionClassName = captionClassName.join( ' ' );
  251. caption = dom.select( 'dd.wp-caption-dd', captionBlock );
  252. if ( caption.length ) {
  253. caption = caption[0];
  254. metadata.caption = editor.serializer.serialize( caption )
  255. .replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
  256. }
  257. }
  258. // Extract linkTo
  259. if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' ) {
  260. link = imageNode.parentNode;
  261. metadata.linkUrl = dom.getAttrib( link, 'href' );
  262. metadata.linkTargetBlank = dom.getAttrib( link, 'target' ) === '_blank' ? true : false;
  263. metadata.linkRel = dom.getAttrib( link, 'rel' );
  264. metadata.linkClassName = link.className;
  265. }
  266. return metadata;
  267. }
  268. function hasTextContent( node ) {
  269. return node && !! ( node.textContent || node.innerText ).replace( /\ufeff/g, '' );
  270. }
  271. // Verify HTML in captions
  272. function verifyHTML( caption ) {
  273. if ( ! caption || ( caption.indexOf( '<' ) === -1 && caption.indexOf( '>' ) === -1 ) ) {
  274. return caption;
  275. }
  276. if ( ! serializer ) {
  277. serializer = new tinymce.html.Serializer( {}, editor.schema );
  278. }
  279. return serializer.serialize( editor.parser.parse( caption, { forced_root_block: false } ) );
  280. }
  281. function updateImage( $imageNode, imageData ) {
  282. var classes, className, node, html, parent, wrap, linkNode, imageNode,
  283. captionNode, dd, dl, id, attrs, linkAttrs, width, height, align,
  284. $imageNode, srcset, src,
  285. dom = editor.dom;
  286. if ( ! $imageNode || ! $imageNode.length ) {
  287. return;
  288. }
  289. imageNode = $imageNode[0];
  290. classes = tinymce.explode( imageData.extraClasses, ' ' );
  291. if ( ! classes ) {
  292. classes = [];
  293. }
  294. if ( ! imageData.caption ) {
  295. classes.push( 'align' + imageData.align );
  296. }
  297. if ( imageData.attachment_id ) {
  298. classes.push( 'wp-image-' + imageData.attachment_id );
  299. if ( imageData.size && imageData.size !== 'custom' ) {
  300. classes.push( 'size-' + imageData.size );
  301. }
  302. }
  303. width = imageData.width;
  304. height = imageData.height;
  305. if ( imageData.size === 'custom' ) {
  306. width = imageData.customWidth;
  307. height = imageData.customHeight;
  308. }
  309. attrs = {
  310. src: imageData.url,
  311. width: width || null,
  312. height: height || null,
  313. title: imageData.title || null,
  314. 'class': classes.join( ' ' ) || null
  315. };
  316. dom.setAttribs( imageNode, attrs );
  317. // Preserve empty alt attributes.
  318. $imageNode.attr( 'alt', imageData.alt || '' );
  319. linkAttrs = {
  320. href: imageData.linkUrl,
  321. rel: imageData.linkRel || null,
  322. target: imageData.linkTargetBlank ? '_blank': null,
  323. 'class': imageData.linkClassName || null
  324. };
  325. if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
  326. // Update or remove an existing link wrapped around the image
  327. if ( imageData.linkUrl ) {
  328. dom.setAttribs( imageNode.parentNode, linkAttrs );
  329. } else {
  330. dom.remove( imageNode.parentNode, true );
  331. }
  332. } else if ( imageData.linkUrl ) {
  333. if ( linkNode = dom.getParent( imageNode, 'a' ) ) {
  334. // The image is inside a link together with other nodes,
  335. // or is nested in another node, move it out
  336. dom.insertAfter( imageNode, linkNode );
  337. }
  338. // Add link wrapped around the image
  339. linkNode = dom.create( 'a', linkAttrs );
  340. imageNode.parentNode.insertBefore( linkNode, imageNode );
  341. linkNode.appendChild( imageNode );
  342. }
  343. captionNode = editor.dom.getParent( imageNode, '.mceTemp' );
  344. if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
  345. node = imageNode.parentNode;
  346. } else {
  347. node = imageNode;
  348. }
  349. if ( imageData.caption ) {
  350. imageData.caption = verifyHTML( imageData.caption );
  351. id = imageData.attachment_id ? 'attachment_' + imageData.attachment_id : null;
  352. align = 'align' + ( imageData.align || 'none' );
  353. className = 'wp-caption ' + align;
  354. if ( imageData.captionClassName ) {
  355. className += ' ' + imageData.captionClassName.replace( /[<>&]+/g, '' );
  356. }
  357. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  358. width = parseInt( width, 10 );
  359. width += 10;
  360. }
  361. if ( captionNode ) {
  362. dl = dom.select( 'dl.wp-caption', captionNode );
  363. if ( dl.length ) {
  364. dom.setAttribs( dl, {
  365. id: id,
  366. 'class': className,
  367. style: 'width: ' + width + 'px'
  368. } );
  369. }
  370. dd = dom.select( '.wp-caption-dd', captionNode );
  371. if ( dd.length ) {
  372. dom.setHTML( dd[0], imageData.caption );
  373. }
  374. } else {
  375. id = id ? 'id="'+ id +'" ' : '';
  376. // should create a new function for generating the caption markup
  377. html = '<dl ' + id + 'class="' + className +'" style="width: '+ width +'px">' +
  378. '<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ imageData.caption +'</dd></dl>';
  379. wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
  380. if ( parent = dom.getParent( node, 'p' ) ) {
  381. parent.parentNode.insertBefore( wrap, parent );
  382. } else {
  383. node.parentNode.insertBefore( wrap, node );
  384. }
  385. editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
  386. if ( parent && dom.isEmpty( parent ) ) {
  387. dom.remove( parent );
  388. }
  389. }
  390. } else if ( captionNode ) {
  391. // Remove the caption wrapper and place the image in new paragraph
  392. parent = dom.create( 'p' );
  393. captionNode.parentNode.insertBefore( parent, captionNode );
  394. parent.appendChild( node );
  395. dom.remove( captionNode );
  396. }
  397. $imageNode = editor.$( imageNode );
  398. srcset = $imageNode.attr( 'srcset' );
  399. src = $imageNode.attr( 'src' );
  400. // Remove srcset and sizes if the image file was edited or the image was replaced.
  401. if ( srcset && src ) {
  402. src = src.replace( /[?#].*/, '' );
  403. if ( srcset.indexOf( src ) === -1 ) {
  404. $imageNode.attr( 'srcset', null ).attr( 'sizes', null );
  405. }
  406. }
  407. if ( wp.media.events ) {
  408. wp.media.events.trigger( 'editor:image-update', {
  409. editor: editor,
  410. metadata: imageData,
  411. image: imageNode
  412. } );
  413. }
  414. editor.nodeChanged();
  415. }
  416. function editImage( img ) {
  417. var frame, callback, metadata, imageNode;
  418. if ( typeof wp === 'undefined' || ! wp.media ) {
  419. editor.execCommand( 'mceImage' );
  420. return;
  421. }
  422. metadata = extractImageData( img );
  423. // Mark the image node so we can select it later.
  424. editor.$( img ).attr( 'data-wp-editing', 1 );
  425. // Manipulate the metadata by reference that is fed into the PostImage model used in the media modal
  426. wp.media.events.trigger( 'editor:image-edit', {
  427. editor: editor,
  428. metadata: metadata,
  429. image: img
  430. } );
  431. frame = wp.media({
  432. frame: 'image',
  433. state: 'image-details',
  434. metadata: metadata
  435. } );
  436. wp.media.events.trigger( 'editor:frame-create', { frame: frame } );
  437. callback = function( imageData ) {
  438. editor.undoManager.transact( function() {
  439. updateImage( imageNode, imageData );
  440. } );
  441. frame.detach();
  442. };
  443. frame.state('image-details').on( 'update', callback );
  444. frame.state('replace-image').on( 'replace', callback );
  445. frame.on( 'close', function() {
  446. editor.focus();
  447. frame.detach();
  448. // `close` fires first...
  449. // To be able to update the image node, we need to find it here,
  450. // and use it in the callback.
  451. imageNode = editor.$( 'img[data-wp-editing]' )
  452. imageNode.removeAttr( 'data-wp-editing' );
  453. });
  454. frame.open();
  455. }
  456. function removeImage( node ) {
  457. var wrap = editor.dom.getParent( node, 'div.mceTemp' );
  458. if ( ! wrap && node.nodeName === 'IMG' ) {
  459. wrap = editor.dom.getParent( node, 'a' );
  460. }
  461. if ( wrap ) {
  462. if ( wrap.nextSibling ) {
  463. editor.selection.select( wrap.nextSibling );
  464. } else if ( wrap.previousSibling ) {
  465. editor.selection.select( wrap.previousSibling );
  466. } else {
  467. editor.selection.select( wrap.parentNode );
  468. }
  469. editor.selection.collapse( true );
  470. editor.dom.remove( wrap );
  471. } else {
  472. editor.dom.remove( node );
  473. }
  474. editor.nodeChanged();
  475. editor.undoManager.add();
  476. }
  477. editor.on( 'init', function() {
  478. var dom = editor.dom,
  479. captionClass = editor.getParam( 'wpeditimage_html5_captions' ) ? 'html5-captions' : 'html4-captions';
  480. dom.addClass( editor.getBody(), captionClass );
  481. // Prevent IE11 from making dl.wp-caption resizable
  482. if ( tinymce.Env.ie && tinymce.Env.ie > 10 ) {
  483. // The 'mscontrolselect' event is supported only in IE11+
  484. dom.bind( editor.getBody(), 'mscontrolselect', function( event ) {
  485. if ( event.target.nodeName === 'IMG' && dom.getParent( event.target, '.wp-caption' ) ) {
  486. // Hide the thick border with resize handles around dl.wp-caption
  487. editor.getBody().focus(); // :(
  488. } else if ( event.target.nodeName === 'DL' && dom.hasClass( event.target, 'wp-caption' ) ) {
  489. // Trigger the thick border with resize handles...
  490. // This will make the caption text editable.
  491. event.target.focus();
  492. }
  493. });
  494. }
  495. });
  496. editor.on( 'ObjectResized', function( event ) {
  497. var node = event.target;
  498. if ( node.nodeName === 'IMG' ) {
  499. editor.undoManager.transact( function() {
  500. var parent, width,
  501. dom = editor.dom;
  502. node.className = node.className.replace( /\bsize-[^ ]+/, '' );
  503. if ( parent = dom.getParent( node, '.wp-caption' ) ) {
  504. width = event.width || dom.getAttrib( node, 'width' );
  505. if ( width ) {
  506. width = parseInt( width, 10 );
  507. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  508. width += 10;
  509. }
  510. dom.setStyle( parent, 'width', width + 'px' );
  511. }
  512. }
  513. });
  514. }
  515. });
  516. editor.on( 'pastePostProcess', function( event ) {
  517. // Pasting in a caption node.
  518. if ( editor.dom.getParent( editor.selection.getNode(), 'dd.wp-caption-dd' ) ) {
  519. // Remove "non-block" elements that should not be in captions.
  520. editor.$( 'img, audio, video, object, embed, iframe, script, style', event.node ).remove();
  521. editor.$( '*', event.node ).each( function( i, node ) {
  522. if ( editor.dom.isBlock( node ) ) {
  523. // Insert <br> where the blocks used to be. Makes it look better after pasting in the caption.
  524. if ( tinymce.trim( node.textContent || node.innerText ) ) {
  525. editor.dom.insertAfter( editor.dom.create( 'br' ), node );
  526. editor.dom.remove( node, true );
  527. } else {
  528. editor.dom.remove( node );
  529. }
  530. }
  531. });
  532. // Trim <br> tags.
  533. editor.$( 'br', event.node ).each( function( i, node ) {
  534. if ( ! node.nextSibling || node.nextSibling.nodeName === 'BR' ||
  535. ! node.previousSibling || node.previousSibling.nodeName === 'BR' ) {
  536. editor.dom.remove( node );
  537. }
  538. } );
  539. // Pasted HTML is cleaned up for inserting in the caption.
  540. pasteInCaption = true;
  541. }
  542. });
  543. editor.on( 'BeforeExecCommand', function( event ) {
  544. var node, p, DL, align, replacement, captionParent,
  545. cmd = event.command,
  546. dom = editor.dom;
  547. if ( cmd === 'mceInsertContent' || cmd === 'Indent' || cmd === 'Outdent' ) {
  548. node = editor.selection.getNode();
  549. captionParent = dom.getParent( node, 'div.mceTemp' );
  550. if ( captionParent ) {
  551. if ( cmd === 'mceInsertContent' ) {
  552. if ( pasteInCaption ) {
  553. pasteInCaption = false;
  554. // We are in the caption element, and in 'paste' context,
  555. // and the pasted HTML was cleaned up on 'pastePostProcess' above.
  556. // Let it be pasted in the caption.
  557. return;
  558. }
  559. // The paste is somewhere else in the caption DL element.
  560. // Prevent pasting in there as it will break the caption.
  561. // Make new paragraph under the caption DL and move the caret there.
  562. p = dom.create( 'p' );
  563. dom.insertAfter( p, captionParent );
  564. editor.selection.setCursorLocation( p, 0 );
  565. // If the image is selected and the user pastes "over" it,
  566. // replace both the image and the caption elements with the pasted content.
  567. // This matches the behavior when pasting over non-caption images.
  568. if ( node.nodeName === 'IMG' ) {
  569. editor.$( captionParent ).remove();
  570. }
  571. editor.nodeChanged();
  572. } else {
  573. // Clicking Indent or Outdent while an image with a caption is selected breaks the caption.
  574. // See #38313.
  575. event.preventDefault();
  576. event.stopImmediatePropagation();
  577. return false;
  578. }
  579. }
  580. } else if ( cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'wpAlignNone' ) {
  581. node = editor.selection.getNode();
  582. align = 'align' + cmd.slice( 7 ).toLowerCase();
  583. DL = editor.dom.getParent( node, '.wp-caption' );
  584. if ( node.nodeName !== 'IMG' && ! DL ) {
  585. return;
  586. }
  587. node = DL || node;
  588. if ( editor.dom.hasClass( node, align ) ) {
  589. replacement = ' alignnone';
  590. } else {
  591. replacement = ' ' + align;
  592. }
  593. node.className = trim( node.className.replace( / ?align(left|center|right|none)/g, '' ) + replacement );
  594. editor.nodeChanged();
  595. event.preventDefault();
  596. if ( toolbar ) {
  597. toolbar.reposition();
  598. }
  599. editor.fire( 'ExecCommand', {
  600. command: cmd,
  601. ui: event.ui,
  602. value: event.value
  603. } );
  604. }
  605. });
  606. editor.on( 'keydown', function( event ) {
  607. var node, wrap, P, spacer,
  608. selection = editor.selection,
  609. keyCode = event.keyCode,
  610. dom = editor.dom,
  611. VK = tinymce.util.VK;
  612. if ( keyCode === VK.ENTER ) {
  613. // When pressing Enter inside a caption move the caret to a new parapraph under it
  614. node = selection.getNode();
  615. wrap = dom.getParent( node, 'div.mceTemp' );
  616. if ( wrap ) {
  617. dom.events.cancel( event ); // Doesn't cancel all :(
  618. // Remove any extra dt and dd cleated on pressing Enter...
  619. tinymce.each( dom.select( 'dt, dd', wrap ), function( element ) {
  620. if ( dom.isEmpty( element ) ) {
  621. dom.remove( element );
  622. }
  623. });
  624. spacer = tinymce.Env.ie && tinymce.Env.ie < 11 ? '' : '<br data-mce-bogus="1" />';
  625. P = dom.create( 'p', null, spacer );
  626. if ( node.nodeName === 'DD' ) {
  627. dom.insertAfter( P, wrap );
  628. } else {
  629. wrap.parentNode.insertBefore( P, wrap );
  630. }
  631. editor.nodeChanged();
  632. selection.setCursorLocation( P, 0 );
  633. }
  634. } else if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
  635. node = selection.getNode();
  636. if ( node.nodeName === 'DIV' && dom.hasClass( node, 'mceTemp' ) ) {
  637. wrap = node;
  638. } else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) {
  639. wrap = dom.getParent( node, 'div.mceTemp' );
  640. }
  641. if ( wrap ) {
  642. dom.events.cancel( event );
  643. removeImage( node );
  644. return false;
  645. }
  646. }
  647. });
  648. // After undo/redo FF seems to set the image height very slowly when it is set to 'auto' in the CSS.
  649. // This causes image.getBoundingClientRect() to return wrong values and the resize handles are shown in wrong places.
  650. // Collapse the selection to remove the resize handles.
  651. if ( tinymce.Env.gecko ) {
  652. editor.on( 'undo redo', function() {
  653. if ( editor.selection.getNode().nodeName === 'IMG' ) {
  654. editor.selection.collapse();
  655. }
  656. });
  657. }
  658. editor.wpSetImgCaption = function( content ) {
  659. return parseShortcode( content );
  660. };
  661. editor.wpGetImgCaption = function( content ) {
  662. return getShortcode( content );
  663. };
  664. editor.on( 'beforeGetContent', function( event ) {
  665. if ( event.format !== 'raw' ) {
  666. editor.$( 'img[id="__wp-temp-img-id"]' ).removeAttr( 'id' );
  667. }
  668. });
  669. editor.on( 'BeforeSetContent', function( event ) {
  670. if ( event.format !== 'raw' ) {
  671. event.content = editor.wpSetImgCaption( event.content );
  672. }
  673. });
  674. editor.on( 'PostProcess', function( event ) {
  675. if ( event.get ) {
  676. event.content = editor.wpGetImgCaption( event.content );
  677. }
  678. });
  679. ( function() {
  680. var wrap;
  681. editor.on( 'dragstart', function() {
  682. var node = editor.selection.getNode();
  683. if ( node.nodeName === 'IMG' ) {
  684. wrap = editor.dom.getParent( node, '.mceTemp' );
  685. if ( ! wrap && node.parentNode.nodeName === 'A' && ! hasTextContent( node.parentNode ) ) {
  686. wrap = node.parentNode;
  687. }
  688. }
  689. } );
  690. editor.on( 'drop', function( event ) {
  691. var dom = editor.dom,
  692. rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint( event.clientX, event.clientY, editor.getDoc() );
  693. // Don't allow anything to be dropped in a captioned image.
  694. if ( rng && dom.getParent( rng.startContainer, '.mceTemp' ) ) {
  695. event.preventDefault();
  696. } else if ( wrap ) {
  697. event.preventDefault();
  698. editor.undoManager.transact( function() {
  699. if ( rng ) {
  700. editor.selection.setRng( rng );
  701. }
  702. editor.selection.setNode( wrap );
  703. dom.remove( wrap );
  704. } );
  705. }
  706. wrap = null;
  707. } );
  708. } )();
  709. // Add to editor.wp
  710. editor.wp = editor.wp || {};
  711. editor.wp.isPlaceholder = isPlaceholder;
  712. // Back-compat.
  713. return {
  714. _do_shcode: parseShortcode,
  715. _get_shcode: getShortcode
  716. };
  717. });