3 window.wp = window.wp || {};
6 * The TinyMCE view API.
8 * Note: this API is "experimental" meaning that it will probably change
9 * in the next few releases based on feedback from 3.9.0.
10 * If you decide to use it, please follow the development closely.
14 * |- registered view constructor (type)
15 * | |- view instance (unique text)
27 ( function( window, wp, $ ) {
33 wp.mce = wp.mce || {};
38 * A set of utilities that simplifies adding custom UI within a TinyMCE editor.
39 * At its core, it serves as a series of converters, transforming text to a
40 * custom UI, and back again.
45 * Registers a new view type.
47 * @param {String} type The view type.
48 * @param {Object} extend An object to extend wp.mce.View.prototype with.
50 register: function( type, extend ) {
51 views[ type ] = wp.mce.View.extend( _.extend( extend, { type: type } ) );
55 * Unregisters a view type.
57 * @param {String} type The view type.
59 unregister: function( type ) {
64 * Returns the settings of a view type.
66 * @param {String} type The view type.
68 * @return {Function} The view constructor.
70 get: function( type ) {
75 * Unbinds all view nodes.
76 * Runs before removing all view nodes from the DOM.
79 _.each( instances, function( instance ) {
85 * Scans a given string for each view's pattern,
86 * replacing any matches with markers,
87 * and creates a new instance for every match.
89 * @param {String} content The string to scan.
91 * @return {String} The string with markers.
93 setMarkers: function( content ) {
94 var pieces = [ { content: content } ],
98 _.each( views, function( view, type ) {
99 current = pieces.slice();
102 _.each( current, function( piece ) {
103 var remaining = piece.content,
106 // Ignore processed pieces, but retain their location.
107 if ( piece.processed ) {
108 pieces.push( piece );
112 // Iterate through the string progressively matching views
113 // and slicing the string as we go.
114 while ( remaining && ( result = view.prototype.match( remaining ) ) ) {
115 // Any text before the match becomes an unprocessed piece.
116 if ( result.index ) {
117 pieces.push( { content: remaining.substring( 0, result.index ) } );
120 instance = self.createInstance( type, result.content, result.options );
121 text = instance.loader ? '.' : instance.text;
123 // Add the processed piece for the match.
125 content: '<p data-wpview-marker="' + instance.encodedText + '">' + text + '</p>',
129 // Update the remaining content.
130 remaining = remaining.slice( result.index + result.content.length );
133 // There are no additional matches.
134 // If any content remains, add it as an unprocessed piece.
136 pieces.push( { content: remaining } );
141 content = _.pluck( pieces, 'content' ).join( '' );
142 return content.replace( /<p>\s*<p data-wpview-marker=/g, '<p data-wpview-marker=' ).replace( /<\/p>\s*<\/p>/g, '</p>' );
146 * Create a view instance.
148 * @param {String} type The view type.
149 * @param {String} text The textual representation of the view.
150 * @param {Object} options Options.
152 * @return {wp.mce.View} The view instance.
154 createInstance: function( type, text, options ) {
155 var View = this.get( type ),
159 text = tinymce.DOM.decode( text );
160 instance = this.getInstance( text );
166 encodedText = encodeURIComponent( text );
168 options = _.extend( options || {}, {
170 encodedText: encodedText
173 return instances[ encodedText ] = new View( options );
177 * Get a view instance.
179 * @param {(String|HTMLElement)} object The textual representation of the view or the view node.
181 * @return {wp.mce.View} The view instance or undefined.
183 getInstance: function( object ) {
184 if ( typeof object === 'string' ) {
185 return instances[ encodeURIComponent( object ) ];
188 return instances[ $( object ).attr( 'data-wpview-text' ) ];
192 * Given a view node, get the view's text.
194 * @param {HTMLElement} node The view node.
196 * @return {String} The textual representation of the view.
198 getText: function( node ) {
199 return decodeURIComponent( $( node ).attr( 'data-wpview-text' ) || '' );
203 * Renders all view nodes that are not yet rendered.
205 * @param {Boolean} force Rerender all view nodes.
207 render: function( force ) {
208 _.each( instances, function( instance ) {
209 instance.render( force );
214 * Update the text of a given view node.
216 * @param {String} text The new text.
217 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
218 * @param {HTMLElement} node The view node to update.
220 update: function( text, editor, node ) {
221 var instance = this.getInstance( node );
224 instance.update( text, editor, node );
229 * Renders any editing interface based on the view type.
231 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
232 * @param {HTMLElement} node The view node to edit.
234 edit: function( editor, node ) {
235 var instance = this.getInstance( node );
237 if ( instance && instance.edit ) {
238 instance.edit( instance.text, function( text ) {
239 instance.update( text, editor, node );
245 * Remove a given view node from the DOM.
247 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
248 * @param {HTMLElement} node The view node to remove.
250 remove: function( editor, node ) {
251 var instance = this.getInstance( node );
254 instance.remove( editor, node );
260 * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
261 * The main difference is that the TinyMCE View is not tied to a particular DOM node.
263 * @param {Object} options Options.
265 wp.mce.View = function( options ) {
266 _.extend( this, options );
270 wp.mce.View.extend = Backbone.View.extend;
272 _.extend( wp.mce.View.prototype, {
282 * Whether or not to display a loader.
289 * Runs after the view instance is created.
291 initialize: function() {},
294 * Retuns the content to render in the view node.
298 getContent: function() {
303 * Renders all view nodes tied to this view instance that are not yet rendered.
305 * @param {String} content The content to render. Optional.
306 * @param {Boolean} force Rerender all view nodes tied to this view instance.
308 render: function( content, force ) {
309 if ( content != null ) {
310 this.content = content;
313 content = this.getContent();
315 // If there's nothing to render an no loader needs to be shown, stop.
316 if ( ! this.loader && ! content ) {
320 // We're about to rerender all views of this instance, so unbind rendered views.
321 force && this.unbind();
323 // Replace any left over markers.
324 this.replaceMarkers();
327 this.setContent( content, function( editor, node, contentNode ) {
328 $( node ).data( 'rendered', true );
329 this.bindNode.call( this, editor, node, contentNode );
330 }, force ? null : false );
337 * Binds a given node after its content is added to the DOM.
339 bindNode: function() {},
342 * Unbinds a given node before its content is removed from the DOM.
344 unbindNode: function() {},
347 * Unbinds all view nodes tied to this view instance.
348 * Runs before their content is removed from the DOM.
351 this.getNodes( function( editor, node, contentNode ) {
352 this.unbindNode.call( this, editor, node, contentNode );
353 $( node ).trigger( 'wp-mce-view-unbind' );
358 * Gets all the TinyMCE editor instances that support views.
360 * @param {Function} callback A callback.
362 getEditors: function( callback ) {
363 _.each( tinymce.editors, function( editor ) {
364 if ( editor.plugins.wpview ) {
365 callback.call( this, editor );
371 * Gets all view nodes tied to this view instance.
373 * @param {Function} callback A callback.
374 * @param {Boolean} rendered Get (un)rendered view nodes. Optional.
376 getNodes: function( callback, rendered ) {
377 this.getEditors( function( editor ) {
380 $( editor.getBody() )
381 .find( '[data-wpview-text="' + self.encodedText + '"]' )
382 .filter( function() {
385 if ( rendered == null ) {
389 data = $( this ).data( 'rendered' ) === true;
391 return rendered ? data : ! data;
394 callback.call( self, editor, this, $( this ).find( '.wpview-content' ).get( 0 ) );
400 * Gets all marker nodes tied to this view instance.
402 * @param {Function} callback A callback.
404 getMarkers: function( callback ) {
405 this.getEditors( function( editor ) {
408 $( editor.getBody() )
409 .find( '[data-wpview-marker="' + this.encodedText + '"]' )
411 callback.call( self, editor, this );
417 * Replaces all marker nodes tied to this view instance.
419 replaceMarkers: function() {
420 this.getMarkers( function( editor, node ) {
421 if ( ! this.loader && $( node ).text() !== this.text ) {
422 editor.dom.setAttrib( node, 'data-wpview-marker', null );
427 editor.dom.createFragment(
428 '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
429 '<p class="wpview-selection-before">\u00a0</p>' +
430 '<div class="wpview-body" contenteditable="false">' +
431 '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
433 '<p class="wpview-selection-after">\u00a0</p>' +
442 * Removes all marker nodes tied to this view instance.
444 removeMarkers: function() {
445 this.getMarkers( function( editor, node ) {
446 editor.dom.setAttrib( node, 'data-wpview-marker', null );
451 * Sets the content for all view nodes tied to this view instance.
453 * @param {*} content The content to set.
454 * @param {Function} callback A callback. Optional.
455 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
457 setContent: function( content, callback, rendered ) {
458 if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
459 this.setIframes( content.head || '', content.body, callback, rendered );
460 } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
461 this.setIframes( '', content, callback, rendered );
463 this.getNodes( function( editor, node, contentNode ) {
464 content = content.body || content;
466 if ( content.indexOf( '<iframe' ) !== -1 ) {
467 content += '<div class="wpview-overlay"></div>';
470 contentNode.innerHTML = '';
471 contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
473 callback && callback.call( this, editor, node, contentNode );
479 * Sets the content in an iframe for all view nodes tied to this view instance.
481 * @param {String} head HTML string to be added to the head of the document.
482 * @param {String} body HTML string to be added to the body of the document.
483 * @param {Function} callback A callback. Optional.
484 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
486 setIframes: function( head, body, callback, rendered ) {
487 var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
490 this.getNodes( function( editor, node, contentNode ) {
491 var dom = editor.dom,
493 bodyClasses = editor.getBody().className || '',
494 editorHead = editor.getDoc().getElementsByTagName( 'head' )[0];
496 tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
497 if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
498 link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
500 styles += dom.getOuterHTML( link );
504 // Seems the browsers need a bit of time to insert/set the view nodes,
505 // or the iframe will fail especially when switching Text => Visual.
506 setTimeout( function() {
507 var iframe, iframeDoc, observer, i;
509 contentNode.innerHTML = '';
511 iframe = dom.add( contentNode, 'iframe', {
512 /* jshint scripturl: true */
513 src: tinymce.Env.ie ? 'javascript:""' : '',
515 allowTransparency: 'true',
517 'class': 'wpview-sandbox',
524 dom.add( contentNode, 'div', { 'class': 'wpview-overlay' } );
526 iframeDoc = iframe.contentWindow.document;
534 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
539 'background: transparent;' +
543 'body#wpview-iframe-sandbox {' +
544 'background: transparent;' +
545 'padding: 1px 0 !important;' +
546 'margin: -1px 0 0 !important;' +
548 'body#wpview-iframe-sandbox:before,' +
549 'body#wpview-iframe-sandbox:after {' +
555 '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
564 var $iframe, iframeDocHeight;
566 // Make sure the iframe still exists.
567 if ( iframe.contentWindow ) {
568 $iframe = $( iframe );
569 iframeDocHeight = $( iframeDoc.body ).height();
571 if ( $iframe.height() !== iframeDocHeight ) {
572 $iframe.height( iframeDocHeight );
573 editor.nodeChanged();
578 $( iframe.contentWindow ).on( 'load', resize );
580 if ( MutationObserver ) {
581 observer = new MutationObserver( _.debounce( resize, 100 ) );
583 observer.observe( iframeDoc.body, {
589 $( node ).one( 'wp-mce-view-unbind', function() {
590 observer.disconnect();
593 for ( i = 1; i < 6; i++ ) {
594 setTimeout( resize, i * 700 );
598 function classChange() {
599 iframeDoc.body.className = editor.getBody().className;
602 editor.on( 'wp-body-class-change', classChange );
604 $( node ).one( 'wp-mce-view-unbind', function() {
605 editor.off( 'wp-body-class-change', classChange );
608 callback && callback.call( self, editor, node, contentNode );
614 * Sets a loader for all view nodes tied to this view instance.
616 setLoader: function() {
618 '<div class="loading-placeholder">' +
619 '<div class="dashicons dashicons-admin-media"></div>' +
620 '<div class="wpview-loading"><ins></ins></div>' +
626 * Sets an error for all view nodes tied to this view instance.
628 * @param {String} message The error message to set.
629 * @param {String} dashicon A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
631 setError: function( message, dashicon ) {
633 '<div class="wpview-error">' +
634 '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
635 '<p>' + message + '</p>' +
641 * Tries to find a text match in a given string.
643 * @param {String} content The string to scan.
647 match: function( content ) {
648 var match = wp.shortcode.next( this.type, content );
653 content: match.content,
655 shortcode: match.shortcode
662 * Update the text of a given view node.
664 * @param {String} text The new text.
665 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
666 * @param {HTMLElement} node The view node to update.
668 update: function( text, editor, node ) {
669 _.find( views, function( view, type ) {
670 var match = view.prototype.match( text );
673 $( node ).data( 'rendered', false );
674 editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
675 wp.mce.views.createInstance( type, text, match.options ).render();
684 * Remove a given view node from the DOM.
686 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
687 * @param {HTMLElement} node The view node to remove.
689 remove: function( editor, node ) {
690 this.unbindNode.call( this, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
691 $( node ).trigger( 'wp-mce-view-unbind' );
692 editor.dom.remove( node );
696 } )( window, window.wp, window.jQuery );
699 * The WordPress core TinyMCE views.
700 * Views for the gallery, audio, video, playlist and embed shortcodes,
701 * and a view for embeddable URLs.
703 ( function( window, views, $ ) {
704 var postID = $( '#post_ID' ).val() || 0,
705 media, gallery, av, embed;
710 edit: function( text, update ) {
711 var media = wp.media[ this.type ],
712 frame = media.edit( text );
714 this.pausePlayers && this.pausePlayers();
716 _.each( this.state, function( state ) {
717 frame.state( state ).on( 'update', function( selection ) {
718 update( media.shortcode( selection ).string() );
722 frame.on( 'close', function() {
730 gallery = _.extend( {}, media, {
731 state: [ 'gallery-edit' ],
732 template: wp.media.template( 'editor-gallery' ),
734 initialize: function() {
735 var attachments = wp.media.gallery.attachments( this.shortcode, postID ),
736 attrs = this.shortcode.attrs.named,
741 attachments = attachments.toJSON();
743 _.each( attachments, function( attachment ) {
744 if ( attachment.sizes ) {
745 if ( attrs.size && attachment.sizes[ attrs.size ] ) {
746 attachment.thumbnail = attachment.sizes[ attrs.size ];
747 } else if ( attachment.sizes.thumbnail ) {
748 attachment.thumbnail = attachment.sizes.thumbnail;
749 } else if ( attachment.sizes.full ) {
750 attachment.thumbnail = attachment.sizes.full;
755 self.render( self.template( {
756 attachments: attachments,
757 columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
760 .fail( function( jqXHR, textStatus ) {
761 self.setError( textStatus );
766 av = _.extend( {}, media, {
767 action: 'parse-media-shortcode',
769 initialize: function() {
774 this.shortcode = wp.media.embed.shortcode( {
779 wp.ajax.post( this.action, {
781 type: this.shortcode.tag,
782 shortcode: this.shortcode.string()
784 .done( function( response ) {
785 self.render( response );
787 .fail( function( response ) {
789 self.removeMarkers();
791 self.setError( response.message || response.statusText, 'admin-media' );
795 this.getEditors( function( editor ) {
796 editor.on( 'wpview-selected', function() {
802 pausePlayers: function() {
803 this.getNodes( function( editor, node, content ) {
804 var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
806 if ( win && ( win = win.contentWindow ) && win.mejs ) {
807 _.each( win.mejs.players, function( player ) {
817 embed = _.extend( {}, av, {
818 action: 'parse-embed',
820 edit: function( text, update ) {
821 var media = wp.media.embed,
822 frame = media.edit( text, this.url ),
827 frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
828 if ( url && model.get( 'url' ) ) {
829 frame.state( 'embed' ).metadata = model.toJSON();
833 frame.state( 'embed' ).on( 'select', function() {
834 var data = frame.state( 'embed' ).metadata;
839 update( media.shortcode( data ).string() );
843 frame.on( 'close', function() {
851 views.register( 'gallery', _.extend( {}, gallery ) );
853 views.register( 'audio', _.extend( {}, av, {
854 state: [ 'audio-details' ]
857 views.register( 'video', _.extend( {}, av, {
858 state: [ 'video-details' ]
861 views.register( 'playlist', _.extend( {}, av, {
862 state: [ 'playlist-edit', 'video-playlist-edit' ]
865 views.register( 'embed', _.extend( {}, embed ) );
867 views.register( 'embedURL', _.extend( {}, embed, {
868 match: function( content ) {
869 var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
870 match = re.exec( content );
874 index: match.index + match[1].length,
883 } )( window, window.wp.mce.views, window.jQuery );