]> scripts.mit.edu Git - autoinstalls/wordpress.git/blobdiff - wp-includes/js/mce-view.js
Wordpress 4.6-scripts
[autoinstalls/wordpress.git] / wp-includes / js / mce-view.js
index ec167ca47c586226a96af37a57cd66d904fd1312..3d2616d7852eb1b9c4661e0a2fb11d4b222f2ae9 100644 (file)
@@ -1,60 +1,35 @@
-/* global tinymce, MediaElementPlayer, WPPlaylistView */
-/**
+/* global tinymce */
+
+/*
+ * The TinyMCE view API.
+ *
  * Note: this API is "experimental" meaning that it will probably change
  * in the next few releases based on feedback from 3.9.0.
  * If you decide to use it, please follow the development closely.
+ *
+ * Diagram
+ *
+ * |- registered view constructor (type)
+ * |  |- view instance (unique text)
+ * |  |  |- editor 1
+ * |  |  |  |- view node
+ * |  |  |  |- view node
+ * |  |  |  |- ...
+ * |  |  |- editor 2
+ * |  |  |  |- ...
+ * |  |- view instance
+ * |  |  |- ...
+ * |- registered view
+ * |  |- ...
  */
+( function( window, wp, shortcode, $ ) {
+       'use strict';
 
-// Ensure the global `wp` object exists.
-window.wp = window.wp || {};
-
-(function($){
        var views = {},
-               instances = {},
-               media = wp.media,
-               viewOptions = ['encodedText'];
+               instances = {};
 
-       // Create the `wp.mce` object if necessary.
        wp.mce = wp.mce || {};
 
-       /**
-        * wp.mce.View
-        *
-        * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
-        * that the TinyMCE View is not tied to a particular DOM node.
-        */
-       wp.mce.View = function( options ) {
-               options || (options = {});
-               _.extend(this, _.pick(options, viewOptions));
-               this.initialize.apply(this, arguments);
-       };
-
-       _.extend( wp.mce.View.prototype, {
-               initialize: function() {},
-               getHtml: function() {},
-               render: function() {
-                       var html = this.getHtml();
-                       // Search all tinymce editor instances and update the placeholders
-                       _.each( tinymce.editors, function( editor ) {
-                               var doc, self = this;
-                               if ( editor.plugins.wpview ) {
-                                       doc = editor.getDoc();
-                                       $( doc ).find( '[data-wpview-text="' + this.encodedText + '"]' ).each(function (i, elem) {
-                                               var node = $( elem );
-                                               // The <ins> is used to mark the end of the wrapper div. Needed when comparing
-                                               // the content as string for preventing extra undo levels.
-                                               node.html( html ).append( '<ins data-wpview-end="1"></ins>' );
-                                               $( self ).trigger( 'ready', elem );
-                                       });
-                               }
-                       }, this );
-               },
-               unbind: function() {}
-       } );
-
-       // take advantage of the Backbone extend method
-       wp.mce.View.extend = Backbone.View.extend;
-
        /**
         * wp.mce.views
         *
@@ -65,40 +40,38 @@ window.wp = window.wp || {};
        wp.mce.views = {
 
                /**
-                * wp.mce.views.register( type, view )
-                *
-                * Registers a new TinyMCE view.
-                *
-                * @param type
-                * @param constructor
+                * Registers a new view type.
                 *
+                * @param {String} type   The view type.
+                * @param {Object} extend An object to extend wp.mce.View.prototype with.
                 */
-               register: function( type, constructor ) {
-                       views[ type ] = constructor;
+               register: function( type, extend ) {
+                       views[ type ] = wp.mce.View.extend( _.extend( extend, { type: type } ) );
                },
 
                /**
-                * wp.mce.views.get( id )
+                * Unregisters a view type.
                 *
-                * Returns a TinyMCE view constructor.
+                * @param {String} type The view type.
                 */
-               get: function( type ) {
-                       return views[ type ];
+               unregister: function( type ) {
+                       delete views[ type ];
                },
 
                /**
-                * wp.mce.views.unregister( type )
+                * Returns the settings of a view type.
                 *
-                * Unregisters a TinyMCE view.
+                * @param {String} type The view type.
+                *
+                * @return {Function} The view constructor.
                 */
-               unregister: function( type ) {
-                       delete views[ type ];
+               get: function( type ) {
+                       return views[ type ];
                },
 
                /**
-                * wp.mce.views.unbind( editor )
-                *
-                * The editor DOM is being rebuilt, run cleanup.
+                * Unbinds all view nodes.
+                * Runs before removing all view nodes from the DOM.
                 */
                unbind: function() {
                        _.each( instances, function( instance ) {
@@ -107,23 +80,26 @@ window.wp = window.wp || {};
                },
 
                /**
-                * toViews( content )
-                * Scans a `content` string for each view's pattern, replacing any
-                * matches with wrapper elements, and creates a new instance for
-                * every match, which triggers the related data to be fetched.
+                * Scans a given string for each view's pattern,
+                * replacing any matches with markers,
+                * and creates a new instance for every match.
+                *
+                * @param {String} content The string to scan.
                 *
+                * @return {String} The string with markers.
                 */
-               toViews: function( content ) {
+               setMarkers: function( content ) {
                        var pieces = [ { content: content } ],
-                               current;
+                               self = this,
+                               instance, current;
 
-                       _.each( views, function( view, viewType ) {
+                       _.each( views, function( view, type ) {
                                current = pieces.slice();
                                pieces  = [];
 
                                _.each( current, function( piece ) {
                                        var remaining = piece.content,
-                                               result;
+                                               result, text;
 
                                        // Ignore processed pieces, but retain their location.
                                        if ( piece.processed ) {
@@ -133,561 +109,817 @@ window.wp = window.wp || {};
 
                                        // Iterate through the string progressively matching views
                                        // and slicing the string as we go.
-                                       while ( remaining && (result = view.toView( remaining )) ) {
+                                       while ( remaining && ( result = view.prototype.match( remaining ) ) ) {
                                                // Any text before the match becomes an unprocessed piece.
                                                if ( result.index ) {
-                                                       pieces.push({ content: remaining.substring( 0, result.index ) });
+                                                       pieces.push( { content: remaining.substring( 0, result.index ) } );
                                                }
 
+                                               instance = self.createInstance( type, result.content, result.options );
+                                               text = instance.loader ? '.' : instance.text;
+
                                                // Add the processed piece for the match.
-                                               pieces.push({
-                                                       content: wp.mce.views.toView( viewType, result.content, result.options ),
+                                               pieces.push( {
+                                                       content: instance.ignore ? text : '<p data-wpview-marker="' + instance.encodedText + '">' + text + '</p>',
                                                        processed: true
-                                               });
+                                               } );
 
                                                // Update the remaining content.
                                                remaining = remaining.slice( result.index + result.content.length );
                                        }
 
-                                       // There are no additional matches. If any content remains,
-                                       // add it as an unprocessed piece.
+                                       // There are no additional matches.
+                                       // If any content remains, add it as an unprocessed piece.
                                        if ( remaining ) {
-                                               pieces.push({ content: remaining });
+                                               pieces.push( { content: remaining } );
                                        }
-                               });
-                       });
+                               } );
+                       } );
 
-                       return _.pluck( pieces, 'content' ).join('');
+                       content = _.pluck( pieces, 'content' ).join( '' );
+                       return content.replace( /<p>\s*<p data-wpview-marker=/g, '<p data-wpview-marker=' ).replace( /<\/p>\s*<\/p>/g, '</p>' );
                },
 
                /**
-                * Create a placeholder for a particular view type
+                * Create a view instance.
                 *
-                * @param viewType
-                * @param text
-                * @param options
+                * @param {String}  type    The view type.
+                * @param {String}  text    The textual representation of the view.
+                * @param {Object}  options Options.
+                * @param {Boolean} force   Recreate the instance. Optional.
                 *
+                * @return {wp.mce.View} The view instance.
                 */
-               toView: function( viewType, text, options ) {
-                       var view = wp.mce.views.get( viewType ),
-                               encodedText = window.encodeURIComponent( text ),
-                               instance, viewOptions;
+               createInstance: function( type, text, options, force ) {
+                       var View = this.get( type ),
+                               encodedText,
+                               instance;
 
+                       text = tinymce.DOM.decode( text );
 
-                       if ( ! view ) {
-                               return text;
-                       }
+                       if ( ! force ) {
+                               instance = this.getInstance( text );
 
-                       if ( ! wp.mce.views.getInstance( encodedText ) ) {
-                               viewOptions = options;
-                               viewOptions.encodedText = encodedText;
-                               instance = new view.View( viewOptions );
-                               instances[ encodedText ] = instance;
+                               if ( instance ) {
+                                       return instance;
+                               }
                        }
 
-                       return wp.html.string({
-                               tag: 'div',
+                       encodedText = encodeURIComponent( text );
 
-                               attrs: {
-                                       'class': 'wpview-wrap wpview-type-' + viewType,
-                                       'data-wpview-text': encodedText,
-                                       'data-wpview-type': viewType,
-                                       'contenteditable': 'false'
-                               },
+                       options = _.extend( options || {}, {
+                               text: text,
+                               encodedText: encodedText
+                       } );
 
-                               content: '\u00a0'
-                       });
+                       return instances[ encodedText ] = new View( options );
                },
 
                /**
-                * Refresh views after an update is made
+                * Get a view instance.
+                *
+                * @param {(String|HTMLElement)} object The textual representation of the view or the view node.
                 *
-                * @param view {object} being refreshed
-                * @param text {string} textual representation of the view
-                */
-               refreshView: function( view, text ) {
-                       var encodedText = window.encodeURIComponent( text ),
-                               viewOptions,
-                               result, instance;
-
-                       instance = wp.mce.views.getInstance( encodedText );
-
-                       if ( ! instance ) {
-                               result = view.toView( text );
-                               viewOptions = result.options;
-                               viewOptions.encodedText = encodedText;
-                               instance = new view.View( viewOptions );
-                               instances[ encodedText ] = instance;
+                * @return {wp.mce.View} The view instance or undefined.
+                */
+               getInstance: function( object ) {
+                       if ( typeof object === 'string' ) {
+                               return instances[ encodeURIComponent( object ) ];
                        }
 
-                       wp.mce.views.render();
+                       return instances[ $( object ).attr( 'data-wpview-text' ) ];
                },
 
-               getInstance: function( encodedText ) {
-                       return instances[ encodedText ];
+               /**
+                * Given a view node, get the view's text.
+                *
+                * @param {HTMLElement} node The view node.
+                *
+                * @return {String} The textual representation of the view.
+                */
+               getText: function( node ) {
+                       return decodeURIComponent( $( node ).attr( 'data-wpview-text' ) || '' );
                },
 
                /**
-                * render( scope )
+                * Renders all view nodes that are not yet rendered.
                 *
-                * Renders any view instances inside a DOM node `scope`.
-                *
-                * View instances are detected by the presence of wrapper elements.
-                * To generate wrapper elements, pass your content through
-                * `wp.mce.view.toViews( content )`.
+                * @param {Boolean} force Rerender all view nodes.
                 */
-               render: function() {
+               render: function( force ) {
                        _.each( instances, function( instance ) {
-                               instance.render();
+                               instance.render( force );
                        } );
                },
 
-               edit: function( node ) {
-                       var viewType = $( node ).data('wpview-type'),
-                               view = wp.mce.views.get( viewType );
+               /**
+                * Update the text of a given view node.
+                *
+                * @param {String}         text   The new text.
+                * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
+                * @param {HTMLElement}    node   The view node to update.
+                * @param {Boolean}        force  Recreate the instance. Optional.
+                */
+               update: function( text, editor, node, force ) {
+                       var instance = this.getInstance( node );
 
-                       if ( view ) {
-                               view.edit( node );
+                       if ( instance ) {
+                               instance.update( text, editor, node, force );
                        }
-               }
-       };
+               },
 
-       wp.mce.gallery = {
-               shortcode: 'gallery',
-               toView:  function( content ) {
-                       var match = wp.shortcode.next( this.shortcode, content );
+               /**
+                * Renders any editing interface based on the view type.
+                *
+                * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
+                * @param {HTMLElement}    node   The view node to edit.
+                */
+               edit: function( editor, node ) {
+                       var instance = this.getInstance( node );
 
-                       if ( ! match ) {
-                               return;
+                       if ( instance && instance.edit ) {
+                               instance.edit( instance.text, function( text, force ) {
+                                       instance.update( text, editor, node, force );
+                               } );
                        }
-
-                       return {
-                               index:   match.index,
-                               content: match.content,
-                               options: {
-                                       shortcode: match.shortcode
-                               }
-                       };
                },
-               View: wp.mce.View.extend({
-                       className: 'editor-gallery',
-                       template:  media.template('editor-gallery'),
-
-                       // The fallback post ID to use as a parent for galleries that don't
-                       // specify the `ids` or `include` parameters.
-                       //
-                       // Uses the hidden input on the edit posts page by default.
-                       postID: $('#post_ID').val(),
-
-                       initialize: function( options ) {
-                               this.shortcode = options.shortcode;
-                               this.fetch();
-                       },
-
-                       fetch: function() {
-                               this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID );
-                               this.dfd = this.attachments.more().done( _.bind( this.render, this ) );
-                       },
-
-                       getHtml: function() {
-                               var attrs = this.shortcode.attrs.named,
-                                       attachments = false,
-                                       options;
-
-                               // Don't render errors while still fetching attachments
-                               if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
-                                       return;
-                               }
-
-                               if ( this.attachments.length ) {
-                                       attachments = this.attachments.toJSON();
-
-                                       _.each( attachments, function( attachment ) {
-                                               if ( attachment.sizes ) {
-                                                       if ( attachment.sizes.thumbnail ) {
-                                                               attachment.thumbnail = attachment.sizes.thumbnail;
-                                                       } else if ( attachment.sizes.full ) {
-                                                               attachment.thumbnail = attachment.sizes.full;
-                                                       }
-                                               }
-                                       } );
-                               }
-
-                               options = {
-                                       attachments: attachments,
-                                       columns: attrs.columns ? parseInt( attrs.columns, 10 ) : 3
-                               };
 
-                               return this.template( options );
+               /**
+                * Remove a given view node from the DOM.
+                *
+                * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
+                * @param {HTMLElement}    node   The view node to remove.
+                */
+               remove: function( editor, node ) {
+                       var instance = this.getInstance( node );
 
+                       if ( instance ) {
+                               instance.remove( editor, node );
                        }
-               }),
-
-               edit: function( node ) {
-                       var gallery = wp.media.gallery,
-                               self = this,
-                               frame, data;
-
-                       data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
-                       frame = gallery.edit( data );
-
-                       frame.state('gallery-edit').on( 'update', function( selection ) {
-                               var shortcode = gallery.shortcode( selection ).string();
-                               $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
-                               wp.mce.views.refreshView( self, shortcode );
-                               frame.detach();
-                       });
                }
-
        };
-       wp.mce.views.register( 'gallery', wp.mce.gallery );
 
        /**
-        * Tiny MCE Views for Audio / Video
+        * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
+        * The main difference is that the TinyMCE View is not tied to a particular DOM node.
         *
+        * @param {Object} options Options.
         */
+       wp.mce.View = function( options ) {
+               _.extend( this, options );
+               this.initialize();
+       };
+
+       wp.mce.View.extend = Backbone.View.extend;
+
+       _.extend( wp.mce.View.prototype, {
 
-       /**
-        * These are base methods that are shared by each shortcode's MCE controller
-        *
-        * @mixin
-        */
-       wp.mce.media = {
-               loaded: false,
                /**
-                * @global wp.shortcode
+                * The content.
                 *
-                * @param {string} content
-                * @returns {Object}
+                * @type {*}
                 */
-               toView:  function( content ) {
-                       var match = wp.shortcode.next( this.shortcode, content );
+               content: null,
 
-                       if ( ! match ) {
-                               return;
-                       }
+               /**
+                * Whether or not to display a loader.
+                *
+                * @type {Boolean}
+                */
+               loader: true,
 
-                       return {
-                               index:   match.index,
-                               content: match.content,
-                               options: {
-                                       shortcode: match.shortcode
-                               }
-                       };
+               /**
+                * Runs after the view instance is created.
+                */
+               initialize: function() {},
+
+               /**
+                * Retuns the content to render in the view node.
+                *
+                * @return {*}
+                */
+               getContent: function() {
+                       return this.content;
                },
 
                /**
-                * Called when a TinyMCE view is clicked for editing.
-                * - Parses the shortcode out of the element's data attribute
-                * - Calls the `edit` method on the shortcode model
-                * - Launches the model window
-                * - Bind's an `update` callback which updates the element's data attribute
-                *   re-renders the view
+                * Renders all view nodes tied to this view instance that are not yet rendered.
                 *
-                * @param {HTMLElement} node
+                * @param {String}  content The content to render. Optional.
+                * @param {Boolean} force   Rerender all view nodes tied to this view instance. Optional.
                 */
-               edit: function( node ) {
-                       var media = wp.media[ this.shortcode ],
-                               self = this,
-                               frame, data, callback;
+               render: function( content, force ) {
+                       if ( content != null ) {
+                               this.content = content;
+                       }
 
-                       wp.media.mixin.pauseAllPlayers();
+                       content = this.getContent();
 
-                       data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
-                       frame = media.edit( data );
-                       frame.on( 'close', function() {
-                               frame.detach();
-                       } );
+                       // If there's nothing to render an no loader needs to be shown, stop.
+                       if ( ! this.loader && ! content ) {
+                               return;
+                       }
 
-                       callback = function( selection ) {
-                               var shortcode = wp.media[ self.shortcode ].shortcode( selection ).string();
-                               $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
-                               wp.mce.views.refreshView( self, shortcode );
-                               frame.detach();
-                       };
-                       if ( _.isArray( self.state ) ) {
-                               _.each( self.state, function (state) {
-                                       frame.state( state ).on( 'update', callback );
-                               } );
+                       // We're about to rerender all views of this instance, so unbind rendered views.
+                       force && this.unbind();
+
+                       // Replace any left over markers.
+                       this.replaceMarkers();
+
+                       if ( content ) {
+                               this.setContent( content, function( editor, node ) {
+                                       $( node ).data( 'rendered', true );
+                                       this.bindNode.call( this, editor, node );
+                               }, force ? null : false );
                        } else {
-                               frame.state( self.state ).on( 'update', callback );
+                               this.setLoader();
                        }
-                       frame.open();
-               }
-       };
+               },
 
-       /**
-        * Base View class for audio and video shortcodes
-        *
-        * @constructor
-        * @augments wp.mce.View
-        * @mixes wp.media.mixin
-        */
-       wp.mce.media.View = wp.mce.View.extend({
-               initialize: function( options ) {
-                       this.players = [];
-                       this.shortcode = options.shortcode;
-                       _.bindAll( this, 'setPlayer' );
-                       $(this).on( 'ready', this.setPlayer );
+               /**
+                * Binds a given node after its content is added to the DOM.
+                */
+               bindNode: function() {},
+
+               /**
+                * Unbinds a given node before its content is removed from the DOM.
+                */
+               unbindNode: function() {},
+
+               /**
+                * Unbinds all view nodes tied to this view instance.
+                * Runs before their content is removed from the DOM.
+                */
+               unbind: function() {
+                       this.getNodes( function( editor, node ) {
+                               this.unbindNode.call( this, editor, node );
+                       }, true );
                },
 
                /**
-                * Creates the player instance for the current node
+                * Gets all the TinyMCE editor instances that support views.
                 *
-                * @global MediaElementPlayer
-                * @global _wpmejsSettings
+                * @param {Function} callback A callback.
+                */
+               getEditors: function( callback ) {
+                       _.each( tinymce.editors, function( editor ) {
+                               if ( editor.plugins.wpview ) {
+                                       callback.call( this, editor );
+                               }
+                       }, this );
+               },
+
+               /**
+                * Gets all view nodes tied to this view instance.
                 *
-                * @param {Event} e
-                * @param {HTMLElement} node
+                * @param {Function} callback A callback.
+                * @param {Boolean}  rendered Get (un)rendered view nodes. Optional.
                 */
-               setPlayer: function(e, node) {
-                       // if the ready event fires on an empty node
-                       if ( ! node ) {
-                               return;
-                       }
+               getNodes: function( callback, rendered ) {
+                       this.getEditors( function( editor ) {
+                               var self = this;
 
-                       var self = this,
-                               media,
-                               firefox = this.ua.is( 'ff' ),
-                               className = '.wp-' +  this.shortcode.tag + '-shortcode';
+                               $( editor.getBody() )
+                                       .find( '[data-wpview-text="' + self.encodedText + '"]' )
+                                       .filter( function() {
+                                               var data;
 
-                       media = $( node ).find( className );
+                                               if ( rendered == null ) {
+                                                       return true;
+                                               }
 
-                       if ( ! this.isCompatible( media ) ) {
-                               media.closest( '.wpview-wrap' ).addClass( 'wont-play' );
-                               if ( ! media.parent().hasClass( 'wpview-wrap' ) ) {
-                                       media.parent().replaceWith( media );
-                               }
-                               media.replaceWith( '<p>' + media.find( 'source' ).eq(0).prop( 'src' ) + '</p>' );
-                               return;
-                       } else {
-                               media.closest( '.wpview-wrap' ).removeClass( 'wont-play' );
-                               if ( firefox ) {
-                                       media.prop( 'preload', 'metadata' );
-                               } else {
-                                       media.prop( 'preload', 'none' );
+                                               data = $( this ).data( 'rendered' ) === true;
+
+                                               return rendered ? data : ! data;
+                                       } )
+                                       .each( function() {
+                                               callback.call( self, editor, this, this /* back compat */ );
+                                       } );
+                       } );
+               },
+
+               /**
+                * Gets all marker nodes tied to this view instance.
+                *
+                * @param {Function} callback A callback.
+                */
+               getMarkers: function( callback ) {
+                       this.getEditors( function( editor ) {
+                               var self = this;
+
+                               $( editor.getBody() )
+                                       .find( '[data-wpview-marker="' + this.encodedText + '"]' )
+                                       .each( function() {
+                                               callback.call( self, editor, this );
+                                       } );
+                       } );
+               },
+
+               /**
+                * Replaces all marker nodes tied to this view instance.
+                */
+               replaceMarkers: function() {
+                       this.getMarkers( function( editor, node ) {
+                               var $viewNode;
+
+                               if ( ! this.loader && $( node ).text() !== this.text ) {
+                                       editor.dom.setAttrib( node, 'data-wpview-marker', null );
+                                       return;
                                }
-                       }
 
-                       media = wp.media.view.MediaDetails.prepareSrc( media.get(0) );
+                               $viewNode = editor.$(
+                                       '<div class="wpview wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '" contenteditable="false"></div>'
+                               );
+
+                               editor.$( node ).replaceWith( $viewNode );
+                       } );
+               },
 
-                       setTimeout( function() {
-                               wp.mce.media.loaded = true;
-                               self.players.push( new MediaElementPlayer( media, self.mejsSettings ) );
-                       }, wp.mce.media.loaded ? 10 : 500 );
+               /**
+                * Removes all marker nodes tied to this view instance.
+                */
+               removeMarkers: function() {
+                       this.getMarkers( function( editor, node ) {
+                               editor.dom.setAttrib( node, 'data-wpview-marker', null );
+                       } );
                },
 
                /**
-                * Pass data to the View's Underscore template and return the compiled output
+                * Sets the content for all view nodes tied to this view instance.
                 *
-                * @returns {string}
+                * @param {*}        content  The content to set.
+                * @param {Function} callback A callback. Optional.
+                * @param {Boolean}  rendered Only set for (un)rendered nodes. Optional.
                 */
-               getHtml: function() {
-                       var attrs = this.shortcode.attrs.named;
-                       attrs.content = this.shortcode.content;
+               setContent: function( content, callback, rendered ) {
+                       if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
+                               this.setIframes( content.head || '', content.body, callback, rendered );
+                       } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
+                               this.setIframes( '', content, callback, rendered );
+                       } else {
+                               this.getNodes( function( editor, node ) {
+                                       content = content.body || content;
 
-                       return this.template({ model: _.defaults(
-                               attrs,
-                               wp.media[ this.shortcode.tag ].defaults )
-                       });
+                                       if ( content.indexOf( '<iframe' ) !== -1 ) {
+                                               content += '<span class="mce-shim"></span>';
+                                       }
+
+                                       editor.undoManager.transact( function() {
+                                               node.innerHTML = '';
+                                               node.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
+                                               editor.dom.add( node, 'span', { 'class': 'wpview-end' } );
+                                       } );
+
+                                       callback && callback.call( this, editor, node );
+                               }, rendered );
+                       }
                },
 
-               unbind: function() {
-                       this.unsetPlayers();
-               }
-       });
-       _.extend( wp.mce.media.View.prototype, wp.media.mixin );
+               /**
+                * Sets the content in an iframe for all view nodes tied to this view instance.
+                *
+                * @param {String}   head     HTML string to be added to the head of the document.
+                * @param {String}   body     HTML string to be added to the body of the document.
+                * @param {Function} callback A callback. Optional.
+                * @param {Boolean}  rendered Only set for (un)rendered nodes. Optional.
+                */
+               setIframes: function( head, body, callback, rendered ) {
+                       var self = this;
 
-       /**
-        * TinyMCE handler for the video shortcode
-        *
-        * @mixes wp.mce.media
-        */
-       wp.mce.video = _.extend( {}, wp.mce.media, {
-               shortcode: 'video',
-               state: 'video-details',
-               View: wp.mce.media.View.extend({
-                       className: 'editor-video',
-                       template:  media.template('editor-video')
-               })
-       } );
-       wp.mce.views.register( 'video', wp.mce.video );
+                       this.getNodes( function( editor, node ) {
+                               var dom = editor.dom,
+                                       styles = '',
+                                       bodyClasses = editor.getBody().className || '',
+                                       editorHead = editor.getDoc().getElementsByTagName( 'head' )[0];
 
-       /**
-        * TinyMCE handler for the audio shortcode
-        *
-        * @mixes wp.mce.media
-        */
-       wp.mce.audio = _.extend( {}, wp.mce.media, {
-               shortcode: 'audio',
-               state: 'audio-details',
-               View: wp.mce.media.View.extend({
-                       className: 'editor-audio',
-                       template:  media.template('editor-audio')
-               })
-       } );
-       wp.mce.views.register( 'audio', wp.mce.audio );
+                               tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
+                                       if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
+                                               link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
 
-       /**
-        * Base View class for playlist shortcodes
-        *
-        * @constructor
-        * @augments wp.mce.View
-        * @mixes wp.media.mixin
-        */
-       wp.mce.media.PlaylistView = wp.mce.View.extend({
-               className: 'editor-playlist',
-               template:  media.template('editor-playlist'),
-
-               initialize: function( options ) {
-                       this.players = [];
-                       this.data = {};
-                       this.attachments = [];
-                       this.shortcode = options.shortcode;
-                       this.fetch();
+                                               styles += dom.getOuterHTML( link );
+                                       }
+                               } );
+
+                               if ( self.iframeHeight ) {
+                                       dom.add( node, 'span', {
+                                               'data-mce-bogus': 1,
+                                               style: {
+                                                       display: 'block',
+                                                       width: '100%',
+                                                       height: self.iframeHeight
+                                               }
+                                       }, '\u200B' );
+                               }
+
+                               // Seems the browsers need a bit of time to insert/set the view nodes,
+                               // or the iframe will fail especially when switching Text => Visual.
+                               setTimeout( function() {
+                                       var iframe, iframeWin, iframeDoc, MutationObserver, observer, i, block;
+
+                                       editor.undoManager.transact( function() {
+                                               node.innerHTML = '';
+
+                                               iframe = dom.add( node, 'iframe', {
+                                                       /* jshint scripturl: true */
+                                                       src: tinymce.Env.ie ? 'javascript:""' : '',
+                                                       frameBorder: '0',
+                                                       allowTransparency: 'true',
+                                                       scrolling: 'no',
+                                                       'class': 'wpview-sandbox',
+                                                       style: {
+                                                               width: '100%',
+                                                               display: 'block'
+                                                       },
+                                                       height: self.iframeHeight
+                                               } );
+
+                                               dom.add( node, 'span', { 'class': 'mce-shim' } );
+                                               dom.add( node, 'span', { 'class': 'wpview-end' } );
+                                       } );
+
+                                       // Bail if the iframe node is not attached to the DOM.
+                                       // Happens when the view is dragged in the editor.
+                                       // There is a browser restriction when iframes are moved in the DOM. They get emptied.
+                                       // The iframe will be rerendered after dropping the view node at the new location.
+                                       if ( ! iframe.contentWindow ) {
+                                               return;
+                                       }
+
+                                       iframeWin = iframe.contentWindow;
+                                       iframeDoc = iframeWin.document;
+                                       iframeDoc.open();
+
+                                       iframeDoc.write(
+                                               '<!DOCTYPE html>' +
+                                               '<html>' +
+                                                       '<head>' +
+                                                               '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
+                                                               head +
+                                                               styles +
+                                                               '<style>' +
+                                                                       'html {' +
+                                                                               'background: transparent;' +
+                                                                               'padding: 0;' +
+                                                                               'margin: 0;' +
+                                                                       '}' +
+                                                                       'body#wpview-iframe-sandbox {' +
+                                                                               'background: transparent;' +
+                                                                               'padding: 1px 0 !important;' +
+                                                                               'margin: -1px 0 0 !important;' +
+                                                                       '}' +
+                                                                       'body#wpview-iframe-sandbox:before,' +
+                                                                       'body#wpview-iframe-sandbox:after {' +
+                                                                               'display: none;' +
+                                                                               'content: "";' +
+                                                                       '}' +
+                                                               '</style>' +
+                                                       '</head>' +
+                                                       '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
+                                                               body +
+                                                       '</body>' +
+                                               '</html>'
+                                       );
+
+                                       iframeDoc.close();
+
+                                       function resize() {
+                                               var $iframe;
+
+                                               if ( block ) {
+                                                       return;
+                                               }
+
+                                               // Make sure the iframe still exists.
+                                               if ( iframe.contentWindow ) {
+                                                       $iframe = $( iframe );
+                                                       self.iframeHeight = $( iframeDoc.body ).height();
+
+                                                       if ( $iframe.height() !== self.iframeHeight ) {
+                                                               $iframe.height( self.iframeHeight );
+                                                               editor.nodeChanged();
+                                                       }
+                                               }
+                                       }
+
+                                       if ( self.iframeHeight ) {
+                                               block = true;
+
+                                               setTimeout( function() {
+                                                       block = false;
+                                                       resize();
+                                               }, 3000 );
+                                       }
+
+                                       $( iframeWin ).on( 'load', resize );
+
+                                       MutationObserver = iframeWin.MutationObserver || iframeWin.WebKitMutationObserver || iframeWin.MozMutationObserver;
+
+                                       if ( MutationObserver ) {
+                                               observer = new MutationObserver( _.debounce( resize, 100 ) );
+
+                                               observer.observe( iframeDoc.body, {
+                                                       attributes: true,
+                                                       childList: true,
+                                                       subtree: true
+                                               } );
+                                       } else {
+                                               for ( i = 1; i < 6; i++ ) {
+                                                       setTimeout( resize, i * 700 );
+                                               }
+                                       }
+
+                                       callback && callback.call( self, editor, node );
+                               }, 50 );
+                       }, rendered );
                },
 
                /**
-                * Asynchronously fetch the shortcode's attachments
+                * Sets a loader for all view nodes tied to this view instance.
                 */
-               fetch: function() {
-                       this.attachments = wp.media.playlist.attachments( this.shortcode );
-                       this.dfd = this.attachments.more().done( _.bind( this.render, this ) );
+               setLoader: function() {
+                       this.setContent(
+                               '<div class="loading-placeholder">' +
+                                       '<div class="dashicons dashicons-admin-media"></div>' +
+                                       '<div class="wpview-loading"><ins></ins></div>' +
+                               '</div>'
+                       );
                },
 
                /**
-                * Get the HTML for the view (which also set's the data), replace the
-                *   current HTML, and then invoke the WPPlaylistView instance to render
-                *   the playlist in the editor
+                * Sets an error for all view nodes tied to this view instance.
                 *
-                * @global WPPlaylistView
-                * @global tinymce.editors
+                * @param {String} message  The error message to set.
+                * @param {String} dashicon A dashicon ID. Optional. {@link https://developer.wordpress.org/resource/dashicons/}
                 */
-               render: function() {
-                       var html = this.getHtml(), self = this;
+               setError: function( message, dashicon ) {
+                       this.setContent(
+                               '<div class="wpview-error">' +
+                                       '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
+                                       '<p>' + message + '</p>' +
+                               '</div>'
+                       );
+               },
 
-                       _.each( tinymce.editors, function( editor ) {
-                               var doc;
-                               if ( editor.plugins.wpview ) {
-                                       doc = editor.getDoc();
-                                       $( doc ).find( '[data-wpview-text="' + this.encodedText + '"]' ).each(function (i, elem) {
-                                               var node = $( elem );
+               /**
+                * Tries to find a text match in a given string.
+                *
+                * @param {String} content The string to scan.
+                *
+                * @return {Object}
+                */
+               match: function( content ) {
+                       var match = shortcode.next( this.type, content );
+
+                       if ( match ) {
+                               return {
+                                       index: match.index,
+                                       content: match.content,
+                                       options: {
+                                               shortcode: match.shortcode
+                                       }
+                               };
+                       }
+               },
 
-                                               // The <ins> is used to mark the end of the wrapper div. Needed when comparing
-                                               // the content as string for preventing extra undo levels.
-                                               node.html( html ).append( '<ins data-wpview-end="1"></ins>' );
+               /**
+                * Update the text of a given view node.
+                *
+                * @param {String}         text   The new text.
+                * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
+                * @param {HTMLElement}    node   The view node to update.
+                * @param {Boolean}        force  Recreate the instance. Optional.
+                */
+               update: function( text, editor, node, force ) {
+                       _.find( views, function( view, type ) {
+                               var match = view.prototype.match( text );
 
-                                               if ( ! self.data.tracks ) {
-                                                       return;
-                                               }
+                               if ( match ) {
+                                       $( node ).data( 'rendered', false );
+                                       editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
+                                       wp.mce.views.createInstance( type, text, match.options, force ).render();
+                                       editor.focus();
 
-                                               self.players.push( new WPPlaylistView({
-                                                       el: $( elem ).find( '.wp-playlist' ).get(0),
-                                                       metadata: self.data
-                                               }).player );
-                                       });
+                                       return true;
                                }
-                       }, this );
+                       } );
                },
 
                /**
-                * Set the data that will be used to compile the Underscore template,
-                *  compile the template, and then return it.
+                * Remove a given view node from the DOM.
                 *
-                * @returns {string}
+                * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
+                * @param {HTMLElement}    node   The view node to remove.
                 */
-               getHtml: function() {
-                       var data = this.shortcode.attrs.named,
-                               model = wp.media.playlist,
-                               options,
-                               attachments,
-                               tracks = [];
+               remove: function( editor, node ) {
+                       this.unbindNode.call( this, editor, node );
+                       editor.dom.remove( node );
+                       editor.focus();
+               }
+       } );
+} )( window, window.wp, window.wp.shortcode, window.jQuery );
 
-                       // Don't render errors while still fetching attachments
-                       if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
-                               return;
-                       }
+/*
+ * The WordPress core TinyMCE views.
+ * Views for the gallery, audio, video, playlist and embed shortcodes,
+ * and a view for embeddable URLs.
+ */
+( function( window, views, media, $ ) {
+       var base, gallery, av, embed,
+               schema, parser, serializer;
 
-                       _.each( model.defaults, function( value, key ) {
-                               data[ key ] = model.coerce( data, key );
-                       });
-
-                       options = {
-                               type: data.type,
-                               style: data.style,
-                               tracklist: data.tracklist,
-                               tracknumbers: data.tracknumbers,
-                               images: data.images,
-                               artists: data.artists
-                       };
-
-                       if ( ! this.attachments.length ) {
-                               return this.template( options );
-                       }
+       function verifyHTML( string ) {
+               var settings = {};
 
-                       attachments = this.attachments.toJSON();
+               if ( ! window.tinymce ) {
+                       return string.replace( /<[^>]+>/g, '' );
+               }
 
-                       _.each( attachments, function( attachment ) {
-                               var size = {}, resize = {}, track = {
-                                       src : attachment.url,
-                                       type : attachment.mime,
-                                       title : attachment.title,
-                                       caption : attachment.caption,
-                                       description : attachment.description,
-                                       meta : attachment.meta
-                               };
+               if ( ! string || ( string.indexOf( '<' ) === -1 && string.indexOf( '>' ) === -1 ) ) {
+                       return string;
+               }
 
-                               if ( 'video' === data.type ) {
-                                       size.width = attachment.width;
-                                       size.height = attachment.height;
-                                       if ( media.view.settings.contentWidth ) {
-                                               resize.width = media.view.settings.contentWidth - 22;
-                                               resize.height = Math.ceil( ( size.height * resize.width ) / size.width );
-                                               if ( ! options.width ) {
-                                                       options.width = resize.width;
-                                                       options.height = resize.height;
-                                               }
-                                       } else {
-                                               if ( ! options.width ) {
-                                                       options.width = attachment.width;
-                                                       options.height = attachment.height;
+               schema = schema || new window.tinymce.html.Schema( settings );
+               parser = parser || new window.tinymce.html.DomParser( settings, schema );
+               serializer = serializer || new window.tinymce.html.Serializer( settings, schema );
+
+               return serializer.serialize( parser.parse( string, { forced_root_block: false } ) );
+       }
+
+       base = {
+               state: [],
+
+               edit: function( text, update ) {
+                       var type = this.type,
+                               frame = media[ type ].edit( text );
+
+                       this.pausePlayers && this.pausePlayers();
+
+                       _.each( this.state, function( state ) {
+                               frame.state( state ).on( 'update', function( selection ) {
+                                       update( media[ type ].shortcode( selection ).string(), type === 'gallery' );
+                               } );
+                       } );
+
+                       frame.on( 'close', function() {
+                               frame.detach();
+                       } );
+
+                       frame.open();
+               }
+       };
+
+       gallery = _.extend( {}, base, {
+               state: [ 'gallery-edit' ],
+               template: media.template( 'editor-gallery' ),
+
+               initialize: function() {
+                       var attachments = media.gallery.attachments( this.shortcode, media.view.settings.post.id ),
+                               attrs = this.shortcode.attrs.named,
+                               self = this;
+
+                       attachments.more()
+                       .done( function() {
+                               attachments = attachments.toJSON();
+
+                               _.each( attachments, function( attachment ) {
+                                       if ( attachment.sizes ) {
+                                               if ( attrs.size && attachment.sizes[ attrs.size ] ) {
+                                                       attachment.thumbnail = attachment.sizes[ attrs.size ];
+                                               } else if ( attachment.sizes.thumbnail ) {
+                                                       attachment.thumbnail = attachment.sizes.thumbnail;
+                                               } else if ( attachment.sizes.full ) {
+                                                       attachment.thumbnail = attachment.sizes.full;
                                                }
                                        }
-                                       track.dimensions = {
-                                               original : size,
-                                               resized : _.isEmpty( resize ) ? size : resize
-                                       };
+                               } );
+
+                               self.render( self.template( {
+                                       verifyHTML: verifyHTML,
+                                       attachments: attachments,
+                                       columns: attrs.columns ? parseInt( attrs.columns, 10 ) : media.galleryDefaults.columns
+                               } ) );
+                       } )
+                       .fail( function( jqXHR, textStatus ) {
+                               self.setError( textStatus );
+                       } );
+               }
+       } );
+
+       av = _.extend( {}, base, {
+               action: 'parse-media-shortcode',
+
+               initialize: function() {
+                       var self = this;
+
+                       if ( this.url ) {
+                               this.loader = false;
+                               this.shortcode = media.embed.shortcode( {
+                                       url: this.text
+                               } );
+                       }
+
+                       wp.ajax.post( this.action, {
+                               post_ID: media.view.settings.post.id,
+                               type: this.shortcode.tag,
+                               shortcode: this.shortcode.string()
+                       } )
+                       .done( function( response ) {
+                               self.render( response );
+                       } )
+                       .fail( function( response ) {
+                               if ( self.url ) {
+                                       self.ignore = true;
+                                       self.removeMarkers();
                                } else {
-                                       options.width = 400;
+                                       self.setError( response.message || response.statusText, 'admin-media' );
+                               }
+                       } );
+
+                       this.getEditors( function( editor ) {
+                               editor.on( 'wpview-selected', function() {
+                                       self.pausePlayers();
+                               } );
+                       } );
+               },
+
+               pausePlayers: function() {
+                       this.getNodes( function( editor, node, content ) {
+                               var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
+
+                               if ( win && ( win = win.contentWindow ) && win.mejs ) {
+                                       _.each( win.mejs.players, function( player ) {
+                                               try {
+                                                       player.pause();
+                                               } catch ( e ) {}
+                                       } );
                                }
+                       } );
+               }
+       } );
+
+       embed = _.extend( {}, av, {
+               action: 'parse-embed',
+
+               edit: function( text, update ) {
+                       var frame = media.embed.edit( text, this.url ),
+                               self = this;
 
-                               track.image = attachment.image;
-                               track.thumb = attachment.thumb;
+                       this.pausePlayers();
 
-                               tracks.push( track );
+                       frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
+                               if ( url && model.get( 'url' ) ) {
+                                       frame.state( 'embed' ).metadata = model.toJSON();
+                               }
                        } );
 
-                       options.tracks = tracks;
-                       this.data = options;
+                       frame.state( 'embed' ).on( 'select', function() {
+                               var data = frame.state( 'embed' ).metadata;
 
-                       return this.template( options );
-               },
+                               if ( self.url ) {
+                                       update( data.url );
+                               } else {
+                                       update( media.embed.shortcode( data ).string() );
+                               }
+                       } );
 
-               unbind: function() {
-                       this.unsetPlayers();
-               }
-       });
-       _.extend( wp.mce.media.PlaylistView.prototype, wp.media.mixin );
+                       frame.on( 'close', function() {
+                               frame.detach();
+                       } );
 
-       /**
-        * TinyMCE handler for the playlist shortcode
-        *
-        * @mixes wp.mce.media
-        */
-       wp.mce.playlist = _.extend( {}, wp.mce.media, {
-               shortcode: 'playlist',
-               state: ['playlist-edit', 'video-playlist-edit'],
-               View: wp.mce.media.PlaylistView
+                       frame.open();
+               }
        } );
-       wp.mce.views.register( 'playlist', wp.mce.playlist );
-}(jQuery));
+
+       views.register( 'gallery', _.extend( {}, gallery ) );
+
+       views.register( 'audio', _.extend( {}, av, {
+               state: [ 'audio-details' ]
+       } ) );
+
+       views.register( 'video', _.extend( {}, av, {
+               state: [ 'video-details' ]
+       } ) );
+
+       views.register( 'playlist', _.extend( {}, av, {
+               state: [ 'playlist-edit', 'video-playlist-edit' ]
+       } ) );
+
+       views.register( 'embed', _.extend( {}, embed ) );
+
+       views.register( 'embedURL', _.extend( {}, embed, {
+               match: function( content ) {
+                       var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
+                               match = re.exec( content );
+
+                       if ( match ) {
+                               return {
+                                       index: match.index + match[1].length,
+                                       content: match[2],
+                                       options: {
+                                               url: true
+                                       }
+                               };
+                       }
+               }
+       } ) );
+} )( window, window.wp.mce.views, window.wp.media, window.jQuery );