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