Make WordPress Core

Ticket #31412: 31412.patch

File 31412.patch, 41.9 KB (added by iseulde, 10 years ago)
  • src/wp-includes/js/mce-view.js

     
    11/* global tinymce */
    2 /**
     2
     3/*
     4 * The TinyMCE view API.
     5 *
    36 * Note: this API is "experimental" meaning that it will probably change
    47 * in the next few releases based on feedback from 3.9.0.
    58 * If you decide to use it, please follow the development closely.
    69 */
    7 
    8 // Ensure the global `wp` object exists.
    9 window.wp = window.wp || {};
    10 
    1110( function( $ ) {
    1211        'use strict';
    1312
    1413        var views = {},
    15                 instances = {},
    16                 media = wp.media,
    17                 mediaWindows = [],
    18                 windowIdx = 0,
    19                 waitInterval = 50,
    20                 viewOptions = ['encodedText'];
     14                instances = {};
    2115
    22         // Create the `wp.mce` object if necessary.
     16        window.wp = window.wp || {};
    2317        wp.mce = wp.mce || {};
    2418
    2519        /**
    26          * wp.mce.View
    27          *
    28          * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
    29          * that the TinyMCE View is not tied to a particular DOM node.
    30          *
    31          * @param {Object} [options={}]
    32          */
    33         wp.mce.View = function( options ) {
    34                 options = options || {};
    35                 this.type = options.type;
    36                 _.extend( this, _.pick( options, viewOptions ) );
    37                 this.initialize.apply( this, arguments );
    38         };
    39 
    40         _.extend( wp.mce.View.prototype, {
    41                 initialize: function() {},
    42                 getHtml: function() {
    43                         return '';
    44                 },
    45                 loadingPlaceholder: function() {
    46                         return '' +
    47                                 '<div class="loading-placeholder">' +
    48                                         '<div class="dashicons dashicons-admin-media"></div>' +
    49                                         '<div class="wpview-loading"><ins></ins></div>' +
    50                                 '</div>';
    51                 },
    52                 render: function( force ) {
    53                         if ( force || ! this.rendered() ) {
    54                                 this.unbind();
    55 
    56                                 this.setContent(
    57                                         '<p class="wpview-selection-before">\u00a0</p>' +
    58                                         '<div class="wpview-body" contenteditable="false">' +
    59                                                 '<div class="toolbar mce-arrow-down">' +
    60                                                         ( _.isFunction( views[ this.type ].edit ) ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
    61                                                         '<div class="dashicons dashicons-no remove"></div>' +
    62                                                 '</div>' +
    63                                                 '<div class="wpview-content wpview-type-' + this.type + '">' +
    64                                                         ( this.getHtml() || this.loadingPlaceholder() ) +
    65                                                 '</div>' +
    66                                                 ( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
    67                                         '</div>' +
    68                                         '<p class="wpview-selection-after">\u00a0</p>',
    69                                         'wrap'
    70                                 );
    71 
    72                                 $( this ).trigger( 'ready' );
    73 
    74                                 this.rendered( true );
    75                         }
    76                 },
    77                 unbind: function() {},
    78                 getEditors: function( callback ) {
    79                         var editors = [];
    80 
    81                         _.each( tinymce.editors, function( editor ) {
    82                                 if ( editor.plugins.wpview ) {
    83                                         if ( callback ) {
    84                                                 callback( editor );
    85                                         }
    86 
    87                                         editors.push( editor );
    88                                 }
    89                         }, this );
    90 
    91                         return editors;
    92                 },
    93                 getNodes: function( callback ) {
    94                         var nodes = [],
    95                                 self = this;
    96 
    97                         this.getEditors( function( editor ) {
    98                                 $( editor.getBody() )
    99                                 .find( '[data-wpview-text="' + self.encodedText + '"]' )
    100                                 .each( function ( i, node ) {
    101                                         if ( callback ) {
    102                                                 callback( editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
    103                                         }
    104 
    105                                         nodes.push( node );
    106                                 } );
    107                         } );
    108 
    109                         return nodes;
    110                 },
    111                 setContent: function( html, option ) {
    112                         this.getNodes( function ( editor, node, content ) {
    113                                 var el = ( option === 'wrap' || option === 'replace' ) ? node : content,
    114                                         insert = html;
    115 
    116                                 if ( _.isString( insert ) ) {
    117                                         insert = editor.dom.createFragment( insert );
    118                                 }
    119 
    120                                 if ( option === 'replace' ) {
    121                                         editor.dom.replace( insert, el );
    122                                 } else {
    123                                         el.innerHTML = '';
    124                                         el.appendChild( insert );
    125                                 }
    126                         } );
    127                 },
    128                 /* jshint scripturl: true */
    129                 setIframes: function ( head, body ) {
    130                         var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
    131                                 importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
    132 
    133                         if ( head || body.indexOf( '<script' ) !== -1 ) {
    134                                 this.getNodes( function ( editor, node, content ) {
    135                                         var dom = editor.dom,
    136                                                 styles = '',
    137                                                 bodyClasses = editor.getBody().className || '',
    138                                                 iframe, iframeDoc, i, resize;
    139 
    140                                         content.innerHTML = '';
    141                                         head = head || '';
    142 
    143                                         if ( importStyles ) {
    144                                                 if ( ! wp.mce.views.sandboxStyles ) {
    145                                                         tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
    146                                                                 if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
    147                                                                         link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
    148 
    149                                                                         styles += dom.getOuterHTML( link ) + '\n';
    150                                                                 }
    151                                                         });
    152 
    153                                                         wp.mce.views.sandboxStyles = styles;
    154                                                 } else {
    155                                                         styles = wp.mce.views.sandboxStyles;
    156                                                 }
    157                                         }
    158 
    159                                         // Seems Firefox needs a bit of time to insert/set the view nodes, or the iframe will fail
    160                                         // especially when switching Text => Visual.
    161                                         setTimeout( function() {
    162                                                 iframe = dom.add( content, 'iframe', {
    163                                                         src: tinymce.Env.ie ? 'javascript:""' : '',
    164                                                         frameBorder: '0',
    165                                                         allowTransparency: 'true',
    166                                                         scrolling: 'no',
    167                                                         'class': 'wpview-sandbox',
    168                                                         style: {
    169                                                                 width: '100%',
    170                                                                 display: 'block'
    171                                                         }
    172                                                 } );
    173 
    174                                                 iframeDoc = iframe.contentWindow.document;
    175 
    176                                                 iframeDoc.open();
    177                                                 iframeDoc.write(
    178                                                         '<!DOCTYPE html>' +
    179                                                         '<html>' +
    180                                                                 '<head>' +
    181                                                                         '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
    182                                                                         head +
    183                                                                         styles +
    184                                                                         '<style>' +
    185                                                                                 'html {' +
    186                                                                                         'background: transparent;' +
    187                                                                                         'padding: 0;' +
    188                                                                                         'margin: 0;' +
    189                                                                                 '}' +
    190                                                                                 'body#wpview-iframe-sandbox {' +
    191                                                                                         'background: transparent;' +
    192                                                                                         'padding: 1px 0 !important;' +
    193                                                                                         'margin: -1px 0 0 !important;' +
    194                                                                                 '}' +
    195                                                                                 'body#wpview-iframe-sandbox:before,' +
    196                                                                                 'body#wpview-iframe-sandbox:after {' +
    197                                                                                         'display: none;' +
    198                                                                                         'content: "";' +
    199                                                                                 '}' +
    200                                                                         '</style>' +
    201                                                                 '</head>' +
    202                                                                 '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
    203                                                                         body +
    204                                                                 '</body>' +
    205                                                         '</html>'
    206                                                 );
    207                                                 iframeDoc.close();
    208 
    209                                                 resize = function() {
    210                                                         var $iframe, iframeDocHeight;
    211 
    212                                                         // Make sure the iframe still exists.
    213                                                         if ( iframe.contentWindow ) {
    214                                                                 $iframe = $( iframe );
    215                                                                 iframeDocHeight = $( iframeDoc.body ).height();
    216 
    217                                                                 if ( $iframe.height() !== iframeDocHeight ) {
    218                                                                         $iframe.height( iframeDocHeight );
    219                                                                         editor.nodeChanged();
    220                                                                 }
    221                                                         }
    222                                                 };
    223 
    224                                                 if ( MutationObserver ) {
    225                                                         new MutationObserver( _.debounce( function() {
    226                                                                 resize();
    227                                                         }, 100 ) )
    228                                                         .observe( iframeDoc.body, {
    229                                                                 attributes: true,
    230                                                                 childList: true,
    231                                                                 subtree: true
    232                                                         } );
    233                                                 } else {
    234                                                         for ( i = 1; i < 6; i++ ) {
    235                                                                 setTimeout( resize, i * 700 );
    236                                                         }
    237                                                 }
    238 
    239                                                 if ( importStyles ) {
    240                                                         editor.on( 'wp-body-class-change', function() {
    241                                                                 iframeDoc.body.className = editor.getBody().className;
    242                                                         });
    243                                                 }
    244                                         }, waitInterval );
    245                                 });
    246                         } else {
    247                                 this.setContent( body );
    248                         }
    249                 },
    250                 setError: function( message, dashicon ) {
    251                         this.setContent(
    252                                 '<div class="wpview-error">' +
    253                                         '<div class="dashicons dashicons-' + ( dashicon ? dashicon : 'no' ) + '"></div>' +
    254                                         '<p>' + message + '</p>' +
    255                                 '</div>'
    256                         );
    257                 },
    258                 rendered: function( value ) {
    259                         var notRendered;
    260 
    261                         this.getNodes( function( editor, node ) {
    262                                 if ( value != null ) {
    263                                         $( node ).data( 'rendered', value === true );
    264                                 } else {
    265                                         notRendered = notRendered || ! $( node ).data( 'rendered' );
    266                                 }
    267                         } );
    268 
    269                         return ! notRendered;
    270                 }
    271         } );
    272 
    273         // take advantage of the Backbone extend method
    274         wp.mce.View.extend = Backbone.View.extend;
    275 
    276         /**
    27720         * wp.mce.views
    27821         *
    27922         * A set of utilities that simplifies adding custom UI within a TinyMCE editor.
     
    28326        wp.mce.views = {
    28427
    28528                /**
    286                  * wp.mce.views.register( type, view )
    287                  *
    28829                 * Registers a new TinyMCE view.
    28930                 *
    290                  * @param type
    291                  * @param constructor
    292                  *
     31                 * @param {String} The view type.
     32                 * @param {Object} Options.
    29333                 */
    294                 register: function( type, constructor ) {
    295                         var defaultConstructor = {
    296                                         type: type,
    297                                         View: {},
    298                                         toView: function( content ) {
    299                                                 var match = wp.shortcode.next( this.type, content );
     34                register: function( type, options ) {
     35                        if ( ! options.View ) {
     36                                options = { View: options };
    30037
    301                                                 if ( ! match ) {
    302                                                         return;
    303                                                 }
     38                                if ( options.View.toView ) {
     39                                        options.toView = options.View.toView;
     40                                        delete options.View.toView;
     41                                }
     42                        }
    30443
    305                                                 return {
    306                                                         index: match.index,
    307                                                         content: match.content,
    308                                                         options: {
    309                                                                 shortcode: match.shortcode
    310                                                         }
    311                                                 };
     44                        options = _.defaults( options, {
     45                                type: type,
     46                                View: {},
     47                                toView: function( content ) {
     48                                        var match = wp.shortcode.next( this.type, content );
     49
     50                                        if ( ! match ) {
     51                                                return;
    31252                                        }
    313                                 };
    31453
    315                         constructor = _.defaults( constructor, defaultConstructor );
    316                         constructor.View = wp.mce.View.extend( constructor.View );
     54                                        return {
     55                                                index: match.index,
     56                                                content: match.content,
     57                                                options: {
     58                                                        shortcode: match.shortcode
     59                                                }
     60                                        };
     61                                }
     62                        } );
    31763
    318                         views[ type ] = constructor;
    319                 },
     64                        options.View = wp.mce.View.extend( options.View );
    32065
    321                 /**
    322                  * wp.mce.views.get( id )
    323                  *
    324                  * Returns a TinyMCE view constructor.
    325                  *
    326                  * @param type
    327                  */
    328                 get: function( type ) {
    329                         return views[ type ];
     66                        views[ type ] = options;
    33067                },
    33168
    33269                /**
    333                  * wp.mce.views.unregister( type )
    334                  *
    33570                 * Unregisters a TinyMCE view.
    33671                 *
    337                  * @param type
     72                 * @param {String} The view type.
    33873                 */
    33974                unregister: function( type ) {
    34075                        delete views[ type ];
    34176                },
    34277
    34378                /**
    344                  * wp.mce.views.unbind( editor )
     79                 * Returns a TinyMCE view constructor.
    34580                 *
     81                 * @param {String} The view type.
     82                 */
     83                get: function( type ) {
     84                        return views[ type ];
     85                },
     86
     87                /**
    34688                 * The editor DOM is being rebuilt, run cleanup.
    34789                 */
    34890                unbind: function() {
     
    35294                },
    35395
    35496                /**
    355                  * toViews( content )
    356                  * Scans a `content` string for each view's pattern, replacing any
    357                  * matches with wrapper elements, and creates a new instance for
    358                  * every match, which triggers the related data to be fetched.
     97                 * Scans a given string for each view's pattern,
     98                 * replacing any matches with markers,
     99                 * and creates a new instance for every match,
     100                 * which triggers the related data to be fetched.
    359101                 *
    360                  * @param content
     102                 * @param {String} String to scan.
    361103                 */
    362104                toViews: function( content ) {
    363105                        var pieces = [ { content: content } ],
    364106                                current;
    365107
    366                         _.each( views, function( view, viewType ) {
     108                        _.each( views, function( view, type ) {
    367109                                current = pieces.slice();
    368110                                pieces  = [];
    369111
     
    379121
    380122                                        // Iterate through the string progressively matching views
    381123                                        // and slicing the string as we go.
    382                                         while ( remaining && (result = view.toView( remaining )) ) {
     124                                        while ( remaining && ( result = view.toView( remaining ) ) ) {
    383125                                                // Any text before the match becomes an unprocessed piece.
    384126                                                if ( result.index ) {
    385                                                         pieces.push({ content: remaining.substring( 0, result.index ) });
     127                                                        pieces.push( { content: remaining.substring( 0, result.index ) } );
    386128                                                }
    387129
    388130                                                // Add the processed piece for the match.
    389                                                 pieces.push({
    390                                                         content: wp.mce.views.toView( viewType, result.content, result.options ),
     131                                                pieces.push( {
     132                                                        content: wp.mce.views.toView( type, result.content, result.options ),
    391133                                                        processed: true
    392                                                 });
     134                                                } );
    393135
    394136                                                // Update the remaining content.
    395137                                                remaining = remaining.slice( result.index + result.content.length );
     
    398140                                        // There are no additional matches. If any content remains,
    399141                                        // add it as an unprocessed piece.
    400142                                        if ( remaining ) {
    401                                                 pieces.push({ content: remaining });
     143                                                pieces.push( { content: remaining } );
    402144                                        }
    403                                 });
    404                         });
     145                                } );
     146                        } );
    405147
    406                         return _.pluck( pieces, 'content' ).join('');
     148                        return _.pluck( pieces, 'content' ).join( '' );
    407149                },
    408150
    409151                /**
    410                  * Create a placeholder for a particular view type
    411                  *
    412                  * @param viewType
    413                  * @param text
    414                  * @param options
     152                 * Returns the marked text for a particular view type,
     153                 * and creates a new instance for that view type if it does not exist.
     154                 * The text will be returned unmarked if no view of that type is registered.
     155                 *
     156                 * @param {String} The view type.
     157                 * @param {String} The textual representation of the view.
     158                 * @param {Object} Options.
    415159                 *
     160                 * @return {String} The markered text.
    416161                 */
    417                 toView: function( viewType, text, options ) {
    418                         var view = wp.mce.views.get( viewType ),
    419                                 encodedText = window.encodeURIComponent( text ),
    420                                 instance, viewOptions;
    421 
     162                toView: function( type, text, options ) {
     163                        var view = this.get( type ),
     164                                encodedText = window.encodeURIComponent( text );
    422165
    423166                        if ( ! view ) {
    424167                                return text;
    425168                        }
    426169
    427                         if ( ! wp.mce.views.getInstance( encodedText ) ) {
    428                                 viewOptions = options;
    429                                 viewOptions.type = viewType;
    430                                 viewOptions.encodedText = encodedText;
    431                                 instance = new view.View( viewOptions );
    432                                 instances[ encodedText ] = instance;
     170                        if ( ! this.getInstance( encodedText ) ) {
     171                                instances[ encodedText ] = new view.View( _.extend( options, {
     172                                        encodedText: encodedText,
     173                                        type: type
     174                                } ) );
    433175                        }
    434176
    435                         return wp.html.string({
    436                                 tag: 'div',
    437 
    438                                 attrs: {
    439                                         'class': 'wpview-wrap',
    440                                         'data-wpview-text': encodedText,
    441                                         'data-wpview-type': viewType
    442                                 },
    443 
    444                                 content: '\u00a0'
    445                         });
     177                        return '<p data-wpview-marker="' + encodedText + '">' + text + '</p>';
    446178                },
    447179
    448180                /**
    449                  * Refresh views after an update is made
     181                 * Refresh views after an update is made.
    450182                 *
    451                  * @param view {object} being refreshed
    452                  * @param text {string} textual representation of the view
    453                  * @param force {Boolean} whether to force rendering
     183                 * @param {Object} The view to refresh.
     184                 * @param {String} The textual representation of the view.
     185                 * @param {Boolean} Whether or not to force rendering.
    454186                 */
    455187                refreshView: function( view, text, force ) {
    456                         var encodedText = window.encodeURIComponent( text ),
    457                                 viewOptions,
    458                                 result, instance;
    459 
    460                         instance = wp.mce.views.getInstance( encodedText );
    461 
    462                         if ( ! instance ) {
    463                                 result = view.toView( text );
    464                                 viewOptions = result.options;
    465                                 viewOptions.type = view.type;
    466                                 viewOptions.encodedText = encodedText;
    467                                 instance = new view.View( viewOptions );
    468                                 instances[ encodedText ] = instance;
     188                        var encodedText = encodeURIComponent( text );
     189
     190                        if ( ! this.getInstance( encodedText ) ) {
     191                                instances[ encodedText ] = new view.View( _.extend( view.toView( text ).options, {
     192                                        encodedText: encodedText,
     193                                        type: view.type
     194                                } ) );
    469195                        }
    470196
    471                         instance.render( force );
     197                        instances[ encodedText ].render( force );
    472198                },
    473199
     200                /**
     201                 * @param {String} The textual representation of the view, encoded.
     202                 */
    474203                getInstance: function( encodedText ) {
    475204                        return instances[ encodedText ];
    476205                },
    477206
    478207                /**
    479                  * render( scope )
     208                 * Renders any view instances.
    480209                 *
    481                  * Renders any view instances inside a DOM node `scope`.
     210                 * View instances are detected by the presence of markers.
     211                 * To generate markers, pass your content through `toViews`.
    482212                 *
    483                  * View instances are detected by the presence of wrapper elements.
    484                  * To generate wrapper elements, pass your content through
    485                  * `wp.mce.view.toViews( content )`.
     213                 * @param {Boolean} Whether or not to force rendering.
    486214                 */
    487215                render: function( force ) {
    488216                        _.each( instances, function( instance ) {
     
    490218                        } );
    491219                },
    492220
    493                 edit: function( node ) {
    494                         var viewType = $( node ).data('wpview-type'),
    495                                 view = wp.mce.views.get( viewType );
     221                /**
     222                 * @param {HTMLElement} A view node.
     223                 */
     224                edit: function( editor, node ) {
     225                        var instance = this.getInstance( $( node ).data( 'wpview-text' ) ),
     226                                view = wp.mce.views.get( instance.type ),
     227                                self = this;
    496228
    497                         if ( view ) {
     229                        if ( view && view.edit ) {
    498230                                view.edit( node );
     231                        } else if ( instance && instance.edit ) {
     232                                instance.edit( decodeURIComponent( instance.encodedText ), function( text ) {
     233                                        $( node ).data( 'rendered', false );
     234                                        editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
     235                                        self.refreshView( view, text );
     236                                } );
    499237                        }
    500238                }
    501239        };
    502240
    503         wp.mce.views.register( 'gallery', {
    504                 View: {
    505                         template: media.template( 'editor-gallery' ),
    506 
    507                         // The fallback post ID to use as a parent for galleries that don't
    508                         // specify the `ids` or `include` parameters.
    509                         //
    510                         // Uses the hidden input on the edit posts page by default.
    511                         postID: $('#post_ID').val(),
    512 
    513                         initialize: function( options ) {
    514                                 this.shortcode = options.shortcode;
    515                                 this.fetch();
    516                         },
     241        /**
     242         * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
     243         * that the TinyMCE View is not tied to a particular DOM node.
     244         *
     245         * @param {Object} Options.
     246         */
     247        wp.mce.View = function( options ) {
     248                _.extend( this, options || {} );
     249                this.initialize.apply( this, arguments );
     250        };
    517251
    518                         fetch: function() {
    519                                 var self = this;
     252        _.extend( wp.mce.View.prototype, {
    520253
    521                                 this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID );
    522                                 this.dfd = this.attachments.more().done( function() {
    523                                         self.render( true );
    524                                 } );
    525                         },
     254                /**
     255                 * Whether or not to display a loader.
     256                 *
     257                 * @type {Boolean}
     258                 */
     259                loader: true,
    526260
    527                         getHtml: function() {
    528                                 var attrs = this.shortcode.attrs.named,
    529                                         attachments = false,
    530                                         options;
    531 
    532                                 // Don't render errors while still fetching attachments
    533                                 if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
    534                                         return '';
    535                                 }
    536 
    537                                 if ( this.attachments.length ) {
    538                                         attachments = this.attachments.toJSON();
    539 
    540                                         _.each( attachments, function( attachment ) {
    541                                                 if ( attachment.sizes ) {
    542                                                         if ( attrs.size && attachment.sizes[ attrs.size ] ) {
    543                                                                 attachment.thumbnail = attachment.sizes[ attrs.size ];
    544                                                         } else if ( attachment.sizes.thumbnail ) {
    545                                                                 attachment.thumbnail = attachment.sizes.thumbnail;
    546                                                         } else if ( attachment.sizes.full ) {
    547                                                                 attachment.thumbnail = attachment.sizes.full;
    548                                                         }
    549                                                 }
    550                                         } );
    551                                 }
     261                /**
     262                 * Runs after the view instance is created.
     263                 */
     264                initialize: function() {},
     265
     266                /**
     267                 * Retuns the HTML string to render in the view.
     268                 *
     269                 * @return {*}
     270                 */
     271                getHtml: function() {},
     272
     273                /**
     274                 * Retuns the HTML string to render in the view.
     275                 *
     276                 * @param {Boolean} Whether or not to rerender.
     277                 */
     278                render: function( rerender ) {
     279                        var i = 0;
     280
     281                        // If there's nothing to render an no loader needs to be shown, stop.
     282                        if ( ! this.loader && ! this.getHtml() ) {
     283                                return;
     284                        }
     285
     286                        // We're about to rerender all views of this instance, so unbind rendered views.
     287                        rerender && this.unbind();
    552288
    553                                 options = {
    554                                         attachments: attachments,
    555                                         columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
    556                                 };
     289                        // Replace any left over markers.
     290                        this.replaceMarkers();
    557291
    558                                 return this.template( options );
     292                        if ( this.getHtml() ) {
     293                                this.setContent( this.getHtml(), function( editor, node ) {
     294                                        $( node ).data( 'rendered', true );
     295                                        this.bindNodes.apply( this, arguments );
     296                                        i++;
     297                                }, rerender ? null : false );
     298
     299                                // Use `bindNodes` if possible.
     300                                i && $( this ).trigger( 'ready' );
     301                        } else {
     302                                this.setLoader();
    559303                        }
    560304                },
    561305
    562                 edit: function( node ) {
    563                         var gallery = wp.media.gallery,
    564                                 self = this,
    565                                 frame, data;
     306                /**
     307                 * Runs after a view is added to the DOM.
     308                 *
     309                 * @param {tinymce.Editor} The editor instance the view node is in.
     310                 * @param {HTMLElement} The view node.
     311                 * @param {HTMLElement} The view's content node.
     312                 */
     313                bindNodes: function() {},
    566314
    567                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    568                         frame = gallery.edit( data );
     315                /**
     316                 * Runs before a view is removed from the DOM.
     317                 */
     318                unbind: function() {
     319                        this.getNodes( function() {
     320                                this.unbindNodes.apply( this, arguments );
     321                        }, true );
     322                },
    569323
    570                         frame.state('gallery-edit').on( 'update', function( selection ) {
    571                                 var shortcode = gallery.shortcode( selection ).string();
    572                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
    573                                 wp.mce.views.refreshView( self, shortcode, true );
    574                         });
     324                /**
     325                 * Runs before a view is removed from the DOM.
     326                 *
     327                 * @param {tinymce.Editor} The editor instance the view node is in.
     328                 * @param {HTMLElement} The view node.
     329                 * @param {HTMLElement} The view's content node.
     330                 */
     331                unbindNodes: function() {},
    575332
    576                         frame.on( 'close', function() {
    577                                 frame.detach();
    578                         });
    579                 }
    580         } );
     333                /**
     334                 * Gets all the TinyMCE editors that support views.
     335                 *
     336                 * @param {Function} A callback (optional).
     337                 *
     338                 * @return {tinymce.Editor[]} An array of TinyMCE editor instances.
     339                 */
     340                getEditors: function( callback ) {
     341                        var editors = [];
    581342
    582         /**
    583          * These are base methods that are shared by the audio and video shortcode's MCE controller.
    584          *
    585          * @mixin
    586          */
    587         wp.mce.av = {
    588                 View: {
    589                         overlay: true,
     343                        _.each( tinymce.editors, function( editor ) {
     344                                if ( editor.plugins.wpview ) {
     345                                        editors.push( editor );
     346                                        callback && callback.call( this, editor );
     347                                }
     348                        }, this );
    590349
    591                         action: 'parse-media-shortcode',
     350                        return editors;
     351                },
    592352
    593                         initialize: function( options ) {
    594                                 var self = this;
     353                /**
     354                 * Gets all the view nodes in each editor.
     355                 *
     356                 * @param {Function} A callback (optional).
     357                 * @param {Boolean} Get (un)rendered nodes (optional).
     358                 *
     359                 * @return {HTMLElement[]} An array of view nodes.
     360                 */
     361                getNodes: function( callback, rendered ) {
     362                        var nodes = [];
    595363
    596                                 this.shortcode = options.shortcode;
     364                        this.getEditors( function( editor ) {
     365                                var self = this;
    597366
    598                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' );
    599                                 $( this ).on( 'ready', this.setNodes );
     367                                $( editor.getBody() )
     368                                        .find( '[data-wpview-text="' + self.encodedText + '"]' )
     369                                        .filter( function() {
     370                                                var data;
    600371
    601                                 $( document ).on( 'media:edit', this.stopPlayers );
     372                                                if ( rendered == null ) {
     373                                                        return true;
     374                                                }
    602375
    603                                 this.fetch();
     376                                                data = $( this ).data( 'rendered' ) === true;
    604377
    605                                 this.getEditors( function( editor ) {
    606                                         editor.on( 'hide', function () {
    607                                                 mediaWindows = [];
    608                                                 windowIdx = 0;
    609                                                 self.stopPlayers();
     378                                                return rendered ? data : ! data;
     379                                        } )
     380                                        .each( function( i, node ) {
     381                                                nodes.push( node );
     382                                                callback && callback.call( self, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
    610383                                        } );
    611                                 });
    612                         },
     384                        } );
    613385
    614                         pauseOtherWindows: function ( win ) {
    615                                 _.each( mediaWindows, function ( mediaWindow ) {
    616                                         if ( mediaWindow.sandboxId !== win.sandboxId ) {
    617                                                 _.each( mediaWindow.mejs.players, function ( player ) {
    618                                                         player.pause();
    619                                                 } );
    620                                         }
    621                                 } );
    622                         },
     386                        return nodes;
     387                },
    623388
    624                         iframeLoaded: function (win) {
    625                                 return _.bind( function () {
    626                                         var callback;
    627                                         if ( ! win.mejs || _.isEmpty( win.mejs.players ) ) {
    628                                                 return;
    629                                         }
     389                /**
     390                 * Gets all the markers in each editor.
     391                 *
     392                 * @param {Function} A callback (optional).
     393                 *
     394                 * @return {HTMLElement[]} An array of marker nodes.
     395                 */
     396                getMarkers: function( callback ) {
     397                        var markers = [];
    630398
    631                                         win.sandboxId = windowIdx;
    632                                         windowIdx++;
    633                                         mediaWindows.push( win );
    634 
    635                                         callback = _.bind( function () {
    636                                                 this.pauseOtherWindows( win );
    637                                         }, this );
    638 
    639                                         if ( ! _.isEmpty( win.mejs.MediaPluginBridge.pluginMediaElements ) ) {
    640                                                 _.each( win.mejs.MediaPluginBridge.pluginMediaElements, function ( mediaElement ) {
    641                                                         mediaElement.addEventListener( 'play', callback );
    642                                                 } );
    643                                         }
     399                        this.getEditors( function( editor ) {
     400                                var self = this;
    644401
    645                                         _.each( win.mejs.players, function ( player ) {
    646                                                 $( player.node ).on( 'play', callback );
    647                                         }, this );
    648                                 }, this );
    649                         },
    650 
    651                         listenToSandboxes: function () {
    652                                 _.each( this.getNodes(), function ( node ) {
    653                                         var win, iframe = $( '.wpview-sandbox', node ).get( 0 );
    654                                         if ( iframe && ( win = iframe.contentWindow ) ) {
    655                                                 $( win ).load( _.bind( this.iframeLoaded( win ), this ) );
    656                                         }
    657                                 }, this );
    658                         },
     402                                $( editor.getBody() )
     403                                        .find( '[data-wpview-marker="' + this.encodedText + '"]' )
     404                                        .each( function( i, node ) {
     405                                                markers.push( node );
     406                                                callback && callback.call( self, editor, node );
     407                                        } );
     408                        } );
    659409
    660                         deferredListen: function () {
    661                                 window.setTimeout( _.bind( this.listenToSandboxes, this ), this.getNodes().length * waitInterval );
    662                         },
    663 
    664                         setNodes: function () {
    665                                 if ( this.parsed ) {
    666                                         this.setIframes( this.parsed.head, this.parsed.body );
    667                                         this.deferredListen();
    668                                 } else {
    669                                         this.fail();
     410                        return markers;
     411                },
     412
     413                /**
     414                 * Replaces all markers with view nodes.
     415                 */
     416                replaceMarkers: function() {
     417                        this.getMarkers( function( editor, node ) {
     418                                if ( $( node ).text() !== decodeURIComponent( this.encodedText ) ) {
     419                                        editor.dom.setAttrib( node, 'data-wpview-marker', null );
     420                                        return;
    670421                                }
    671                         },
    672422
    673                         fetch: function () {
    674                                 var self = this;
     423                                editor.dom.replace(
     424                                        editor.dom.createFragment(
     425                                                '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
     426                                                        '<p class="wpview-selection-before">\u00a0</p>' +
     427                                                        '<div class="wpview-body" contenteditable="false">' +
     428                                                                '<div class="toolbar mce-arrow-down">' +
     429                                                                        ( this.edit || views[ this.type ].edit ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
     430                                                                        '<div class="dashicons dashicons-no remove"></div>' +
     431                                                                '</div>' +
     432                                                                '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
     433                                                                ( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
     434                                                        '</div>' +
     435                                                        '<p class="wpview-selection-after">\u00a0</p>' +
     436                                                '</div>'
     437                                        ),
     438                                        node
     439                                );
     440                        } );
     441                },
    675442
    676                                 wp.ajax.send( this.action, {
    677                                         data: {
    678                                                 post_ID: $( '#post_ID' ).val() || 0,
    679                                                 type: this.shortcode.tag,
    680                                                 shortcode: this.shortcode.string()
    681                                         }
    682                                 } )
    683                                 .done( function( response ) {
    684                                         if ( response ) {
    685                                                 self.parsed = response;
    686                                                 self.setIframes( response.head, response.body );
    687                                                 self.deferredListen();
    688                                         } else {
    689                                                 self.fail( true );
    690                                         }
    691                                 } )
    692                                 .fail( function( response ) {
    693                                         self.fail( response || true );
    694                                 } );
    695                         },
     443                /**
     444                 * Removes all markers.
     445                 */
     446                removeMarkers: function() {
     447                        this.getMarkers( function( editor, node ) {
     448                                editor.dom.setAttrib( node, 'data-wpview-marker', null );
     449                        } );
     450                },
     451
     452                /**
     453                 * Gets all the markers in each editor.
     454                 *
     455                 * @param {(String|HTMLElement)} The content to set.
     456                 * @param {Function} A callback (optional).
     457                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     458                 */
     459                setContent: function( content, callback, rendered ) {
     460                        if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
     461                                this.setIframes( content.head, content.body, callback, rendered );
     462                        } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
     463                                this.setIframes( null, content, callback, rendered );
     464                        } else {
     465                                this.getNodes( function( editor, node, contentNode ) {
     466                                        content = content.body || content;
     467
     468                                        contentNode.innerHTML = '';
     469                                        contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
     470
     471                                        callback && callback.apply( this, arguments );
     472                                }, rendered );
     473                        }
     474                },
     475
     476                /**
     477                 * Set an iframe as the view content.
     478                 */
     479                setIframes: function( head, body, callback, rendered ) {
     480                        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
     481                                importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
     482
     483                        this.getNodes( function( editor, node, content ) {
     484                                var dom = editor.dom,
     485                                        styles = '',
     486                                        bodyClasses = editor.getBody().className || '',
     487                                        iframe, iframeDoc, i, resize;
     488
     489                                content.innerHTML = '';
     490                                head = head || '';
     491
     492                                if ( importStyles ) {
     493                                        if ( ! wp.mce.views.sandboxStyles ) {
     494                                                tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
     495                                                        if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
     496                                                                link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
    696497
    697                         fail: function( error ) {
    698                                 if ( ! this.error ) {
    699                                         if ( error ) {
    700                                                 this.error = error;
     498                                                                styles += dom.getOuterHTML( link ) + '\n';
     499                                                        }
     500                                                });
     501
     502                                                wp.mce.views.sandboxStyles = styles;
    701503                                        } else {
    702                                                 return;
     504                                                styles = wp.mce.views.sandboxStyles;
    703505                                        }
    704506                                }
    705507
    706                                 if ( this.error.message ) {
    707                                         if ( ( this.error.type === 'not-embeddable' && this.type === 'embed' ) || this.error.type === 'not-ssl' ||
    708                                                 this.error.type === 'no-items' ) {
     508                                // Seems Firefox needs a bit of time to insert/set the view nodes,
     509                                // or the iframe will fail especially when switching Text => Visual.
     510                                setTimeout( function() {
     511                                        iframe = dom.add( content, 'iframe', {
     512                                                /* jshint scripturl: true */
     513                                                src: tinymce.Env.ie ? 'javascript:""' : '',
     514                                                frameBorder: '0',
     515                                                allowTransparency: 'true',
     516                                                scrolling: 'no',
     517                                                'class': 'wpview-sandbox',
     518                                                style: {
     519                                                        width: '100%',
     520                                                        display: 'block'
     521                                                }
     522                                        } );
    709523
    710                                                 this.setError( this.error.message, 'admin-media' );
    711                                         } else {
    712                                                 this.setContent( '<p>' + this.original + '</p>', 'replace' );
    713                                         }
    714                                 } else if ( this.error.statusText ) {
    715                                         this.setError( this.error.statusText, 'admin-media' );
    716                                 } else if ( this.original ) {
    717                                         this.setContent( '<p>' + this.original + '</p>', 'replace' );
    718                                 }
    719                         },
    720 
    721                         stopPlayers: function( remove ) {
    722                                 var rem = remove === 'remove';
    723 
    724                                 this.getNodes( function( editor, node, content ) {
    725                                         var p, win,
    726                                                 iframe = $( 'iframe.wpview-sandbox', content ).get(0);
     524                                        iframeDoc = iframe.contentWindow.document;
    727525
    728                                         if ( iframe && ( win = iframe.contentWindow ) && win.mejs ) {
    729                                                 // Sometimes ME.js may show a "Download File" placeholder and player.remove() doesn't exist there.
    730                                                 try {
    731                                                         for ( p in win.mejs.players ) {
    732                                                                 win.mejs.players[p].pause();
     526                                        iframeDoc.open();
    733527
    734                                                                 if ( rem ) {
    735                                                                         win.mejs.players[p].remove();
    736                                                                 }
     528                                        iframeDoc.write(
     529                                                '<!DOCTYPE html>' +
     530                                                '<html>' +
     531                                                        '<head>' +
     532                                                                '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
     533                                                                head +
     534                                                                styles +
     535                                                                '<style>' +
     536                                                                        'html {' +
     537                                                                                'background: transparent;' +
     538                                                                                'padding: 0;' +
     539                                                                                'margin: 0;' +
     540                                                                        '}' +
     541                                                                        'body#wpview-iframe-sandbox {' +
     542                                                                                'background: transparent;' +
     543                                                                                'padding: 1px 0 !important;' +
     544                                                                                'margin: -1px 0 0 !important;' +
     545                                                                        '}' +
     546                                                                        'body#wpview-iframe-sandbox:before,' +
     547                                                                        'body#wpview-iframe-sandbox:after {' +
     548                                                                                'display: none;' +
     549                                                                                'content: "";' +
     550                                                                        '}' +
     551                                                                '</style>' +
     552                                                        '</head>' +
     553                                                        '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
     554                                                                body +
     555                                                        '</body>' +
     556                                                '</html>'
     557                                        );
     558
     559                                        iframeDoc.close();
     560
     561                                        resize = function() {
     562                                                var $iframe, iframeDocHeight;
     563
     564                                                // Make sure the iframe still exists.
     565                                                if ( iframe.contentWindow ) {
     566                                                        $iframe = $( iframe );
     567                                                        iframeDocHeight = $( iframeDoc.body ).height();
     568
     569                                                        if ( $iframe.height() !== iframeDocHeight ) {
     570                                                                $iframe.height( iframeDocHeight );
     571                                                                editor.nodeChanged();
    737572                                                        }
    738                                                 } catch( er ) {}
     573                                                }
     574                                        };
     575
     576                                        if ( MutationObserver ) {
     577                                                new MutationObserver( _.debounce( function() {
     578                                                        resize();
     579                                                }, 100 ) )
     580                                                .observe( iframeDoc.body, {
     581                                                        attributes: true,
     582                                                        childList: true,
     583                                                        subtree: true
     584                                                } );
     585                                        } else {
     586                                                for ( i = 1; i < 6; i++ ) {
     587                                                        setTimeout( resize, i * 700 );
     588                                                }
    739589                                        }
    740                                 });
    741                         },
    742590
    743                         unbind: function() {
    744                                 this.stopPlayers( 'remove' );
    745                         }
     591                                        if ( importStyles ) {
     592                                                editor.on( 'wp-body-class-change', function() {
     593                                                        iframeDoc.body.className = editor.getBody().className;
     594                                                } );
     595                                        }
     596                                }, 50 );
     597
     598                                callback && callback.apply( this, arguments );
     599                        }, rendered );
    746600                },
    747601
    748602                /**
    749                  * Called when a TinyMCE view is clicked for editing.
    750                  * - Parses the shortcode out of the element's data attribute
    751                  * - Calls the `edit` method on the shortcode model
    752                  * - Launches the model window
    753                  * - Bind's an `update` callback which updates the element's data attribute
    754                  *   re-renders the view
     603                 * Set a loader.
     604                 */
     605                setLoader: function() {
     606                        this.setContent(
     607                                '<div class="loading-placeholder">' +
     608                                        '<div class="dashicons dashicons-admin-media"></div>' +
     609                                        '<div class="wpview-loading"><ins></ins></div>' +
     610                                '</div>'
     611                        );
     612                },
     613
     614                /**
     615                 * Set an error.
    755616                 *
    756                  * @param {HTMLElement} node
     617                 * @param {String} The error message to set.
     618                 * @param {String} A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
    757619                 */
    758                 edit: function( node ) {
     620                setError: function( message, dashicon ) {
     621                        this.setContent(
     622                                '<div class="wpview-error">' +
     623                                        '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
     624                                        '<p>' + message + '</p>' +
     625                                '</div>'
     626                        );
     627                }
     628        } );
     629
     630        // Take advantage of the Backbone extend method.
     631        wp.mce.View.extend = Backbone.View.extend;
     632} )( jQuery );
     633
     634/*
     635 * The WordPress core TinyMCE views.
     636 * Views for the gallery, audio, video, playlist and embed shortcodes,
     637 * and a view for embeddable URLs.
     638 */
     639( function( $, views ) {
     640        var postID = $( '#post_ID' ).val() || 0,
     641                media, gallery, av, embed;
     642
     643        media = {
     644                state: [],
     645
     646                edit: function( text, callback ) {
    759647                        var media = wp.media[ this.type ],
    760                                 self = this,
    761                                 frame, data, callback;
     648                                frame = media.edit( text );
     649
     650                        this.stopPlayers && this.stopPlayers();
    762651
    763                         $( document ).trigger( 'media:edit' );
     652                        _.each( this.state, function( state ) {
     653                                frame.state( state ).on( 'update', function( selection ) {
     654                                        callback( media.shortcode( selection ).string() );
     655                                } );
     656                        } );
    764657
    765                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    766                         frame = media.edit( data );
    767658                        frame.on( 'close', function() {
    768659                                frame.detach();
    769660                        } );
     661                }
     662        };
     663
     664        gallery = _.extend( {}, media, {
     665                state: [ 'gallery-edit' ],
     666
     667                initialize: function() {
     668                        var self = this;
     669
     670                        this.template = wp.media.template( 'editor-gallery' );
     671                        this.attachments = wp.media.gallery.attachments( this.shortcode, postID );
     672                        this.dfd = this.attachments.more().done( function() {
     673                                self.render();
     674                        } );
     675                },
    770676
    771                         callback = function( selection ) {
    772                                 var shortcode = wp.media[ self.type ].shortcode( selection ).string();
    773                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
    774                                 wp.mce.views.refreshView( self, shortcode );
    775                                 frame.detach();
    776                         };
    777                         if ( _.isArray( self.state ) ) {
    778                                 _.each( self.state, function (state) {
    779                                         frame.state( state ).on( 'update', callback );
     677                getHtml: function() {
     678                        var attrs = this.shortcode.attrs.named,
     679                                attachments = false;
     680
     681                        // Don't render errors while still fetching attachments
     682                        if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
     683                                return '';
     684                        }
     685
     686                        if ( this.attachments.length ) {
     687                                attachments = this.attachments.toJSON();
     688
     689                                _.each( attachments, function( attachment ) {
     690                                        if ( attachment.sizes ) {
     691                                                if ( attrs.size && attachment.sizes[ attrs.size ] ) {
     692                                                        attachment.thumbnail = attachment.sizes[ attrs.size ];
     693                                                } else if ( attachment.sizes.thumbnail ) {
     694                                                        attachment.thumbnail = attachment.sizes.thumbnail;
     695                                                } else if ( attachment.sizes.full ) {
     696                                                        attachment.thumbnail = attachment.sizes.full;
     697                                                }
     698                                        }
    780699                                } );
    781                         } else {
    782                                 frame.state( self.state ).on( 'update', callback );
    783700                        }
    784                         frame.open();
     701
     702                        return this.template( {
     703                                attachments: attachments,
     704                                columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
     705                        } );
    785706                }
    786         };
     707        } );
    787708
    788         /**
    789          * TinyMCE handler for the video shortcode
    790          *
    791          * @mixes wp.mce.av
    792          */
    793         wp.mce.views.register( 'video', _.extend( {}, wp.mce.av, {
    794                 state: 'video-details'
    795         } ) );
     709        av = _.extend( {}, media, {
     710                overlay: true,
     711                action: 'parse-media-shortcode',
     712
     713                initialize: function() {
     714                        var self = this;
     715
     716                        if ( this.url ) {
     717                                this.loader = false;
     718                                this.shortcode = wp.media.embed.shortcode( {
     719                                        url: this.url
     720                                } );
     721                        }
    796722
    797         /**
    798          * TinyMCE handler for the audio shortcode
    799          *
    800          * @mixes wp.mce.av
    801          */
    802         wp.mce.views.register( 'audio', _.extend( {}, wp.mce.av, {
    803                 state: 'audio-details'
    804         } ) );
     723                        wp.ajax.send( this.action, {
     724                                data: {
     725                                        post_ID: postID,
     726                                        type: this.shortcode.tag,
     727                                        shortcode: this.shortcode.string()
     728                                }
     729                        } )
     730                        .done( function( response ) {
     731                                self.parsed = response;
     732                                self.render();
     733                        } )
     734                        .fail( function( response ) {
     735                                if ( self.type === 'embedURL' ) {
     736                                        self.removeMarkers();
     737                                } else {
     738                                        self.setError( response.message || response.statusText, 'admin-media' );
     739                                }
     740                        } );
    805741
    806         /**
    807          * TinyMCE handler for the playlist shortcode
    808          *
    809          * @mixes wp.mce.av
    810          */
    811         wp.mce.views.register( 'playlist', _.extend( {}, wp.mce.av, {
    812                 state: [ 'playlist-edit', 'video-playlist-edit' ]
    813         } ) );
     742                        this.getEditors( function( editor ) {
     743                                editor.on( 'wpview-selected', function() {
     744                                        self.stopPlayers();
     745                                } );
     746                        } );
     747                },
    814748
    815         /**
    816          * TinyMCE handler for the embed shortcode
    817          */
    818         wp.mce.embedMixin = {
    819                 View: _.extend( {}, wp.mce.av.View, {
    820                         overlay: true,
    821                         action: 'parse-embed',
    822                         initialize: function( options ) {
    823                                 this.content = options.content;
    824                                 this.original = options.url || options.shortcode.string();
    825 
    826                                 if ( options.url ) {
    827                                         this.shortcode = media.embed.shortcode( {
    828                                                 url: options.url
     749                stopPlayers: function( remove ) {
     750                        this.getNodes( function( editor, node, content ) {
     751                                var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
     752
     753                                if ( win && ( win = win.contentWindow ) && win.mejs ) {
     754                                        _.each( win.mejs.players, function( player ) {
     755                                                try {
     756                                                        player[ remove ? 'remove' : 'pause' ]();
     757                                                } catch ( e ) {}
    829758                                        } );
    830                                 } else {
    831                                         this.shortcode = options.shortcode;
    832759                                }
     760                        } );
     761                },
    833762
    834                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch' );
    835                                 $( this ).on( 'ready', this.setNodes );
    836 
    837                                 this.fetch();
    838                         }
    839                 } ),
    840                 edit: function( node ) {
    841                         var embed = media.embed,
    842                                 self = this,
    843                                 frame,
    844                                 data,
    845                                 isURL = 'embedURL' === this.type;
     763                getHtml: function() {
     764                        return this.parsed;
     765                }
     766        } );
    846767
    847                         $( document ).trigger( 'media:edit' );
     768        embed = _.extend( {}, av, {
     769                action: 'parse-embed',
    848770
    849                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    850                         frame = embed.edit( data, isURL );
    851                         frame.on( 'close', function() {
    852                                 frame.detach();
    853                         } );
    854                         frame.state( 'embed' ).props.on( 'change:url', function (model, url) {
    855                                 if ( ! url ) {
    856                                         return;
     771                edit: function( text, callback ) {
     772                        var media = wp.media.embed,
     773                                isURL = 'embedURL' === this.type,
     774                                frame = media.edit( text, isURL );
     775
     776                        this.stopPlayers();
     777
     778                        frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
     779                                if ( url ) {
     780                                        frame.state( 'embed' ).metadata = model.toJSON();
    857781                                }
    858                                 frame.state( 'embed' ).metadata = model.toJSON();
    859782                        } );
    860                         frame.state( 'embed' ).on( 'select', function() {
    861                                 var shortcode;
    862783
     784                        frame.state( 'embed' ).on( 'select', function() {
    863785                                if ( isURL ) {
    864                                         shortcode = frame.state( 'embed' ).metadata.url;
     786                                        callback( frame.state( 'embed' ).metadata.url );
    865787                                } else {
    866                                         shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string();
     788                                        callback( media.shortcode( frame.state( 'embed' ).metadata ).string() );
    867789                                }
    868                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
    869                                 wp.mce.views.refreshView( self, shortcode );
     790                        } );
     791
     792                        frame.on( 'close', function() {
    870793                                frame.detach();
    871794                        } );
     795
    872796                        frame.open();
    873797                }
    874         };
     798        } );
     799
     800        views.register( 'gallery', _.extend( {}, gallery ) );
     801
     802        views.register( 'audio', _.extend( {}, av, {
     803                state: [ 'audio-details' ]
     804        } ) );
    875805
    876         wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
     806        views.register( 'video', _.extend( {}, av, {
     807                state: [ 'video-details' ]
     808        } ) );
     809
     810        views.register( 'playlist', _.extend( {}, av, {
     811                state: [ 'playlist-edit', 'video-playlist-edit' ]
     812        } ) );
     813
     814        views.register( 'embed', _.extend( {}, embed ) );
    877815
    878         wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
     816        views.register( 'embedURL', _.extend( {}, embed, {
    879817                toView: function( content ) {
    880818                        var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
    881819                                match = re.exec( tinymce.trim( content ) );
     
    893831                        };
    894832                }
    895833        } ) );
    896 
    897 }(jQuery));
     834} )( jQuery, wp.mce.views );
  • src/wp-includes/js/tinymce/plugins/wpview/plugin.js

     
    341341                                                        editor.focus();
    342342                                                }
    343343
    344                                                 wp.mce.views.edit( view );
     344                                                wp.mce.views.edit( editor, view );
    345345                                                return false;
    346346                                        } else if ( editor.dom.hasClass( event.target, 'remove' ) ) {
    347347                                                removeView( view );