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