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