]> scripts.mit.edu Git - autoinstalls/wordpress.git/blobdiff - wp-includes/js/tinymce/plugins/wpview/plugin.js
WordPress 4.3.1-scripts
[autoinstalls/wordpress.git] / wp-includes / js / tinymce / plugins / wpview / plugin.js
index 4e224b0683da03c61da8cdf7d86ecf29678b2ba2..9db30087e9928b4181f5297fb45005840e224f8c 100644 (file)
 /* global tinymce */
+
 /**
  * WordPress View plugin.
  */
 tinymce.PluginManager.add( 'wpview', function( editor ) {
-       var selected,
+       var $ = editor.$,
+               selected,
+               Env = tinymce.Env,
                VK = tinymce.util.VK,
                TreeWalker = tinymce.dom.TreeWalker,
-               toRemove = false;
+               toRemove = false,
+               firstFocus = true,
+               _noop = function() { return false; },
+               isios = /iPad|iPod|iPhone/.test( navigator.userAgent ),
+               cursorInterval,
+               lastKeyDownNode,
+               setViewCursorTries,
+               focus,
+               execCommandView,
+               execCommandBefore,
+               toolbar;
+
+       function getView( node ) {
+               return getParent( node, 'wpview-wrap' );
+       }
 
-       function getParentView( node ) {
-               while ( node && node.nodeName !== 'BODY' ) {
-                       if ( isView( node ) ) {
+       /**
+        * Returns the node or a parent of the node that has the passed className.
+        * Doing this directly is about 40% faster
+        */
+       function getParent( node, className ) {
+               while ( node && node.parentNode ) {
+                       if ( node.className && ( ' ' + node.className + ' ' ).indexOf( ' ' + className + ' ' ) !== -1 ) {
                                return node;
                        }
 
                        node = node.parentNode;
                }
+
+               return false;
        }
 
-       function isView( node ) {
-               return node && /\bwpview-wrap\b/.test( node.className );
+       function _stop( event ) {
+               event.stopPropagation();
        }
 
-       function createPadNode() {
-               return editor.dom.create( 'p', { 'data-wpview-pad': 1 },
-                       ( tinymce.Env.ie && tinymce.Env.ie < 11 ) ? '' : '<br data-mce-bogus="1" />' );
+       function setViewCursor( before, view ) {
+               var location = before ? 'before' : 'after',
+                       offset = before ? 0 : 1;
+               deselect();
+               editor.selection.setCursorLocation( editor.dom.select( '.wpview-selection-' + location, view )[0], offset );
+               editor.nodeChanged();
        }
 
-       /**
-        * Get the text/shortcode string for a view.
-        *
-        * @param view The view wrapper's HTML id or node
-        * @returns string The text/shoercode string of the view
-        */
-       function getViewText( view ) {
-               view = getParentView( typeof view === 'string' ? editor.dom.get( view ) : view );
+       function handleEnter( view, before, key ) {
+               var dom = editor.dom,
+                       padNode = dom.create( 'p' );
 
-               if ( view ) {
-                       return window.decodeURIComponent( editor.dom.getAttrib( view, 'data-wpview-text' ) || '' );
+               if ( ! ( Env.ie && Env.ie < 11 ) ) {
+                       padNode.innerHTML = '<br data-mce-bogus="1">';
                }
-               return '';
-       }
 
-       /**
-        * Set the view's original text/shortcode string
-        *
-        * @param view The view wrapper's HTML id or node
-        * @param text The text string to be set
-        */
-       function setViewText( view, text ) {
-               view = getParentView( typeof view === 'string' ? editor.dom.get( view ) : view );
+               if ( before ) {
+                       view.parentNode.insertBefore( padNode, view );
+               } else {
+                       dom.insertAfter( padNode, view );
+               }
 
-               if ( view ) {
-                       editor.dom.setAttrib( view, 'data-wpview-text', window.encodeURIComponent( text || '' ) );
-                       return true;
+               deselect();
+
+               if ( before && key === VK.ENTER ) {
+                       setViewCursor( before, view );
+               } else {
+                       editor.selection.setCursorLocation( padNode, 0 );
                }
-               return false;
+
+               editor.nodeChanged();
        }
 
-       function _stop( event ) {
-               event.stopPropagation();
+       function removeView( view ) {
+               editor.undoManager.transact( function() {
+                       handleEnter( view );
+                       wp.mce.views.remove( editor, view );
+               });
        }
 
        function select( viewNode ) {
                var clipboard,
                        dom = editor.dom;
 
-               // Bail if node is already selected.
-               if ( viewNode === selected ) {
+               if ( ! viewNode ) {
                        return;
                }
 
-               deselect();
-               selected = viewNode;
-               dom.addClass( viewNode, 'selected' );
+               if ( viewNode !== selected ) {
+                       // Make sure that the editor is focused.
+                       // It is possible that the editor is not focused when the mouse event fires
+                       // without focus, the selection will not work properly.
+                       editor.getBody().focus();
 
-               clipboard = dom.create( 'div', {
-                       'class': 'wpview-clipboard',
-                       'contenteditable': 'true'
-               }, getViewText( viewNode ) );
+                       deselect();
+                       selected = viewNode;
+                       dom.setAttrib( viewNode, 'data-mce-selected', 1 );
 
-               // Prepend inside the wrapper
-               viewNode.insertBefore( clipboard, viewNode.firstChild );
+                       clipboard = dom.create( 'div', {
+                               'class': 'wpview-clipboard',
+                               'contenteditable': 'true'
+                       }, wp.mce.views.getText( viewNode ) );
 
-               // Both of the following are necessary to prevent manipulating the selection/focus
-               dom.bind( clipboard, 'beforedeactivate focusin focusout', _stop );
-               dom.bind( selected, 'beforedeactivate focusin focusout', _stop );
+                       editor.dom.select( '.wpview-body', viewNode )[0].appendChild( clipboard );
 
-               // Make sure that the editor is focused.
-               // It is possible that the editor is not focused when the mouse event fires
-               // without focus, the selection will not work properly.
-               editor.getBody().focus();
+                       // Both of the following are necessary to prevent manipulating the selection/focus
+                       dom.bind( clipboard, 'beforedeactivate focusin focusout', _stop );
+                       dom.bind( selected, 'beforedeactivate focusin focusout', _stop );
 
-               // select the hidden div
-               editor.selection.select( clipboard, true );
+                       // select the hidden div
+                       if ( isios ) {
+                               editor.selection.select( clipboard );
+                       } else {
+                               editor.selection.select( clipboard, true );
+                       }
+               }
+
+               editor.nodeChanged();
+               editor.fire( 'wpview-selected', viewNode );
        }
 
        /**
@@ -109,47 +139,33 @@ tinymce.PluginManager.add( 'wpview', function( editor ) {
                        dom.remove( clipboard );
 
                        dom.unbind( selected, 'beforedeactivate focusin focusout click mouseup', _stop );
-                       dom.removeClass( selected, 'selected' );
+                       dom.setAttrib( selected, 'data-mce-selected', null );
                }
 
                selected = null;
        }
 
-       function selectSiblingView( node, direction ) {
-               var body = editor.getBody(),
-                       sibling = direction === 'previous' ? 'previousSibling' : 'nextSibling';
-
-               while ( node && node.parentNode !== body ) {
-                       if ( node[sibling] ) {
-                               // The caret will be in another element
-                               return false;
-                       }
-
-                       node = node.parentNode;
-               }
-
-               if ( isView( node[sibling] ) ) {
-                       select( node[sibling] );
-                       return true;
-               }
-
-               return false;
-       }
-
        // Check if the `wp.mce` API exists.
        if ( typeof wp === 'undefined' || ! wp.mce ) {
-               return;
+               return {
+                       getView: _noop
+               };
+       }
+
+       function resetViewsCallback( match, viewText ) {
+               return '<p>' + window.decodeURIComponent( viewText ) + '</p>';
        }
 
-       // Remove the content of view wrappers from HTML string
-       function emptyViews( content ) {
-               return content.replace(/(<div[^>]+wpview-wrap[^>]+>)[\s\S]+?data-wpview-end[^>]*><\/ins><\/div>/g, '$1</div>' );
+       // Replace the view tags with the view string
+       function resetViews( content ) {
+               return content.replace( /<div[^>]+data-wpview-text="([^"]+)"[^>]*>(?:[\s\S]+?wpview-selection-after[^>]+>[^<>]*<\/p>\s*|\.)<\/div>/g, resetViewsCallback )
+                       .replace( /<p [^>]*?data-wpview-marker="([^"]+)"[^>]*>[\s\S]*?<\/p>/g, resetViewsCallback );
        }
 
        // Prevent adding undo levels on changes inside a view wrapper
        editor.on( 'BeforeAddUndo', function( event ) {
-               if ( event.lastLevel && emptyViews( event.level.content ) === emptyViews( event.lastLevel.content ) ) {
-                       event.preventDefault();
+               if ( event.level.content ) {
+                       event.level.content = resetViews( event.level.content );
                }
        });
 
@@ -157,90 +173,122 @@ tinymce.PluginManager.add( 'wpview', function( editor ) {
        // matching view patterns, and transform the matches into
        // view wrappers.
        editor.on( 'BeforeSetContent', function( event ) {
+               var node;
+
+               if ( ! event.selection ) {
+                       wp.mce.views.unbind();
+               }
+
                if ( ! event.content ) {
                        return;
                }
 
-               if ( ! event.initial ) {
-                       wp.mce.views.unbind( editor );
+               if ( ! event.load ) {
+                       if ( selected ) {
+                               removeView( selected );
+                       }
+
+                       node = editor.selection.getNode();
+
+                       if ( node && node !== editor.getBody() && /^\s*https?:\/\/\S+\s*$/i.test( event.content ) ) {
+                               // When a url is pasted or inserted, only try to embed it when it is in an empty paragrapgh.
+                               node = editor.dom.getParent( node, 'p' );
+
+                               if ( node && /^[\s\uFEFF\u00A0]*$/.test( $( node ).text() || '' ) ) {
+                                       // Make sure there are no empty inline elements in the <p>
+                                       node.innerHTML = '';
+                               } else {
+                                       return;
+                               }
+                       }
                }
 
-               event.content = wp.mce.views.toViews( event.content );
+               event.content = wp.mce.views.setMarkers( event.content );
+       });
+
+       // When pasting strip all tags and check if the string is an URL.
+       // Then replace the pasted content with the cleaned URL.
+       editor.on( 'pastePreProcess', function( event ) {
+               var pastedStr = event.content;
+
+               if ( pastedStr ) {
+                       pastedStr = tinymce.trim( pastedStr.replace( /<[^>]+>/g, '' ) );
+
+                       if ( /^https?:\/\/\S+$/i.test( pastedStr ) ) {
+                               event.content = pastedStr;
+                       }
+               }
        });
 
        // When the editor's content has been updated and the DOM has been
        // processed, render the views in the document.
-       editor.on( 'SetContent', function( event ) {
-               var body, padNode;
-
+       editor.on( 'SetContent', function() {
                wp.mce.views.render();
+       });
+
+       // Set the cursor before or after a view when clicking next to it.
+       editor.on( 'click', function( event ) {
+               var x = event.clientX,
+                       y = event.clientY,
+                       body = editor.getBody(),
+                       bodyRect = body.getBoundingClientRect(),
+                       first = body.firstChild,
+                       last = body.lastChild,
+                       firstRect, lastRect, view;
 
-               // Add padding <p> if the noneditable node is last
-               if ( event.load || ! event.set ) {
-                       body = editor.getBody();
+               if ( ! first || ! last ) {
+                       return;
+               }
 
-                       if ( isView( body.lastChild ) ) {
-                               padNode = createPadNode();
-                               body.appendChild( padNode );
+               firstRect = first.getBoundingClientRect();
+               lastRect = last.getBoundingClientRect();
 
-                               if ( ! event.initial ) {
-                                       editor.selection.setCursorLocation( padNode, 0 );
+               if ( y < firstRect.top && ( view = getView( first ) ) ) {
+                       setViewCursor( true, view );
+                       event.preventDefault();
+               } else if ( y > lastRect.bottom && ( view = getView( last ) ) ) {
+                       setViewCursor( false, view );
+                       event.preventDefault();
+               } else if ( x < bodyRect.left || x > bodyRect.right ) {
+                       tinymce.each( editor.dom.select( '.wpview-wrap' ), function( view ) {
+                               var rect = view.getBoundingClientRect();
+
+                               if ( y < rect.top ) {
+                                       return false;
                                }
-                       }
-               }
-       });
 
-       // Detect mouse down events that are adjacent to a view when a view is the first view or the last view
-       editor.on( 'click', function( event ) {
-               var body = editor.getBody(),
-                       doc = editor.getDoc(),
-                       scrollTop = doc.documentElement.scrollTop || body.scrollTop || 0,
-                       x, y, firstNode, lastNode, padNode;
-
-               if ( event.target.nodeName === 'HTML' && ! event.metaKey && ! event.ctrlKey ) {
-                       firstNode = body.firstChild;
-                       lastNode = body.lastChild;
-                       x = event.clientX;
-                       y = event.clientY;
-
-                       // Detect clicks above or to the left if the first node is a wpview
-                       if ( isView( firstNode ) && ( ( x < firstNode.offsetLeft && y < ( firstNode.offsetHeight - scrollTop ) ) ||
-                               y < firstNode.offsetTop ) ) {
-
-                               padNode = createPadNode();
-                               body.insertBefore( padNode, firstNode );
-
-                       // Detect clicks to the right and below the last view
-                       } else if ( isView( lastNode ) && ( x > ( lastNode.offsetLeft + lastNode.offsetWidth ) ||
-                               ( ( scrollTop + y ) - ( lastNode.offsetTop + lastNode.offsetHeight ) ) > 0 ) ) {
-
-                               padNode = createPadNode();
-                               body.appendChild( padNode );
-                       }
+                               if ( y >= rect.top && y <= rect.bottom ) {
+                                       if ( x < bodyRect.left ) {
+                                               setViewCursor( true, view );
+                                               event.preventDefault();
+                                       } else if ( x > bodyRect.right ) {
+                                               setViewCursor( false, view );
+                                               event.preventDefault();
+                                       }
 
-                       if ( padNode ) {
-                               // Make sure that a selected view is deselected so that focus and selection are handled properly
-                               deselect();
-                               editor.getBody().focus();
-                               editor.selection.setCursorLocation( padNode, 0 );
-                       }
+                                       return false;
+                               }
+                       });
                }
        });
 
        editor.on( 'init', function() {
-               var selection = editor.selection;
+               var scrolled = false,
+                       selection = editor.selection,
+                       MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
+
                // When a view is selected, ensure content that is being pasted
                // or inserted is added to a text node (instead of the view).
                editor.on( 'BeforeSetContent', function() {
                        var walker, target,
-                               view = getParentView( selection.getNode() );
+                               view = getView( selection.getNode() );
 
                        // If the selection is not within a view, bail.
                        if ( ! view ) {
                                return;
                        }
 
-                       if ( ! view.nextSibling || isView( view.nextSibling ) ) {
+                       if ( ! view.nextSibling || getView( view.nextSibling ) ) {
                                // If there are no additional nodes or the next node is a
                                // view, create a text node after the current view.
                                target = editor.getDoc().createTextNode('');
@@ -256,257 +304,437 @@ tinymce.PluginManager.add( 'wpview', function( editor ) {
                        selection.collapse( true );
                });
 
-               // When the selection's content changes, scan any new content
-               // for matching views.
-               //
-               // Runs on paste and on inserting nodes/html.
-               editor.on( 'SetContent', function( e ) {
-                       if ( ! e.context ) {
-                               return;
-                       }
-
-                       var node = selection.getNode();
-
-                       if ( ! node.innerHTML ) {
-                               return;
-                       }
-
-                       node.innerHTML = wp.mce.views.toViews( node.innerHTML );
+               editor.dom.bind( editor.getDoc(), 'touchmove', function() {
+                       scrolled = true;
                });
 
-               editor.dom.bind( editor.getBody(), 'mousedown mouseup click', function( event ) {
-                       var view = getParentView( event.target ),
-                               deselectEventType;
+               editor.on( 'mousedown mouseup click touchend', function( event ) {
+                       var view = getView( event.target );
+
+                       firstFocus = false;
 
                        // Contain clicks inside the view wrapper
                        if ( view ) {
-                               event.stopPropagation();
+                               event.stopImmediatePropagation();
+                               event.preventDefault();
 
-                               // Hack to try and keep the block resize handles from appearing. They will show on mousedown and then be removed on mouseup.
-                               if ( tinymce.Env.ie <= 10 ) {
-                                       deselect();
+                               if ( event.type === 'touchend' && scrolled ) {
+                                       scrolled = false;
+                               } else {
+                                       select( view );
                                }
 
-                               select( view );
-
-                               if ( event.type === 'click' && ! event.metaKey && ! event.ctrlKey ) {
-                                       if ( editor.dom.hasClass( event.target, 'edit' ) ) {
-                                               wp.mce.views.edit( view );
-                                       } else if ( editor.dom.hasClass( event.target, 'remove' ) ) {
-                                               editor.dom.remove( view );
-                                       }
-                               }
                                // Returning false stops the ugly bars from appearing in IE11 and stops the view being selected as a range in FF.
                                // Unfortunately, it also inhibits the dragging of views to a new location.
                                return false;
                        } else {
-
-                               // Fix issue with deselecting a view in IE8. Without this hack, clicking content above the view wouldn't actually deselect it
-                               // and the caret wouldn't be placed at the mouse location
-                               if ( tinymce.Env.ie && tinymce.Env.ie <= 8 ) {
-                                       deselectEventType = 'mouseup';
-                               } else {
-                                       deselectEventType = 'mousedown';
-                               }
-
-                               if ( event.type === deselectEventType ) {
+                               if ( event.type === 'touchend' || event.type === 'mousedown' ) {
                                        deselect();
                                }
                        }
-               });
-       });
 
-       editor.on( 'PreProcess', function( event ) {
-               var dom = editor.dom;
-
-               // Remove empty padding nodes
-               tinymce.each( dom.select( 'p[data-wpview-pad]', event.node ), function( node ) {
-                       if ( dom.isEmpty( node ) ) {
-                               dom.remove( node );
-                       } else {
-                               dom.setAttrib( node, 'data-wpview-pad', null );
+                       if ( event.type === 'touchend' && scrolled ) {
+                               scrolled = false;
                        }
-               });
+               }, true );
+
+               if ( MutationObserver ) {
+                       new MutationObserver( function() {
+                               editor.fire( 'wp-body-class-change' );
+                       } )
+                       .observe( editor.getBody(), {
+                               attributes: true,
+                               attributeFilter: ['class']
+                       } );
+               }
+       });
 
-               // Replace the wpview node with the wpview string/shortcode?
-               tinymce.each( dom.select( 'div[data-wpview-text]', event.node ), function( node ) {
-                       // Empty the wrap node
-                       if ( 'textContent' in node ) {
-                               node.textContent = '\u00a0';
-                       } else {
-                               node.innerText = '\u00a0';
-                       }
+       // Empty the wpview wrap and marker nodes
+       function emptyViewNodes( rootNode ) {
+               $( 'div[data-wpview-text], p[data-wpview-marker]', rootNode ).each( function( i, node ) {
+                       node.innerHTML = '.';
                });
-    });
+       }
+
+       // Run that before the DOM cleanup
+       editor.on( 'PreProcess', function( event ) {
+               emptyViewNodes( event.node );
+       }, true );
 
-    editor.on( 'PostProcess', function( event ) {
+       editor.on( 'hide', function() {
+               wp.mce.views.unbind();
+               deselect();
+               emptyViewNodes();
+       });
+
+       editor.on( 'PostProcess', function( event ) {
                if ( event.content ) {
-                       event.content = event.content.replace( /<div [^>]*?data-wpview-text="([^"]*)"[^>]*>[\s\S]*?<\/div>/g, function( match, shortcode ) {
-                               if ( shortcode ) {
-                                       return '<p>' + window.decodeURIComponent( shortcode ) + '</p>';
-                               }
-                               return ''; // If error, remove the view wrapper
-                       });
+                       event.content = event.content.replace( /<div [^>]*?data-wpview-text="([^"]+)"[^>]*>[\s\S]*?<\/div>/g, resetViewsCallback )
+                               .replace( /<p [^>]*?data-wpview-marker="([^"]+)"[^>]*>[\s\S]*?<\/p>/g, resetViewsCallback );
                }
        });
 
+       // Excludes arrow keys, delete, backspace, enter, space bar.
+       // Ref: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
+       function isSpecialKey( key ) {
+               return ( ( key <= 47 && key !== VK.SPACEBAR && key !== VK.ENTER && key !== VK.DELETE && key !== VK.BACKSPACE && ( key < 37 || key > 40 ) ) ||
+                       key >= 224 || // OEM or non-printable
+                       ( key >= 144 && key <= 150 ) || // Num Lock, Scroll Lock, OEM
+                       ( key >= 91 && key <= 93 ) || // Windows keys
+                       ( key >= 112 && key <= 135 ) ); // F keys
+       }
+
+       // (De)select views when arrow keys are used to navigate the content of the editor.
        editor.on( 'keydown', function( event ) {
-               var keyCode = event.keyCode,
-                       body = editor.getBody(),
-                       view, padNode;
+               var key = event.keyCode,
+                       dom = editor.dom,
+                       selection = editor.selection,
+                       node, view, cursorBefore, cursorAfter,
+                       range, clonedRange, tempRange;
 
-               // If a view isn't selected, let the event go on its merry way.
-               if ( ! selected ) {
-                       return;
-               }
+               if ( selected ) {
+                       // Ignore key presses that involve the command or control key, but continue when in combination with backspace or v.
+                       // Also ignore the F# keys.
+                       if ( ( ( event.metaKey || event.ctrlKey ) && key !== VK.BACKSPACE && key !== 86 ) || ( key >= 112 && key <= 123 ) ) {
+                               // Remove the view when pressing cmd/ctrl+x on keyup, otherwise the browser can't copy the content.
+                               if ( ( event.metaKey || event.ctrlKey ) && key === 88 ) {
+                                       toRemove = selected;
+                               }
+                               return;
+                       }
+
+                       view = getView( selection.getNode() );
 
-               // Let keypresses that involve the command or control keys through.
-               // Also, let any of the F# keys through.
-               if ( event.metaKey || event.ctrlKey || ( keyCode >= 112 && keyCode <= 123 ) ) {
-                       if ( ( event.metaKey || event.ctrlKey ) && keyCode === 88 ) {
-                               toRemove = selected;
+                       // If the caret is not within the selected view, deselect the view and bail.
+                       if ( view !== selected ) {
+                               deselect();
+                               return;
                        }
-                       return;
-               }
 
-               view = getParentView( editor.selection.getNode() );
+                       if ( key === VK.LEFT ) {
+                               setViewCursor( true, view );
+                               event.preventDefault();
+                       } else if ( key === VK.UP ) {
+                               if ( view.previousSibling ) {
+                                       if ( getView( view.previousSibling ) ) {
+                                               setViewCursor( true, view.previousSibling );
+                                       } else {
+                                               deselect();
+                                               selection.select( view.previousSibling, true );
+                                               selection.collapse();
+                                       }
+                               } else {
+                                       setViewCursor( true, view );
+                               }
+                               event.preventDefault();
+                       } else if ( key === VK.RIGHT ) {
+                               setViewCursor( false, view );
+                               event.preventDefault();
+                       } else if ( key === VK.DOWN ) {
+                               if ( view.nextSibling ) {
+                                       if ( getView( view.nextSibling ) ) {
+                                               setViewCursor( false, view.nextSibling );
+                                       } else {
+                                               deselect();
+                                               selection.setCursorLocation( view.nextSibling, 0 );
+                                       }
+                               } else {
+                                       setViewCursor( false, view );
+                               }
 
-               // If the caret is not within the selected view, deselect the
-               // view and bail.
-               if ( view !== selected ) {
-                       deselect();
-                       return;
-               }
+                               event.preventDefault();
+                       // Ignore keys that don't insert anything.
+                       } else if ( ! isSpecialKey( key ) ) {
+                               removeView( selected );
 
-               // Deselect views with the arrow keys
-               if ( keyCode === VK.LEFT || keyCode === VK.UP ) {
-                       deselect();
-                       // Handle case where two views are stacked on top of one another
-                       if ( isView( view.previousSibling ) ) {
-                               select( view.previousSibling );
-                       // Handle case where view is the first node
-                       } else if ( ! view.previousSibling ) {
-                               padNode = createPadNode();
-                               body.insertBefore( padNode, body.firstChild );
-                               editor.selection.setCursorLocation( body.firstChild, 0 );
-                       // Handle default case
-                       } else {
-                               editor.selection.select( view.previousSibling, true );
-                               editor.selection.collapse();
+                               if ( key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE ) {
+                                       event.preventDefault();
+                               }
                        }
-               } else if ( keyCode === VK.RIGHT || keyCode === VK.DOWN ) {
-                       deselect();
-                       // Handle case where the next node is another wpview
-                       if ( isView( view.nextSibling ) ) {
-                               select( view.nextSibling );
-                       // Handle case were the view is that last node
-                       } else if ( ! view.nextSibling ) {
-                               padNode = createPadNode();
-                               body.appendChild( padNode );
-                               editor.selection.setCursorLocation( body.lastChild, 0 );
-                       // Handle default case where the next node is a non-wpview
-                       } else {
-                               editor.selection.setCursorLocation( view.nextSibling, 0 );
+               } else {
+                       if ( event.metaKey || event.ctrlKey || ( key >= 112 && key <= 123 ) ) {
+                               return;
                        }
-               } else if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
-                       // If delete or backspace is pressed, delete the view.
-                       editor.dom.remove( selected );
-               }
-
-               event.preventDefault();
-       });
 
-       // Select views when arrow keys are used to navigate the content of the editor.
-       editor.on( 'keydown', function( event ) {
-               var keyCode = event.keyCode,
-                       dom = editor.dom,
-                       range = editor.selection.getRng(),
-                       startNode = range.startContainer,
-                       body = editor.getBody(),
-                       node, container;
-
-               if ( ! startNode || startNode === body || event.metaKey || event.ctrlKey ) {
-                       return;
-               }
+                       node = selection.getNode();
+                       lastKeyDownNode = node;
+                       view = getView( node );
+
+                       // Make sure we don't delete part of a view.
+                       // If the range ends or starts with the view, we'll need to trim it.
+                       if ( ! selection.isCollapsed() ) {
+                               range = selection.getRng();
+
+                               if ( view = getView( range.endContainer ) ) {
+                                       clonedRange = range.cloneRange();
+                                       selection.select( view.previousSibling, true );
+                                       selection.collapse();
+                                       tempRange = selection.getRng();
+                                       clonedRange.setEnd( tempRange.endContainer, tempRange.endOffset );
+                                       selection.setRng( clonedRange );
+                               } else if ( view = getView( range.startContainer ) ) {
+                                       clonedRange = range.cloneRange();
+                                       clonedRange.setStart( view.nextSibling, 0 );
+                                       selection.setRng( clonedRange );
+                               }
+                       }
 
-               if ( keyCode === VK.UP || keyCode === VK.LEFT ) {
-                       if ( keyCode === VK.LEFT && ( ! range.collapsed || range.startOffset !== 0 ) ) {
-                               // Not at the beginning of the current range
+                       if ( ! view ) {
+                               // Make sure we don't eat any content.
+                               if ( event.keyCode === VK.BACKSPACE ) {
+                                       if ( editor.dom.isEmpty( node ) ) {
+                                               if ( view = getView( node.previousSibling ) ) {
+                                                       setViewCursor( false, view );
+                                                       editor.dom.remove( node );
+                                                       event.preventDefault();
+                                               }
+                                       } else if ( ( range = selection.getRng() ) &&
+                                                       range.startOffset === 0 &&
+                                                       range.endOffset === 0 &&
+                                                       ( view = getView( node.previousSibling ) ) ) {
+                                               setViewCursor( false, view );
+                                               event.preventDefault();
+                                       }
+                               }
                                return;
                        }
 
-                       if ( ! ( node = dom.getParent( startNode, dom.isBlock ) ) ) {
+                       if ( ! ( ( cursorBefore = dom.hasClass( view, 'wpview-selection-before' ) ) ||
+                                       ( cursorAfter = dom.hasClass( view, 'wpview-selection-after' ) ) ) ) {
                                return;
                        }
 
-                       if ( selectSiblingView( node, 'previous' ) ) {
-                               event.preventDefault();
-                       }
-               } else if ( keyCode === VK.DOWN || keyCode === VK.RIGHT ) {
-                       if ( ! ( node = dom.getParent( startNode, dom.isBlock ) ) ) {
+                       if ( isSpecialKey( key ) ) {
+                               // ignore
                                return;
                        }
 
-                       if ( keyCode === VK.RIGHT ) {
-                               container = range.endContainer;
-
-                               if ( ! range.collapsed || ( range.startOffset === 0 && container.length ) ||
-                                       container.nextSibling ||
-                                       ( container.nodeType === 3 && range.startOffset !== container.length ) ) { // Not at the end of the current range
-
-                                       return;
+                       if ( ( cursorAfter && key === VK.UP ) || ( cursorBefore && key === VK.BACKSPACE ) ) {
+                               if ( view.previousSibling ) {
+                                       if ( getView( view.previousSibling ) ) {
+                                               setViewCursor( false, view.previousSibling );
+                                       } else {
+                                               if ( dom.isEmpty( view.previousSibling ) && key === VK.BACKSPACE ) {
+                                                       dom.remove( view.previousSibling );
+                                               } else {
+                                                       selection.select( view.previousSibling, true );
+                                                       selection.collapse();
+                                               }
+                                       }
+                               } else {
+                                       setViewCursor( true, view );
                                }
-
-                               // In a child element
-                               while ( container && container !== node && container !== body ) {
-                                       if ( container.nextSibling ) {
-                                               return;
+                               event.preventDefault();
+                       } else if ( cursorAfter && ( key === VK.DOWN || key === VK.RIGHT ) ) {
+                               if ( view.nextSibling ) {
+                                       if ( getView( view.nextSibling ) ) {
+                                               setViewCursor( key === VK.RIGHT, view.nextSibling );
+                                       } else {
+                                               selection.setCursorLocation( view.nextSibling, 0 );
                                        }
-                                       container = container.parentNode;
                                }
+                               event.preventDefault();
+                       } else if ( cursorBefore && ( key === VK.UP || key ===  VK.LEFT ) ) {
+                               if ( view.previousSibling ) {
+                                       if ( getView( view.previousSibling ) ) {
+                                               setViewCursor( key === VK.UP, view.previousSibling );
+                                       } else {
+                                               selection.select( view.previousSibling, true );
+                                               selection.collapse();
+                                       }
+                               }
+                               event.preventDefault();
+                       } else if ( cursorBefore && key === VK.DOWN ) {
+                               if ( view.nextSibling ) {
+                                       if ( getView( view.nextSibling ) ) {
+                                               setViewCursor( true, view.nextSibling );
+                                       } else {
+                                               selection.setCursorLocation( view.nextSibling, 0 );
+                                       }
+                               } else {
+                                       setViewCursor( false, view );
+                               }
+                               event.preventDefault();
+                       } else if ( ( cursorAfter && key === VK.LEFT ) || ( cursorBefore && key === VK.RIGHT ) ) {
+                               select( view );
+                               event.preventDefault();
+                       } else if ( cursorAfter && key === VK.BACKSPACE ) {
+                               removeView( view );
+                               event.preventDefault();
+                       } else if ( cursorAfter ) {
+                               handleEnter( view );
+                       } else if ( cursorBefore ) {
+                               handleEnter( view , true, key );
                        }
 
-                       if ( selectSiblingView( node, 'next' ) ) {
+                       if ( key === VK.ENTER ) {
                                event.preventDefault();
                        }
                }
        });
 
-       editor.on( 'keyup', function( event ) {
-               var padNode,
-                       keyCode = event.keyCode,
-                       body = editor.getBody(),
-                       range;
-
+       editor.on( 'keyup', function() {
                if ( toRemove ) {
-                       editor.dom.remove( toRemove );
+                       removeView( toRemove );
                        toRemove = false;
                }
+       });
+
+       editor.on( 'focus', function() {
+               var view;
 
-               if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
-                       // Make sure there is padding if the last element is a view
-                       if ( isView( body.lastChild ) ) {
-                               padNode = createPadNode();
-                               body.appendChild( padNode );
+               focus = true;
+               editor.dom.addClass( editor.getBody(), 'has-focus' );
 
-                               if ( body.childNodes.length === 2 ) {
-                                       editor.selection.setCursorLocation( padNode, 0 );
+               // Edge case: show the fake caret when the editor is focused for the first time
+               // and the first element is a view.
+               if ( firstFocus && ( view = getView( editor.getBody().firstChild ) ) ) {
+                       setViewCursor( true, view );
+               }
+
+               firstFocus = false;
+       } );
+
+       editor.on( 'blur', function() {
+               focus = false;
+               editor.dom.removeClass( editor.getBody(), 'has-focus' );
+       } );
+
+       editor.on( 'NodeChange', function( event ) {
+               var dom = editor.dom,
+                       views = editor.dom.select( '.wpview-wrap' ),
+                       className = event.element.className,
+                       view = getView( event.element ),
+                       lKDN = lastKeyDownNode;
+
+               lastKeyDownNode = false;
+
+               clearInterval( cursorInterval );
+
+               // This runs a lot and is faster than replacing each class separately
+               tinymce.each( views, function ( view ) {
+                       if ( view.className ) {
+                               view.className = view.className.replace( / ?\bwpview-(?:selection-before|selection-after|cursor-hide)\b/g, '' );
+                       }
+               });
+
+               if ( focus && view ) {
+                       if ( ( className === 'wpview-selection-before' || className === 'wpview-selection-after' ) &&
+                               editor.selection.isCollapsed() ) {
+
+                               setViewCursorTries = 0;
+
+                               deselect();
+
+                               // Make sure the cursor arrived in the right node.
+                               // This is necessary for Firefox.
+                               if ( lKDN === view.previousSibling ) {
+                                       setViewCursor( true, view );
+                                       return;
+                               } else if ( lKDN === view.nextSibling ) {
+                                       setViewCursor( false, view );
+                                       return;
                                }
+
+                               dom.addClass( view, className );
+
+                               cursorInterval = setInterval( function() {
+                                       if ( dom.hasClass( view, 'wpview-cursor-hide' ) ) {
+                                               dom.removeClass( view, 'wpview-cursor-hide' );
+                                       } else {
+                                               dom.addClass( view, 'wpview-cursor-hide' );
+                                       }
+                               }, 500 );
+                       // If the cursor lands anywhere else in the view, set the cursor before it.
+                       // Only try this once to prevent a loop. (You never know.)
+                       } else if ( ! getParent( event.element, 'wpview-clipboard' ) && ! setViewCursorTries ) {
+                               deselect();
+                               setViewCursorTries++;
+                               setViewCursor( true, view );
                        }
+               }
+       });
+
+       editor.on( 'BeforeExecCommand', function() {
+               var node = editor.selection.getNode(),
+                       view;
 
-                       range = editor.selection.getRng();
+               if ( node && ( ( execCommandBefore = node.className === 'wpview-selection-before' ) || node.className === 'wpview-selection-after' ) && ( view = getView( node ) ) ) {
+                       handleEnter( view, execCommandBefore );
+                       execCommandView = view;
+               }
+       });
+
+       editor.on( 'ExecCommand', function() {
+               var toSelect, node;
+
+               if ( selected ) {
+                       toSelect = selected;
+                       deselect();
+                       select( toSelect );
+               }
 
-                       // Allow an initial element in the document to be removed when it is before a view
-                       if ( body.firstChild === range.startContainer && range.collapsed === true &&
-                                       isView( range.startContainer.nextSibling ) && range.startOffset === 0 ) {
+               if ( execCommandView ) {
+                       node = execCommandView[ execCommandBefore ? 'previousSibling' : 'nextSibling' ];
 
-                               editor.dom.remove( range.startContainer );
+                       if ( node && node.nodeName === 'P' && editor.dom.isEmpty( node ) ) {
+                               editor.dom.remove( node );
+                               setViewCursor( execCommandBefore, execCommandView );
                        }
+
+                       execCommandView = false;
                }
        });
 
+       editor.on( 'ResolveName', function( event ) {
+               if ( editor.dom.hasClass( event.target, 'wpview-wrap' ) ) {
+                       event.name = editor.dom.getAttrib( event.target, 'data-wpview-type' ) || 'wpview';
+                       event.stopPropagation();
+               } else if ( getView( event.target ) ) {
+                       event.preventDefault();
+                       event.stopPropagation();
+               }
+       });
+
+       editor.addButton( 'wp_view_edit', {
+               tooltip: 'Edit ', // trailing space is needed, used for context
+               icon: 'dashicon dashicons-edit',
+               onclick: function() {
+                       selected && wp.mce.views.edit( editor, selected );
+               }
+       } );
+
+       editor.addButton( 'wp_view_remove', {
+               tooltip: 'Remove',
+               icon: 'dashicon dashicons-no',
+               onclick: function() {
+                       selected && removeView( selected );
+               }
+       } );
+
+       editor.once( 'preinit', function() {
+               if ( editor.wp && editor.wp._createToolbar ) {
+                       toolbar = editor.wp._createToolbar( [
+                               'wp_view_edit',
+                               'wp_view_remove'
+                       ] );
+               }
+       } );
+
+       editor.on( 'wptoolbar', function( event ) {
+               if ( selected ) {
+                       event.element = selected;
+                       event.toolbar = toolbar;
+               }
+       } );
+
+       // Add to editor.wp
+       editor.wp = editor.wp || {};
+       editor.wp.getView = getView;
+       editor.wp.setViewCursor = setViewCursor;
+
+       // Keep for back-compat.
        return {
-               getViewText: getViewText,
-               setViewText: setViewText
+               getView: getView
        };
 });