Make WordPress Core

Ticket #31412: 31412.4.patch

File 31412.4.patch, 43.3 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 constructor (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} An object to extend wp.mce.View.prototype with.
    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 );
    300 
    301                                                 if ( ! match ) {
    302                                                         return;
    303                                                 }
    304 
    305                                                 return {
    306                                                         index: match.index,
    307                                                         content: match.content,
    308                                                         options: {
    309                                                                 shortcode: match.shortcode
    310                                                         }
    311                                                 };
    312                                         }
    313                                 };
    314 
    315                         constructor = _.defaults( constructor, defaultConstructor );
    316                         constructor.View = wp.mce.View.extend( constructor.View );
    317 
    318                         views[ type ] = constructor;
     49                register: function( type, extend ) {
     50                        views[ type ] = wp.mce.View.extend( _.extend( extend, { type: type } ) );
    31951                },
    32052
    32153                /**
    322                  * wp.mce.views.get( id )
     54                 * Unregisters a view type.
    32355                 *
    324                  * Returns a TinyMCE view constructor.
    325                  *
    326                  * @param type
     56                 * @param {String} The view type.
    32757                 */
    328                 get: function( type ) {
    329                         return views[ type ];
     58                unregister: function( type ) {
     59                        delete views[ type ];
    33060                },
    33161
    33262                /**
    333                  * wp.mce.views.unregister( type )
    334                  *
    335                  * Unregisters a TinyMCE view.
     63                 * Returns the settings of a view type.
    33664                 *
    337                  * @param type
     65                 * @param {String} The view type.
    33866                 */
    339                 unregister: function( type ) {
    340                         delete views[ type ];
     67                get: function( type ) {
     68                        return views[ type ];
    34169                },
    34270
    34371                /**
    344                  * wp.mce.views.unbind( editor )
    345                  *
    346                  * The editor DOM is being rebuilt, run cleanup.
     72                 * Unbinds all view nodes.
     73                 * Runs before removing all view nodes from the DOM.
    34774                 */
    34875                unbind: function() {
    34976                        _.each( instances, function( instance ) {
     
    35279                },
    35380
    35481                /**
    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.
     82                 * Scans a given string for each view's pattern,
     83                 * replacing any matches with markers,
     84                 * and creates a new instance for every match.
    35985                 *
    360                  * @param content
     86                 * @param {String} The string to scan.
    36187                 */
    362                 toViews: function( content ) {
     88                setMarkers: function( content ) {
    36389                        var pieces = [ { content: content } ],
     90                                self = this,
    36491                                current;
    36592
    366                         _.each( views, function( view, viewType ) {
     93                        _.each( views, function( view, type ) {
    36794                                current = pieces.slice();
    36895                                pieces  = [];
    36996
     
    379106
    380107                                        // Iterate through the string progressively matching views
    381108                                        // and slicing the string as we go.
    382                                         while ( remaining && (result = view.toView( remaining )) ) {
     109                                        while ( remaining && ( result = view.prototype.match( remaining ) ) ) {
    383110                                                // Any text before the match becomes an unprocessed piece.
    384111                                                if ( result.index ) {
    385                                                         pieces.push({ content: remaining.substring( 0, result.index ) });
     112                                                        pieces.push( { content: remaining.substring( 0, result.index ) } );
    386113                                                }
    387114
     115                                                self.createInstance( type, result.content, result.options );
     116
    388117                                                // Add the processed piece for the match.
    389                                                 pieces.push({
    390                                                         content: wp.mce.views.toView( viewType, result.content, result.options ),
     118                                                pieces.push( {
     119                                                        content: '<p data-wpview-marker="' + encodeURIComponent( result.content ) + '">' + result.content + '</p>',
    391120                                                        processed: true
    392                                                 });
     121                                                } );
    393122
    394123                                                // Update the remaining content.
    395124                                                remaining = remaining.slice( result.index + result.content.length );
    396125                                        }
    397126
    398                                         // There are no additional matches. If any content remains,
    399                                         // add it as an unprocessed piece.
     127                                        // There are no additional matches.
     128                                        // If any content remains, add it as an unprocessed piece.
    400129                                        if ( remaining ) {
    401                                                 pieces.push({ content: remaining });
     130                                                pieces.push( { content: remaining } );
    402131                                        }
    403                                 });
    404                         });
     132                                } );
     133                        } );
    405134
    406                         return _.pluck( pieces, 'content' ).join('');
     135                        return _.pluck( pieces, 'content' ).join( '' );
    407136                },
    408137
    409138                /**
    410                  * Create a placeholder for a particular view type
    411                  *
    412                  * @param viewType
    413                  * @param text
    414                  * @param options
     139                 * Create a view instance.
    415140                 *
     141                 * @param {String} The view type.
     142                 * @param {String} The textual representation of the view.
     143                 * @param {Object} Options.
    416144                 */
    417                 toView: function( viewType, text, options ) {
    418                         var view = wp.mce.views.get( viewType ),
    419                                 encodedText = window.encodeURIComponent( text ),
    420                                 instance, viewOptions;
    421 
    422 
    423                         if ( ! view ) {
    424                                 return text;
    425                         }
    426 
    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;
     145                createInstance: function( type, text, options ) {
     146                        var View = this.get( type ),
     147                                encodedText = encodeURIComponent( text ),
     148                                instance = this.getInstance( encodedText );
     149
     150                        if ( instance ) {
     151                                return instance;
    433152                        }
    434153
    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                                 },
     154                        options = _.extend( options || {}, {
     155                                text: text,
     156                                encodedText: encodedText
     157                        } );
    443158
    444                                 content: '\u00a0'
    445                         });
     159                        return instances[ encodedText ] = new View( options );
    446160                },
    447161
    448162                /**
    449                  * Refresh views after an update is made
     163                 * Get a view instance.
    450164                 *
    451                  * @param view {object} being refreshed
    452                  * @param text {string} textual representation of the view
    453                  * @param force {Boolean} whether to force rendering
     165                 * @param {String} The textual representation of the view.
    454166                 */
    455                 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;
    469                         }
    470 
    471                         instance.render( force );
    472                 },
    473 
    474                 getInstance: function( encodedText ) {
    475                         return instances[ encodedText ];
     167                getInstance: function( text ) {
     168                        return instances[ encodeURIComponent( text ) ];
    476169                },
    477170
    478171                /**
    479                  * render( scope )
    480                  *
    481                  * Renders any view instances inside a DOM node `scope`.
     172                 * Renders all view nodes that are not yet rendered.
    482173                 *
    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 )`.
     174                 * @param {Boolean} Rerender all view nodes.
    486175                 */
    487176                render: function( force ) {
    488177                        _.each( instances, function( instance ) {
     
    490179                        } );
    491180                },
    492181
    493                 edit: function( node ) {
    494                         var viewType = $( node ).data('wpview-type'),
    495                                 view = wp.mce.views.get( viewType );
     182                /**
     183                 * Update the text of a given view node.
     184                 *
     185                 * @param {String} The new text.
     186                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     187                 * @param {HTMLElement} The view node to update.
     188                 */
     189                update: function( text, editor, node ) {
     190                        var oldText = decodeURIComponent( $( node ).data( 'wpview-text' ) ),
     191                                instance = this.getInstance( oldText );
     192
     193                        if ( instance ) {
     194                                instance.update( text, editor, node );
     195                        }
     196                },
    496197
    497                         if ( view ) {
    498                                 view.edit( node );
     198                /**
     199                 * Renders any editing interface based on the view type.
     200                 *
     201                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     202                 * @param {HTMLElement} The view node to edit.
     203                 */
     204                edit: function( editor, node ) {
     205                        var text = decodeURIComponent( $( node ).data( 'wpview-text' ) ),
     206                                instance = this.getInstance( text );
     207
     208                        if ( instance && instance.edit ) {
     209                                instance.edit( text, function( text ) {
     210                                        instance.update( text, editor, node );
     211                                } );
    499212                        }
    500213                }
    501214        };
    502215
    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                         },
     216        /**
     217         * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
     218         * The main difference is that the TinyMCE View is not tied to a particular DOM node.
     219         *
     220         * @param {Object} Options.
     221         */
     222        wp.mce.View = function( options ) {
     223                _.extend( this, options );
     224                this.initialize();
     225        };
    517226
    518                         fetch: function() {
    519                                 var self = this;
     227        wp.mce.View.extend = Backbone.View.extend;
    520228
    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                         },
     229        _.extend( wp.mce.View.prototype, {
    526230
    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                                 }
     231                /**
     232                 * The content.
     233                 *
     234                 * @type {*}
     235                 */
     236                content: null,
    536237
    537                                 if ( this.attachments.length ) {
    538                                         attachments = this.attachments.toJSON();
     238                /**
     239                 * Whether or not to display a loader.
     240                 *
     241                 * @type {Boolean}
     242                 */
     243                loader: true,
    539244
    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                                 }
     245                /**
     246                 * Runs after the view instance is created.
     247                 */
     248                initialize: function() {},
    552249
    553                                 options = {
    554                                         attachments: attachments,
    555                                         columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
    556                                 };
     250                /**
     251                 * Retuns the content to render in the view node.
     252                 *
     253                 * @return {*}
     254                 */
     255                getContent: function() {
     256                        return this.content;
     257                },
    557258
    558                                 return this.template( options );
     259                /**
     260                 * Renders all view nodes tied to this view instance that are not yet rendered.
     261                 *
     262                 * @param {Boolean} Rerender all view nodes tied to this view instance.
     263                 */
     264                render: function( force ) {
     265                        // If there's nothing to render an no loader needs to be shown, stop.
     266                        if ( ! this.loader && ! this.getContent() ) {
     267                                return;
    559268                        }
    560                 },
    561269
    562                 edit: function( node ) {
    563                         var gallery = wp.media.gallery,
    564                                 self = this,
    565                                 frame, data;
     270                        // We're about to rerender all views of this instance, so unbind rendered views.
     271                        force && this.unbind();
    566272
    567                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    568                         frame = gallery.edit( data );
     273                        // Replace any left over markers.
     274                        this.replaceMarkers();
    569275
    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                         });
     276                        if ( this.getContent() ) {
     277                                this.setContent( this.getContent(), function( editor, node ) {
     278                                        $( node ).data( 'rendered', true );
     279                                        this.bindNodes.apply( this, arguments );
     280                                }, force ? null : false );
     281                        } else {
     282                                this.setLoader();
     283                        }
     284                },
    575285
    576                         frame.on( 'close', function() {
    577                                 frame.detach();
    578                         });
    579                 }
    580         } );
     286                /**
     287                 * Binds a given rendered view node.
     288                 * Runs after a view node's content is added to the DOM.
     289                 *
     290                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     291                 * @param {HTMLElement} The view node.
     292                 * @param {HTMLElement} The view's content node.
     293                 */
     294                bindNodes: function() {},
    581295
    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,
     296                /**
     297                 * Unbinds all view nodes tied to this view instance.
     298                 * Runs before their content is removed from the DOM.
     299                 */
     300                unbind: function() {
     301                        this.getNodes( function() {
     302                                this.unbindNodes.apply( this, arguments );
     303                        }, true );
     304                },
    590305
    591                         action: 'parse-media-shortcode',
     306                /**
     307                 * Unbinds a given view node.
     308                 * Runs before the view node's content is removed from the DOM.
     309                 *
     310                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     311                 * @param {HTMLElement} The view node.
     312                 * @param {HTMLElement} The view's content node.
     313                 */
     314                unbindNodes: function() {},
    592315
    593                         initialize: function( options ) {
     316                /**
     317                 * Gets all the TinyMCE editor instances that support views.
     318                 *
     319                 * @param {Function} A callback.
     320                 */
     321                getEditors: function( callback ) {
     322                        _.each( tinymce.editors, function( editor ) {
     323                                if ( editor.plugins.wpview ) {
     324                                        callback.call( this, editor );
     325                                }
     326                        }, this );
     327                },
     328
     329                /**
     330                 * Gets all view nodes tied to this view instance.
     331                 *
     332                 * @param {Function} A callback.
     333                 * @param {Boolean} Get (un)rendered view nodes (optional).
     334                 */
     335                getNodes: function( callback, rendered ) {
     336                        this.getEditors( function( editor ) {
    594337                                var self = this;
    595338
    596                                 this.shortcode = options.shortcode;
     339                                $( editor.getBody() )
     340                                        .find( '[data-wpview-text="' + self.encodedText + '"]' )
     341                                        .filter( function() {
     342                                                var data;
    597343
    598                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' );
    599                                 $( this ).on( 'ready', this.setNodes );
     344                                                if ( rendered == null ) {
     345                                                        return true;
     346                                                }
     347
     348                                                data = $( this ).data( 'rendered' ) === true;
    600349
    601                                 $( document ).on( 'media:edit', this.stopPlayers );
     350                                                return rendered ? data : ! data;
     351                                        } )
     352                                        .each( function() {
     353                                                callback.call( self, editor, this, $( this ).find( '.wpview-content' ).get( 0 ) );
     354                                        } );
     355                        } );
     356                },
    602357
    603                                 this.fetch();
     358                /**
     359                 * Gets all marker nodes tied to this view instance.
     360                 *
     361                 * @param {Function} A callback.
     362                 */
     363                getMarkers: function( callback ) {
     364                        this.getEditors( function( editor ) {
     365                                var self = this;
    604366
    605                                 this.getEditors( function( editor ) {
    606                                         editor.on( 'hide', function () {
    607                                                 mediaWindows = [];
    608                                                 windowIdx = 0;
    609                                                 self.stopPlayers();
     367                                $( editor.getBody() )
     368                                        .find( '[data-wpview-marker="' + this.encodedText + '"]' )
     369                                        .each( function() {
     370                                                callback.call( self, editor, this );
    610371                                        } );
    611                                 });
    612                         },
     372                        } );
     373                },
    613374
    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                         },
     375                /**
     376                 * Replaces all marker nodes tied to this view instance.
     377                 */
     378                replaceMarkers: function() {
     379                        this.getMarkers( function( editor, node ) {
     380                                if ( $( node ).text() !== this.text ) {
     381                                        editor.dom.setAttrib( node, 'data-wpview-marker', null );
     382                                        return;
     383                                }
    623384
    624                         iframeLoaded: function (win) {
    625                                 return _.bind( function () {
    626                                         var callback;
    627                                         if ( ! win.mejs || _.isEmpty( win.mejs.players ) ) {
    628                                                 return;
    629                                         }
     385                                editor.dom.replace(
     386                                        editor.dom.createFragment(
     387                                                '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
     388                                                        '<p class="wpview-selection-before">\u00a0</p>' +
     389                                                        '<div class="wpview-body" contenteditable="false">' +
     390                                                                '<div class="toolbar mce-arrow-down">' +
     391                                                                        ( this.edit ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
     392                                                                        '<div class="dashicons dashicons-no remove"></div>' +
     393                                                                '</div>' +
     394                                                                '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
     395                                                        '</div>' +
     396                                                        '<p class="wpview-selection-after">\u00a0</p>' +
     397                                                '</div>'
     398                                        ),
     399                                        node
     400                                );
     401                        } );
     402                },
    630403
    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                                         }
     404                /**
     405                 * Removes all marker nodes tied to this view instance.
     406                 */
     407                removeMarkers: function() {
     408                        this.getMarkers( function( editor, node ) {
     409                                editor.dom.setAttrib( node, 'data-wpview-marker', null );
     410                        } );
     411                },
     412
     413                /**
     414                 * Sets the content for all view nodes tied to this view instance.
     415                 *
     416                 * @param {*} The content to set.
     417                 * @param {Function} A callback (optional).
     418                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     419                 */
     420                setContent: function( content, callback, rendered ) {
     421                        if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
     422                                this.setIframes( content.head, content.body, callback, rendered );
     423                        } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
     424                                this.setIframes( null, content, callback, rendered );
     425                        } else {
     426                                this.getNodes( function( editor, node, contentNode ) {
     427                                        content = content.body || content;
    644428
    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 ) );
     429                                        if ( content.indexOf( '<iframe' ) !== -1 ) {
     430                                                content += '<div class="wpview-overlay"></div>';
    656431                                        }
    657                                 }, this );
    658                         },
    659432
    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();
    670                                 }
    671                         },
     433                                        contentNode.innerHTML = '';
     434                                        contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
    672435
    673                         fetch: function () {
    674                                 var self = this;
     436                                        callback && callback.apply( this, arguments );
     437                                }, rendered );
     438                        }
     439                },
    675440
    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                         },
     441                /**
     442                 * Sets the content in an iframe for all view nodes tied to this view instance.
     443                 *
     444                 * @param {String} HTML string to be added to the head of the document.
     445                 * @param {String} HTML string to be added to the body of the document.
     446                 * @param {Function} A callback (optional).
     447                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     448                 */
     449                setIframes: function( head, body, callback, rendered ) {
     450                        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
     451                                importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
    696452
    697                         fail: function( error ) {
    698                                 if ( ! this.error ) {
    699                                         if ( error ) {
    700                                                 this.error = error;
    701                                         } else {
    702                                                 return;
    703                                         }
    704                                 }
     453                        this.getNodes( function( editor, node, content ) {
     454                                var dom = editor.dom,
     455                                        styles = '',
     456                                        bodyClasses = editor.getBody().className || '',
     457                                        iframe, iframeDoc, i, resize;
     458
     459                                content.innerHTML = '';
     460                                head = head || '';
     461
     462                                if ( importStyles ) {
     463                                        if ( ! wp.mce.views.sandboxStyles ) {
     464                                                tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
     465                                                        if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
     466                                                                link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
    705467
    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' ) {
     468                                                                styles += dom.getOuterHTML( link ) + '\n';
     469                                                        }
     470                                                });
    709471
    710                                                 this.setError( this.error.message, 'admin-media' );
     472                                                wp.mce.views.sandboxStyles = styles;
    711473                                        } else {
    712                                                 this.setContent( '<p>' + this.original + '</p>', 'replace' );
     474                                                styles = wp.mce.views.sandboxStyles;
    713475                                        }
    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' );
    718476                                }
    719                         },
    720477
    721                         stopPlayers: function( remove ) {
    722                                 var rem = remove === 'remove';
     478                                // Seems Firefox needs a bit of time to insert/set the view nodes,
     479                                // or the iframe will fail especially when switching Text => Visual.
     480                                setTimeout( function() {
     481                                        iframe = dom.add( content, 'iframe', {
     482                                                /* jshint scripturl: true */
     483                                                src: tinymce.Env.ie ? 'javascript:""' : '',
     484                                                frameBorder: '0',
     485                                                allowTransparency: 'true',
     486                                                scrolling: 'no',
     487                                                'class': 'wpview-sandbox',
     488                                                style: {
     489                                                        width: '100%',
     490                                                        display: 'block'
     491                                                }
     492                                        } );
     493
     494                                        dom.add( content, 'div', { 'class': 'wpview-overlay' } );
    723495
    724                                 this.getNodes( function( editor, node, content ) {
    725                                         var p, win,
    726                                                 iframe = $( 'iframe.wpview-sandbox', content ).get(0);
     496                                        iframeDoc = iframe.contentWindow.document;
    727497
    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();
     498                                        iframeDoc.open();
    733499
    734                                                                 if ( rem ) {
    735                                                                         win.mejs.players[p].remove();
    736                                                                 }
     500                                        iframeDoc.write(
     501                                                '<!DOCTYPE html>' +
     502                                                '<html>' +
     503                                                        '<head>' +
     504                                                                '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
     505                                                                head +
     506                                                                styles +
     507                                                                '<style>' +
     508                                                                        'html {' +
     509                                                                                'background: transparent;' +
     510                                                                                'padding: 0;' +
     511                                                                                'margin: 0;' +
     512                                                                        '}' +
     513                                                                        'body#wpview-iframe-sandbox {' +
     514                                                                                'background: transparent;' +
     515                                                                                'padding: 1px 0 !important;' +
     516                                                                                'margin: -1px 0 0 !important;' +
     517                                                                        '}' +
     518                                                                        'body#wpview-iframe-sandbox:before,' +
     519                                                                        'body#wpview-iframe-sandbox:after {' +
     520                                                                                'display: none;' +
     521                                                                                'content: "";' +
     522                                                                        '}' +
     523                                                                '</style>' +
     524                                                        '</head>' +
     525                                                        '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
     526                                                                body +
     527                                                        '</body>' +
     528                                                '</html>'
     529                                        );
     530
     531                                        iframeDoc.close();
     532
     533                                        resize = function() {
     534                                                var $iframe, iframeDocHeight;
     535
     536                                                // Make sure the iframe still exists.
     537                                                if ( iframe.contentWindow ) {
     538                                                        $iframe = $( iframe );
     539                                                        iframeDocHeight = $( iframeDoc.body ).height();
     540
     541                                                        if ( $iframe.height() !== iframeDocHeight ) {
     542                                                                $iframe.height( iframeDocHeight );
     543                                                                editor.nodeChanged();
    737544                                                        }
    738                                                 } catch( er ) {}
     545                                                }
     546                                        };
     547
     548                                        if ( MutationObserver ) {
     549                                                new MutationObserver( _.debounce( function() {
     550                                                        resize();
     551                                                }, 100 ) )
     552                                                .observe( iframeDoc.body, {
     553                                                        attributes: true,
     554                                                        childList: true,
     555                                                        subtree: true
     556                                                } );
     557                                        } else {
     558                                                for ( i = 1; i < 6; i++ ) {
     559                                                        setTimeout( resize, i * 700 );
     560                                                }
     561                                        }
     562
     563                                        if ( importStyles ) {
     564                                                editor.on( 'wp-body-class-change', function() {
     565                                                        iframeDoc.body.className = editor.getBody().className;
     566                                                } );
    739567                                        }
    740                                 });
    741                         },
     568                                }, 50 );
     569
     570                                callback && callback.apply( this, arguments );
     571                        }, rendered );
     572                },
     573
     574                /**
     575                 * Sets a loader for all view nodes tied to this view instance.
     576                 */
     577                setLoader: function() {
     578                        this.setContent(
     579                                '<div class="loading-placeholder">' +
     580                                        '<div class="dashicons dashicons-admin-media"></div>' +
     581                                        '<div class="wpview-loading"><ins></ins></div>' +
     582                                '</div>'
     583                        );
     584                },
     585
     586                /**
     587                 * Sets an error for all view nodes tied to this view instance.
     588                 *
     589                 * @param {String} The error message to set.
     590                 * @param {String} A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
     591                 */
     592                setError: function( message, dashicon ) {
     593                        this.setContent(
     594                                '<div class="wpview-error">' +
     595                                        '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
     596                                        '<p>' + message + '</p>' +
     597                                '</div>'
     598                        );
     599                },
    742600
    743                         unbind: function() {
    744                                 this.stopPlayers( 'remove' );
     601                /**
     602                 * Tries to find a text match in a given string.
     603                 *
     604                 * @param {String} The string to scan.
     605                 *
     606                 * @return {Object}
     607                 */
     608                match: function( content ) {
     609                        var match = wp.shortcode.next( this.type, content );
     610
     611                        if ( match ) {
     612                                return {
     613                                        index: match.index,
     614                                        content: match.content,
     615                                        options: {
     616                                                shortcode: match.shortcode
     617                                        }
     618                                };
    745619                        }
    746620                },
    747621
    748622                /**
    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
     623                 * Update the text of a given view node.
    755624                 *
    756                  * @param {HTMLElement} node
     625                 * @param {String} The new text.
     626                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     627                 * @param {HTMLElement} The view node to update.
    757628                 */
    758                 edit: function( node ) {
     629                update: function( text, editor, node ) {
     630                        $( node ).data( 'rendered', false );
     631                        editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
     632                        wp.mce.views.createInstance( this.type, text, this.match( text ).options ).render();
     633                }
     634        } );
     635} )( window.jQuery );
     636
     637/*
     638 * The WordPress core TinyMCE views.
     639 * Views for the gallery, audio, video, playlist and embed shortcodes,
     640 * and a view for embeddable URLs.
     641 */
     642( function( $, views ) {
     643        var postID = $( '#post_ID' ).val() || 0,
     644                media, gallery, av, embed;
     645
     646        media = {
     647                state: [],
     648
     649                edit: function( text, update ) {
    759650                        var media = wp.media[ this.type ],
    760                                 self = this,
    761                                 frame, data, callback;
     651                                frame = media.edit( text );
     652
     653                        this.stopPlayers && this.stopPlayers();
    762654
    763                         $( document ).trigger( 'media:edit' );
     655                        _.each( this.state, function( state ) {
     656                                frame.state( state ).on( 'update', function( selection ) {
     657                                        update( media.shortcode( selection ).string() );
     658                                } );
     659                        } );
    764660
    765                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    766                         frame = media.edit( data );
    767661                        frame.on( 'close', function() {
    768662                                frame.detach();
    769663                        } );
     664                }
     665        };
    770666
    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 );
     667        gallery = _.extend( {}, media, {
     668                state: [ 'gallery-edit' ],
     669
     670                initialize: function() {
     671                        var self = this;
     672
     673                        this.template = wp.media.template( 'editor-gallery' );
     674                        this.attachments = wp.media.gallery.attachments( this.shortcode, postID );
     675                        this.dfd = this.attachments.more().done( function() {
     676                                self.render();
     677                        } );
     678                },
     679
     680                getContent: function() {
     681                        var attrs = this.shortcode.attrs.named,
     682                                attachments = false;
     683
     684                        // Don't render errors while still fetching attachments
     685                        if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
     686                                return '';
     687                        }
     688
     689                        if ( this.attachments.length ) {
     690                                attachments = this.attachments.toJSON();
     691
     692                                _.each( attachments, function( attachment ) {
     693                                        if ( attachment.sizes ) {
     694                                                if ( attrs.size && attachment.sizes[ attrs.size ] ) {
     695                                                        attachment.thumbnail = attachment.sizes[ attrs.size ];
     696                                                } else if ( attachment.sizes.thumbnail ) {
     697                                                        attachment.thumbnail = attachment.sizes.thumbnail;
     698                                                } else if ( attachment.sizes.full ) {
     699                                                        attachment.thumbnail = attachment.sizes.full;
     700                                                }
     701                                        }
    780702                                } );
    781                         } else {
    782                                 frame.state( self.state ).on( 'update', callback );
    783703                        }
    784                         frame.open();
     704
     705                        return this.template( {
     706                                attachments: attachments,
     707                                columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
     708                        } );
    785709                }
    786         };
     710        } );
    787711
    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         } ) );
     712        av = _.extend( {}, media, {
     713                action: 'parse-media-shortcode',
    796714
    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         } ) );
     715                initialize: function() {
     716                        var self = this;
    805717
    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         } ) );
     718                        if ( this.url ) {
     719                                this.loader = false;
     720                                this.shortcode = wp.media.embed.shortcode( {
     721                                        url: this.url
     722                                } );
     723                        }
    814724
    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
    829                                         } );
     725                        wp.ajax.send( this.action, {
     726                                data: {
     727                                        post_ID: postID,
     728                                        type: this.shortcode.tag,
     729                                        shortcode: this.shortcode.string()
     730                                }
     731                        } )
     732                        .done( function( response ) {
     733                                self.content = response;
     734                                self.render();
     735                        } )
     736                        .fail( function( response ) {
     737                                if ( self.type === 'embedURL' ) {
     738                                        self.removeMarkers();
    830739                                } else {
    831                                         this.shortcode = options.shortcode;
     740                                        self.setError( response.message || response.statusText, 'admin-media' );
    832741                                }
     742                        } );
    833743
    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;
     744                        this.getEditors( function( editor ) {
     745                                editor.on( 'wpview-selected', function() {
     746                                        self.stopPlayers();
     747                                } );
     748                        } );
     749                },
    846750
    847                         $( document ).trigger( 'media:edit' );
     751                stopPlayers: function( remove ) {
     752                        this.getNodes( function( editor, node, content ) {
     753                                var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
    848754
    849                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    850                         frame = embed.edit( data, isURL );
    851                         frame.on( 'close', function() {
    852                                 frame.detach();
     755                                if ( win && ( win = win.contentWindow ) && win.mejs ) {
     756                                        _.each( win.mejs.players, function( player ) {
     757                                                try {
     758                                                        player[ remove ? 'remove' : 'pause' ]();
     759                                                } catch ( e ) {}
     760                                        } );
     761                                }
    853762                        } );
    854                         frame.state( 'embed' ).props.on( 'change:url', function (model, url) {
    855                                 if ( ! url ) {
    856                                         return;
     763                }
     764        } );
     765
     766        embed = _.extend( {}, av, {
     767                action: 'parse-embed',
     768
     769                edit: function( text, update ) {
     770                        var media = wp.media.embed,
     771                                isURL = 'embedURL' === this.type,
     772                                frame = media.edit( text, isURL );
     773
     774                        this.stopPlayers();
     775
     776                        frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
     777                                if ( url ) {
     778                                        frame.state( 'embed' ).metadata = model.toJSON();
    857779                                }
    858                                 frame.state( 'embed' ).metadata = model.toJSON();
    859780                        } );
    860                         frame.state( 'embed' ).on( 'select', function() {
    861                                 var shortcode;
    862781
     782                        frame.state( 'embed' ).on( 'select', function() {
    863783                                if ( isURL ) {
    864                                         shortcode = frame.state( 'embed' ).metadata.url;
     784                                        update( frame.state( 'embed' ).metadata.url );
    865785                                } else {
    866                                         shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string();
     786                                        update( media.shortcode( frame.state( 'embed' ).metadata ).string() );
    867787                                }
    868                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
    869                                 wp.mce.views.refreshView( self, shortcode );
     788                        } );
     789
     790                        frame.on( 'close', function() {
    870791                                frame.detach();
    871792                        } );
     793
    872794                        frame.open();
    873795                }
    874         };
     796        } );
     797
     798        views.register( 'gallery', _.extend( {}, gallery ) );
     799
     800        views.register( 'audio', _.extend( {}, av, {
     801                state: [ 'audio-details' ]
     802        } ) );
     803
     804        views.register( 'video', _.extend( {}, av, {
     805                state: [ 'video-details' ]
     806        } ) );
     807
     808        views.register( 'playlist', _.extend( {}, av, {
     809                state: [ 'playlist-edit', 'video-playlist-edit' ]
     810        } ) );
    875811
    876         wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
     812        views.register( 'embed', _.extend( {}, embed ) );
    877813
    878         wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
    879                 toView: function( content ) {
     814        views.register( 'embedURL', _.extend( {}, embed, {
     815                match: function( content ) {
    880816                        var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
    881817                                match = re.exec( tinymce.trim( content ) );
    882818
    883                         if ( ! match ) {
    884                                 return;
     819                        if ( match ) {
     820                                return {
     821                                        index: match.index + match[1].length,
     822                                        content: match[2],
     823                                        options: {
     824                                                url: match[2]
     825                                        }
     826                                };
    885827                        }
    886 
    887                         return {
    888                                 index: match.index + match[1].length,
    889                                 content: match[2],
    890                                 options: {
    891                                         url: match[2]
    892                                 }
    893                         };
    894828                }
    895829        } ) );
    896 
    897 }(jQuery));
     830} )( window.jQuery, window.wp.mce.views );
  • src/wp-includes/js/tinymce/plugins/wpview/plugin.js

     
    237237                        return;
    238238                }
    239239
    240                 event.content = wp.mce.views.toViews( event.content );
     240                event.content = wp.mce.views.setMarkers( event.content );
    241241        });
    242242
    243243        // When the editor's content has been updated and the DOM has been
     
    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 );