Make WordPress Core

Ticket #31412: 31412.2.patch

File 31412.2.patch, 43.5 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.
     9 *
     10 * Diagram
     11 *
     12 * |- registered view (type)
     13 * |  |- view instance (unique text)
     14 * |  |  |- editor 1
     15 * |  |  |  |- view node
     16 * |  |  |  |- view node
     17 * |  |  |  |- ...
     18 * |  |  |- editor 2
     19 * |  |  |  |- ...
     20 * |  |- view instance
     21 * |  |  |- ...
     22 * |- registered view
     23 * |  |- ...
    624 */
    7 
    8 // Ensure the global `wp` object exists.
    9 window.wp = window.wp || {};
    10 
    1125( function( $ ) {
    1226        'use strict';
    1327
    1428        var views = {},
    15                 instances = {},
    16                 media = wp.media,
    17                 mediaWindows = [],
    18                 windowIdx = 0,
    19                 waitInterval = 50,
    20                 viewOptions = ['encodedText'];
     29                instances = {};
    2130
    22         // Create the `wp.mce` object if necessary.
     31        window.wp = window.wp || {};
    2332        wp.mce = wp.mce || {};
    2433
    2534        /**
    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         /**
    27735         * wp.mce.views
    27836         *
    27937         * A set of utilities that simplifies adding custom UI within a TinyMCE editor.
     
    28341        wp.mce.views = {
    28442
    28543                /**
    286                  * wp.mce.views.register( type, view )
    287                  *
    288                  * Registers a new TinyMCE view.
    289                  *
    290                  * @param type
    291                  * @param constructor
     44                 * Registers a new view type.
    29245                 *
     46                 * @param {String} The view type.
     47                 * @param {Object} Options.
    29348                 */
    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 );
     49                register: function( type, options ) {
     50                        if ( ! options.View ) {
     51                                options = { View: options };
    30052
    301                                                 if ( ! match ) {
    302                                                         return;
    303                                                 }
     53                                if ( options.View.toView ) {
     54                                        options.toView = options.View.toView;
     55                                        delete options.View.toView;
     56                                }
     57                        }
    30458
    305                                                 return {
    306                                                         index: match.index,
    307                                                         content: match.content,
    308                                                         options: {
    309                                                                 shortcode: match.shortcode
    310                                                         }
    311                                                 };
     59                        options = _.defaults( options, {
     60                                type: type,
     61                                View: {},
     62                                toView: function( content ) {
     63                                        var match = wp.shortcode.next( this.type, content );
     64
     65                                        if ( ! match ) {
     66                                                return;
    31267                                        }
    313                                 };
    31468
    315                         constructor = _.defaults( constructor, defaultConstructor );
    316                         constructor.View = wp.mce.View.extend( constructor.View );
     69                                        return {
     70                                                index: match.index,
     71                                                content: match.content,
     72                                                options: {
     73                                                        shortcode: match.shortcode
     74                                                }
     75                                        };
     76                                }
     77                        } );
     78
     79                        options.View = wp.mce.View.extend( options.View );
    31780
    318                         views[ type ] = constructor;
     81                        views[ type ] = options;
    31982                },
    32083
    32184                /**
    322                  * wp.mce.views.get( id )
     85                 * Unregisters a view type.
    32386                 *
    324                  * Returns a TinyMCE view constructor.
    325                  *
    326                  * @param type
     87                 * @param {String} The view type.
    32788                 */
    328                 get: function( type ) {
    329                         return views[ type ];
     89                unregister: function( type ) {
     90                        delete views[ type ];
    33091                },
    33192
    33293                /**
    333                  * wp.mce.views.unregister( type )
    334                  *
    335                  * Unregisters a TinyMCE view.
     94                 * Returns the settings of a view type.
    33695                 *
    337                  * @param type
     96                 * @param {String} The view type.
    33897                 */
    339                 unregister: function( type ) {
    340                         delete views[ type ];
     98                get: function( type ) {
     99                        return views[ type ];
    341100                },
    342101
    343102                /**
    344                  * wp.mce.views.unbind( editor )
    345                  *
    346                  * The editor DOM is being rebuilt, run cleanup.
     103                 * Unbinds all view nodes.
     104                 * This should be run before removing all view nodes from the DOM.
    347105                 */
    348106                unbind: function() {
    349107                        _.each( instances, function( instance ) {
     
    352110                },
    353111
    354112                /**
    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.
     113                 * Scans a given string for each view's pattern,
     114                 * replacing any matches with markers,
     115                 * and creates a new instance for every match.
    359116                 *
    360                  * @param content
     117                 * @param {String} String to scan.
    361118                 */
    362119                toViews: function( content ) {
    363120                        var pieces = [ { content: content } ],
    364121                                current;
    365122
    366                         _.each( views, function( view, viewType ) {
     123                        _.each( views, function( view, type ) {
    367124                                current = pieces.slice();
    368125                                pieces  = [];
    369126
     
    379136
    380137                                        // Iterate through the string progressively matching views
    381138                                        // and slicing the string as we go.
    382                                         while ( remaining && (result = view.toView( remaining )) ) {
     139                                        while ( remaining && ( result = view.toView( remaining ) ) ) {
    383140                                                // Any text before the match becomes an unprocessed piece.
    384141                                                if ( result.index ) {
    385                                                         pieces.push({ content: remaining.substring( 0, result.index ) });
     142                                                        pieces.push( { content: remaining.substring( 0, result.index ) } );
    386143                                                }
    387144
    388145                                                // Add the processed piece for the match.
    389                                                 pieces.push({
    390                                                         content: wp.mce.views.toView( viewType, result.content, result.options ),
     146                                                pieces.push( {
     147                                                        content: wp.mce.views.toView( type, result.content, result.options ),
    391148                                                        processed: true
    392                                                 });
     149                                                } );
    393150
    394151                                                // Update the remaining content.
    395152                                                remaining = remaining.slice( result.index + result.content.length );
    396153                                        }
    397154
    398                                         // There are no additional matches. If any content remains,
    399                                         // add it as an unprocessed piece.
     155                                        // There are no additional matches.
     156                                        // If any content remains, add it as an unprocessed piece.
    400157                                        if ( remaining ) {
    401                                                 pieces.push({ content: remaining });
     158                                                pieces.push( { content: remaining } );
    402159                                        }
    403                                 });
    404                         });
     160                                } );
     161                        } );
    405162
    406                         return _.pluck( pieces, 'content' ).join('');
     163                        return _.pluck( pieces, 'content' ).join( '' );
    407164                },
    408165
    409166                /**
    410                  * Create a placeholder for a particular view type
    411                  *
    412                  * @param viewType
    413                  * @param text
    414                  * @param options
     167                 * Returns the marked text for a particular view type and a given text,
     168                 * and creates a new instance for that view type if it does not exist.
     169                 * The text will be returned unmarked if no view of that type is registered.
     170                 *
     171                 * @param {String} The view type.
     172                 * @param {String} The textual representation of the view.
     173                 * @param {Object} Options.
    415174                 *
     175                 * @return {String} The markered text.
    416176                 */
    417                 toView: function( viewType, text, options ) {
    418                         var view = wp.mce.views.get( viewType ),
    419                                 encodedText = window.encodeURIComponent( text ),
    420                                 instance, viewOptions;
    421 
     177                toView: function( type, text, options ) {
     178                        var view = this.get( type ),
     179                                encodedText = window.encodeURIComponent( text );
    422180
    423181                        if ( ! view ) {
    424182                                return text;
    425183                        }
    426184
    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;
     185                        if ( ! this.getInstance( encodedText ) ) {
     186                                instances[ encodedText ] = new view.View( _.extend( options, {
     187                                        encodedText: encodedText,
     188                                        type: type
     189                                } ) );
    433190                        }
    434191
    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                         });
     192                        return '<p data-wpview-marker="' + encodedText + '">' + text + '</p>';
    446193                },
    447194
    448195                /**
    449                  * Refresh views after an update is made
     196                 * Refresh view nodes tied to an instance after an update is made.
     197                 * Note: this function assumes the updated node is not marked as rendered.
    450198                 *
    451                  * @param view {object} being refreshed
    452                  * @param text {string} textual representation of the view
    453                  * @param force {Boolean} whether to force rendering
     199                 * @param {Object} The view instance.
     200                 * @param {String} The textual representation of the view.
     201                 * @param {Boolean} Rerender all view nodes tied to this instance.
    454202                 */
    455203                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;
     204                        var encodedText = encodeURIComponent( text );
     205
     206                        if ( ! this.getInstance( encodedText ) ) {
     207                                instances[ encodedText ] = new view.View( _.extend( view.toView( text ).options, {
     208                                        encodedText: encodedText,
     209                                        type: view.type
     210                                } ) );
    469211                        }
    470212
    471                         instance.render( force );
     213                        instances[ encodedText ].render( force );
    472214                },
    473215
     216                /**
     217                 * Get an instance based on the encded text.
     218                 *
     219                 * @param {String} The textual representation of the view, encoded.
     220                 */
    474221                getInstance: function( encodedText ) {
    475222                        return instances[ encodedText ];
    476223                },
    477224
    478225                /**
    479                  * render( scope )
     226                 * Renders all view nodes that are not yet rendered.
    480227                 *
    481                  * Renders any view instances inside a DOM node `scope`.
     228                 * Views are detected by the presence of markers.
     229                 * To generate markers, pass your content through `toViews`.
    482230                 *
    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 )`.
     231                 * @param {Boolean} Rerender all view nodes.
    486232                 */
    487233                render: function( force ) {
    488234                        _.each( instances, function( instance ) {
     
    490236                        } );
    491237                },
    492238
    493                 edit: function( node ) {
    494                         var viewType = $( node ).data('wpview-type'),
    495                                 view = wp.mce.views.get( viewType );
     239                /**
     240                 * Renders any editing interface based on the view type.
     241                 *
     242                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     243                 * @param {HTMLElement} The view node to edit.
     244                 */
     245                edit: function( editor, node ) {
     246                        var instance = this.getInstance( $( node ).data( 'wpview-text' ) ),
     247                                view = wp.mce.views.get( instance.type ),
     248                                self = this;
    496249
    497                         if ( view ) {
     250                        if ( view && view.edit ) {
    498251                                view.edit( node );
     252                        } else if ( instance && instance.edit ) {
     253                                instance.edit( decodeURIComponent( instance.encodedText ), function( text ) {
     254                                        $( node ).data( 'rendered', false );
     255                                        editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
     256                                        self.refreshView( view, text );
     257                                } );
    499258                        }
    500259                }
    501260        };
    502261
    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                         },
     262        /**
     263         * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
     264         * The main difference is that the TinyMCE View is not tied to a particular DOM node.
     265         *
     266         * @param {Object} Options.
     267         */
     268        wp.mce.View = function( options ) {
     269                _.extend( this, options || {} );
     270                this.initialize.apply( this, arguments );
     271        };
    517272
    518                         fetch: function() {
    519                                 var self = this;
     273        _.extend( wp.mce.View.prototype, {
    520274
    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                         },
     275                /**
     276                 * Whether or not to display a loader.
     277                 *
     278                 * @type {Boolean}
     279                 */
     280                loader: true,
    526281
    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                                 }
     282                /**
     283                 * Runs after the view instance is created.
     284                 */
     285                initialize: function() {},
     286
     287                /**
     288                 * Retuns the content to render in the view node.
     289                 *
     290                 * @return {*}
     291                 */
     292                getHtml: function() {},
     293
     294                /**
     295                 * Renders all view nodes tied to this view instance that are not yet rendered.
     296                 *
     297                 * @param {Boolean} Rerender all view nodes tied to this view instance.
     298                 */
     299                render: function( force ) {
     300                        var i = 0;
     301
     302                        // If there's nothing to render an no loader needs to be shown, stop.
     303                        if ( ! this.loader && ! this.getHtml() ) {
     304                                return;
     305                        }
     306
     307                        // We're about to rerender all views of this instance, so unbind rendered views.
     308                        force && this.unbind();
    552309
    553                                 options = {
    554                                         attachments: attachments,
    555                                         columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
    556                                 };
     310                        // Replace any left over markers.
     311                        this.replaceMarkers();
    557312
    558                                 return this.template( options );
     313                        if ( this.getHtml() ) {
     314                                this.setContent( this.getHtml(), function( editor, node ) {
     315                                        $( node ).data( 'rendered', true );
     316                                        this.bindNodes.apply( this, arguments );
     317                                        i++;
     318                                }, force ? null : false );
     319
     320                                // Use `bindNodes` if possible.
     321                                i && $( this ).trigger( 'ready' );
     322                        } else {
     323                                this.setLoader();
    559324                        }
    560325                },
    561326
    562                 edit: function( node ) {
    563                         var gallery = wp.media.gallery,
    564                                 self = this,
    565                                 frame, data;
     327                /**
     328                 * Binds a given rendered view node.
     329                 * Runs after a view node's content is added to the DOM.
     330                 *
     331                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     332                 * @param {HTMLElement} The view node.
     333                 * @param {HTMLElement} The view's content node.
     334                 */
     335                bindNodes: function() {},
    566336
    567                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    568                         frame = gallery.edit( data );
     337                /**
     338                 * Unbinds all view nodes tied to this view instance.
     339                 * Runs before their content is removed from the DOM.
     340                 */
     341                unbind: function() {
     342                        this.getNodes( function() {
     343                                this.unbindNodes.apply( this, arguments );
     344                        }, true );
     345                },
    569346
    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                         });
     347                /**
     348                 * Unbinds a given view node.
     349                 * Runs before the view node's content is removed from the DOM.
     350                 *
     351                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     352                 * @param {HTMLElement} The view node.
     353                 * @param {HTMLElement} The view's content node.
     354                 */
     355                unbindNodes: function() {},
    575356
    576                         frame.on( 'close', function() {
    577                                 frame.detach();
    578                         });
    579                 }
    580         } );
     357                /**
     358                 * Gets all the TinyMCE editor instances that support views.
     359                 *
     360                 * @param {Function} A callback (optional).
     361                 *
     362                 * @return {tinymce.Editor[]} An array of TinyMCE editor instances.
     363                 */
     364                getEditors: function( callback ) {
     365                        var editors = [];
    581366
    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,
     367                        _.each( tinymce.editors, function( editor ) {
     368                                if ( editor.plugins.wpview ) {
     369                                        editors.push( editor );
     370                                        callback && callback.call( this, editor );
     371                                }
     372                        }, this );
    590373
    591                         action: 'parse-media-shortcode',
     374                        return editors;
     375                },
    592376
    593                         initialize: function( options ) {
    594                                 var self = this;
     377                /**
     378                 * Gets all view nodes tied to this view instance.
     379                 *
     380                 * @param {Function} A callback (optional).
     381                 * @param {Boolean} Get (un)rendered view nodes (optional).
     382                 *
     383                 * @return {HTMLElement[]} An array of view nodes.
     384                 */
     385                getNodes: function( callback, rendered ) {
     386                        var nodes = [];
    595387
    596                                 this.shortcode = options.shortcode;
     388                        this.getEditors( function( editor ) {
     389                                var self = this;
    597390
    598                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' );
    599                                 $( this ).on( 'ready', this.setNodes );
     391                                $( editor.getBody() )
     392                                        .find( '[data-wpview-text="' + self.encodedText + '"]' )
     393                                        .filter( function() {
     394                                                var data;
    600395
    601                                 $( document ).on( 'media:edit', this.stopPlayers );
     396                                                if ( rendered == null ) {
     397                                                        return true;
     398                                                }
    602399
    603                                 this.fetch();
     400                                                data = $( this ).data( 'rendered' ) === true;
    604401
    605                                 this.getEditors( function( editor ) {
    606                                         editor.on( 'hide', function () {
    607                                                 mediaWindows = [];
    608                                                 windowIdx = 0;
    609                                                 self.stopPlayers();
     402                                                return rendered ? data : ! data;
     403                                        } )
     404                                        .each( function( i, node ) {
     405                                                nodes.push( node );
     406                                                callback && callback.call( self, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
    610407                                        } );
    611                                 });
    612                         },
     408                        } );
    613409
    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                         },
     410                        return nodes;
     411                },
    623412
    624                         iframeLoaded: function (win) {
    625                                 return _.bind( function () {
    626                                         var callback;
    627                                         if ( ! win.mejs || _.isEmpty( win.mejs.players ) ) {
    628                                                 return;
    629                                         }
     413                /**
     414                 * Gets all marker nodes tied to this view instance.
     415                 *
     416                 * @param {Function} A callback (optional).
     417                 *
     418                 * @return {HTMLElement[]} An array of marker nodes.
     419                 */
     420                getMarkers: function( callback ) {
     421                        var markers = [];
    630422
    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                                         }
     423                        this.getEditors( function( editor ) {
     424                                var self = this;
    644425
    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                         },
     426                                $( editor.getBody() )
     427                                        .find( '[data-wpview-marker="' + this.encodedText + '"]' )
     428                                        .each( function( i, node ) {
     429                                                markers.push( node );
     430                                                callback && callback.call( self, editor, node );
     431                                        } );
     432                        } );
    659433
    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();
     434                        return markers;
     435                },
     436
     437                /**
     438                 * Replaces all marker nodes tied to this view instance.
     439                 */
     440                replaceMarkers: function() {
     441                        this.getMarkers( function( editor, node ) {
     442                                if ( $( node ).text() !== decodeURIComponent( this.encodedText ) ) {
     443                                        editor.dom.setAttrib( node, 'data-wpview-marker', null );
     444                                        return;
    670445                                }
    671                         },
    672446
    673                         fetch: function () {
    674                                 var self = this;
     447                                editor.dom.replace(
     448                                        editor.dom.createFragment(
     449                                                '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
     450                                                        '<p class="wpview-selection-before">\u00a0</p>' +
     451                                                        '<div class="wpview-body" contenteditable="false">' +
     452                                                                '<div class="toolbar mce-arrow-down">' +
     453                                                                        ( this.edit || views[ this.type ].edit ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
     454                                                                        '<div class="dashicons dashicons-no remove"></div>' +
     455                                                                '</div>' +
     456                                                                '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
     457                                                                ( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
     458                                                        '</div>' +
     459                                                        '<p class="wpview-selection-after">\u00a0</p>' +
     460                                                '</div>'
     461                                        ),
     462                                        node
     463                                );
     464                        } );
     465                },
    675466
    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                         },
     467                /**
     468                 * Removes all marker nodes tied to this view instance.
     469                 */
     470                removeMarkers: function() {
     471                        this.getMarkers( function( editor, node ) {
     472                                editor.dom.setAttrib( node, 'data-wpview-marker', null );
     473                        } );
     474                },
     475
     476                /**
     477                 * Sets the content for all view nodes tied to this view instance.
     478                 *
     479                 * @param {*} The content to set.
     480                 * @param {Function} A callback (optional).
     481                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     482                 */
     483                setContent: function( content, callback, rendered ) {
     484                        if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
     485                                this.setIframes( content.head, content.body, callback, rendered );
     486                        } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
     487                                this.setIframes( null, content, callback, rendered );
     488                        } else {
     489                                this.getNodes( function( editor, node, contentNode ) {
     490                                        content = content.body || content;
     491
     492                                        contentNode.innerHTML = '';
     493                                        contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
     494
     495                                        callback && callback.apply( this, arguments );
     496                                }, rendered );
     497                        }
     498                },
     499
     500                /**
     501                 * Sets the content in an iframe for all view nodes tied to this view instance.
     502                 *
     503                 * @param {String} HTML string to be added to the head of the document.
     504                 * @param {String} HTML string to be added to the body of the document.
     505                 * @param {Function} A callback (optional).
     506                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     507                 */
     508                setIframes: function( head, body, callback, rendered ) {
     509                        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
     510                                importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
     511
     512                        this.getNodes( function( editor, node, content ) {
     513                                var dom = editor.dom,
     514                                        styles = '',
     515                                        bodyClasses = editor.getBody().className || '',
     516                                        iframe, iframeDoc, i, resize;
     517
     518                                content.innerHTML = '';
     519                                head = head || '';
     520
     521                                if ( importStyles ) {
     522                                        if ( ! wp.mce.views.sandboxStyles ) {
     523                                                tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
     524                                                        if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
     525                                                                link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
     526
     527                                                                styles += dom.getOuterHTML( link ) + '\n';
     528                                                        }
     529                                                });
    696530
    697                         fail: function( error ) {
    698                                 if ( ! this.error ) {
    699                                         if ( error ) {
    700                                                 this.error = error;
     531                                                wp.mce.views.sandboxStyles = styles;
    701532                                        } else {
    702                                                 return;
     533                                                styles = wp.mce.views.sandboxStyles;
    703534                                        }
    704535                                }
    705536
    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' ) {
     537                                // Seems Firefox needs a bit of time to insert/set the view nodes,
     538                                // or the iframe will fail especially when switching Text => Visual.
     539                                setTimeout( function() {
     540                                        iframe = dom.add( content, 'iframe', {
     541                                                /* jshint scripturl: true */
     542                                                src: tinymce.Env.ie ? 'javascript:""' : '',
     543                                                frameBorder: '0',
     544                                                allowTransparency: 'true',
     545                                                scrolling: 'no',
     546                                                'class': 'wpview-sandbox',
     547                                                style: {
     548                                                        width: '100%',
     549                                                        display: 'block'
     550                                                }
     551                                        } );
    709552
    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);
     553                                        iframeDoc = iframe.contentWindow.document;
    727554
    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();
     555                                        iframeDoc.open();
    733556
    734                                                                 if ( rem ) {
    735                                                                         win.mejs.players[p].remove();
    736                                                                 }
     557                                        iframeDoc.write(
     558                                                '<!DOCTYPE html>' +
     559                                                '<html>' +
     560                                                        '<head>' +
     561                                                                '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
     562                                                                head +
     563                                                                styles +
     564                                                                '<style>' +
     565                                                                        'html {' +
     566                                                                                'background: transparent;' +
     567                                                                                'padding: 0;' +
     568                                                                                'margin: 0;' +
     569                                                                        '}' +
     570                                                                        'body#wpview-iframe-sandbox {' +
     571                                                                                'background: transparent;' +
     572                                                                                'padding: 1px 0 !important;' +
     573                                                                                'margin: -1px 0 0 !important;' +
     574                                                                        '}' +
     575                                                                        'body#wpview-iframe-sandbox:before,' +
     576                                                                        'body#wpview-iframe-sandbox:after {' +
     577                                                                                'display: none;' +
     578                                                                                'content: "";' +
     579                                                                        '}' +
     580                                                                '</style>' +
     581                                                        '</head>' +
     582                                                        '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
     583                                                                body +
     584                                                        '</body>' +
     585                                                '</html>'
     586                                        );
     587
     588                                        iframeDoc.close();
     589
     590                                        resize = function() {
     591                                                var $iframe, iframeDocHeight;
     592
     593                                                // Make sure the iframe still exists.
     594                                                if ( iframe.contentWindow ) {
     595                                                        $iframe = $( iframe );
     596                                                        iframeDocHeight = $( iframeDoc.body ).height();
     597
     598                                                        if ( $iframe.height() !== iframeDocHeight ) {
     599                                                                $iframe.height( iframeDocHeight );
     600                                                                editor.nodeChanged();
    737601                                                        }
    738                                                 } catch( er ) {}
     602                                                }
     603                                        };
     604
     605                                        if ( MutationObserver ) {
     606                                                new MutationObserver( _.debounce( function() {
     607                                                        resize();
     608                                                }, 100 ) )
     609                                                .observe( iframeDoc.body, {
     610                                                        attributes: true,
     611                                                        childList: true,
     612                                                        subtree: true
     613                                                } );
     614                                        } else {
     615                                                for ( i = 1; i < 6; i++ ) {
     616                                                        setTimeout( resize, i * 700 );
     617                                                }
    739618                                        }
    740                                 });
    741                         },
    742619
    743                         unbind: function() {
    744                                 this.stopPlayers( 'remove' );
    745                         }
     620                                        if ( importStyles ) {
     621                                                editor.on( 'wp-body-class-change', function() {
     622                                                        iframeDoc.body.className = editor.getBody().className;
     623                                                } );
     624                                        }
     625                                }, 50 );
     626
     627                                callback && callback.apply( this, arguments );
     628                        }, rendered );
    746629                },
    747630
    748631                /**
    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
     632                 * Sets a loader for all view nodes tied to this view instance.
     633                 */
     634                setLoader: function() {
     635                        this.setContent(
     636                                '<div class="loading-placeholder">' +
     637                                        '<div class="dashicons dashicons-admin-media"></div>' +
     638                                        '<div class="wpview-loading"><ins></ins></div>' +
     639                                '</div>'
     640                        );
     641                },
     642
     643                /**
     644                 * Sets an error for all view nodes tied to this view instance.
    755645                 *
    756                  * @param {HTMLElement} node
     646                 * @param {String} The error message to set.
     647                 * @param {String} A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
    757648                 */
    758                 edit: function( node ) {
     649                setError: function( message, dashicon ) {
     650                        this.setContent(
     651                                '<div class="wpview-error">' +
     652                                        '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
     653                                        '<p>' + message + '</p>' +
     654                                '</div>'
     655                        );
     656                }
     657        } );
     658
     659        // Take advantage of the Backbone extend method.
     660        wp.mce.View.extend = Backbone.View.extend;
     661} )( window.jQuery );
     662
     663/*
     664 * The WordPress core TinyMCE views.
     665 * Views for the gallery, audio, video, playlist and embed shortcodes,
     666 * and a view for embeddable URLs.
     667 */
     668( function( $, views ) {
     669        var postID = $( '#post_ID' ).val() || 0,
     670                media, gallery, av, embed;
     671
     672        media = {
     673                state: [],
     674
     675                edit: function( text, update ) {
    759676                        var media = wp.media[ this.type ],
    760                                 self = this,
    761                                 frame, data, callback;
     677                                frame = media.edit( text );
    762678
    763                         $( document ).trigger( 'media:edit' );
     679                        this.stopPlayers && this.stopPlayers();
     680
     681                        _.each( this.state, function( state ) {
     682                                frame.state( state ).on( 'update', function( selection ) {
     683                                        update( media.shortcode( selection ).string() );
     684                                } );
     685                        } );
    764686
    765                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    766                         frame = media.edit( data );
    767687                        frame.on( 'close', function() {
    768688                                frame.detach();
    769689                        } );
     690                }
     691        };
    770692
    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 );
     693        gallery = _.extend( {}, media, {
     694                state: [ 'gallery-edit' ],
     695
     696                initialize: function() {
     697                        var self = this;
     698
     699                        this.template = wp.media.template( 'editor-gallery' );
     700                        this.attachments = wp.media.gallery.attachments( this.shortcode, postID );
     701                        this.dfd = this.attachments.more().done( function() {
     702                                self.render();
     703                        } );
     704                },
     705
     706                getHtml: function() {
     707                        var attrs = this.shortcode.attrs.named,
     708                                attachments = false;
     709
     710                        // Don't render errors while still fetching attachments
     711                        if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
     712                                return '';
     713                        }
     714
     715                        if ( this.attachments.length ) {
     716                                attachments = this.attachments.toJSON();
     717
     718                                _.each( attachments, function( attachment ) {
     719                                        if ( attachment.sizes ) {
     720                                                if ( attrs.size && attachment.sizes[ attrs.size ] ) {
     721                                                        attachment.thumbnail = attachment.sizes[ attrs.size ];
     722                                                } else if ( attachment.sizes.thumbnail ) {
     723                                                        attachment.thumbnail = attachment.sizes.thumbnail;
     724                                                } else if ( attachment.sizes.full ) {
     725                                                        attachment.thumbnail = attachment.sizes.full;
     726                                                }
     727                                        }
    780728                                } );
    781                         } else {
    782                                 frame.state( self.state ).on( 'update', callback );
    783729                        }
    784                         frame.open();
     730
     731                        return this.template( {
     732                                attachments: attachments,
     733                                columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
     734                        } );
    785735                }
    786         };
     736        } );
    787737
    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         } ) );
     738        av = _.extend( {}, media, {
     739                overlay: true,
     740                action: 'parse-media-shortcode',
     741
     742                initialize: function() {
     743                        var self = this;
     744
     745                        if ( this.url ) {
     746                                this.loader = false;
     747                                this.shortcode = wp.media.embed.shortcode( {
     748                                        url: this.url
     749                                } );
     750                        }
    796751
    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         } ) );
     752                        wp.ajax.send( this.action, {
     753                                data: {
     754                                        post_ID: postID,
     755                                        type: this.shortcode.tag,
     756                                        shortcode: this.shortcode.string()
     757                                }
     758                        } )
     759                        .done( function( response ) {
     760                                self.parsed = response;
     761                                self.render();
     762                        } )
     763                        .fail( function( response ) {
     764                                if ( self.type === 'embedURL' ) {
     765                                        self.removeMarkers();
     766                                } else {
     767                                        self.setError( response.message || response.statusText, 'admin-media' );
     768                                }
     769                        } );
    805770
    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         } ) );
     771                        this.getEditors( function( editor ) {
     772                                editor.on( 'wpview-selected', function() {
     773                                        self.stopPlayers();
     774                                } );
     775                        } );
     776                },
    814777
    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
     778                stopPlayers: function( remove ) {
     779                        this.getNodes( function( editor, node, content ) {
     780                                var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
     781
     782                                if ( win && ( win = win.contentWindow ) && win.mejs ) {
     783                                        _.each( win.mejs.players, function( player ) {
     784                                                try {
     785                                                        player[ remove ? 'remove' : 'pause' ]();
     786                                                } catch ( e ) {}
    829787                                        } );
    830                                 } else {
    831                                         this.shortcode = options.shortcode;
    832788                                }
     789                        } );
     790                },
    833791
    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;
     792                getHtml: function() {
     793                        return this.parsed;
     794                }
     795        } );
    846796
    847                         $( document ).trigger( 'media:edit' );
     797        embed = _.extend( {}, av, {
     798                action: 'parse-embed',
    848799
    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;
     800                edit: function( text, update ) {
     801                        var media = wp.media.embed,
     802                                isURL = 'embedURL' === this.type,
     803                                frame = media.edit( text, isURL );
     804
     805                        this.stopPlayers();
     806
     807                        frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
     808                                if ( url ) {
     809                                        frame.state( 'embed' ).metadata = model.toJSON();
    857810                                }
    858                                 frame.state( 'embed' ).metadata = model.toJSON();
    859811                        } );
    860                         frame.state( 'embed' ).on( 'select', function() {
    861                                 var shortcode;
    862812
     813                        frame.state( 'embed' ).on( 'select', function() {
    863814                                if ( isURL ) {
    864                                         shortcode = frame.state( 'embed' ).metadata.url;
     815                                        update( frame.state( 'embed' ).metadata.url );
    865816                                } else {
    866                                         shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string();
     817                                        update( media.shortcode( frame.state( 'embed' ).metadata ).string() );
    867818                                }
    868                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
    869                                 wp.mce.views.refreshView( self, shortcode );
     819                        } );
     820
     821                        frame.on( 'close', function() {
    870822                                frame.detach();
    871823                        } );
     824
    872825                        frame.open();
    873826                }
    874         };
     827        } );
     828
     829        views.register( 'gallery', _.extend( {}, gallery ) );
    875830
    876         wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
     831        views.register( 'audio', _.extend( {}, av, {
     832                state: [ 'audio-details' ]
     833        } ) );
     834
     835        views.register( 'video', _.extend( {}, av, {
     836                state: [ 'video-details' ]
     837        } ) );
    877838
    878         wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
     839        views.register( 'playlist', _.extend( {}, av, {
     840                state: [ 'playlist-edit', 'video-playlist-edit' ]
     841        } ) );
     842
     843        views.register( 'embed', _.extend( {}, embed ) );
     844
     845        views.register( 'embedURL', _.extend( {}, embed, {
    879846                toView: function( content ) {
    880847                        var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
    881848                                match = re.exec( tinymce.trim( content ) );
     
    893860                        };
    894861                }
    895862        } ) );
    896 
    897 }(jQuery));
     863} )( window.jQuery, window.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 );