Make WordPress Core

Ticket #29841: 29841.5.patch

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

     
    11/* global tinymce */
    2 /**
     2
     3/*
     4 * The TinyMCE view API.
     5 *
    36 * Note: this API is "experimental" meaning that it will probably change
    47 * in the next few releases based on feedback from 3.9.0.
    58 * If you decide to use it, please follow the development closely.
    69 */
    7 
    8 // Ensure the global `wp` object exists.
    9 window.wp = window.wp || {};
    10 
    1110( function( $ ) {
    1211        'use strict';
    1312
    1413        var views = {},
    1514                instances = {},
    16                 media = wp.media,
    17                 mediaWindows = [],
    18                 windowIdx = 0,
    19                 waitInterval = 50,
    20                 viewOptions = ['encodedText'];
     15                viewOptions = [ 'encodedText' ];
    2116
    22         // Create the `wp.mce` object if necessary.
     17        window.wp = window.wp || {};
    2318        wp.mce = wp.mce || {};
    2419
    2520        /**
    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         /**
    27721         * wp.mce.views
    27822         *
    27923         * A set of utilities that simplifies adding custom UI within a TinyMCE editor.
     
    28327        wp.mce.views = {
    28428
    28529                /**
    286                  * wp.mce.views.register( type, view )
    287                  *
    28830                 * Registers a new TinyMCE view.
    28931                 *
    290                  * @param type
    291                  * @param constructor
    292                  *
     32                 * @param {String} The view type.
     33                 * @param {Object} A constructor.
    29334                 */
    29435                register: function( type, constructor ) {
    29536                        var defaultConstructor = {
     
    31960                },
    32061
    32162                /**
    322                  * wp.mce.views.get( id )
    323                  *
    324                  * Returns a TinyMCE view constructor.
     63                 * Unregisters a TinyMCE view.
    32564                 *
    326                  * @param type
     65                 * @param {String} The view type.
    32766                 */
    328                 get: function( type ) {
    329                         return views[ type ];
     67                unregister: function( type ) {
     68                        delete views[ type ];
    33069                },
    33170
    33271                /**
    333                  * wp.mce.views.unregister( type )
    334                  *
    335                  * Unregisters a TinyMCE view.
     72                 * Returns a TinyMCE view constructor.
    33673                 *
    337                  * @param type
     74                 * @param {String} The view type.
    33875                 */
    339                 unregister: function( type ) {
    340                         delete views[ type ];
     76                get: function( type ) {
     77                        return views[ type ];
    34178                },
    34279
    34380                /**
    344                  * wp.mce.views.unbind( editor )
    345                  *
    34681                 * The editor DOM is being rebuilt, run cleanup.
    34782                 */
    34883                unbind: function() {
     
    35287                },
    35388
    35489                /**
    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.
     90                 * Scans a given string for each view's pattern,
     91                 * replacing any matches with markers,
     92                 * and creates a new instance for every match,
     93                 * which triggers the related data to be fetched.
    35994                 *
    360                  * @param content
     95                 * @param {String} String to scan.
    36196                 */
    36297                toViews: function( content ) {
    36398                        var pieces = [ { content: content } ],
    36499                                current;
    365100
    366                         _.each( views, function( view, viewType ) {
     101                        _.each( views, function( view, type ) {
    367102                                current = pieces.slice();
    368103                                pieces  = [];
    369104
     
    379114
    380115                                        // Iterate through the string progressively matching views
    381116                                        // and slicing the string as we go.
    382                                         while ( remaining && (result = view.toView( remaining )) ) {
     117                                        while ( remaining && ( result = view.toView( remaining ) ) ) {
    383118                                                // Any text before the match becomes an unprocessed piece.
    384119                                                if ( result.index ) {
    385                                                         pieces.push({ content: remaining.substring( 0, result.index ) });
     120                                                        pieces.push( { content: remaining.substring( 0, result.index ) } );
    386121                                                }
    387122
    388123                                                // Add the processed piece for the match.
    389                                                 pieces.push({
    390                                                         content: wp.mce.views.toView( viewType, result.content, result.options ),
     124                                                pieces.push( {
     125                                                        content: wp.mce.views.toView( type, result.content, result.options ),
    391126                                                        processed: true
    392                                                 });
     127                                                } );
    393128
    394129                                                // Update the remaining content.
    395130                                                remaining = remaining.slice( result.index + result.content.length );
     
    398133                                        // There are no additional matches. If any content remains,
    399134                                        // add it as an unprocessed piece.
    400135                                        if ( remaining ) {
    401                                                 pieces.push({ content: remaining });
     136                                                pieces.push( { content: remaining } );
    402137                                        }
    403                                 });
    404                         });
     138                                } );
     139                        } );
    405140
    406                         return _.pluck( pieces, 'content' ).join('');
     141                        return _.pluck( pieces, 'content' ).join( '' );
    407142                },
    408143
    409144                /**
    410                  * Create a placeholder for a particular view type
    411                  *
    412                  * @param viewType
    413                  * @param text
    414                  * @param options
     145                 * Returns the marked text for a particular view type,
     146                 * and creates a new instance for that view type if it does not exist.
     147                 * The text will be returned unmarked if no view of that type is registered.
     148                 *
     149                 * @param {String} The view type.
     150                 * @param {String} The textual representation of the view.
     151                 * @param {Object} Options.
    415152                 *
     153                 * @return {String} The markered text.
    416154                 */
    417                 toView: function( viewType, text, options ) {
    418                         var view = wp.mce.views.get( viewType ),
    419                                 encodedText = window.encodeURIComponent( text ),
    420                                 instance, viewOptions;
    421 
     155                toView: function( type, text, options ) {
     156                        var view = this.get( type ),
     157                                encodedText = window.encodeURIComponent( text );
    422158
    423159                        if ( ! view ) {
    424160                                return text;
    425161                        }
    426162
    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;
     163                        if ( ! this.getInstance( encodedText ) ) {
     164                                instances[ encodedText ] = new view.View( _.extend( options, {
     165                                        encodedText: encodedText,
     166                                        type: type
     167                                } ) );
    433168                        }
    434169
    435                         return wp.html.string({
    436                                 tag: 'div',
    437 
    438                                 attrs: {
    439                                         'class': 'wpview-wrap',
    440                                         'data-wpview-text': encodedText,
    441                                         'data-wpview-type': viewType
    442                                 },
    443 
    444                                 content: '\u00a0'
    445                         });
     170                        return '<p data-wpview-marker="' + encodedText + '">' + text + '</p>';
    446171                },
    447172
    448173                /**
    449                  * Refresh views after an update is made
     174                 * Refresh views after an update is made.
    450175                 *
    451                  * @param view {object} being refreshed
    452                  * @param text {string} textual representation of the view
    453                  * @param force {Boolean} whether to force rendering
     176                 * @param {Object} The view to refresh.
     177                 * @param {String} The textual representation of the view.
     178                 * @param {Boolean} Whether or not to force rendering.
    454179                 */
    455180                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;
     181                        var encodedText = encodeURIComponent( text );
     182
     183                        if ( ! this.getInstance( encodedText ) ) {
     184                                instances[ encodedText ] = new view.View( _.extend( view.toView( text ).options, {
     185                                        encodedText: encodedText,
     186                                        type: view.type
     187                                } ) );
    469188                        }
    470189
    471                         instance.render( force );
     190                        instances[ encodedText ].render( force );
    472191                },
    473192
     193                /**
     194                 * @param {String} The textual representation of the view, encoded.
     195                 */
    474196                getInstance: function( encodedText ) {
    475197                        return instances[ encodedText ];
    476198                },
    477199
     200                getInstances: function() {
     201                        return instances;
     202                },
     203
    478204                /**
    479                  * render( scope )
     205                 * Renders any view instances.
    480206                 *
    481                  * Renders any view instances inside a DOM node `scope`.
     207                 * View instances are detected by the presence of markers.
     208                 * To generate markers, pass your content through `toViews`.
    482209                 *
    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 )`.
     210                 * @param {Boolean} Whether or not to force rendering.
    486211                 */
    487212                render: function( force ) {
    488213                        _.each( instances, function( instance ) {
     
    490215                        } );
    491216                },
    492217
    493                 edit: function( node ) {
    494                         var viewType = $( node ).data('wpview-type'),
    495                                 view = wp.mce.views.get( viewType );
     218                /**
     219                 * @param {HTMLElement} A view node.
     220                 */
     221                edit: function( editor, node ) {
     222                        var instance = this.getInstance( $( node ).data( 'wpview-text' ) ),
     223                                view = wp.mce.views.get( instance.type ),
     224                                self = this;
    496225
    497                         if ( view ) {
     226                        if ( view && view.edit ) {
    498227                                view.edit( node );
     228                        } else if ( instance && instance.edit ) {
     229                                instance.edit( decodeURIComponent( instance.encodedText ), function( text ) {
     230                                        $( node ).data( 'rendered', false );
     231                                        editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
     232                                        self.refreshView( view, text );
     233                                } );
    499234                        }
    500235                }
    501236        };
    502237
    503         wp.mce.views.register( 'gallery', {
     238        /**
     239         * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
     240         * that the TinyMCE View is not tied to a particular DOM node.
     241         *
     242         * @param {Object} Options.
     243         */
     244        wp.mce.View = function( options ) {
     245                options = options || {};
     246                this.type = options.type;
     247                _.extend( this, _.pick( options, viewOptions ) );
     248                this.initialize.apply( this, arguments );
     249        };
     250
     251        _.extend( wp.mce.View.prototype, {
     252
     253                /**
     254                 * Whether or not to display a loader.
     255                 *
     256                 * @type {Boolean}
     257                 */
     258                loader: true,
     259
     260                /**
     261                 * Runs after the view instance is created.
     262                 */
     263                initialize: function() {},
     264
     265                /**
     266                 * Retuns the HTML string to render in the view.
     267                 *
     268                 * @return {*}
     269                 */
     270                getHtml: function() {},
     271
     272                /**
     273                 * Retuns the HTML string to render in the view.
     274                 *
     275                 * @param {Boolean} Whether or not to rerender.
     276                 */
     277                render: function( rerender ) {
     278                        var i = 0;
     279
     280                        // If there's nothing to render an no loader needs to be shown, stop.
     281                        if ( ! this.loader && ! this.getHtml() ) {
     282                                return;
     283                        }
     284
     285                        // We're about to rerender all views of this instance, so unbind rendered views.
     286                        rerender && this.unbind();
     287
     288                        // Replace any left over markers.
     289                        this.replaceMarkers();
     290
     291                        if ( this.getHtml() ) {
     292                                this.setContent( this.getHtml(), function( editor, node ) {
     293                                        $( node ).data( 'rendered', true );
     294                                        this.bindNodes.apply( this, arguments );
     295                                        i++;
     296                                }, rerender ? null : false );
     297
     298                                // Use `bindNodes` if possible.
     299                                i && $( this ).trigger( 'ready' );
     300                        } else {
     301                                this.setLoader();
     302                        }
     303                },
     304
     305                /**
     306                 * Runs after a view is added to the DOM.
     307                 *
     308                 * @param {tinymce.Editor} The editor instance the view node is in.
     309                 * @param {HTMLElement} The view node.
     310                 * @param {HTMLElement} The view's content node.
     311                 */
     312                bindNodes: function() {},
     313
     314                /**
     315                 * Runs before a view is removed from the DOM.
     316                 */
     317                unbind: function() {
     318                        this.getNodes( function() {
     319                                this.unbindNodes.apply( this, arguments );
     320                        }, true );
     321                },
     322
     323                /**
     324                 * Runs before a view is removed from the DOM.
     325                 *
     326                 * @param {tinymce.Editor} The editor instance the view node is in.
     327                 * @param {HTMLElement} The view node.
     328                 * @param {HTMLElement} The view's content node.
     329                 */
     330                unbindNodes: function() {},
     331
     332                /**
     333                 * Gets all the TinyMCE editors that support views.
     334                 *
     335                 * @param {Function} A callback (optional).
     336                 *
     337                 * @return {tinymce.Editor[]} An array of TinyMCE editor instances.
     338                 */
     339                getEditors: function( callback ) {
     340                        var editors = [];
     341
     342                        _.each( tinymce.editors, function( editor ) {
     343                                if ( editor.plugins.wpview ) {
     344                                        editors.push( editor );
     345                                        callback && callback.call( this, editor );
     346                                }
     347                        }, this );
     348
     349                        return editors;
     350                },
     351
     352                /**
     353                 * Gets all the view nodes in each editor.
     354                 *
     355                 * @param {Function} A callback (optional).
     356                 * @param {Boolean} Get (un)rendered nodes (optional).
     357                 *
     358                 * @return {HTMLElement[]} An array of view nodes.
     359                 */
     360                getNodes: function( callback, rendered ) {
     361                        var nodes = [];
     362
     363                        this.getEditors( function( editor ) {
     364                                var self = this;
     365
     366                                $( editor.getBody() )
     367                                        .find( '[data-wpview-text="' + self.encodedText + '"]' )
     368                                        .filter( function() {
     369                                                var data;
     370
     371                                                if ( rendered == null ) {
     372                                                        return true;
     373                                                }
     374
     375                                                data = $( this ).data( 'rendered' ) === true;
     376
     377                                                return rendered ? data : ! data;
     378                                        } )
     379                                        .each( function ( i, node ) {
     380                                                nodes.push( node );
     381                                                callback && callback.call( self, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
     382                                        } );
     383                        } );
     384
     385                        return nodes;
     386                },
     387
     388                /**
     389                 * Gets all the markers in each editor.
     390                 *
     391                 * @param {Function} A callback (optional).
     392                 *
     393                 * @return {HTMLElement[]} An array of marker nodes.
     394                 */
     395                getMarkers: function( callback ) {
     396                        var markers = [];
     397
     398                        this.getEditors( function( editor ) {
     399                                var self = this;
     400
     401                                $( editor.getBody() )
     402                                        .find( '[data-wpview-marker="' + this.encodedText + '"]' )
     403                                        .each( function( i, node ) {
     404                                                markers.push( node );
     405                                                callback && callback.call( self, editor, node );
     406                                        } );
     407                        } );
     408
     409                        return markers;
     410                },
     411
     412                /**
     413                 * Replaces all markers with view nodes.
     414                 */
     415                replaceMarkers: function() {
     416                        this.getMarkers( function( editor, node ) {
     417                                if ( $( node ).text() !== decodeURIComponent( this.encodedText ) ) {
     418                                        editor.dom.setAttrib( node, 'data-wpview-marker', null );
     419                                        return;
     420                                }
     421
     422                                editor.dom.replace(
     423                                        editor.dom.createFragment(
     424                                                '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
     425                                                        '<p class="wpview-selection-before">\u00a0</p>' +
     426                                                        '<div class="wpview-body" contenteditable="false">' +
     427                                                                '<div class="toolbar mce-arrow-down">' +
     428                                                                        ( this.edit || views[ this.type ].edit ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) +
     429                                                                        '<div class="dashicons dashicons-no remove"></div>' +
     430                                                                '</div>' +
     431                                                                '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
     432                                                                ( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) +
     433                                                        '</div>' +
     434                                                        '<p class="wpview-selection-after">\u00a0</p>' +
     435                                                '</div>'
     436                                        ),
     437                                        node
     438                                );
     439                        } );
     440                },
     441
     442                /**
     443                 * Removes all markers.
     444                 */
     445                removeMarkers: function() {
     446                        this.getMarkers( function( editor, node ) {
     447                                editor.dom.setAttrib( node, 'data-wpview-marker', null );
     448                        } );
     449                },
     450
     451                /**
     452                 * Gets all the markers in each editor.
     453                 *
     454                 * @param {(String|HTMLElement)} The content to set.
     455                 * @param {Function} A callback (optional).
     456                 * @param {Boolean} Only set for (un)rendered nodes (optional).
     457                 */
     458                setContent: function( content, callback, rendered ) {
     459                        if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
     460                                this.setIframes( content.head, content.body, callback, rendered );
     461                        } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
     462                                this.setIframes( null, content, callback, rendered );
     463                        } else {
     464                                this.getNodes( function( editor, node, contentNode ) {
     465                                        content = content.body || content;
     466
     467                                        contentNode.innerHTML = '';
     468                                        contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
     469
     470                                        callback && callback.apply( this, arguments );
     471                                }, rendered );
     472                        }
     473                },
     474
     475                /**
     476                 * Set an iframe as the view content.
     477                 */
     478                setIframes: function( head, body, callback, rendered ) {
     479                        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
     480                                importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist';
     481
     482                        this.getNodes( function( editor, node, content ) {
     483                                var dom = editor.dom,
     484                                        styles = '',
     485                                        bodyClasses = editor.getBody().className || '',
     486                                        iframe, iframeDoc, i, resize;
     487
     488                                content.innerHTML = '';
     489                                head = head || '';
     490
     491                                if ( importStyles ) {
     492                                        if ( ! wp.mce.views.sandboxStyles ) {
     493                                                tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) {
     494                                                        if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
     495                                                                link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
     496
     497                                                                styles += dom.getOuterHTML( link ) + '\n';
     498                                                        }
     499                                                });
     500
     501                                                wp.mce.views.sandboxStyles = styles;
     502                                        } else {
     503                                                styles = wp.mce.views.sandboxStyles;
     504                                        }
     505                                }
     506
     507                                // Seems Firefox needs a bit of time to insert/set the view nodes,
     508                                // or the iframe will fail especially when switching Text => Visual.
     509                                setTimeout( function() {
     510                                        iframe = dom.add( content, 'iframe', {
     511                                                /* jshint scripturl: true */
     512                                                src: tinymce.Env.ie ? 'javascript:""' : '',
     513                                                frameBorder: '0',
     514                                                allowTransparency: 'true',
     515                                                scrolling: 'no',
     516                                                'class': 'wpview-sandbox',
     517                                                style: {
     518                                                        width: '100%',
     519                                                        display: 'block'
     520                                                }
     521                                        } );
     522
     523                                        iframeDoc = iframe.contentWindow.document;
     524
     525                                        iframeDoc.open();
     526
     527                                        iframeDoc.write(
     528                                                '<!DOCTYPE html>' +
     529                                                '<html>' +
     530                                                        '<head>' +
     531                                                                '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
     532                                                                head +
     533                                                                styles +
     534                                                                '<style>' +
     535                                                                        'html {' +
     536                                                                                'background: transparent;' +
     537                                                                                'padding: 0;' +
     538                                                                                'margin: 0;' +
     539                                                                        '}' +
     540                                                                        'body#wpview-iframe-sandbox {' +
     541                                                                                'background: transparent;' +
     542                                                                                'padding: 1px 0 !important;' +
     543                                                                                'margin: -1px 0 0 !important;' +
     544                                                                        '}' +
     545                                                                        'body#wpview-iframe-sandbox:before,' +
     546                                                                        'body#wpview-iframe-sandbox:after {' +
     547                                                                                'display: none;' +
     548                                                                                'content: "";' +
     549                                                                        '}' +
     550                                                                '</style>' +
     551                                                        '</head>' +
     552                                                        '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
     553                                                                body +
     554                                                        '</body>' +
     555                                                '</html>'
     556                                        );
     557
     558                                        iframeDoc.close();
     559
     560                                        resize = function() {
     561                                                var $iframe, iframeDocHeight;
     562
     563                                                // Make sure the iframe still exists.
     564                                                if ( iframe.contentWindow ) {
     565                                                        $iframe = $( iframe );
     566                                                        iframeDocHeight = $( iframeDoc.body ).height();
     567
     568                                                        if ( $iframe.height() !== iframeDocHeight ) {
     569                                                                $iframe.height( iframeDocHeight );
     570                                                                editor.nodeChanged();
     571                                                        }
     572                                                }
     573                                        };
     574
     575                                        if ( MutationObserver ) {
     576                                                new MutationObserver( _.debounce( function() {
     577                                                        resize();
     578                                                }, 100 ) )
     579                                                .observe( iframeDoc.body, {
     580                                                        attributes: true,
     581                                                        childList: true,
     582                                                        subtree: true
     583                                                } );
     584                                        } else {
     585                                                for ( i = 1; i < 6; i++ ) {
     586                                                        setTimeout( resize, i * 700 );
     587                                                }
     588                                        }
     589
     590                                        if ( importStyles ) {
     591                                                editor.on( 'wp-body-class-change', function() {
     592                                                        iframeDoc.body.className = editor.getBody().className;
     593                                                } );
     594                                        }
     595                                }, 50 );
     596
     597                                callback && callback.apply( this, arguments );
     598                        }, rendered );
     599                },
     600
     601                /**
     602                 * Set a loader.
     603                 */
     604                setLoader: function() {
     605                        this.setContent(
     606                                '<div class="loading-placeholder">' +
     607                                        '<div class="dashicons dashicons-admin-media"></div>' +
     608                                        '<div class="wpview-loading"><ins></ins></div>' +
     609                                '</div>'
     610                        );
     611                },
     612
     613                /**
     614                 * Set an error.
     615                 *
     616                 * @param {String} The error message to set.
     617                 * @param {String} A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
     618                 */
     619                setError: function( message, dashicon ) {
     620                        this.setContent(
     621                                '<div class="wpview-error">' +
     622                                        '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
     623                                        '<p>' + message + '</p>' +
     624                                '</div>'
     625                        );
     626                }
     627        } );
     628
     629        // Take advantage of the Backbone extend method.
     630        wp.mce.View.extend = Backbone.View.extend;
     631} )( jQuery );
     632
     633/*
     634 * The WordPress core TinyMCE views.
     635 * Views for the gallery, audio, video, playlist and embed shortcodes,
     636 * and a view for embeddable URLs.
     637 */
     638( function( $, views ) {
     639        views.register( 'gallery', {
    504640                View: {
    505                         template: media.template( 'editor-gallery' ),
    506641
    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(),
     642                        template: wp.media.template( 'editor-gallery' ),
     643
     644                        postID: $( '#post_ID' ).val(),
    512645
    513646                        initialize: function( options ) {
    514647                                this.shortcode = options.shortcode;
     
    520653
    521654                                this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID );
    522655                                this.dfd = this.attachments.more().done( function() {
    523                                         self.render( true );
     656                                        self.render();
    524657                                } );
    525658                        },
    526659
     
    556689                                };
    557690
    558691                                return this.template( options );
    559                         }
    560                 },
    561 
    562                 edit: function( node ) {
    563                         var gallery = wp.media.gallery,
    564                                 self = this,
    565                                 frame, data;
    566 
    567                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
    568                         frame = gallery.edit( data );
     692                        },
    569693
    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                         });
     694                        edit: function( text, callback ) {
     695                                var gallery = wp.media.gallery,
     696                                        frame = gallery.edit( text );
     697
     698                                frame.state( 'gallery-edit' ).on( 'update', function( selection ) {
     699                                        // var shortcode = gallery.shortcode( selection ).string();
     700                                        // $( node ).attr( 'data-wpview-text', encodeURIComponent( shortcode ) );
     701                                        // wp.mce.views.refreshView( self, shortcode, true );
     702                                        callback( gallery.shortcode( selection ).string() );
     703                                } );
    575704
    576                         frame.on( 'close', function() {
    577                                 frame.detach();
    578                         });
     705                                frame.on( 'close', function() {
     706                                        frame.detach();
     707                                } );
     708                        }
    579709                }
    580710        } );
    581711
     
    593723                        initialize: function( options ) {
    594724                                var self = this;
    595725
    596                                 this.shortcode = options.shortcode;
    597 
    598                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' );
    599                                 $( this ).on( 'ready', this.setNodes );
    600 
    601                                 $( document ).on( 'media:edit', this.stopPlayers );
     726                                if ( options.url ) {
     727                                        this.loader = false;
     728                                        this.shortcode = wp.media.embed.shortcode( {
     729                                                url: options.url
     730                                        } );
     731                                } else {
     732                                        this.shortcode = options.shortcode;
     733                                }
    602734
    603735                                this.fetch();
    604736
    605737                                this.getEditors( function( editor ) {
    606                                         editor.on( 'hide', function () {
    607                                                 mediaWindows = [];
    608                                                 windowIdx = 0;
     738                                        editor.on( 'wpview-selected', function() {
    609739                                                self.stopPlayers();
    610740                                        } );
    611                                 });
    612                         },
    613 
    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                                         }
    621741                                } );
    622742                        },
    623743
    624                         iframeLoaded: function (win) {
    625                                 return _.bind( function () {
    626                                         var callback;
    627                                         if ( ! win.mejs || _.isEmpty( win.mejs.players ) ) {
    628                                                 return;
    629                                         }
    630 
    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                                         }
    644 
    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                         },
    659 
    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                         },
    672 
    673744                        fetch: function () {
    674745                                var self = this;
    675746
     
    681752                                        }
    682753                                } )
    683754                                .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                                         }
     755                                        self.parsed = response;
     756                                        self.render();
    691757                                } )
    692758                                .fail( function( response ) {
    693                                         self.fail( response || true );
    694                                 } );
    695                         },
    696 
    697                         fail: function( error ) {
    698                                 if ( ! this.error ) {
    699                                         if ( error ) {
    700                                                 this.error = error;
    701                                         } else {
    702                                                 return;
    703                                         }
    704                                 }
    705 
    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' ) {
    709 
    710                                                 this.setError( this.error.message, 'admin-media' );
     759                                        if ( self.type === 'embedURL' ) {
     760                                                self.removeMarkers();
    711761                                        } else {
    712                                                 this.setContent( '<p>' + this.original + '</p>', 'replace' );
     762                                                self.setError( response.message || response.statusText, 'admin-media' );
    713763                                        }
    714                                 } else if ( this.error.statusText ) {
    715                                         this.setError( this.error.statusText, 'admin-media' );
    716                                 } else if ( this.original ) {
    717                                         this.setContent( '<p>' + this.original + '</p>', 'replace' );
    718                                 }
     764                                } );
    719765                        },
    720766
    721767                        stopPlayers: function( remove ) {
    722                                 var rem = remove === 'remove';
    723 
    724768                                this.getNodes( function( editor, node, content ) {
    725                                         var p, win,
    726                                                 iframe = $( 'iframe.wpview-sandbox', content ).get(0);
     769                                        var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
    727770
    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();
    733 
    734                                                                 if ( rem ) {
    735                                                                         win.mejs.players[p].remove();
    736                                                                 }
    737                                                         }
    738                                                 } catch( er ) {}
     771                                        if ( win && ( win = win.contentWindow ) && win.mejs ) {
     772                                                _.each( win.mejs.players, function( player ) {
     773                                                        try {
     774                                                                player[ remove ? 'remove' : 'pause' ]();
     775                                                        } catch ( e ) {}
     776                                                } );
    739777                                        }
    740                                 });
     778                                } );
    741779                        },
    742780
    743                         unbind: function() {
    744                                 this.stopPlayers( 'remove' );
     781                        getHtml: function() {
     782                                return this.parsed;
    745783                        }
    746784                },
    747785
     
    760798                                self = this,
    761799                                frame, data, callback;
    762800
    763                         $( document ).trigger( 'media:edit' );
     801                        _.each( views.getInstances(), function( instance ) {
     802                                instance.stopPlayers && instance.stopPlayers();
     803                        } );
    764804
    765                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
     805                        data = decodeURIComponent( $( node ).attr('data-wpview-text') );
    766806                        frame = media.edit( data );
     807
    767808                        frame.on( 'close', function() {
    768809                                frame.detach();
    769810                        } );
    770811
    771812                        callback = function( selection ) {
    772813                                var shortcode = wp.media[ self.type ].shortcode( selection ).string();
    773                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
     814                                $( node ).attr( 'data-wpview-text', encodeURIComponent( shortcode ) );
    774815                                wp.mce.views.refreshView( self, shortcode );
    775816                                frame.detach();
    776817                        };
     818
    777819                        if ( _.isArray( self.state ) ) {
    778820                                _.each( self.state, function (state) {
    779821                                        frame.state( state ).on( 'update', callback );
     
    781823                        } else {
    782824                                frame.state( self.state ).on( 'update', callback );
    783825                        }
     826
    784827                        frame.open();
    785828                }
    786829        };
     
    790833         *
    791834         * @mixes wp.mce.av
    792835         */
    793         wp.mce.views.register( 'video', _.extend( {}, wp.mce.av, {
     836        views.register( 'video', _.extend( {}, wp.mce.av, {
    794837                state: 'video-details'
    795838        } ) );
    796839
     
    799842         *
    800843         * @mixes wp.mce.av
    801844         */
    802         wp.mce.views.register( 'audio', _.extend( {}, wp.mce.av, {
     845        views.register( 'audio', _.extend( {}, wp.mce.av, {
    803846                state: 'audio-details'
    804847        } ) );
    805848
     
    808851         *
    809852         * @mixes wp.mce.av
    810853         */
    811         wp.mce.views.register( 'playlist', _.extend( {}, wp.mce.av, {
     854        views.register( 'playlist', _.extend( {}, wp.mce.av, {
    812855                state: [ 'playlist-edit', 'video-playlist-edit' ]
    813856        } ) );
    814857
     
    818861        wp.mce.embedMixin = {
    819862                View: _.extend( {}, wp.mce.av.View, {
    820863                        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                                 }
    833 
    834                                 _.bindAll( this, 'setIframes', 'setNodes', 'fetch' );
    835                                 $( this ).on( 'ready', this.setNodes );
    836 
    837                                 this.fetch();
    838                         }
     864                        action: 'parse-embed'
    839865                } ),
    840866                edit: function( node ) {
    841                         var embed = media.embed,
     867                        var embed = wp.media.embed,
    842868                                self = this,
    843869                                frame,
    844870                                data,
    845871                                isURL = 'embedURL' === this.type;
    846872
    847                         $( document ).trigger( 'media:edit' );
    848 
    849                         data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
     873                        data = decodeURIComponent( $( node ).attr('data-wpview-text') );
    850874                        frame = embed.edit( data, isURL );
     875
    851876                        frame.on( 'close', function() {
    852877                                frame.detach();
    853878                        } );
     879
    854880                        frame.state( 'embed' ).props.on( 'change:url', function (model, url) {
    855881                                if ( ! url ) {
    856882                                        return;
    857883                                }
    858884                                frame.state( 'embed' ).metadata = model.toJSON();
    859885                        } );
     886
    860887                        frame.state( 'embed' ).on( 'select', function() {
    861888                                var shortcode;
    862889
     
    865892                                } else {
    866893                                        shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string();
    867894                                }
    868                                 $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
     895                                $( node ).attr( 'data-wpview-text', encodeURIComponent( shortcode ) );
    869896                                wp.mce.views.refreshView( self, shortcode );
    870897                                frame.detach();
    871898                        } );
     899
    872900                        frame.open();
    873901                }
    874902        };
    875903
    876         wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
     904        views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) );
    877905
    878         wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
     906        views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, {
    879907                toView: function( content ) {
    880908                        var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
    881909                                match = re.exec( tinymce.trim( content ) );
     
    893921                        };
    894922                }
    895923        } ) );
    896 
    897 }(jQuery));
     924} )( jQuery, wp.mce.views );
  • src/wp-includes/js/tinymce/plugins/wpview/plugin.js

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