]> scripts.mit.edu Git - autoinstalls/wordpress.git/blobdiff - wp-includes/js/tinymce/plugins/wordpress/plugin.js
WordPress 4.7-scripts
[autoinstalls/wordpress.git] / wp-includes / js / tinymce / plugins / wordpress / plugin.js
index 57b09a4a8e92dfaad916f4399143e5f4430cdae9..a38a26d3d404125cf274cf6b6a5df23a52131fa2 100644 (file)
@@ -1,17 +1,19 @@
-/* global tinymce, getUserSetting, setUserSetting */
-
+/* global getUserSetting, setUserSetting */
+( function( tinymce ) {
 // Set the minimum value for the modals z-index higher than #wpadminbar (100000)
 tinymce.ui.FloatPanel.zIndex = 100100;
 
 tinymce.PluginManager.add( 'wordpress', function( editor ) {
-       var DOM = tinymce.DOM,
+       var wpAdvButton, style,
+               DOM = tinymce.DOM,
                each = tinymce.each,
                __ = editor.editorManager.i18n.translate,
-               wpAdvButton, style,
-               last = 0;
+               $ = window.jQuery,
+               wp = window.wp,
+               hasWpautop = ( wp && wp.editor && wp.editor.autop && editor.getParam( 'wpautop', true ) );
 
-       if ( typeof window.jQuery !== 'undefined' ) {
-               window.jQuery( document ).triggerHandler( 'tinymce-editor-setup', [ editor ] );
+       if ( $ ) {
+               $( document ).triggerHandler( 'tinymce-editor-setup', [ editor ] );
        }
 
        function toggleToolbars( state ) {
@@ -88,47 +90,80 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
         window.wpActiveEditor = editor.id;
     });
 
-       // Replace Read More/Next Page tags with images
-       editor.on( 'BeforeSetContent', function( e ) {
+       editor.on( 'BeforeSetContent', function( event ) {
                var title;
 
-               if ( e.content ) {
-                       if ( e.content.indexOf( '<!--more' ) !== -1 ) {
+               if ( event.content ) {
+                       if ( event.content.indexOf( '<!--more' ) !== -1 ) {
                                title = __( 'Read more...' );
 
-                               e.content = e.content.replace( /<!--more(.*?)-->/g, function( match, moretext ) {
+                               event.content = event.content.replace( /<!--more(.*?)-->/g, function( match, moretext ) {
                                        return '<img src="' + tinymce.Env.transparentSrc + '" data-wp-more="more" data-wp-more-text="' + moretext + '" ' +
-                                               'class="wp-more-tag mce-wp-more" title="' + title + '" data-mce-resize="false" data-mce-placeholder="1" />';
+                                               'class="wp-more-tag mce-wp-more" alt="" title="' + title + '" data-mce-resize="false" data-mce-placeholder="1" />';
                                });
                        }
 
-                       if ( e.content.indexOf( '<!--nextpage-->' ) !== -1 ) {
+                       if ( event.content.indexOf( '<!--nextpage-->' ) !== -1 ) {
                                title = __( 'Page break' );
 
-                               e.content = e.content.replace( /<!--nextpage-->/g,
+                               event.content = event.content.replace( /<!--nextpage-->/g,
                                        '<img src="' + tinymce.Env.transparentSrc + '" data-wp-more="nextpage" class="wp-more-tag mce-wp-nextpage" ' +
-                                               'title="' + title + '" data-mce-resize="false" data-mce-placeholder="1" />' );
+                                               'alt="" title="' + title + '" data-mce-resize="false" data-mce-placeholder="1" />' );
+                       }
+
+                       if ( event.load && event.format !== 'raw' && hasWpautop ) {
+                               event.content = wp.editor.autop( event.content );
                        }
+
+                       if ( event.content.indexOf( '<script' ) !== -1 || event.content.indexOf( '<style' ) !== -1 ) {
+                               event.content = event.content.replace( /<(script|style)[^>]*>[\s\S]*?<\/\1>/g, function( match, tag ) {
+                                       return '<img ' +
+                                               'src="' + tinymce.Env.transparentSrc + '" ' +
+                                               'data-wp-preserve="' + encodeURIComponent( match ) + '" ' +
+                                               'data-mce-resize="false" ' +
+                                               'data-mce-placeholder="1" '+
+                                               'class="mce-object" ' +
+                                               'width="20" height="20" '+
+                                               'alt="&lt;' + tag + '&gt;" ' +
+                                               'title="&lt;' + tag + '&gt;" ' +
+                                       '/>';
+                               } );
+                       }
+
+                       // Remove spaces from empty paragraphs.
+                       // Try to avoid a lot of backtracking, can freeze the editor. See #35890 and #38294.
+                       event.content = event.content.replace( /<p>([^<>]+)<\/p>/gi, function( tag, text ) {
+                               if ( text === '&nbsp;' || ! /\S/.test( text ) ) {
+                                       return '<p><br /></p>';
+                               }
+
+                               return tag;
+                       });
                }
        });
 
-       // Replace images with tags
-       editor.on( 'PostProcess', function( e ) {
-               if ( e.get ) {
-                       e.content = e.content.replace(/<img[^>]+>/g, function( image ) {
-                               var match, moretext = '';
+       editor.on( 'PostProcess', function( event ) {
+               if ( event.get ) {
+                       event.content = event.content.replace(/<img[^>]+>/g, function( image ) {
+                               var match,
+                                       string,
+                                       moretext = '';
 
                                if ( image.indexOf( 'data-wp-more="more"' ) !== -1 ) {
                                        if ( match = image.match( /data-wp-more-text="([^"]+)"/ ) ) {
                                                moretext = match[1];
                                        }
 
-                                       image = '<!--more' + moretext + '-->';
+                                       string = '<!--more' + moretext + '-->';
                                } else if ( image.indexOf( 'data-wp-more="nextpage"' ) !== -1 ) {
-                                       image = '<!--nextpage-->';
+                                       string = '<!--nextpage-->';
+                               } else if ( image.indexOf( 'data-wp-preserve' ) !== -1 ) {
+                                       if ( match = image.match( / data-wp-preserve="([^"]+)"/ ) ) {
+                                               string = decodeURIComponent( match[1] );
+                                       }
                                }
 
-                               return image;
+                               return string || image;
                        });
                }
        });
@@ -153,7 +188,7 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                classname += ' mce-wp-' + tag;
                title = tag === 'more' ? 'Read more...' : 'Next page';
                title = __( title );
-               html = '<img src="' + tinymce.Env.transparentSrc + '" title="' + title + '" class="' + classname + '" ' +
+               html = '<img src="' + tinymce.Env.transparentSrc + '" alt="" title="' + title + '" class="' + classname + '" ' +
                        'data-wp-more="' + tag + '" data-mce-resize="false" data-mce-placeholder="1" />';
 
                // Most common case
@@ -191,18 +226,165 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
        });
 
        editor.addCommand( 'WP_Help', function() {
-               editor.windowManager.open({
-                       url: tinymce.baseURL + '/wp-mce-help.php',
+               var access = tinymce.Env.mac ? __( 'Ctrl + Alt + letter:' ) : __( 'Shift + Alt + letter:' ),
+                       meta = tinymce.Env.mac ? __( 'Cmd + letter:' ) : __( 'Ctrl + letter:' ),
+                       table1 = [],
+                       table2 = [],
+                       row1 = {},
+                       row2 = {},
+                       i1 = 0,
+                       i2 = 0,
+                       labels = editor.settings.wp_shortcut_labels,
+                       header, html, dialog, $wrap;
+
+               if ( ! labels ) {
+                       return;
+               }
+
+               function tr( row, columns ) {
+                       var out = '<tr>';
+                       var i = 0;
+
+                       columns = columns || 1;
+
+                       each( row, function( text, key ) {
+                               out += '<td><kbd>' + key + '</kbd></td><td>' + __( text ) + '</td>';
+                               i++;
+                       });
+
+                       while ( i < columns ) {
+                               out += '<td></td><td></td>';
+                               i++;
+                       }
+
+                       return out + '</tr>';
+               }
+
+               each ( labels, function( label, name ) {
+                       var letter;
+
+                       if ( label.indexOf( 'meta' ) !== -1 ) {
+                               i1++;
+                               letter = label.replace( 'meta', '' ).toLowerCase();
+
+                               if ( letter ) {
+                                       row1[ letter ] = name;
+
+                                       if ( i1 % 2 === 0 ) {
+                                               table1.push( tr( row1, 2 ) );
+                                               row1 = {};
+                                       }
+                               }
+                       } else if ( label.indexOf( 'access' ) !== -1 ) {
+                               i2++;
+                               letter = label.replace( 'access', '' ).toLowerCase();
+
+                               if ( letter ) {
+                                       row2[ letter ] = name;
+
+                                       if ( i2 % 2 === 0 ) {
+                                               table2.push( tr( row2, 2 ) );
+                                               row2 = {};
+                                       }
+                               }
+                       }
+               } );
+
+               // Add remaining single entries.
+               if ( i1 % 2 > 0 ) {
+                       table1.push( tr( row1, 2 ) );
+               }
+
+               if ( i2 % 2 > 0 ) {
+                       table2.push( tr( row2, 2 ) );
+               }
+
+               header = [ __( 'Letter' ), __( 'Action' ), __( 'Letter' ), __( 'Action' ) ];
+               header = '<tr><th>' + header.join( '</th><th>' ) + '</th></tr>';
+
+               html = '<div class="wp-editor-help">';
+
+               // Main section, default and additional shortcuts
+               html = html +
+                       '<h2>' + __( 'Default shortcuts,' ) + ' ' + meta + '</h2>' +
+                       '<table class="wp-help-th-center fixed">' +
+                               header +
+                               table1.join('') +
+                       '</table>' +
+                       '<h2>' + __( 'Additional shortcuts,' ) + ' ' + access + '</h2>' +
+                       '<table class="wp-help-th-center fixed">' +
+                               header +
+                               table2.join('') +
+                       '</table>';
+
+               if ( editor.plugins.wptextpattern && ( ! tinymce.Env.ie || tinymce.Env.ie > 8 ) ) {
+                       // Text pattern section
+                       html = html +
+                               '<h2>' + __( 'When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.' ) + '</h2>' +
+                               '<table class="wp-help-th-center fixed">' +
+                                       tr({ '*':  'Bullet list', '1.':  'Numbered list' }) +
+                                       tr({ '-':  'Bullet list', '1)':  'Numbered list' }) +
+                               '</table>';
+
+                       html = html +
+                               '<h2>' + __( 'The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.' ) + '</h2>' +
+                               '<table class="wp-help-single">' +
+                                       tr({ '>': 'Blockquote' }) +
+                                       tr({ '##': 'Heading 2' }) +
+                                       tr({ '###': 'Heading 3' }) +
+                                       tr({ '####': 'Heading 4' }) +
+                                       tr({ '#####': 'Heading 5' }) +
+                                       tr({ '######': 'Heading 6' }) +
+                                       tr({ '---': 'Horizontal line' }) +
+                               '</table>';
+               }
+
+               // Focus management section
+               html = html +
+                       '<h2>' + __( 'Focus shortcuts:' ) + '</h2>' +
+                       '<table class="wp-help-single">' +
+                               tr({ 'Alt + F8':  'Inline toolbar (when an image, link or preview is selected)' }) +
+                               tr({ 'Alt + F9':  'Editor menu (when enabled)' }) +
+                               tr({ 'Alt + F10': 'Editor toolbar' }) +
+                               tr({ 'Alt + F11': 'Elements path' }) +
+                       '</table>' +
+                       '<p>' + __( 'To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.' ) + '</p>';
+
+               html += '</div>';
+
+               dialog = editor.windowManager.open( {
                        title: 'Keyboard Shortcuts',
-                       width: 450,
-                       height: 420,
-                       classes: 'wp-help',
-                       buttons: { text: 'Close', onclick: 'close' }
-               });
-       });
+                       items: {
+                               type: 'container',
+                               classes: 'wp-help',
+                               html: html
+                       },
+                       buttons: {
+                               text: 'Close',
+                               onclick: 'close'
+                       }
+               } );
+
+               if ( dialog.$el ) {
+                       dialog.$el.find( 'div[role="application"]' ).attr( 'role', 'document' );
+                       $wrap = dialog.$el.find( '.mce-wp-help' );
+
+                       if ( $wrap[0] ) {
+                               $wrap.attr( 'tabindex', '0' );
+                               $wrap[0].focus();
+                               $wrap.on( 'keydown', function( event ) {
+                                       // Prevent use of: page up, page down, end, home, left arrow, up arrow, right arrow, down arrow
+                                       // in the dialog keydown handler.
+                                       if ( event.keyCode >= 33 && event.keyCode <= 40 ) {
+                                               event.stopPropagation();
+                                       }
+                               });
+                       }
+               }
+       } );
 
        editor.addCommand( 'WP_Medialib', function() {
-               if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) {
+               if ( wp && wp.media && wp.media.editor ) {
                        wp.media.editor.open( editor.id );
                }
        });
@@ -235,7 +417,7 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
 
        // Menubar
        // Insert->Add Media
-       if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) {
+       if ( wp && wp.media && wp.media.editor ) {
                editor.addMenuItem( 'add_media', {
                        text: 'Add Media',
                        icon: 'wp-media-library',
@@ -289,7 +471,7 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                        doc = editor.getDoc(),
                        dom = editor.dom;
 
-               if ( tinymce.Env.iOS ) {
+               if ( env.iOS ) {
                        dom.addClass( doc.documentElement, 'ios' );
                }
 
@@ -298,6 +480,8 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                        dom.setAttrib( doc.documentElement, 'dir', 'rtl' );
                }
 
+               dom.setAttrib( doc.documentElement, 'lang', editor.getParam( 'wp_lang_attr' ) );
+
                if ( env.ie ) {
                        if ( parseInt( env.ie, 10 ) === 9 ) {
                                bodyClass.push('ie9');
@@ -319,38 +503,40 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                });
 
                // Remove invalid parent paragraphs when inserting HTML
-               // TODO: still needed?
-               editor.on( 'BeforeSetContent', function( e ) {
-                       if ( e.content ) {
-                               e.content = e.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>');
-                               e.content = e.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>');
+               editor.on( 'BeforeSetContent', function( event ) {
+                       if ( event.content ) {
+                               event.content = event.content.replace( /<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)( [^>]*)?>/gi, '<$1$2>' )
+                                       .replace( /<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre)>\s*<\/p>/gi, '</$1>' );
                        }
                });
 
-               if ( typeof window.jQuery !== 'undefined' ) {
-                       window.jQuery( document ).triggerHandler( 'tinymce-editor-init', [editor] );
+               if ( $ ) {
+                       $( document ).triggerHandler( 'tinymce-editor-init', [editor] );
                }
 
                if ( window.tinyMCEPreInit && window.tinyMCEPreInit.dragDropUpload ) {
                        dom.bind( doc, 'dragstart dragend dragover drop', function( event ) {
-                               if ( typeof window.jQuery !== 'undefined' ) {
+                               if ( $ ) {
                                        // Trigger the jQuery handlers.
-                                       window.jQuery( document ).trigger( new window.jQuery.Event( event ) );
+                                       $( document ).trigger( new $.Event( event ) );
                                }
                        });
                }
 
                if ( editor.getParam( 'wp_paste_filters', true ) ) {
-                       if ( ! tinymce.Env.webkit ) {
-                               // In WebKit handled by removeWebKitStyles()
-                               editor.on( 'PastePreProcess', function( event ) {
+                       editor.on( 'PastePreProcess', function( event ) {
+                               // Remove trailing <br> added by WebKit browsers to the clipboard
+                               event.content = event.content.replace( /<br class="?Apple-interchange-newline"?>/gi, '' );
+
+                               // In WebKit this is handled by removeWebKitStyles()
+                               if ( ! tinymce.Env.webkit ) {
                                        // Remove all inline styles
                                        event.content = event.content.replace( /(<[^>]+) style="[^"]*"([^>]*>)/gi, '$1$2' );
 
                                        // Put back the internal styles
                                        event.content = event.content.replace(/(<[^>]+) data-mce-style=([^>]+>)/gi, '$1 style=$2' );
-                               });
-                       }
+                               }
+                       });
 
                        editor.on( 'PastePostProcess', function( event ) {
                                // Remove empty paragraphs
@@ -361,52 +547,66 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                                });
                        });
                }
-       });
 
-       // Word count
-       if ( typeof window.jQuery !== 'undefined' ) {
-               editor.on( 'keyup', function( e ) {
-                       var key = e.keyCode || e.charCode;
+               if ( editor.settings.wp_shortcut_labels && editor.theme.panel ) {
+                       var labels = {};
+                       var access = 'Shift+Alt+';
+                       var meta = 'Ctrl+';
 
-                       if ( key === last ) {
-                               return;
-                       }
+                       // For Mac: ctrl = \u2303, cmd = \u2318, alt = \u2325
 
-                       if ( 13 === key || 8 === last || 46 === last ) {
-                               window.jQuery( document ).triggerHandler( 'wpcountwords', [ editor.getContent({ format : 'raw' }) ] );
+                       if ( tinymce.Env.mac ) {
+                               access = '\u2303\u2325';
+                               meta = '\u2318';
                        }
 
-                       last = key;
-               });
-       }
+                       each( editor.settings.wp_shortcut_labels, function( value, name ) {
+                               labels[ name ] = value.replace( 'access', access ).replace( 'meta', meta );
+                       } );
+
+                       each( editor.theme.panel.find('button'), function( button ) {
+                               if ( button && button.settings.tooltip && labels.hasOwnProperty( button.settings.tooltip ) ) {
+                                       // Need to translate now. We are changing the string so it won't match and cannot be translated later.
+                                       button.settings.tooltip = editor.translate( button.settings.tooltip ) + ' (' + labels[ button.settings.tooltip ] + ')';
+                               }
+                       } );
+
+                       // listbox for the "blocks" drop-down
+                       each( editor.theme.panel.find('listbox'), function( listbox ) {
+                               if ( listbox && listbox.settings.text === 'Paragraph' ) {
+                                       each( listbox.settings.values, function( item ) {
+                                               if ( item.text && labels.hasOwnProperty( item.text ) ) {
+                                                       item.shortcut = '(' + labels[ item.text ] + ')';
+                                               }
+                                       } );
+                               }
+                       } );
+               }
+       });
 
-       editor.on( 'SaveContent', function( e ) {
+       editor.on( 'SaveContent', function( event ) {
                // If editor is hidden, we just want the textarea's value to be saved
                if ( ! editor.inline && editor.isHidden() ) {
-                       e.content = e.element.value;
+                       event.content = event.element.value;
                        return;
                }
 
                // Keep empty paragraphs :(
-               e.content = e.content.replace( /<p>(?:<br ?\/?>|\u00a0|\uFEFF| )*<\/p>/g, '<p>&nbsp;</p>' );
-
-               if ( editor.getParam( 'wpautop', true ) && typeof window.switchEditors !== 'undefined' ) {
-                       e.content = window.switchEditors.pre_wpautop( e.content );
-               }
-       });
-
-       // Remove spaces from empty paragraphs.
-       editor.on( 'BeforeSetContent', function( event ) {
-               var paragraph = tinymce.Env.webkit ? '<p><br /></p>' : '<p></p>';
+               event.content = event.content.replace( /<p>(?:<br ?\/?>|\u00a0|\uFEFF| )*<\/p>/g, '<p>&nbsp;</p>' );
 
-               if ( event.content ) {
-                       event.content = event.content.replace( /<p>(?:&nbsp;|\u00a0|\uFEFF|\s)+<\/p>/gi, paragraph );
+               if ( hasWpautop ) {
+                       event.content = wp.editor.removep( event.content );
                }
        });
 
        editor.on( 'preInit', function() {
-               // Don't replace <i> with <em> and <b> with <strong> and don't remove them when empty
-               editor.schema.addValidElements( '@[id|accesskey|class|dir|lang|style|tabindex|title|contenteditable|draggable|dropzone|hidden|spellcheck|translate],i,b' );
+               var validElementsSetting = '@[id|accesskey|class|dir|lang|style|tabindex|' +
+                       'title|contenteditable|draggable|dropzone|hidden|spellcheck|translate],' + // Global attributes.
+                       'i,' + // Don't replace <i> with <em> and <b> with <strong> and don't remove them when empty.
+                       'b,' +
+                       'script[src|async|defer|type|charset|crossorigin|integrity]'; // Add support for <script>.
+
+               editor.schema.addValidElements( validElementsSetting );
 
                if ( tinymce.Env.iOS ) {
                        editor.settings.height = 300;
@@ -420,7 +620,6 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                        q: 'mceBlockQuote',
                        u: 'InsertUnorderedList',
                        o: 'InsertOrderedList',
-                       s: 'unlink',
                        m: 'WP_Medialib',
                        z: 'WP_Adv',
                        t: 'WP_More',
@@ -433,23 +632,59 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                } );
 
                editor.addShortcut( 'meta+s', '', function() {
-                       if ( typeof wp !== 'undefined' && wp.autosave ) {
+                       if ( wp && wp.autosave ) {
                                wp.autosave.server.triggerSave();
                        }
                } );
+
+               if ( window.getUserSetting( 'editor_plain_text_paste_warning' ) > 1 ) {
+                       editor.settings.paste_plaintext_inform = false;
+               }
+
+               // Change the editor iframe title on MacOS, add the correct help shortcut.
+               if ( tinymce.Env.mac ) {
+                       tinymce.$( editor.iframeElement ).attr( 'title', __( 'Rich Text Area. Press Control-Option-H for help.' ) );
+               }
        } );
 
+       editor.on( 'PastePlainTextToggle', function( event ) {
+               // Warn twice, then stop.
+               if ( event.state === true ) {
+                       var times = parseInt( window.getUserSetting( 'editor_plain_text_paste_warning' ), 10 ) || 0;
+
+                       if ( times < 2 ) {
+                               window.setUserSetting( 'editor_plain_text_paste_warning', ++times );
+                       }
+               }
+       });
+
        /**
         * Experimental: create a floating toolbar.
         * This functionality will change in the next releases. Not recommended for use by plugins.
         */
-       ( function() {
+       editor.on( 'preinit', function() {
                var Factory = tinymce.ui.Factory,
                        settings = editor.settings,
-                       currentToolbar,
-                       currentSelection;
+                       activeToolbar,
+                       currentSelection,
+                       timeout,
+                       container = editor.getContainer(),
+                       wpAdminbar = document.getElementById( 'wpadminbar' ),
+                       mceIframe = document.getElementById( editor.id + '_ifr' ),
+                       mceToolbar,
+                       mceStatusbar,
+                       wpStatusbar;
+
+                       if ( container ) {
+                               mceToolbar = tinymce.$( '.mce-toolbar-grp', container )[0];
+                               mceStatusbar = tinymce.$( '.mce-statusbar', container )[0];
+                       }
 
-               function create( buttons ) {
+                       if ( editor.id === 'content' ) {
+                               wpStatusbar = document.getElementById( 'post-status-info' );
+                       }
+
+               function create( buttons, bottom ) {
                        var toolbar,
                                toolbarItems = [],
                                buttonGroup;
@@ -573,120 +808,117 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                                } ]
                        } );
 
-                       function hide() {
-                               toolbar.hide();
-                       }
+                       toolbar.bottom = bottom;
 
                        function reposition() {
-                               var top, left, minTop, className,
-                                       windowPos, adminbar, mceToolbar, boundary,
-                                       boundaryMiddle, boundaryVerticalMiddle, spaceTop,
-                                       spaceBottom, windowWidth, toolbarWidth, toolbarHalf,
-                                       iframe, iframePos, iframeWidth, iframeHeigth,
-                                       toolbarNodeHeight, verticalSpaceNeeded,
-                                       toolbarNode = this.getEl(),
-                                       buffer = 5,
-                                       margin = 8,
-                                       adminbarHeight = 0;
-
                                if ( ! currentSelection ) {
-                                       return;
+                                       return this;
                                }
 
-                               windowPos = window.pageYOffset || document.documentElement.scrollTop;
-                               adminbar = tinymce.$( '#wpadminbar' )[0];
-                               mceToolbar = tinymce.$( '.mce-toolbar-grp', editor.getContainer() )[0];
-                               boundary = currentSelection.getBoundingClientRect();
-                               boundaryMiddle = ( boundary.left + boundary.right ) / 2;
-                               boundaryVerticalMiddle = ( boundary.top + boundary.bottom ) / 2;
-                               spaceTop = boundary.top;
-                               spaceBottom = iframeHeigth - boundary.bottom;
-                               windowWidth = window.innerWidth;
-                               toolbarWidth = toolbarNode.offsetWidth;
-                               toolbarHalf = toolbarWidth / 2;
-                               iframe = document.getElementById( editor.id + '_ifr' );
-                               iframePos = DOM.getPos( iframe );
-                               iframeWidth = iframe.offsetWidth;
-                               iframeHeigth = iframe.offsetHeight;
-                               toolbarNodeHeight = toolbarNode.offsetHeight;
-                               verticalSpaceNeeded = toolbarNodeHeight + margin + buffer;
-
-                               if ( spaceTop >= verticalSpaceNeeded ) {
-                                       className = ' mce-arrow-down';
-                                       top = boundary.top + iframePos.y - toolbarNodeHeight - margin;
-                               } else if ( spaceBottom >= verticalSpaceNeeded ) {
-                                       className = ' mce-arrow-up';
-                                       top = boundary.bottom + iframePos.y;
-                               } else {
-                                       top = buffer;
-
-                                       if ( boundaryVerticalMiddle >= verticalSpaceNeeded ) {
-                                               className = ' mce-arrow-down';
-                                       } else {
-                                               className = ' mce-arrow-up';
-                                       }
+                               var scrollX = window.pageXOffset || document.documentElement.scrollLeft,
+                                       scrollY = window.pageYOffset || document.documentElement.scrollTop,
+                                       windowWidth = window.innerWidth,
+                                       windowHeight = window.innerHeight,
+                                       iframeRect = mceIframe ? mceIframe.getBoundingClientRect() : {
+                                               top: 0,
+                                               right: windowWidth,
+                                               bottom: windowHeight,
+                                               left: 0,
+                                               width: windowWidth,
+                                               height: windowHeight
+                                       },
+                                       toolbar = this.getEl(),
+                                       toolbarWidth = toolbar.offsetWidth,
+                                       toolbarHeight = toolbar.clientHeight,
+                                       selection = currentSelection.getBoundingClientRect(),
+                                       selectionMiddle = ( selection.left + selection.right ) / 2,
+                                       buffer = 5,
+                                       spaceNeeded = toolbarHeight + buffer,
+                                       wpAdminbarBottom = wpAdminbar ? wpAdminbar.getBoundingClientRect().bottom : 0,
+                                       mceToolbarBottom = mceToolbar ? mceToolbar.getBoundingClientRect().bottom : 0,
+                                       mceStatusbarTop = mceStatusbar ? windowHeight - mceStatusbar.getBoundingClientRect().top : 0,
+                                       wpStatusbarTop = wpStatusbar ? windowHeight - wpStatusbar.getBoundingClientRect().top : 0,
+                                       blockedTop = Math.max( 0, wpAdminbarBottom, mceToolbarBottom, iframeRect.top ),
+                                       blockedBottom = Math.max( 0, mceStatusbarTop, wpStatusbarTop, windowHeight - iframeRect.bottom ),
+                                       spaceTop = selection.top + iframeRect.top - blockedTop,
+                                       spaceBottom = windowHeight - iframeRect.top - selection.bottom - blockedBottom,
+                                       editorHeight = windowHeight - blockedTop - blockedBottom,
+                                       className = '',
+                                       iosOffsetTop = 0,
+                                       iosOffsetBottom = 0,
+                                       top, left;
+
+                               if ( spaceTop >= editorHeight || spaceBottom >= editorHeight ) {
+                                       this.scrolling = true;
+                                       this.hide();
+                                       this.scrolling = false;
+                                       return this;
                                }
 
-                               // Make sure the image toolbar is below the main toolbar.
-                               if ( mceToolbar ) {
-                                       minTop = DOM.getPos( mceToolbar ).y + mceToolbar.clientHeight;
-                               } else {
-                                       minTop = iframePos.y;
+                               // Add offset in iOS to move the menu over the image, out of the way of the default iOS menu.
+                               if ( tinymce.Env.iOS && currentSelection.nodeName === 'IMG' ) {
+                                       iosOffsetTop = 54;
+                                       iosOffsetBottom = 46;
                                }
 
-                               // Make sure the image toolbar is below the adminbar (if visible) or below the top of the window.
-                               if ( windowPos ) {
-                                       if ( adminbar && adminbar.getBoundingClientRect().top === 0 ) {
-                                               adminbarHeight = adminbar.clientHeight;
+                               if ( this.bottom ) {
+                                       if ( spaceBottom >= spaceNeeded ) {
+                                               className = ' mce-arrow-up';
+                                               top = selection.bottom + iframeRect.top + scrollY - iosOffsetBottom;
+                                       } else if ( spaceTop >= spaceNeeded ) {
+                                               className = ' mce-arrow-down';
+                                               top = selection.top + iframeRect.top + scrollY - toolbarHeight + iosOffsetTop;
                                        }
-
-                                       if ( windowPos + adminbarHeight > minTop ) {
-                                               minTop = windowPos + adminbarHeight;
+                               } else {
+                                       if ( spaceTop >= spaceNeeded ) {
+                                               className = ' mce-arrow-down';
+                                               top = selection.top + iframeRect.top + scrollY - toolbarHeight + iosOffsetTop;
+                                       } else if ( spaceBottom >= spaceNeeded && editorHeight / 2 > selection.bottom + iframeRect.top - blockedTop ) {
+                                               className = ' mce-arrow-up';
+                                               top = selection.bottom + iframeRect.top + scrollY - iosOffsetBottom;
                                        }
                                }
 
-                               if ( top && minTop && ( minTop + buffer > top ) ) {
-                                       top = minTop + buffer;
-                                       className = '';
+                               if ( typeof top === 'undefined' ) {
+                                       top = scrollY + blockedTop + buffer + iosOffsetBottom;
                                }
 
-                               left = boundaryMiddle - toolbarHalf;
-                               left += iframePos.x;
+                               left = selectionMiddle - toolbarWidth / 2 + iframeRect.left + scrollX;
 
-                               if ( boundary.left < 0 || boundary.right > iframeWidth ) {
-                                       left = iframePos.x + ( iframeWidth - toolbarWidth ) / 2;
+                               if ( selection.left < 0 || selection.right > iframeRect.width ) {
+                                       left = iframeRect.left + scrollX + ( iframeRect.width - toolbarWidth ) / 2;
                                } else if ( toolbarWidth >= windowWidth ) {
                                        className += ' mce-arrow-full';
                                        left = 0;
-                               } else if ( ( left < 0 && boundary.left + toolbarWidth > windowWidth ) ||
-                                       ( left + toolbarWidth > windowWidth && boundary.right - toolbarWidth < 0 ) ) {
-
+                               } else if ( ( left < 0 && selection.left + toolbarWidth > windowWidth ) || ( left + toolbarWidth > windowWidth && selection.right - toolbarWidth < 0 ) ) {
                                        left = ( windowWidth - toolbarWidth ) / 2;
-                               } else if ( left < iframePos.x ) {
+                               } else if ( left < iframeRect.left + scrollX ) {
                                        className += ' mce-arrow-left';
-                                       left = boundary.left + iframePos.x;
-                               } else if ( left + toolbarWidth > iframeWidth + iframePos.x ) {
+                                       left = selection.left + iframeRect.left + scrollX;
+                               } else if ( left + toolbarWidth > iframeRect.width + iframeRect.left + scrollX ) {
                                        className += ' mce-arrow-right';
-                                       left = boundary.right - toolbarWidth + iframePos.x;
+                                       left = selection.right - toolbarWidth + iframeRect.left + scrollX;
                                }
 
-                               toolbarNode.className = toolbarNode.className.replace( / ?mce-arrow-[\w]+/g, '' );
-                               toolbarNode.className += className;
+                               // No up/down arrows on the menu over images in iOS.
+                               if ( tinymce.Env.iOS && currentSelection.nodeName === 'IMG' ) {
+                                       className = className.replace( / ?mce-arrow-(up|down)/g, '' );
+                               }
 
-                               DOM.setStyles( toolbarNode, { 'left': left, 'top': top } );
+                               toolbar.className = toolbar.className.replace( / ?mce-arrow-[\w]+/g, '' ) + className;
+
+                               DOM.setStyles( toolbar, {
+                                       'left': left,
+                                       'top': top
+                               } );
 
                                return this;
                        }
 
                        toolbar.on( 'show', function() {
-                               currentToolbar = this;
                                this.reposition();
                        } );
 
-                       toolbar.on( 'hide', function() {
-                               currentToolbar = false;
-                       } );
-
                        toolbar.on( 'keydown', function( event ) {
                                if ( event.keyCode === 27 ) {
                                        this.hide();
@@ -694,16 +926,8 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                                }
                        } );
 
-                       toolbar.on( 'remove', function() {
-                               DOM.unbind( window, 'resize scroll', hide );
-                               editor.dom.unbind( editor.getWin(), 'resize scroll', hide );
-                               editor.off( 'blur hide', hide );
-                       } );
-
-                       editor.once( 'init', function() {
-                               DOM.bind( window, 'resize scroll', hide );
-                               editor.dom.bind( editor.getWin(), 'resize scroll', hide );
-                               editor.on( 'blur hide', hide );
+                       editor.on( 'remove', function() {
+                               toolbar.remove();
                        } );
 
                        toolbar.reposition = reposition;
@@ -715,8 +939,8 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                editor.shortcuts.add( 'alt+119', '', function() {
                        var node;
 
-                       if ( currentToolbar ) {
-                               node = currentToolbar.find( 'toolbar' )[0];
+                       if ( activeToolbar ) {
+                               node = activeToolbar.find( 'toolbar' )[0];
                                node && node.focus( true );
                        }
                } );
@@ -734,13 +958,69 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
 
                        currentSelection = args.selection || args.element;
 
-                       currentToolbar && currentToolbar.hide();
-                       args.toolbar && args.toolbar.show();
+                       if ( activeToolbar && activeToolbar !== args.toolbar ) {
+                               activeToolbar.hide();
+                       }
+
+                       if ( args.toolbar ) {
+                               if ( activeToolbar !== args.toolbar ) {
+                                       activeToolbar = args.toolbar;
+                                       activeToolbar.show();
+                               } else {
+                                       activeToolbar.reposition();
+                               }
+                       } else {
+                               activeToolbar = false;
+                       }
+               } );
+
+               editor.on( 'focus', function() {
+                       if ( activeToolbar ) {
+                               activeToolbar.show();
+                       }
                } );
 
+               function hide( event ) {
+                       if ( activeToolbar ) {
+                               if ( activeToolbar.tempHide || event.type === 'hide' ) {
+                                       activeToolbar.hide();
+                                       activeToolbar = false;
+                               } else if ( (
+                                       event.type === 'resizewindow' ||
+                                       event.type === 'scrollwindow' ||
+                                       event.type === 'resize' ||
+                                       event.type === 'scroll'
+                               ) && ! activeToolbar.blockHide ) {
+                                       clearTimeout( timeout );
+
+                                       timeout = setTimeout( function() {
+                                               if ( activeToolbar && typeof activeToolbar.show === 'function' ) {
+                                                       activeToolbar.scrolling = false;
+                                                       activeToolbar.show();
+                                               }
+                                       }, 250 );
+
+                                       activeToolbar.scrolling = true;
+                                       activeToolbar.hide();
+                               }
+                       }
+               }
+
+               // For full height editor.
+               editor.on( 'resizewindow scrollwindow', hide );
+               // For scrollable editor.
+               editor.dom.bind( editor.getWin(), 'resize scroll', hide );
+
+               editor.on( 'remove', function() {
+                       editor.off( 'resizewindow scrollwindow', hide );
+                       editor.dom.unbind( editor.getWin(), 'resize scroll', hide );
+               } );
+
+               editor.on( 'blur hide', hide );
+
                editor.wp = editor.wp || {};
                editor.wp._createToolbar = create;
-       }());
+       }, true );
 
        function noop() {}
 
@@ -752,3 +1032,5 @@ tinymce.PluginManager.add( 'wordpress', function( editor ) {
                _getEmbed: noop
        };
 });
+
+}( window.tinymce ));