Make WordPress Core

Ticket #31412: 31412.3.patch

File 31412.3.patch, 42.7 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 )
     63                 * Returns the settings of a view type.
    33464                 *
    335                  * Unregisters a TinyMCE view.
    336                  *
    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} 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
    409                 /**
    410                  * Create a placeholder for a particular view type
    411                  *
    412                  * @param viewType
    413                  * @param text
    414                  * @param options
    415                  *
    416                  */
    417                 toView: function( viewType, text, options ) {
    418                         var view = wp.mce.views.get( viewType ),
    419                                 encodedText = window.encodeURIComponent( text ),
    420                                 instance, viewOptions;
    421 
     138                createInstance: function( type, text, options ) {
     139                        var View = this.get( type ),
     140                                encodedText = encodeURIComponent( text ),
     141                                instance = this.getInstance( encodedText );
    422142
    423                         if ( ! view ) {
    424                                 return text;
     143                        if ( instance ) {
     144                                return instance;
    425145                        }
    426146
    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;
    433                         }
    434 
    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                                 },
     147                        options = _.extend( options || {}, {
     148                                text: text,
     149                                encodedText: encodedText
     150                        } );
    443151
    444                                 content: '\u00a0'
    445                         });
     152                        return instances[ encodedText ] = new View( options );
    446153                },
    447154
    448155                /**
    449                  * Refresh views after an update is made
     156                 * Get an instance based on the encded text.
    450157                 *
    451                  * @param view {object} being refreshed
    452                  * @param text {string} textual representation of the view
    453                  * @param force {Boolean} whether to force rendering
     158                 * @param {String} The textual representation of the view, encoded.
    454159                 */
    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 ];
     160                getInstance: function( text ) {
     161                        return instances[ encodeURIComponent( text ) ];
    476162                },
    477163
    478164                /**
    479                  * render( scope )
     165                 * Renders all view nodes that are not yet rendered.
    480166                 *
    481                  * Renders any view instances inside a DOM node `scope`.
     167                 * Views are detected by the presence of markers.
     168                 * To generate markers, pass your content through `toViews`.
    482169                 *
    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 )`.
     170                 * @param {Boolean} Rerender all view nodes.
    486171                 */
    487172                render: function( force ) {
    488173                        _.each( instances, function( instance ) {
     
    490175                        } );
    491176                },
    492177
    493                 edit: function( node ) {
    494                         var viewType = $( node ).data('wpview-type'),
    495                                 view = wp.mce.views.get( viewType );
     178                update: function( text, editor, node ) {
     179                        var oldText = decodeURIComponent( $( node ).data( 'wpview-text' ) ),
     180                                instance = this.getInstance( oldText );
     181
     182                        if ( instance ) {
     183                                instance.update( text, editor, node );
     184                        }
     185                },
    496186
    497                         if ( view ) {
    498                                 view.edit( node );
     187                /**
     188                 * Renders any editing interface based on the view type.
     189                 *
     190                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     191                 * @param {HTMLElement} The view node to edit.
     192                 */
     193                edit: function( editor, node ) {
     194                        var text = decodeURIComponent( $( node ).data( 'wpview-text' ) ),
     195                                instance = this.getInstance( text );
     196
     197                        if ( instance && instance.edit ) {
     198                                instance.edit( text, function( text ) {
     199                                        instance.update( text, editor, node );
     200                                } );
    499201                        }
    500202                }
    501203        };
    502204
    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                         },
     205        /**
     206         * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
     207         * The main difference is that the TinyMCE View is not tied to a particular DOM node.
     208         *
     209         * @param {Object} Options.
     210         */
     211        wp.mce.View = function( options ) {
     212                _.extend( this, options );
     213                this.initialize();
     214        };
    517215
    518                         fetch: function() {
    519                                 var self = this;
     216        wp.mce.View.extend = Backbone.View.extend;
    520217
    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                         },
     218        _.extend( wp.mce.View.prototype, {
    526219
    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                                 }
     220                /**
     221                 * The content.
     222                 *
     223                 * @type {*}
     224                 */
     225                content: null,
    536226
    537                                 if ( this.attachments.length ) {
    538                                         attachments = this.attachments.toJSON();
     227                /**
     228                 * Whether or not to display a loader.
     229                 *
     230                 * @type {Boolean}
     231                 */
     232                loader: true,
    539233
    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                                 }
     234                /**
     235                 * Runs after the view instance is created.
     236                 */
     237                initialize: function() {},
    552238
    553                                 options = {
    554                                         attachments: attachments,
    555                                         columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
    556                                 };
     239                /**
     240                 * Retuns the content to render in the view node.
     241                 *
     242                 * @return {*}
     243                 */
     244                getContent: function() {
     245                        return this.content;
     246                },
    557247
    558                                 return this.template( options );
     248                /**
     249                 * Renders all view nodes tied to this view instance that are not yet rendered.
     250                 *
     251                 * @param {Boolean} Rerender all view nodes tied to this view instance.
     252                 */
     253                render: function( force ) {
     254                        // If there's nothing to render an no loader needs to be shown, stop.
     255                        if ( ! this.loader && ! this.getContent() ) {
     256                                return;
    559257                        }
    560                 },
    561258
    562                 edit: function( node ) {
    563                         var gallery = wp.media.gallery,
    564                                 self = this,
    565                                 frame, data;
     259                        // We're about to rerender all views of this instance, so unbind rendered views.
     260                        force && this.unbind();
    566261
    567                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    568                         frame = gallery.edit( data );
     262                        // Replace any left over markers.
     263                        this.replaceMarkers();
    569264
    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                         });
     265                        if ( this.getContent() ) {
     266                                this.setContent( this.getContent(), function( editor, node ) {
     267                                        $( node ).data( 'rendered', true );
     268                                        this.bindNodes.apply( this, arguments );
     269                                }, force ? null : false );
     270                        } else {
     271                                this.setLoader();
     272                        }
     273                },
    575274
    576                         frame.on( 'close', function() {
    577                                 frame.detach();
    578                         });
    579                 }
    580         } );
     275                /**
     276                 * Binds a given rendered view node.
     277                 * Runs after a view node's content is added to the DOM.
     278                 *
     279                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     280                 * @param {HTMLElement} The view node.
     281                 * @param {HTMLElement} The view's content node.
     282                 */
     283                bindNodes: function() {},
    581284
    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,
     285                /**
     286                 * Unbinds all view nodes tied to this view instance.
     287                 * Runs before their content is removed from the DOM.
     288                 */
     289                unbind: function() {
     290                        this.getNodes( function() {
     291                                this.unbindNodes.apply( this, arguments );
     292                        }, true );
     293                },
    590294
    591                         action: 'parse-media-shortcode',
     295                /**
     296                 * Unbinds a given view node.
     297                 * Runs before the view node's content is removed from the DOM.
     298                 *
     299                 * @param {tinymce.Editor} The TinyMCE editor instance the view node is in.
     300                 * @param {HTMLElement} The view node.
     301                 * @param {HTMLElement} The view's content node.
     302                 */
     303                unbindNodes: function() {},
    592304
    593                         initialize: function( options ) {
     305                /**
     306                 * Gets all the TinyMCE editor instances that support views.
     307                 *
     308                 * @param {Function} A callback.
     309                 */
     310                getEditors: function( callback ) {
     311                        _.each( tinymce.editors, function( editor ) {
     312                                if ( editor.plugins.wpview ) {
     313                                        callback.call( this, editor );
     314                                }
     315                        }, this );
     316                },
     317
     318                /**
     319                 * Gets all view nodes tied to this view instance.
     320                 *
     321                 * @param {Function} A callback.
     322                 * @param {Boolean} Get (un)rendered view nodes (optional).
     323                 */
     324                getNodes: function( callback, rendered ) {
     325                        this.getEditors( function( editor ) {
    594326                                var self = this;
    595327
    596                                 this.shortcode = options.shortcode;
     328                                $( editor.getBody() )
     329                                        .find( '[data-wpview-text="' + self.encodedText + '"]' )
     330                                        .filter( function() {
     331                                                var data;
     332
     333                                                if ( rendered == null ) {
     334                                                        return true;
     335                                                }
    597336
    598                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' );
    599                                 $( this ).on( 'ready', this.setNodes );
     337                                                data = $( this ).data( 'rendered' ) === true;
    600338
    601                                 $( document ).on( 'media:edit', this.stopPlayers );
     339                                                return rendered ? data : ! data;
     340                                        } )
     341                                        .each( function() {
     342                                                callback.call( self, editor, this, $( this ).find( '.wpview-content' ).get( 0 ) );
     343                                        } );
     344                        } );
     345                },
    602346
    603                                 this.fetch();
     347                /**
     348                 * Gets all marker nodes tied to this view instance.
     349                 *
     350                 * @param {Function} A callback.
     351                 */
     352                getMarkers: function( callback ) {
     353                        this.getEditors( function( editor ) {
     354                                var self = this;
    604355
    605                                 this.getEditors( function( editor ) {
    606                                         editor.on( 'hide', function () {
    607                                                 mediaWindows = [];
    608                                                 windowIdx = 0;
    609                                                 self.stopPlayers();
     356                                $( editor.getBody() )
     357                                        .find( '[data-wpview-marker="' + this.encodedText + '"]' )
     358                                        .each( function() {
     359                                                callback.call( self, editor, this );
    610360                                        } );
    611                                 });
    612                         },
     361                        } );
     362                },
    613363
    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                         },
     364                /**
     365                 * Replaces all marker nodes tied to this view instance.
     366                 */
     367                replaceMarkers: function() {
     368                        this.getMarkers( function( editor, node ) {
     369                                if ( $( node ).text() !== this.text ) {
     370                                        editor.dom.setAttrib( node, 'data-wpview-marker', null );
     371                                        return;
     372                                }
    623373
    624                         iframeLoaded: function (win) {
    625                                 return _.bind( function () {
    626                                         var callback;
    627                                         if ( ! win.mejs || _.isEmpty( win.mejs.players ) ) {
    628                                                 return;
    629                                         }
     374                                editor.dom.replace(
     375                                        editor.dom.createFragment(
     376                                                '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
     377                                                        '<p class="wpview-selection-before">\u00a0</p>' +
     378                                                        '<div class="wpview-body" contenteditable="false">' +
     379                                                                '<div class="toolbar mce-arrow-down">' +
     380                                                                        ( this.edit ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
     381                                                                        '<div class="dashicons dashicons-no remove"></div>' +
     382                                                                '</div>' +
     383                                                                '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
     384                                                                ( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
     385                                                        '</div>' +
     386                                                        '<p class="wpview-selection-after">\u00a0</p>' +
     387                                                '</div>'
     388                                        ),
     389                                        node
     390                                );
     391                        } );
     392                },
    630393
    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                                         }
     394                /**
     395                 * Removes all marker nodes tied to this view instance.
     396                 */
     397                removeMarkers: function() {
     398                        this.getMarkers( function( editor, node ) {
     399                                editor.dom.setAttrib( node, 'data-wpview-marker', null );
     400                        } );
     401                },
    644402
    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                         },
     403                /**
     404                 * Sets the content for all view nodes tied to this view instance.
     405                 *
     406                 * @param {*} The content to set.
     407                 * @param {Function} A callback (optional).
     408                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     409                 */
     410                setContent: function( content, callback, rendered ) {
     411                        if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
     412                                this.setIframes( content.head, content.body, callback, rendered );
     413                        } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
     414                                this.setIframes( null, content, callback, rendered );
     415                        } else {
     416                                this.getNodes( function( editor, node, contentNode ) {
     417                                        content = content.body || content;
    659418
    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                         },
     419                                        contentNode.innerHTML = '';
     420                                        contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
    672421
    673                         fetch: function () {
    674                                 var self = this;
     422                                        callback && callback.apply( this, arguments );
     423                                }, rendered );
     424                        }
     425                },
    675426
    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                         },
     427                /**
     428                 * Sets the content in an iframe for all view nodes tied to this view instance.
     429                 *
     430                 * @param {String} HTML string to be added to the head of the document.
     431                 * @param {String} HTML string to be added to the body of the document.
     432                 * @param {Function} A callback (optional).
     433                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     434                 */
     435                setIframes: function( head, body, callback, rendered ) {
     436                        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
     437                                importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
    696438
    697                         fail: function( error ) {
    698                                 if ( ! this.error ) {
    699                                         if ( error ) {
    700                                                 this.error = error;
    701                                         } else {
    702                                                 return;
    703                                         }
    704                                 }
     439                        this.getNodes( function( editor, node, content ) {
     440                                var dom = editor.dom,
     441                                        styles = '',
     442                                        bodyClasses = editor.getBody().className || '',
     443                                        iframe, iframeDoc, i, resize;
     444
     445                                content.innerHTML = '';
     446                                head = head || '';
     447
     448                                if ( importStyles ) {
     449                                        if ( ! wp.mce.views.sandboxStyles ) {
     450                                                tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
     451                                                        if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
     452                                                                link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
    705453
    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' ) {
     454                                                                styles += dom.getOuterHTML( link ) + '\n';
     455                                                        }
     456                                                });
    709457
    710                                                 this.setError( this.error.message, 'admin-media' );
     458                                                wp.mce.views.sandboxStyles = styles;
    711459                                        } else {
    712                                                 this.setContent( '<p>' + this.original + '</p>', 'replace' );
     460                                                styles = wp.mce.views.sandboxStyles;
    713461                                        }
    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' );
    718462                                }
    719                         },
    720463
    721                         stopPlayers: function( remove ) {
    722                                 var rem = remove === 'remove';
     464                                // Seems Firefox needs a bit of time to insert/set the view nodes,
     465                                // or the iframe will fail especially when switching Text => Visual.
     466                                setTimeout( function() {
     467                                        iframe = dom.add( content, 'iframe', {
     468                                                /* jshint scripturl: true */
     469                                                src: tinymce.Env.ie ? 'javascript:""' : '',
     470                                                frameBorder: '0',
     471                                                allowTransparency: 'true',
     472                                                scrolling: 'no',
     473                                                'class': 'wpview-sandbox',
     474                                                style: {
     475                                                        width: '100%',
     476                                                        display: 'block'
     477                                                }
     478                                        } );
    723479
    724                                 this.getNodes( function( editor, node, content ) {
    725                                         var p, win,
    726                                                 iframe = $( 'iframe.wpview-sandbox', content ).get(0);
     480                                        iframeDoc = iframe.contentWindow.document;
    727481
    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();
     482                                        iframeDoc.open();
    733483
    734                                                                 if ( rem ) {
    735                                                                         win.mejs.players[p].remove();
    736                                                                 }
     484                                        iframeDoc.write(
     485                                                '<!DOCTYPE html>' +
     486                                                '<html>' +
     487                                                        '<head>' +
     488                                                                '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
     489                                                                head +
     490                                                                styles +
     491                                                                '<style>' +
     492                                                                        'html {' +
     493                                                                                'background: transparent;' +
     494                                                                                'padding: 0;' +
     495                                                                                'margin: 0;' +
     496                                                                        '}' +
     497                                                                        'body#wpview-iframe-sandbox {' +
     498                                                                                'background: transparent;' +
     499                                                                                'padding: 1px 0 !important;' +
     500                                                                                'margin: -1px 0 0 !important;' +
     501                                                                        '}' +
     502                                                                        'body#wpview-iframe-sandbox:before,' +
     503                                                                        'body#wpview-iframe-sandbox:after {' +
     504                                                                                'display: none;' +
     505                                                                                'content: "";' +
     506                                                                        '}' +
     507                                                                '</style>' +
     508                                                        '</head>' +
     509                                                        '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
     510                                                                body +
     511                                                        '</body>' +
     512                                                '</html>'
     513                                        );
     514
     515                                        iframeDoc.close();
     516
     517                                        resize = function() {
     518                                                var $iframe, iframeDocHeight;
     519
     520                                                // Make sure the iframe still exists.
     521                                                if ( iframe.contentWindow ) {
     522                                                        $iframe = $( iframe );
     523                                                        iframeDocHeight = $( iframeDoc.body ).height();
     524
     525                                                        if ( $iframe.height() !== iframeDocHeight ) {
     526                                                                $iframe.height( iframeDocHeight );
     527                                                                editor.nodeChanged();
    737528                                                        }
    738                                                 } catch( er ) {}
     529                                                }
     530                                        };
     531
     532                                        if ( MutationObserver ) {
     533                                                new MutationObserver( _.debounce( function() {
     534                                                        resize();
     535                                                }, 100 ) )
     536                                                .observe( iframeDoc.body, {
     537                                                        attributes: true,
     538                                                        childList: true,
     539                                                        subtree: true
     540                                                } );
     541                                        } else {
     542                                                for ( i = 1; i < 6; i++ ) {
     543                                                        setTimeout( resize, i * 700 );
     544                                                }
    739545                                        }
    740                                 });
    741                         },
    742546
    743                         unbind: function() {
    744                                 this.stopPlayers( 'remove' );
    745                         }
     547                                        if ( importStyles ) {
     548                                                editor.on( 'wp-body-class-change', function() {
     549                                                        iframeDoc.body.className = editor.getBody().className;
     550                                                } );
     551                                        }
     552                                }, 50 );
     553
     554                                callback && callback.apply( this, arguments );
     555                        }, rendered );
     556                },
     557
     558                /**
     559                 * Sets a loader for all view nodes tied to this view instance.
     560                 */
     561                setLoader: function() {
     562                        this.setContent(
     563                                '<div class="loading-placeholder">' +
     564                                        '<div class="dashicons dashicons-admin-media"></div>' +
     565                                        '<div class="wpview-loading"><ins></ins></div>' +
     566                                '</div>'
     567                        );
    746568                },
    747569
    748570                /**
    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
     571                 * Sets an error for all view nodes tied to this view instance.
    755572                 *
    756                  * @param {HTMLElement} node
     573                 * @param {String} The error message to set.
     574                 * @param {String} A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
    757575                 */
    758                 edit: function( node ) {
     576                setError: function( message, dashicon ) {
     577                        this.setContent(
     578                                '<div class="wpview-error">' +
     579                                        '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
     580                                        '<p>' + message + '</p>' +
     581                                '</div>'
     582                        );
     583                },
     584
     585                match: function( content ) {
     586                        var match = wp.shortcode.next( this.type, content );
     587
     588                        if ( match ) {
     589                                return {
     590                                        index: match.index,
     591                                        content: match.content,
     592                                        options: {
     593                                                shortcode: match.shortcode
     594                                        }
     595                                };
     596                        }
     597                },
     598
     599                update: function( text, editor, node ) {
     600                        $( node ).data( 'rendered', false );
     601                        editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
     602                        wp.mce.views.createInstance( this.type, text, this.match( text ).options ).render();
     603                }
     604        } );
     605} )( window.jQuery );
     606
     607/*
     608 * The WordPress core TinyMCE views.
     609 * Views for the gallery, audio, video, playlist and embed shortcodes,
     610 * and a view for embeddable URLs.
     611 */
     612( function( $, views ) {
     613        var postID = $( '#post_ID' ).val() || 0,
     614                media, gallery, av, embed;
     615
     616        media = {
     617                state: [],
     618
     619                edit: function( text, update ) {
    759620                        var media = wp.media[ this.type ],
    760                                 self = this,
    761                                 frame, data, callback;
     621                                frame = media.edit( text );
    762622
    763                         $( document ).trigger( 'media:edit' );
     623                        this.stopPlayers && this.stopPlayers();
    764624
    765                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    766                         frame = media.edit( data );
    767                         frame.on( 'close', function() {
    768                                 frame.detach();
     625                        _.each( this.state, function( state ) {
     626                                frame.state( state ).on( 'update', function( selection ) {
     627                                        update( media.shortcode( selection ).string() );
     628                                } );
    769629                        } );
    770630
    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 );
     631                        frame.on( 'close', function() {
    775632                                frame.detach();
    776                         };
    777                         if ( _.isArray( self.state ) ) {
    778                                 _.each( self.state, function (state) {
    779                                         frame.state( state ).on( 'update', callback );
    780                                 } );
    781                         } else {
    782                                 frame.state( self.state ).on( 'update', callback );
    783                         }
    784                         frame.open();
     633                        } );
    785634                }
    786635        };
    787636
    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         } ) );
     637        gallery = _.extend( {}, media, {
     638                state: [ 'gallery-edit' ],
    796639
    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         } ) );
     640                initialize: function() {
     641                        var self = this;
    805642
    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         } ) );
     643                        this.template = wp.media.template( 'editor-gallery' );
     644                        this.attachments = wp.media.gallery.attachments( this.shortcode, postID );
     645                        this.dfd = this.attachments.more().done( function() {
     646                                self.render();
     647                        } );
     648                },
    814649
    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                                         } );
    830                                 } else {
    831                                         this.shortcode = options.shortcode;
    832                                 }
     650                getContent: function() {
     651                        var attrs = this.shortcode.attrs.named,
     652                                attachments = false;
     653
     654                        // Don't render errors while still fetching attachments
     655                        if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
     656                                return '';
     657                        }
     658
     659                        if ( this.attachments.length ) {
     660                                attachments = this.attachments.toJSON();
     661
     662                                _.each( attachments, function( attachment ) {
     663                                        if ( attachment.sizes ) {
     664                                                if ( attrs.size && attachment.sizes[ attrs.size ] ) {
     665                                                        attachment.thumbnail = attachment.sizes[ attrs.size ];
     666                                                } else if ( attachment.sizes.thumbnail ) {
     667                                                        attachment.thumbnail = attachment.sizes.thumbnail;
     668                                                } else if ( attachment.sizes.full ) {
     669                                                        attachment.thumbnail = attachment.sizes.full;
     670                                                }
     671                                        }
     672                                } );
     673                        }
    833674
    834                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch' );
    835                                 $( this ).on( 'ready', this.setNodes );
     675                        return this.template( {
     676                                attachments: attachments,
     677                                columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
     678                        } );
     679                }
     680        } );
    836681
    837                                 this.fetch();
     682        av = _.extend( {}, media, {
     683                overlay: true,
     684                action: 'parse-media-shortcode',
     685
     686                initialize: function() {
     687                        var self = this;
     688
     689                        if ( this.url ) {
     690                                this.loader = false;
     691                                this.shortcode = wp.media.embed.shortcode( {
     692                                        url: this.url
     693                                } );
    838694                        }
    839                 } ),
    840                 edit: function( node ) {
    841                         var embed = media.embed,
    842                                 self = this,
    843                                 frame,
    844                                 data,
    845                                 isURL = 'embedURL' === this.type;
    846695
    847                         $( document ).trigger( 'media:edit' );
     696                        wp.ajax.send( this.action, {
     697                                data: {
     698                                        post_ID: postID,
     699                                        type: this.shortcode.tag,
     700                                        shortcode: this.shortcode.string()
     701                                }
     702                        } )
     703                        .done( function( response ) {
     704                                self.content = response;
     705                                self.render();
     706                        } )
     707                        .fail( function( response ) {
     708                                if ( self.type === 'embedURL' ) {
     709                                        self.removeMarkers();
     710                                } else {
     711                                        self.setError( response.message || response.statusText, 'admin-media' );
     712                                }
     713                        } );
    848714
    849                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    850                         frame = embed.edit( data, isURL );
    851                         frame.on( 'close', function() {
    852                                 frame.detach();
     715                        this.getEditors( function( editor ) {
     716                                editor.on( 'wpview-selected', function() {
     717                                        self.stopPlayers();
     718                                } );
    853719                        } );
    854                         frame.state( 'embed' ).props.on( 'change:url', function (model, url) {
    855                                 if ( ! url ) {
    856                                         return;
     720                },
     721
     722                stopPlayers: function( remove ) {
     723                        this.getNodes( function( editor, node, content ) {
     724                                var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
     725
     726                                if ( win && ( win = win.contentWindow ) && win.mejs ) {
     727                                        _.each( win.mejs.players, function( player ) {
     728                                                try {
     729                                                        player[ remove ? 'remove' : 'pause' ]();
     730                                                } catch ( e ) {}
     731                                        } );
    857732                                }
    858                                 frame.state( 'embed' ).metadata = model.toJSON();
    859733                        } );
    860                         frame.state( 'embed' ).on( 'select', function() {
    861                                 var shortcode;
     734                }
     735        } );
     736
     737        embed = _.extend( {}, av, {
     738                action: 'parse-embed',
    862739
     740                edit: function( text, update ) {
     741                        var media = wp.media.embed,
     742                                isURL = 'embedURL' === this.type,
     743                                frame = media.edit( text, isURL );
     744
     745                        this.stopPlayers();
     746
     747                        frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
     748                                if ( url ) {
     749                                        frame.state( 'embed' ).metadata = model.toJSON();
     750                                }
     751                        } );
     752
     753                        frame.state( 'embed' ).on( 'select', function() {
    863754                                if ( isURL ) {
    864                                         shortcode = frame.state( 'embed' ).metadata.url;
     755                                        update( frame.state( 'embed' ).metadata.url );
    865756                                } else {
    866                                         shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string();
     757                                        update( media.shortcode( frame.state( 'embed' ).metadata ).string() );
    867758                                }
    868                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
    869                                 wp.mce.views.refreshView( self, shortcode );
     759                        } );
     760
     761                        frame.on( 'close', function() {
    870762                                frame.detach();
    871763                        } );
     764
    872765                        frame.open();
    873766                }
    874         };
     767        } );
     768
     769        views.register( 'gallery', _.extend( {}, gallery ) );
     770
     771        views.register( 'audio', _.extend( {}, av, {
     772                state: [ 'audio-details' ]
     773        } ) );
     774
     775        views.register( 'video', _.extend( {}, av, {
     776                state: [ 'video-details' ]
     777        } ) );
     778
     779        views.register( 'playlist', _.extend( {}, av, {
     780                state: [ 'playlist-edit', 'video-playlist-edit' ]
     781        } ) );
    875782
    876         wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
     783        views.register( 'embed', _.extend( {}, embed ) );
    877784
    878         wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
    879                 toView: function( content ) {
     785        views.register( 'embedURL', _.extend( {}, embed, {
     786                match: function( content ) {
    880787                        var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
    881788                                match = re.exec( tinymce.trim( content ) );
    882789
    883                         if ( ! match ) {
    884                                 return;
     790                        if ( match ) {
     791                                return {
     792                                        index: match.index + match[1].length,
     793                                        content: match[2],
     794                                        options: {
     795                                                url: match[2]
     796                                        }
     797                                };
    885798                        }
    886 
    887                         return {
    888                                 index: match.index + match[1].length,
    889                                 content: match[2],
    890                                 options: {
    891                                         url: match[2]
    892                                 }
    893                         };
    894799                }
    895800        } ) );
    896 
    897 }(jQuery));
     801} )( 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 );