]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/tinymce/plugins/wpeditimage/plugin.js
WordPress 4.3.1
[autoinstalls/wordpress.git] / wp-includes / js / tinymce / plugins / wpeditimage / plugin.js
1 /* global tinymce */
2 tinymce.PluginManager.add( 'wpeditimage', function( editor ) {
3         var toolbar, serializer,
4                 each = tinymce.each,
5                 trim = tinymce.trim,
6                 iOS = tinymce.Env.iOS;
7
8         function isPlaceholder( node ) {
9                 return !! ( editor.dom.getAttrib( node, 'data-mce-placeholder' ) || editor.dom.getAttrib( node, 'data-mce-object' ) );
10         }
11
12         editor.addButton( 'wp_img_remove', {
13                 tooltip: 'Remove',
14                 icon: 'dashicon dashicons-no',
15                 onclick: function() {
16                         removeImage( editor.selection.getNode() );
17                 }
18         } );
19
20         editor.addButton( 'wp_img_edit', {
21                 tooltip: 'Edit ', // trailing space is needed, used for context
22                 icon: 'dashicon dashicons-edit',
23                 onclick: function() {
24                         editImage( editor.selection.getNode() );
25                 }
26         } );
27
28         each( {
29                 alignleft: 'Align left',
30                 aligncenter: 'Align center',
31                 alignright: 'Align right',
32                 alignnone: 'No alignment'
33         }, function( tooltip, name ) {
34                 var direction = name.slice( 5 );
35
36                 editor.addButton( 'wp_img_' + name, {
37                         tooltip: tooltip,
38                         icon: 'dashicon dashicons-align-' + direction,
39                         cmd: 'alignnone' === name ? 'wpAlignNone' : 'Justify' + direction.slice( 0, 1 ).toUpperCase() + direction.slice( 1 ),
40                         onPostRender: function() {
41                                 var self = this;
42
43                                 editor.on( 'NodeChange', function( event ) {
44                                         var node;
45
46                                         // Don't bother.
47                                         if ( event.element.nodeName !== 'IMG' ) {
48                                                 return;
49                                         }
50
51                                         node = editor.dom.getParent( event.element, '.wp-caption' ) || event.element;
52
53                                         if ( 'alignnone' === name ) {
54                                                 self.active( ! /\balign(left|center|right)\b/.test( node.className ) );
55                                         } else {
56                                                 self.active( editor.dom.hasClass( node, name ) );
57                                         }
58                                 } );
59                         }
60                 } );
61         } );
62
63         editor.once( 'preinit', function() {
64                 if ( editor.wp && editor.wp._createToolbar ) {
65                         toolbar = editor.wp._createToolbar( [
66                                 'wp_img_alignleft',
67                                 'wp_img_aligncenter',
68                                 'wp_img_alignright',
69                                 'wp_img_alignnone',
70                                 'wp_img_edit',
71                                 'wp_img_remove'
72                         ] );
73                 }
74         } );
75
76         editor.on( 'wptoolbar', function( event ) {
77                 if ( event.element.nodeName === 'IMG' && ! isPlaceholder( event.element ) ) {
78                         event.toolbar = toolbar;
79                 }
80         } );
81
82         // Safari on iOS fails to select image nodes in contentEditoble mode on touch/click.
83         // Select them again.
84         if ( iOS ) {
85                 editor.on( 'click', function( event ) {
86                         if ( event.target.nodeName === 'IMG' ) {
87                                 var node = event.target;
88
89                                 window.setTimeout( function() {
90                                         editor.selection.select( node );
91                                         editor.nodeChanged();
92                                 }, 200 );
93                         } else if ( toolbar ) {
94                                 toolbar.hide();
95                         }
96                 } );
97         }
98
99         function parseShortcode( content ) {
100                 return content.replace( /(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function( a, b, c ) {
101                         var id, align, classes, caption, img, width;
102
103                         id = b.match( /id=['"]([^'"]*)['"] ?/ );
104                         if ( id ) {
105                                 b = b.replace( id[0], '' );
106                         }
107
108                         align = b.match( /align=['"]([^'"]*)['"] ?/ );
109                         if ( align ) {
110                                 b = b.replace( align[0], '' );
111                         }
112
113                         classes = b.match( /class=['"]([^'"]*)['"] ?/ );
114                         if ( classes ) {
115                                 b = b.replace( classes[0], '' );
116                         }
117
118                         width = b.match( /width=['"]([0-9]*)['"] ?/ );
119                         if ( width ) {
120                                 b = b.replace( width[0], '' );
121                         }
122
123                         c = trim( c );
124                         img = c.match( /((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i );
125
126                         if ( img && img[2] ) {
127                                 caption = trim( img[2] );
128                                 img = trim( img[1] );
129                         } else {
130                                 // old captions shortcode style
131                                 caption = trim( b ).replace( /caption=['"]/, '' ).replace( /['"]$/, '' );
132                                 img = c;
133                         }
134
135                         id = ( id && id[1] ) ? id[1].replace( /[<>&]+/g,  '' ) : '';
136                         align = ( align && align[1] ) ? align[1] : 'alignnone';
137                         classes = ( classes && classes[1] ) ? ' ' + classes[1].replace( /[<>&]+/g,  '' ) : '';
138
139                         if ( ! width && img ) {
140                                 width = img.match( /width=['"]([0-9]*)['"]/ );
141                         }
142
143                         if ( width && width[1] ) {
144                                 width = width[1];
145                         }
146
147                         if ( ! width || ! caption ) {
148                                 return c;
149                         }
150
151                         width = parseInt( width, 10 );
152                         if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
153                                 width += 10;
154                         }
155
156                         return '<div class="mceTemp"><dl id="' + id + '" class="wp-caption ' + align + classes + '" style="width: ' + width + 'px">' +
157                                 '<dt class="wp-caption-dt">'+ img +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl></div>';
158                 });
159         }
160
161         function getShortcode( content ) {
162                 return content.replace( /<div (?:id="attachment_|class="mceTemp)[^>]*>([\s\S]+?)<\/div>/g, function( a, b ) {
163                         var out = '';
164
165                         if ( b.indexOf('<img ') === -1 ) {
166                                 // Broken caption. The user managed to drag the image out?
167                                 // Try to return the caption text as a paragraph.
168                                 out = b.match( /<dd [^>]+>([\s\S]+?)<\/dd>/i );
169
170                                 if ( out && out[1] ) {
171                                         return '<p>' + out[1] + '</p>';
172                                 }
173
174                                 return '';
175                         }
176
177                         out = b.replace( /\s*<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>\s*/gi, function( a, b, c, caption ) {
178                                 var id, classes, align, width;
179
180                                 width = c.match( /width="([0-9]*)"/ );
181                                 width = ( width && width[1] ) ? width[1] : '';
182
183                                 classes = b.match( /class="([^"]*)"/ );
184                                 classes = ( classes && classes[1] ) ? classes[1] : '';
185                                 align = classes.match( /align[a-z]+/i ) || 'alignnone';
186
187                                 if ( ! width || ! caption ) {
188                                         if ( 'alignnone' !== align[0] ) {
189                                                 c = c.replace( /><img/, ' class="' + align[0] + '"><img' );
190                                         }
191                                         return c;
192                                 }
193
194                                 id = b.match( /id="([^"]*)"/ );
195                                 id = ( id && id[1] ) ? id[1] : '';
196
197                                 classes = classes.replace( /wp-caption ?|align[a-z]+ ?/gi, '' );
198
199                                 if ( classes ) {
200                                         classes = ' class="' + classes + '"';
201                                 }
202
203                                 caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
204                                         // no line breaks inside HTML tags
205                                         return a.replace( /[\r\n\t]+/, ' ' );
206                                 });
207
208                                 // convert remaining line breaks to <br>
209                                 caption = caption.replace( /\s*\n\s*/g, '<br />' );
210
211                                 return '[caption id="' + id + '" align="' + align + '" width="' + width + '"' + classes + ']' + c + ' ' + caption + '[/caption]';
212                         });
213
214                         if ( out.indexOf('[caption') === -1 ) {
215                                 // the caption html seems broken, try to find the image that may be wrapped in a link
216                                 // and may be followed by <p> with the caption text.
217                                 out = b.replace( /[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2' );
218                         }
219
220                         return out;
221                 });
222         }
223
224         function extractImageData( imageNode ) {
225                 var classes, extraClasses, metadata, captionBlock, caption, link, width, height,
226                         captionClassName = [],
227                         dom = editor.dom,
228                         isIntRegExp = /^\d+$/;
229
230                 // default attributes
231                 metadata = {
232                         attachment_id: false,
233                         size: 'custom',
234                         caption: '',
235                         align: 'none',
236                         extraClasses: '',
237                         link: false,
238                         linkUrl: '',
239                         linkClassName: '',
240                         linkTargetBlank: false,
241                         linkRel: '',
242                         title: ''
243                 };
244
245                 metadata.url = dom.getAttrib( imageNode, 'src' );
246                 metadata.alt = dom.getAttrib( imageNode, 'alt' );
247                 metadata.title = dom.getAttrib( imageNode, 'title' );
248
249                 width = dom.getAttrib( imageNode, 'width' );
250                 height = dom.getAttrib( imageNode, 'height' );
251
252                 if ( ! isIntRegExp.test( width ) || parseInt( width, 10 ) < 1 ) {
253                         width = imageNode.naturalWidth || imageNode.width;
254                 }
255
256                 if ( ! isIntRegExp.test( height ) || parseInt( height, 10 ) < 1 ) {
257                         height = imageNode.naturalHeight || imageNode.height;
258                 }
259
260                 metadata.customWidth = metadata.width = width;
261                 metadata.customHeight = metadata.height = height;
262
263                 classes = tinymce.explode( imageNode.className, ' ' );
264                 extraClasses = [];
265
266                 tinymce.each( classes, function( name ) {
267
268                         if ( /^wp-image/.test( name ) ) {
269                                 metadata.attachment_id = parseInt( name.replace( 'wp-image-', '' ), 10 );
270                         } else if ( /^align/.test( name ) ) {
271                                 metadata.align = name.replace( 'align', '' );
272                         } else if ( /^size/.test( name ) ) {
273                                 metadata.size = name.replace( 'size-', '' );
274                         } else {
275                                 extraClasses.push( name );
276                         }
277
278                 } );
279
280                 metadata.extraClasses = extraClasses.join( ' ' );
281
282                 // Extract caption
283                 captionBlock = dom.getParents( imageNode, '.wp-caption' );
284
285                 if ( captionBlock.length ) {
286                         captionBlock = captionBlock[0];
287
288                         classes = captionBlock.className.split( ' ' );
289                         tinymce.each( classes, function( name ) {
290                                 if ( /^align/.test( name ) ) {
291                                         metadata.align = name.replace( 'align', '' );
292                                 } else if ( name && name !== 'wp-caption' ) {
293                                         captionClassName.push( name );
294                                 }
295                         } );
296
297                         metadata.captionClassName = captionClassName.join( ' ' );
298
299                         caption = dom.select( 'dd.wp-caption-dd', captionBlock );
300                         if ( caption.length ) {
301                                 caption = caption[0];
302
303                                 metadata.caption = editor.serializer.serialize( caption )
304                                         .replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
305                         }
306                 }
307
308                 // Extract linkTo
309                 if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' ) {
310                         link = imageNode.parentNode;
311                         metadata.linkUrl = dom.getAttrib( link, 'href' );
312                         metadata.linkTargetBlank = dom.getAttrib( link, 'target' ) === '_blank' ? true : false;
313                         metadata.linkRel = dom.getAttrib( link, 'rel' );
314                         metadata.linkClassName = link.className;
315                 }
316
317                 return metadata;
318         }
319
320         function hasTextContent( node ) {
321                 return node && !! ( node.textContent || node.innerText );
322         }
323
324         // Verify HTML in captions
325         function verifyHTML( caption ) {
326                 if ( ! caption || ( caption.indexOf( '<' ) === -1 && caption.indexOf( '>' ) === -1 ) ) {
327                         return caption;
328                 }
329
330                 if ( ! serializer ) {
331                         serializer = new tinymce.html.Serializer( {}, editor.schema );
332                 }
333
334                 return serializer.serialize( editor.parser.parse( caption, { forced_root_block: false } ) );
335         }
336
337         function updateImage( imageNode, imageData ) {
338                 var classes, className, node, html, parent, wrap, linkNode,
339                         captionNode, dd, dl, id, attrs, linkAttrs, width, height, align,
340                         dom = editor.dom;
341
342                 classes = tinymce.explode( imageData.extraClasses, ' ' );
343
344                 if ( ! classes ) {
345                         classes = [];
346                 }
347
348                 if ( ! imageData.caption ) {
349                         classes.push( 'align' + imageData.align );
350                 }
351
352                 if ( imageData.attachment_id ) {
353                         classes.push( 'wp-image-' + imageData.attachment_id );
354                         if ( imageData.size && imageData.size !== 'custom' ) {
355                                 classes.push( 'size-' + imageData.size );
356                         }
357                 }
358
359                 width = imageData.width;
360                 height = imageData.height;
361
362                 if ( imageData.size === 'custom' ) {
363                         width = imageData.customWidth;
364                         height = imageData.customHeight;
365                 }
366
367                 attrs = {
368                         src: imageData.url,
369                         width: width || null,
370                         height: height || null,
371                         alt: imageData.alt,
372                         title: imageData.title || null,
373                         'class': classes.join( ' ' ) || null
374                 };
375
376                 dom.setAttribs( imageNode, attrs );
377
378                 linkAttrs = {
379                         href: imageData.linkUrl,
380                         rel: imageData.linkRel || null,
381                         target: imageData.linkTargetBlank ? '_blank': null,
382                         'class': imageData.linkClassName || null
383                 };
384
385                 if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
386                         // Update or remove an existing link wrapped around the image
387                         if ( imageData.linkUrl ) {
388                                 dom.setAttribs( imageNode.parentNode, linkAttrs );
389                         } else {
390                                 dom.remove( imageNode.parentNode, true );
391                         }
392                 } else if ( imageData.linkUrl ) {
393                         if ( linkNode = dom.getParent( imageNode, 'a' ) ) {
394                                 // The image is inside a link together with other nodes,
395                                 // or is nested in another node, move it out
396                                 dom.insertAfter( imageNode, linkNode );
397                         }
398
399                         // Add link wrapped around the image
400                         linkNode = dom.create( 'a', linkAttrs );
401                         imageNode.parentNode.insertBefore( linkNode, imageNode );
402                         linkNode.appendChild( imageNode );
403                 }
404
405                 captionNode = editor.dom.getParent( imageNode, '.mceTemp' );
406
407                 if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
408                         node = imageNode.parentNode;
409                 } else {
410                         node = imageNode;
411                 }
412
413                 if ( imageData.caption ) {
414                         imageData.caption = verifyHTML( imageData.caption );
415
416                         id = imageData.attachment_id ? 'attachment_' + imageData.attachment_id : null;
417                         align = 'align' + ( imageData.align || 'none' );
418                         className = 'wp-caption ' + align;
419
420                         if ( imageData.captionClassName ) {
421                                 className += ' ' + imageData.captionClassName.replace( /[<>&]+/g,  '' );
422                         }
423
424                         if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
425                                 width = parseInt( width, 10 );
426                                 width += 10;
427                         }
428
429                         if ( captionNode ) {
430                                 dl = dom.select( 'dl.wp-caption', captionNode );
431
432                                 if ( dl.length ) {
433                                         dom.setAttribs( dl, {
434                                                 id: id,
435                                                 'class': className,
436                                                 style: 'width: ' + width + 'px'
437                                         } );
438                                 }
439
440                                 dd = dom.select( '.wp-caption-dd', captionNode );
441
442                                 if ( dd.length ) {
443                                         dom.setHTML( dd[0], imageData.caption );
444                                 }
445
446                         } else {
447                                 id = id ? 'id="'+ id +'" ' : '';
448
449                                 // should create a new function for generating the caption markup
450                                 html =  '<dl ' + id + 'class="' + className +'" style="width: '+ width +'px">' +
451                                         '<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ imageData.caption +'</dd></dl>';
452
453                                 wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
454
455                                 if ( parent = dom.getParent( node, 'p' ) ) {
456                                         parent.parentNode.insertBefore( wrap, parent );
457                                 } else {
458                                         node.parentNode.insertBefore( wrap, node );
459                                 }
460
461                                 editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
462
463                                 if ( parent && dom.isEmpty( parent ) ) {
464                                         dom.remove( parent );
465                                 }
466                         }
467                 } else if ( captionNode ) {
468                         // Remove the caption wrapper and place the image in new paragraph
469                         parent = dom.create( 'p' );
470                         captionNode.parentNode.insertBefore( parent, captionNode );
471                         parent.appendChild( node );
472                         dom.remove( captionNode );
473                 }
474
475                 if ( wp.media.events ) {
476                         wp.media.events.trigger( 'editor:image-update', {
477                                 editor: editor,
478                                 metadata: imageData,
479                                 image: imageNode
480                         } );
481                 }
482
483                 editor.nodeChanged();
484         }
485
486         function editImage( img ) {
487                 var frame, callback, metadata;
488
489                 if ( typeof wp === 'undefined' || ! wp.media ) {
490                         editor.execCommand( 'mceImage' );
491                         return;
492                 }
493
494                 metadata = extractImageData( img );
495
496                 // Manipulate the metadata by reference that is fed into the PostImage model used in the media modal
497                 wp.media.events.trigger( 'editor:image-edit', {
498                         editor: editor,
499                         metadata: metadata,
500                         image: img
501                 } );
502
503                 frame = wp.media({
504                         frame: 'image',
505                         state: 'image-details',
506                         metadata: metadata
507                 } );
508
509                 wp.media.events.trigger( 'editor:frame-create', { frame: frame } );
510
511                 callback = function( imageData ) {
512                         editor.focus();
513                         editor.undoManager.transact( function() {
514                                 updateImage( img, imageData );
515                         } );
516                         frame.detach();
517                 };
518
519                 frame.state('image-details').on( 'update', callback );
520                 frame.state('replace-image').on( 'replace', callback );
521                 frame.on( 'close', function() {
522                         editor.focus();
523                         frame.detach();
524                 });
525
526                 frame.open();
527         }
528
529         function removeImage( node ) {
530                 var wrap = editor.dom.getParent( node, 'div.mceTemp' );
531
532                 if ( ! wrap && node.nodeName === 'IMG' ) {
533                         wrap = editor.dom.getParent( node, 'a' );
534                 }
535
536                 if ( wrap ) {
537                         if ( wrap.nextSibling ) {
538                                 editor.selection.select( wrap.nextSibling );
539                         } else if ( wrap.previousSibling ) {
540                                 editor.selection.select( wrap.previousSibling );
541                         } else {
542                                 editor.selection.select( wrap.parentNode );
543                         }
544
545                         editor.selection.collapse( true );
546                         editor.dom.remove( wrap );
547                 } else {
548                         editor.dom.remove( node );
549                 }
550
551                 editor.nodeChanged();
552                 editor.undoManager.add();
553         }
554
555         editor.on( 'init', function() {
556                 var dom = editor.dom,
557                         captionClass = editor.getParam( 'wpeditimage_html5_captions' ) ? 'html5-captions' : 'html4-captions';
558
559                 dom.addClass( editor.getBody(), captionClass );
560
561                 // Add caption field to the default image dialog
562                 editor.on( 'wpLoadImageForm', function( event ) {
563                         if ( editor.getParam( 'wpeditimage_disable_captions' ) ) {
564                                 return;
565                         }
566
567                         var captionField = {
568                                 type: 'textbox',
569                                 flex: 1,
570                                 name: 'caption',
571                                 minHeight: 60,
572                                 multiline: true,
573                                 scroll: true,
574                                 label: 'Image caption'
575                         };
576
577                         event.data.splice( event.data.length - 1, 0, captionField );
578                 });
579
580                 // Fix caption parent width for images added from URL
581                 editor.on( 'wpNewImageRefresh', function( event ) {
582                         var parent, captionWidth;
583
584                         if ( parent = dom.getParent( event.node, 'dl.wp-caption' ) ) {
585                                 if ( ! parent.style.width ) {
586                                         captionWidth = parseInt( event.node.clientWidth, 10 ) + 10;
587                                         captionWidth = captionWidth ? captionWidth + 'px' : '50%';
588                                         dom.setStyle( parent, 'width', captionWidth );
589                                 }
590                         }
591                 });
592
593                 editor.on( 'wpImageFormSubmit', function( event ) {
594                         var data = event.imgData.data,
595                                 imgNode = event.imgData.node,
596                                 caption = event.imgData.caption,
597                                 captionId = '',
598                                 captionAlign = '',
599                                 captionWidth = '',
600                                 wrap, parent, node, html, imgId;
601
602                         // Temp image id so we can find the node later
603                         data.id = '__wp-temp-img-id';
604                         // Cancel the original callback
605                         event.imgData.cancel = true;
606
607                         if ( ! data.style ) {
608                                 data.style = null;
609                         }
610
611                         if ( ! data.src ) {
612                                 // Delete the image and the caption
613                                 if ( imgNode ) {
614                                         if ( wrap = dom.getParent( imgNode, 'div.mceTemp' ) ) {
615                                                 dom.remove( wrap );
616                                         } else if ( imgNode.parentNode.nodeName === 'A' ) {
617                                                 dom.remove( imgNode.parentNode );
618                                         } else {
619                                                 dom.remove( imgNode );
620                                         }
621
622                                         editor.nodeChanged();
623                                 }
624                                 return;
625                         }
626
627                         if ( caption ) {
628                                 caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<\/?[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
629                                         // No line breaks inside HTML tags
630                                         return a.replace( /[\r\n\t]+/, ' ' );
631                                 });
632
633                                 // Convert remaining line breaks to <br>
634                                 caption = caption.replace( /(<br[^>]*>)\s*\n\s*/g, '$1' ).replace( /\s*\n\s*/g, '<br />' );
635                                 caption = verifyHTML( caption );
636                         }
637
638                         if ( ! imgNode ) {
639                                 // New image inserted
640                                 html = dom.createHTML( 'img', data );
641
642                                 if ( caption ) {
643                                         node = editor.selection.getNode();
644
645                                         if ( data.width ) {
646                                                 captionWidth = parseInt( data.width, 10 );
647
648                                                 if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
649                                                         captionWidth += 10;
650                                                 }
651
652                                                 captionWidth = ' style="width: ' + captionWidth + 'px"';
653                                         }
654
655                                         html = '<dl class="wp-caption alignnone"' + captionWidth + '>' +
656                                                 '<dt class="wp-caption-dt">'+ html +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
657
658                                         if ( node.nodeName === 'P' ) {
659                                                 parent = node;
660                                         } else {
661                                                 parent = dom.getParent( node, 'p' );
662                                         }
663
664                                         if ( parent && parent.nodeName === 'P' ) {
665                                                 wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
666                                                 parent.parentNode.insertBefore( wrap, parent );
667                                                 editor.selection.select( wrap );
668                                                 editor.nodeChanged();
669
670                                                 if ( dom.isEmpty( parent ) ) {
671                                                         dom.remove( parent );
672                                                 }
673                                         } else {
674                                                 editor.selection.setContent( '<div class="mceTemp">' + html + '</div>' );
675                                         }
676                                 } else {
677                                         editor.selection.setContent( html );
678                                 }
679                         } else {
680                                 // Edit existing image
681
682                                 // Store the original image id if any
683                                 imgId = imgNode.id || null;
684                                 // Update the image node
685                                 dom.setAttribs( imgNode, data );
686                                 wrap = dom.getParent( imgNode, 'dl.wp-caption' );
687
688                                 if ( caption ) {
689                                         if ( wrap ) {
690                                                 if ( parent = dom.select( 'dd.wp-caption-dd', wrap )[0] ) {
691                                                         parent.innerHTML = caption;
692                                                 }
693                                         } else {
694                                                 if ( imgNode.className ) {
695                                                         captionId = imgNode.className.match( /wp-image-([0-9]+)/ );
696                                                         captionAlign = imgNode.className.match( /align(left|right|center|none)/ );
697                                                 }
698
699                                                 if ( captionAlign ) {
700                                                         captionAlign = captionAlign[0];
701                                                         imgNode.className = imgNode.className.replace( /align(left|right|center|none)/g, '' );
702                                                 } else {
703                                                         captionAlign = 'alignnone';
704                                                 }
705
706                                                 captionAlign = ' class="wp-caption ' + captionAlign + '"';
707
708                                                 if ( captionId ) {
709                                                         captionId = ' id="attachment_' + captionId[1] + '"';
710                                                 }
711
712                                                 captionWidth = data.width || imgNode.clientWidth;
713
714                                                 if ( captionWidth ) {
715                                                         captionWidth = parseInt( captionWidth, 10 );
716
717                                                         if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
718                                                                 captionWidth += 10;
719                                                         }
720
721                                                         captionWidth = ' style="width: '+ captionWidth +'px"';
722                                                 }
723
724                                                 if ( imgNode.parentNode && imgNode.parentNode.nodeName === 'A' ) {
725                                                         node = imgNode.parentNode;
726                                                 } else {
727                                                         node = imgNode;
728                                                 }
729
730                                                 html = '<dl ' + captionId + captionAlign + captionWidth + '>' +
731                                                         '<dt class="wp-caption-dt"></dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
732
733                                                 wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
734
735                                                 if ( parent = dom.getParent( node, 'p' ) ) {
736                                                         parent.parentNode.insertBefore( wrap, parent );
737                                                 } else {
738                                                         node.parentNode.insertBefore( wrap, node );
739                                                 }
740
741                                                 editor.$( wrap ).find( 'dt.wp-caption-dt' ).append( node );
742
743                                                 if ( parent && dom.isEmpty( parent ) ) {
744                                                         dom.remove( parent );
745                                                 }
746                                         }
747                                 } else {
748                                         if ( wrap ) {
749                                                 // Remove the caption wrapper and place the image in new paragraph
750                                                 if ( imgNode.parentNode.nodeName === 'A' ) {
751                                                         html = dom.getOuterHTML( imgNode.parentNode );
752                                                 } else {
753                                                         html = dom.getOuterHTML( imgNode );
754                                                 }
755
756                                                 parent = dom.create( 'p', {}, html );
757                                                 dom.insertAfter( parent, wrap.parentNode );
758                                                 editor.selection.select( parent );
759                                                 editor.nodeChanged();
760                                                 dom.remove( wrap.parentNode );
761                                         }
762                                 }
763                         }
764
765                         imgNode = dom.get('__wp-temp-img-id');
766                         dom.setAttrib( imgNode, 'id', imgId );
767                         event.imgData.node = imgNode;
768                 });
769
770                 editor.on( 'wpLoadImageData', function( event ) {
771                         var parent,
772                                 data = event.imgData.data,
773                                 imgNode = event.imgData.node;
774
775                         if ( parent = dom.getParent( imgNode, 'dl.wp-caption' ) ) {
776                                 parent = dom.select( 'dd.wp-caption-dd', parent )[0];
777
778                                 if ( parent ) {
779                                         data.caption = editor.serializer.serialize( parent )
780                                                 .replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
781                                 }
782                         }
783                 });
784
785                 dom.bind( editor.getDoc(), 'dragstart', function( event ) {
786                         var node = editor.selection.getNode();
787
788                         // Prevent dragging images out of the caption elements
789                         if ( node.nodeName === 'IMG' && dom.getParent( node, '.wp-caption' ) ) {
790                                 event.preventDefault();
791                         }
792                 });
793
794                 // Prevent IE11 from making dl.wp-caption resizable
795                 if ( tinymce.Env.ie && tinymce.Env.ie > 10 ) {
796                         // The 'mscontrolselect' event is supported only in IE11+
797                         dom.bind( editor.getBody(), 'mscontrolselect', function( event ) {
798                                 if ( event.target.nodeName === 'IMG' && dom.getParent( event.target, '.wp-caption' ) ) {
799                                         // Hide the thick border with resize handles around dl.wp-caption
800                                         editor.getBody().focus(); // :(
801                                 } else if ( event.target.nodeName === 'DL' && dom.hasClass( event.target, 'wp-caption' ) ) {
802                                         // Trigger the thick border with resize handles...
803                                         // This will make the caption text editable.
804                                         event.target.focus();
805                                 }
806                         });
807                 }
808         });
809
810         editor.on( 'ObjectResized', function( event ) {
811                 var node = event.target;
812
813                 if ( node.nodeName === 'IMG' ) {
814                         editor.undoManager.transact( function() {
815                                 var parent, width,
816                                         dom = editor.dom;
817
818                                 node.className = node.className.replace( /\bsize-[^ ]+/, '' );
819
820                                 if ( parent = dom.getParent( node, '.wp-caption' ) ) {
821                                         width = event.width || dom.getAttrib( node, 'width' );
822
823                                         if ( width ) {
824                                                 width = parseInt( width, 10 );
825
826                                                 if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
827                                                         width += 10;
828                                                 }
829
830                                                 dom.setStyle( parent, 'width', width + 'px' );
831                                         }
832                                 }
833                         });
834                 }
835     });
836
837         editor.on( 'BeforeExecCommand', function( event ) {
838                 var node, p, DL, align, replacement,
839                         cmd = event.command,
840                         dom = editor.dom;
841
842                 if ( cmd === 'mceInsertContent' ) {
843                         // When inserting content, if the caret is inside a caption create new paragraph under
844                         // and move the caret there
845                         if ( node = dom.getParent( editor.selection.getNode(), 'div.mceTemp' ) ) {
846                                 p = dom.create( 'p' );
847                                 dom.insertAfter( p, node );
848                                 editor.selection.setCursorLocation( p, 0 );
849                                 editor.nodeChanged();
850                         }
851                 } else if ( cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'wpAlignNone' ) {
852                         node = editor.selection.getNode();
853                         align = 'align' + cmd.slice( 7 ).toLowerCase();
854                         DL = editor.dom.getParent( node, '.wp-caption' );
855
856                         if ( node.nodeName !== 'IMG' && ! DL ) {
857                                 return;
858                         }
859
860                         node = DL || node;
861
862                         if ( editor.dom.hasClass( node, align ) ) {
863                                 replacement = ' alignnone';
864                         } else {
865                                 replacement = ' ' + align;
866                         }
867
868                         node.className = trim( node.className.replace( / ?align(left|center|right|none)/g, '' ) + replacement );
869
870                         editor.nodeChanged();
871                         event.preventDefault();
872
873                         if ( toolbar ) {
874                                 toolbar.reposition();
875                         }
876
877                         editor.fire( 'ExecCommand', {
878                                 command: cmd,
879                                 ui: event.ui,
880                                 value: event.value
881                         } );
882                 }
883         });
884
885         editor.on( 'keydown', function( event ) {
886                 var node, wrap, P, spacer,
887                         selection = editor.selection,
888                         keyCode = event.keyCode,
889                         dom = editor.dom,
890                         VK = tinymce.util.VK;
891
892                 if ( keyCode === VK.ENTER ) {
893                         // When pressing Enter inside a caption move the caret to a new parapraph under it
894                         node = selection.getNode();
895                         wrap = dom.getParent( node, 'div.mceTemp' );
896
897                         if ( wrap ) {
898                                 dom.events.cancel( event ); // Doesn't cancel all :(
899
900                                 // Remove any extra dt and dd cleated on pressing Enter...
901                                 tinymce.each( dom.select( 'dt, dd', wrap ), function( element ) {
902                                         if ( dom.isEmpty( element ) ) {
903                                                 dom.remove( element );
904                                         }
905                                 });
906
907                                 spacer = tinymce.Env.ie && tinymce.Env.ie < 11 ? '' : '<br data-mce-bogus="1" />';
908                                 P = dom.create( 'p', null, spacer );
909
910                                 if ( node.nodeName === 'DD' ) {
911                                         dom.insertAfter( P, wrap );
912                                 } else {
913                                         wrap.parentNode.insertBefore( P, wrap );
914                                 }
915
916                                 editor.nodeChanged();
917                                 selection.setCursorLocation( P, 0 );
918                         }
919                 } else if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
920                         node = selection.getNode();
921
922                         if ( node.nodeName === 'DIV' && dom.hasClass( node, 'mceTemp' ) ) {
923                                 wrap = node;
924                         } else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) {
925                                 wrap = dom.getParent( node, 'div.mceTemp' );
926                         }
927
928                         if ( wrap ) {
929                                 dom.events.cancel( event );
930                                 removeImage( node );
931                                 return false;
932                         }
933                 }
934         });
935
936         // After undo/redo FF seems to set the image height very slowly when it is set to 'auto' in the CSS.
937         // This causes image.getBoundingClientRect() to return wrong values and the resize handles are shown in wrong places.
938         // Collapse the selection to remove the resize handles.
939         if ( tinymce.Env.gecko ) {
940                 editor.on( 'undo redo', function() {
941                         if ( editor.selection.getNode().nodeName === 'IMG' ) {
942                                 editor.selection.collapse();
943                         }
944                 });
945         }
946
947         editor.wpSetImgCaption = function( content ) {
948                 return parseShortcode( content );
949         };
950
951         editor.wpGetImgCaption = function( content ) {
952                 return getShortcode( content );
953         };
954
955         editor.on( 'BeforeSetContent', function( event ) {
956                 if ( event.format !== 'raw' ) {
957                         event.content = editor.wpSetImgCaption( event.content );
958                 }
959         });
960
961         editor.on( 'PostProcess', function( event ) {
962                 if ( event.get ) {
963                         event.content = editor.wpGetImgCaption( event.content );
964                 }
965         });
966
967         // Add to editor.wp
968         editor.wp = editor.wp || {};
969         editor.wp.isPlaceholder = isPlaceholder;
970
971         // Back-compat.
972         return {
973                 _do_shcode: parseShortcode,
974                 _get_shcode: getShortcode
975         };
976 });