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