You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1095 lines
30 KiB

  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 ', // trailing space is needed, 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 );
  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,
  283. captionNode, dd, dl, id, attrs, linkAttrs, width, height, align,
  284. $imageNode, srcset, src,
  285. dom = editor.dom;
  286. classes = tinymce.explode( imageData.extraClasses, ' ' );
  287. if ( ! classes ) {
  288. classes = [];
  289. }
  290. if ( ! imageData.caption ) {
  291. classes.push( 'align' + imageData.align );
  292. }
  293. if ( imageData.attachment_id ) {
  294. classes.push( 'wp-image-' + imageData.attachment_id );
  295. if ( imageData.size && imageData.size !== 'custom' ) {
  296. classes.push( 'size-' + imageData.size );
  297. }
  298. }
  299. width = imageData.width;
  300. height = imageData.height;
  301. if ( imageData.size === 'custom' ) {
  302. width = imageData.customWidth;
  303. height = imageData.customHeight;
  304. }
  305. attrs = {
  306. src: imageData.url,
  307. width: width || null,
  308. height: height || null,
  309. title: imageData.title || null,
  310. 'class': classes.join( ' ' ) || null
  311. };
  312. dom.setAttribs( imageNode, attrs );
  313. // Preserve empty alt attributes.
  314. editor.$( imageNode ).attr( 'alt', imageData.alt || '' );
  315. linkAttrs = {
  316. href: imageData.linkUrl,
  317. rel: imageData.linkRel || null,
  318. target: imageData.linkTargetBlank ? '_blank': null,
  319. 'class': imageData.linkClassName || null
  320. };
  321. if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
  322. // Update or remove an existing link wrapped around the image
  323. if ( imageData.linkUrl ) {
  324. dom.setAttribs( imageNode.parentNode, linkAttrs );
  325. } else {
  326. dom.remove( imageNode.parentNode, true );
  327. }
  328. } else if ( imageData.linkUrl ) {
  329. if ( linkNode = dom.getParent( imageNode, 'a' ) ) {
  330. // The image is inside a link together with other nodes,
  331. // or is nested in another node, move it out
  332. dom.insertAfter( imageNode, linkNode );
  333. }
  334. // Add link wrapped around the image
  335. linkNode = dom.create( 'a', linkAttrs );
  336. imageNode.parentNode.insertBefore( linkNode, imageNode );
  337. linkNode.appendChild( imageNode );
  338. }
  339. captionNode = editor.dom.getParent( imageNode, '.mceTemp' );
  340. if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
  341. node = imageNode.parentNode;
  342. } else {
  343. node = imageNode;
  344. }
  345. if ( imageData.caption ) {
  346. imageData.caption = verifyHTML( imageData.caption );
  347. id = imageData.attachment_id ? 'attachment_' + imageData.attachment_id : null;
  348. align = 'align' + ( imageData.align || 'none' );
  349. className = 'wp-caption ' + align;
  350. if ( imageData.captionClassName ) {
  351. className += ' ' + imageData.captionClassName.replace( /[<>&]+/g, '' );
  352. }
  353. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  354. width = parseInt( width, 10 );
  355. width += 10;
  356. }
  357. if ( captionNode ) {
  358. dl = dom.select( 'dl.wp-caption', captionNode );
  359. if ( dl.length ) {
  360. dom.setAttribs( dl, {
  361. id: id,
  362. 'class': className,
  363. style: 'width: ' + width + 'px'
  364. } );
  365. }
  366. dd = dom.select( '.wp-caption-dd', captionNode );
  367. if ( dd.length ) {
  368. dom.setHTML( dd[0], imageData.caption );
  369. }
  370. } else {
  371. id = id ? 'id="'+ id +'" ' : '';
  372. // should create a new function for generating the caption markup
  373. html = '<dl ' + id + 'class="' + className +'" style="width: '+ width +'px">' +
  374. '<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ imageData.caption +'</dd></dl>';
  375. wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
  376. if ( parent = dom.getParent( node, 'p' ) ) {
  377. parent.parentNode.insertBefore( wrap, parent );
  378. } else {
  379. node.parentNode.insertBefore( wrap, node );
  380. }
  381. editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
  382. if ( parent && dom.isEmpty( parent ) ) {
  383. dom.remove( parent );
  384. }
  385. }
  386. } else if ( captionNode ) {
  387. // Remove the caption wrapper and place the image in new paragraph
  388. parent = dom.create( 'p' );
  389. captionNode.parentNode.insertBefore( parent, captionNode );
  390. parent.appendChild( node );
  391. dom.remove( captionNode );
  392. }
  393. $imageNode = editor.$( imageNode );
  394. srcset = $imageNode.attr( 'srcset' );
  395. src = $imageNode.attr( 'src' );
  396. // Remove srcset and sizes if the image file was edited or the image was replaced.
  397. if ( srcset && src ) {
  398. src = src.replace( /[?#].*/, '' );
  399. if ( srcset.indexOf( src ) === -1 ) {
  400. $imageNode.attr( 'srcset', null ).attr( 'sizes', null );
  401. }
  402. }
  403. if ( wp.media.events ) {
  404. wp.media.events.trigger( 'editor:image-update', {
  405. editor: editor,
  406. metadata: imageData,
  407. image: imageNode
  408. } );
  409. }
  410. editor.nodeChanged();
  411. }
  412. function editImage( img ) {
  413. var frame, callback, metadata;
  414. if ( typeof wp === 'undefined' || ! wp.media ) {
  415. editor.execCommand( 'mceImage' );
  416. return;
  417. }
  418. metadata = extractImageData( img );
  419. // Manipulate the metadata by reference that is fed into the PostImage model used in the media modal
  420. wp.media.events.trigger( 'editor:image-edit', {
  421. editor: editor,
  422. metadata: metadata,
  423. image: img
  424. } );
  425. frame = wp.media({
  426. frame: 'image',
  427. state: 'image-details',
  428. metadata: metadata
  429. } );
  430. wp.media.events.trigger( 'editor:frame-create', { frame: frame } );
  431. callback = function( imageData ) {
  432. editor.focus();
  433. editor.undoManager.transact( function() {
  434. updateImage( img, imageData );
  435. } );
  436. frame.detach();
  437. };
  438. frame.state('image-details').on( 'update', callback );
  439. frame.state('replace-image').on( 'replace', callback );
  440. frame.on( 'close', function() {
  441. editor.focus();
  442. frame.detach();
  443. });
  444. frame.open();
  445. }
  446. function removeImage( node ) {
  447. var wrap = editor.dom.getParent( node, 'div.mceTemp' );
  448. if ( ! wrap && node.nodeName === 'IMG' ) {
  449. wrap = editor.dom.getParent( node, 'a' );
  450. }
  451. if ( wrap ) {
  452. if ( wrap.nextSibling ) {
  453. editor.selection.select( wrap.nextSibling );
  454. } else if ( wrap.previousSibling ) {
  455. editor.selection.select( wrap.previousSibling );
  456. } else {
  457. editor.selection.select( wrap.parentNode );
  458. }
  459. editor.selection.collapse( true );
  460. editor.dom.remove( wrap );
  461. } else {
  462. editor.dom.remove( node );
  463. }
  464. editor.nodeChanged();
  465. editor.undoManager.add();
  466. }
  467. editor.on( 'init', function() {
  468. var dom = editor.dom,
  469. captionClass = editor.getParam( 'wpeditimage_html5_captions' ) ? 'html5-captions' : 'html4-captions';
  470. dom.addClass( editor.getBody(), captionClass );
  471. // Add caption field to the default image dialog
  472. editor.on( 'wpLoadImageForm', function( event ) {
  473. if ( editor.getParam( 'wpeditimage_disable_captions' ) ) {
  474. return;
  475. }
  476. var captionField = {
  477. type: 'textbox',
  478. flex: 1,
  479. name: 'wpcaption',
  480. minHeight: 60,
  481. multiline: true,
  482. scroll: true,
  483. label: 'Image caption'
  484. };
  485. event.data.splice( event.data.length - 1, 0, captionField );
  486. });
  487. // Fix caption parent width for images added from URL
  488. editor.on( 'wpNewImageRefresh', function( event ) {
  489. var parent, captionWidth;
  490. if ( parent = dom.getParent( event.node, 'dl.wp-caption' ) ) {
  491. if ( ! parent.style.width ) {
  492. captionWidth = parseInt( event.node.clientWidth, 10 ) + 10;
  493. captionWidth = captionWidth ? captionWidth + 'px' : '50%';
  494. dom.setStyle( parent, 'width', captionWidth );
  495. }
  496. }
  497. });
  498. editor.on( 'wpImageFormSubmit', function( event ) {
  499. var data = event.imgData.data,
  500. imgNode = event.imgData.node,
  501. caption = event.imgData.wpcaption,
  502. captionId = '',
  503. captionAlign = '',
  504. captionWidth = '',
  505. imgId = null,
  506. wrap, parent, node, html;
  507. // Temp image id so we can find the node later
  508. data.id = '__wp-temp-img-id';
  509. // Cancel the original callback
  510. event.imgData.cancel = true;
  511. if ( ! data.style ) {
  512. data.style = null;
  513. }
  514. if ( ! data.src ) {
  515. // Delete the image and the caption
  516. if ( imgNode ) {
  517. if ( wrap = dom.getParent( imgNode, 'div.mceTemp' ) ) {
  518. dom.remove( wrap );
  519. } else if ( imgNode.parentNode.nodeName === 'A' ) {
  520. dom.remove( imgNode.parentNode );
  521. } else {
  522. dom.remove( imgNode );
  523. }
  524. editor.nodeChanged();
  525. }
  526. return;
  527. }
  528. if ( caption ) {
  529. caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<\/?[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
  530. // No line breaks inside HTML tags
  531. return a.replace( /[\r\n\t]+/, ' ' );
  532. });
  533. // Convert remaining line breaks to <br>
  534. caption = caption.replace( /(<br[^>]*>)\s*\n\s*/g, '$1' ).replace( /\s*\n\s*/g, '<br />' );
  535. caption = verifyHTML( caption );
  536. }
  537. if ( ! imgNode ) {
  538. // New image inserted
  539. html = dom.createHTML( 'img', data );
  540. if ( caption ) {
  541. node = editor.selection.getNode();
  542. if ( data.width ) {
  543. captionWidth = parseInt( data.width, 10 );
  544. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  545. captionWidth += 10;
  546. }
  547. captionWidth = ' style="width: ' + captionWidth + 'px"';
  548. }
  549. html = '<dl class="wp-caption alignnone"' + captionWidth + '>' +
  550. '<dt class="wp-caption-dt">'+ html +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
  551. if ( node.nodeName === 'P' ) {
  552. parent = node;
  553. } else {
  554. parent = dom.getParent( node, 'p' );
  555. }
  556. if ( parent && parent.nodeName === 'P' ) {
  557. wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
  558. parent.parentNode.insertBefore( wrap, parent );
  559. editor.selection.select( wrap );
  560. editor.nodeChanged();
  561. if ( dom.isEmpty( parent ) ) {
  562. dom.remove( parent );
  563. }
  564. } else {
  565. editor.selection.setContent( '<div class="mceTemp">' + html + '</div>' );
  566. }
  567. } else {
  568. editor.selection.setContent( html );
  569. }
  570. } else {
  571. // Edit existing image
  572. // Store the original image id if any
  573. imgId = imgNode.id || null;
  574. // Update the image node
  575. dom.setAttribs( imgNode, data );
  576. wrap = dom.getParent( imgNode, 'dl.wp-caption' );
  577. if ( caption ) {
  578. if ( wrap ) {
  579. if ( parent = dom.select( 'dd.wp-caption-dd', wrap )[0] ) {
  580. parent.innerHTML = caption;
  581. }
  582. } else {
  583. if ( imgNode.className ) {
  584. captionId = imgNode.className.match( /wp-image-([0-9]+)/ );
  585. captionAlign = imgNode.className.match( /align(left|right|center|none)/ );
  586. }
  587. if ( captionAlign ) {
  588. captionAlign = captionAlign[0];
  589. imgNode.className = imgNode.className.replace( /align(left|right|center|none)/g, '' );
  590. } else {
  591. captionAlign = 'alignnone';
  592. }
  593. captionAlign = ' class="wp-caption ' + captionAlign + '"';
  594. if ( captionId ) {
  595. captionId = ' id="attachment_' + captionId[1] + '"';
  596. }
  597. captionWidth = data.width || imgNode.clientWidth;
  598. if ( captionWidth ) {
  599. captionWidth = parseInt( captionWidth, 10 );
  600. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  601. captionWidth += 10;
  602. }
  603. captionWidth = ' style="width: '+ captionWidth +'px"';
  604. }
  605. if ( imgNode.parentNode && imgNode.parentNode.nodeName === 'A' ) {
  606. node = imgNode.parentNode;
  607. } else {
  608. node = imgNode;
  609. }
  610. html = '<dl ' + captionId + captionAlign + captionWidth + '>' +
  611. '<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
  612. wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
  613. if ( parent = dom.getParent( node, 'p' ) ) {
  614. parent.parentNode.insertBefore( wrap, parent );
  615. } else {
  616. node.parentNode.insertBefore( wrap, node );
  617. }
  618. editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
  619. if ( parent && dom.isEmpty( parent ) ) {
  620. dom.remove( parent );
  621. }
  622. }
  623. } else {
  624. if ( wrap ) {
  625. // Remove the caption wrapper and place the image in new paragraph
  626. if ( imgNode.parentNode.nodeName === 'A' ) {
  627. html = dom.getOuterHTML( imgNode.parentNode );
  628. } else {
  629. html = dom.getOuterHTML( imgNode );
  630. }
  631. parent = dom.create( 'p', {}, html );
  632. dom.insertAfter( parent, wrap.parentNode );
  633. editor.selection.select( parent );
  634. editor.nodeChanged();
  635. dom.remove( wrap.parentNode );
  636. }
  637. }
  638. }
  639. imgNode = dom.get('__wp-temp-img-id');
  640. dom.setAttrib( imgNode, 'id', imgId || null );
  641. event.imgData.node = imgNode;
  642. });
  643. editor.on( 'wpLoadImageData', function( event ) {
  644. var parent,
  645. data = event.imgData.data,
  646. imgNode = event.imgData.node;
  647. if ( parent = dom.getParent( imgNode, 'dl.wp-caption' ) ) {
  648. parent = dom.select( 'dd.wp-caption-dd', parent )[0];
  649. if ( parent ) {
  650. data.wpcaption = editor.serializer.serialize( parent )
  651. .replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
  652. }
  653. }
  654. });
  655. // Prevent IE11 from making dl.wp-caption resizable
  656. if ( tinymce.Env.ie && tinymce.Env.ie > 10 ) {
  657. // The 'mscontrolselect' event is supported only in IE11+
  658. dom.bind( editor.getBody(), 'mscontrolselect', function( event ) {
  659. if ( event.target.nodeName === 'IMG' && dom.getParent( event.target, '.wp-caption' ) ) {
  660. // Hide the thick border with resize handles around dl.wp-caption
  661. editor.getBody().focus(); // :(
  662. } else if ( event.target.nodeName === 'DL' && dom.hasClass( event.target, 'wp-caption' ) ) {
  663. // Trigger the thick border with resize handles...
  664. // This will make the caption text editable.
  665. event.target.focus();
  666. }
  667. });
  668. }
  669. });
  670. editor.on( 'ObjectResized', function( event ) {
  671. var node = event.target;
  672. if ( node.nodeName === 'IMG' ) {
  673. editor.undoManager.transact( function() {
  674. var parent, width,
  675. dom = editor.dom;
  676. node.className = node.className.replace( /\bsize-[^ ]+/, '' );
  677. if ( parent = dom.getParent( node, '.wp-caption' ) ) {
  678. width = event.width || dom.getAttrib( node, 'width' );
  679. if ( width ) {
  680. width = parseInt( width, 10 );
  681. if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
  682. width += 10;
  683. }
  684. dom.setStyle( parent, 'width', width + 'px' );
  685. }
  686. }
  687. });
  688. }
  689. });
  690. editor.on( 'pastePostProcess', function( event ) {
  691. // Pasting in a caption node.
  692. if ( editor.dom.getParent( editor.selection.getNode(), 'dd.wp-caption-dd' ) ) {
  693. // Remove "non-block" elements that should not be in captions.
  694. editor.$( 'img, audio, video, object, embed, iframe, script, style', event.node ).remove();
  695. editor.$( '*', event.node ).each( function( i, node ) {
  696. if ( editor.dom.isBlock( node ) ) {
  697. // Insert <br> where the blocks used to be. Makes it look better after pasting in the caption.
  698. if ( tinymce.trim( node.textContent || node.innerText ) ) {
  699. editor.dom.insertAfter( editor.dom.create( 'br' ), node );
  700. editor.dom.remove( node, true );
  701. } else {
  702. editor.dom.remove( node );
  703. }
  704. }
  705. });
  706. // Trim <br> tags.
  707. editor.$( 'br', event.node ).each( function( i, node ) {
  708. if ( ! node.nextSibling || node.nextSibling.nodeName === 'BR' ||
  709. ! node.previousSibling || node.previousSibling.nodeName === 'BR' ) {
  710. editor.dom.remove( node );
  711. }
  712. } );
  713. // Pasted HTML is cleaned up for inserting in the caption.
  714. pasteInCaption = true;
  715. }
  716. });
  717. editor.on( 'BeforeExecCommand', function( event ) {
  718. var node, p, DL, align, replacement, captionParent,
  719. cmd = event.command,
  720. dom = editor.dom;
  721. if ( cmd === 'mceInsertContent' || cmd === 'Indent' || cmd === 'Outdent' ) {
  722. node = editor.selection.getNode();
  723. captionParent = dom.getParent( node, 'div.mceTemp' );
  724. if ( captionParent ) {
  725. if ( cmd === 'mceInsertContent' ) {
  726. if ( pasteInCaption ) {
  727. pasteInCaption = false;
  728. // We are in the caption element, and in 'paste' context,
  729. // and the pasted HTML was cleaned up on 'pastePostProcess' above.
  730. // Let it be pasted in the caption.
  731. return;
  732. }
  733. // The paste is somewhere else in the caption DL element.
  734. // Prevent pasting in there as it will break the caption.
  735. // Make new paragraph under the caption DL and move the caret there.
  736. p = dom.create( 'p' );
  737. dom.insertAfter( p, captionParent );
  738. editor.selection.setCursorLocation( p, 0 );
  739. editor.nodeChanged();
  740. } else {
  741. // Clicking Indent or Outdent while an image with a caption is selected breaks the caption.
  742. // See #38313.
  743. event.preventDefault();
  744. event.stopImmediatePropagation();
  745. return false;
  746. }
  747. }
  748. } else if ( cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'wpAlignNone' ) {
  749. node = editor.selection.getNode();
  750. align = 'align' + cmd.slice( 7 ).toLowerCase();
  751. DL = editor.dom.getParent( node, '.wp-caption' );
  752. if ( node.nodeName !== 'IMG' && ! DL ) {
  753. return;
  754. }
  755. node = DL || node;
  756. if ( editor.dom.hasClass( node, align ) ) {
  757. replacement = ' alignnone';
  758. } else {
  759. replacement = ' ' + align;
  760. }
  761. node.className = trim( node.className.replace( / ?align(left|center|right|none)/g, '' ) + replacement );
  762. editor.nodeChanged();
  763. event.preventDefault();
  764. if ( toolbar ) {
  765. toolbar.reposition();
  766. }
  767. editor.fire( 'ExecCommand', {
  768. command: cmd,
  769. ui: event.ui,
  770. value: event.value
  771. } );
  772. }
  773. });
  774. editor.on( 'keydown', function( event ) {
  775. var node, wrap, P, spacer,
  776. selection = editor.selection,
  777. keyCode = event.keyCode,
  778. dom = editor.dom,
  779. VK = tinymce.util.VK;
  780. if ( keyCode === VK.ENTER ) {
  781. // When pressing Enter inside a caption move the caret to a new parapraph under it
  782. node = selection.getNode();
  783. wrap = dom.getParent( node, 'div.mceTemp' );
  784. if ( wrap ) {
  785. dom.events.cancel( event ); // Doesn't cancel all :(
  786. // Remove any extra dt and dd cleated on pressing Enter...
  787. tinymce.each( dom.select( 'dt, dd', wrap ), function( element ) {
  788. if ( dom.isEmpty( element ) ) {
  789. dom.remove( element );
  790. }
  791. });
  792. spacer = tinymce.Env.ie && tinymce.Env.ie < 11 ? '' : '<br data-mce-bogus="1" />';
  793. P = dom.create( 'p', null, spacer );
  794. if ( node.nodeName === 'DD' ) {
  795. dom.insertAfter( P, wrap );
  796. } else {
  797. wrap.parentNode.insertBefore( P, wrap );
  798. }
  799. editor.nodeChanged();
  800. selection.setCursorLocation( P, 0 );
  801. }
  802. } else if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
  803. node = selection.getNode();
  804. if ( node.nodeName === 'DIV' && dom.hasClass( node, 'mceTemp' ) ) {
  805. wrap = node;
  806. } else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) {
  807. wrap = dom.getParent( node, 'div.mceTemp' );
  808. }
  809. if ( wrap ) {
  810. dom.events.cancel( event );
  811. removeImage( node );
  812. return false;
  813. }
  814. }
  815. });
  816. // After undo/redo FF seems to set the image height very slowly when it is set to 'auto' in the CSS.
  817. // This causes image.getBoundingClientRect() to return wrong values and the resize handles are shown in wrong places.
  818. // Collapse the selection to remove the resize handles.
  819. if ( tinymce.Env.gecko ) {
  820. editor.on( 'undo redo', function() {
  821. if ( editor.selection.getNode().nodeName === 'IMG' ) {
  822. editor.selection.collapse();
  823. }
  824. });
  825. }
  826. editor.wpSetImgCaption = function( content ) {
  827. return parseShortcode( content );
  828. };
  829. editor.wpGetImgCaption = function( content ) {
  830. return getShortcode( content );
  831. };
  832. editor.on( 'beforeGetContent', function( event ) {
  833. if ( event.format !== 'raw' ) {
  834. editor.$( 'img[id="__wp-temp-img-id"]' ).attr( 'id', null );
  835. }
  836. });
  837. editor.on( 'BeforeSetContent', function( event ) {
  838. if ( event.format !== 'raw' ) {
  839. event.content = editor.wpSetImgCaption( event.content );
  840. }
  841. });
  842. editor.on( 'PostProcess', function( event ) {
  843. if ( event.get ) {
  844. event.content = editor.wpGetImgCaption( event.content );
  845. }
  846. });
  847. ( function() {
  848. var wrap;
  849. editor.on( 'dragstart', function() {
  850. var node = editor.selection.getNode();
  851. if ( node.nodeName === 'IMG' ) {
  852. wrap = editor.dom.getParent( node, '.mceTemp' );
  853. if ( ! wrap && node.parentNode.nodeName === 'A' && ! hasTextContent( node.parentNode ) ) {
  854. wrap = node.parentNode;
  855. }
  856. }
  857. } );
  858. editor.on( 'drop', function( event ) {
  859. var dom = editor.dom,
  860. rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint( event.clientX, event.clientY, editor.getDoc() );
  861. // Don't allow anything to be dropped in a captioned image.
  862. if ( rng && dom.getParent( rng.startContainer, '.mceTemp' ) ) {
  863. event.preventDefault();
  864. } else if ( wrap ) {
  865. event.preventDefault();
  866. editor.undoManager.transact( function() {
  867. if ( rng ) {
  868. editor.selection.setRng( rng );
  869. }
  870. editor.selection.setNode( wrap );
  871. dom.remove( wrap );
  872. } );
  873. }
  874. wrap = null;
  875. } );
  876. } )();
  877. // Add to editor.wp
  878. editor.wp = editor.wp || {};
  879. editor.wp.isPlaceholder = isPlaceholder;
  880. // Back-compat.
  881. return {
  882. _do_shcode: parseShortcode,
  883. _get_shcode: getShortcode
  884. };
  885. });