+ var toolbar, serializer, touchOnImage, pasteInCaption,
+ each = tinymce.each,
+ trim = tinymce.trim,
+ iOS = tinymce.Env.iOS;
+
+ function isPlaceholder( node ) {
+ return !! ( editor.dom.getAttrib( node, 'data-mce-placeholder' ) || editor.dom.getAttrib( node, 'data-mce-object' ) );
+ }
+
+ editor.addButton( 'wp_img_remove', {
+ tooltip: 'Remove',
+ icon: 'dashicon dashicons-no',
+ onclick: function() {
+ removeImage( editor.selection.getNode() );
+ }
+ } );
+
+ editor.addButton( 'wp_img_edit', {
+ tooltip: 'Edit ', // trailing space is needed, used for context
+ icon: 'dashicon dashicons-edit',
+ onclick: function() {
+ editImage( editor.selection.getNode() );
+ }
+ } );
+
+ each( {
+ alignleft: 'Align left',
+ aligncenter: 'Align center',
+ alignright: 'Align right',
+ alignnone: 'No alignment'
+ }, function( tooltip, name ) {
+ var direction = name.slice( 5 );
+
+ editor.addButton( 'wp_img_' + name, {
+ tooltip: tooltip,
+ icon: 'dashicon dashicons-align-' + direction,
+ cmd: 'alignnone' === name ? 'wpAlignNone' : 'Justify' + direction.slice( 0, 1 ).toUpperCase() + direction.slice( 1 ),
+ onPostRender: function() {
+ var self = this;
+
+ editor.on( 'NodeChange', function( event ) {
+ var node;
+
+ // Don't bother.
+ if ( event.element.nodeName !== 'IMG' ) {
+ return;
+ }
+
+ node = editor.dom.getParent( event.element, '.wp-caption' ) || event.element;
+
+ if ( 'alignnone' === name ) {
+ self.active( ! /\balign(left|center|right)\b/.test( node.className ) );
+ } else {
+ self.active( editor.dom.hasClass( node, name ) );
+ }
+ } );
+ }
+ } );
+ } );
+
+ editor.once( 'preinit', function() {
+ if ( editor.wp && editor.wp._createToolbar ) {
+ toolbar = editor.wp._createToolbar( [
+ 'wp_img_alignleft',
+ 'wp_img_aligncenter',
+ 'wp_img_alignright',
+ 'wp_img_alignnone',
+ 'wp_img_edit',
+ 'wp_img_remove'
+ ] );
+ }
+ } );
+
+ editor.on( 'wptoolbar', function( event ) {
+ if ( event.element.nodeName === 'IMG' && ! isPlaceholder( event.element ) ) {
+ event.toolbar = toolbar;
+ }
+ } );
+
+ function isNonEditable( node ) {
+ var parent = editor.$( node ).parents( '[contenteditable]' );
+ return parent && parent.attr( 'contenteditable' ) === 'false';
+ }
+
+ // Safari on iOS fails to select images in contentEditoble mode on touch.
+ // Select them again.
+ if ( iOS ) {
+ editor.on( 'init', function() {
+ editor.on( 'touchstart', function( event ) {
+ if ( event.target.nodeName === 'IMG' && ! isNonEditable( event.target ) ) {
+ touchOnImage = true;
+ }
+ });
+
+ editor.dom.bind( editor.getDoc(), 'touchmove', function() {
+ touchOnImage = false;
+ });
+
+ editor.on( 'touchend', function( event ) {
+ if ( touchOnImage && event.target.nodeName === 'IMG' && ! isNonEditable( event.target ) ) {
+ var node = event.target;
+
+ touchOnImage = false;
+
+ window.setTimeout( function() {
+ editor.selection.select( node );
+ editor.nodeChanged();
+ }, 100 );
+ } else if ( toolbar ) {
+ toolbar.hide();
+ }
+ });
+ });
+ }