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