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