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 } ],
99 _.each( views, function( view, type ) {
100 current = pieces.slice();
103 _.each( current, function( piece ) {
104 var remaining = piece.content,
107 // Ignore processed pieces, but retain their location.
108 if ( piece.processed ) {
109 pieces.push( piece );
113 // Iterate through the string progressively matching views
114 // and slicing the string as we go.
115 while ( remaining && ( result = view.prototype.match( remaining ) ) ) {
116 // Any text before the match becomes an unprocessed piece.
117 if ( result.index ) {
118 pieces.push( { content: remaining.substring( 0, result.index ) } );
121 instance = self.createInstance( type, result.content, result.options );
123 // Add the processed piece for the match.
125 content: '<p data-wpview-marker="' + instance.encodedText + '">' + instance.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 return _.pluck( pieces, 'content' ).join( '' );
145 * Create a view instance.
147 * @param {String} type The view type.
148 * @param {String} text The textual representation of the view.
149 * @param {Object} options Options.
151 * @return {wp.mce.View} The view instance.
153 createInstance: function( type, text, options ) {
154 var View = this.get( type ),
158 text = tinymce.DOM.decode( text ),
159 encodedText = encodeURIComponent( text ),
160 instance = this.getInstance( encodedText );
166 options = _.extend( options || {}, {
168 encodedText: encodedText
171 return instances[ encodedText ] = new View( options );
175 * Get a view instance.
177 * @param {(String|HTMLElement)} object The textual representation of the view or the view node.
179 * @return {wp.mce.View} The view instance or undefined.
181 getInstance: function( object ) {
182 if ( typeof object === 'string' ) {
183 return instances[ encodeURIComponent( object ) ];
186 return instances[ $( object ).attr( 'data-wpview-text' ) ];
190 * Given a view node, get the view's text.
192 * @param {HTMLElement} node The view node.
194 * @return {String} The textual representation of the view.
196 getText: function( node ) {
197 return decodeURIComponent( $( node ).attr( 'data-wpview-text' ) || '' );
201 * Renders all view nodes that are not yet rendered.
203 * @param {Boolean} force Rerender all view nodes.
205 render: function( force ) {
206 _.each( instances, function( instance ) {
207 instance.render( force );
212 * Update the text of a given view node.
214 * @param {String} text The new text.
215 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
216 * @param {HTMLElement} node The view node to update.
218 update: function( text, editor, node ) {
219 var instance = this.getInstance( node );
222 instance.update( text, editor, node );
227 * Renders any editing interface based on the view type.
229 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
230 * @param {HTMLElement} node The view node to edit.
232 edit: function( editor, node ) {
233 var instance = this.getInstance( node );
235 if ( instance && instance.edit ) {
236 instance.edit( instance.text, function( text ) {
237 instance.update( text, editor, node );
243 * Remove a given view node from the DOM.
245 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
246 * @param {HTMLElement} node The view node to remove.
248 remove: function( editor, node ) {
249 var instance = this.getInstance( node );
252 instance.remove( editor, node );
258 * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
259 * The main difference is that the TinyMCE View is not tied to a particular DOM node.
261 * @param {Object} options Options.
263 wp.mce.View = function( options ) {
264 _.extend( this, options );
268 wp.mce.View.extend = Backbone.View.extend;
270 _.extend( wp.mce.View.prototype, {
280 * Whether or not to display a loader.
287 * Runs after the view instance is created.
289 initialize: function() {},
292 * Retuns the content to render in the view node.
296 getContent: function() {
301 * Renders all view nodes tied to this view instance that are not yet rendered.
303 * @param {String} content The content to render. Optional.
304 * @param {Boolean} force Rerender all view nodes tied to this view instance.
306 render: function( content, force ) {
307 if ( content != null ) {
308 this.content = content;
311 content = this.getContent();
313 // If there's nothing to render an no loader needs to be shown, stop.
314 if ( ! this.loader && ! content ) {
318 // We're about to rerender all views of this instance, so unbind rendered views.
319 force && this.unbind();
321 // Replace any left over markers.
322 this.replaceMarkers();
325 this.setContent( content, function( editor, node, contentNode ) {
326 $( node ).data( 'rendered', true );
327 this.bindNode.call( this, editor, node, contentNode );
328 }, force ? null : false );
335 * Binds a given node after its content is added to the DOM.
337 bindNode: function() {},
340 * Unbinds a given node before its content is removed from the DOM.
342 unbindNode: function() {},
345 * Unbinds all view nodes tied to this view instance.
346 * Runs before their content is removed from the DOM.
349 this.getNodes( function( editor, node, contentNode ) {
350 this.unbindNode.call( this, editor, node, contentNode );
351 $( node ).trigger( 'wp-mce-view-unbind' );
356 * Gets all the TinyMCE editor instances that support views.
358 * @param {Function} callback A callback.
360 getEditors: function( callback ) {
361 _.each( tinymce.editors, function( editor ) {
362 if ( editor.plugins.wpview ) {
363 callback.call( this, editor );
369 * Gets all view nodes tied to this view instance.
371 * @param {Function} callback A callback.
372 * @param {Boolean} rendered Get (un)rendered view nodes. Optional.
374 getNodes: function( callback, rendered ) {
375 this.getEditors( function( editor ) {
378 $( editor.getBody() )
379 .find( '[data-wpview-text="' + self.encodedText + '"]' )
380 .filter( function() {
383 if ( rendered == null ) {
387 data = $( this ).data( 'rendered' ) === true;
389 return rendered ? data : ! data;
392 callback.call( self, editor, this, $( this ).find( '.wpview-content' ).get( 0 ) );
398 * Gets all marker nodes tied to this view instance.
400 * @param {Function} callback A callback.
402 getMarkers: function( callback ) {
403 this.getEditors( function( editor ) {
406 $( editor.getBody() )
407 .find( '[data-wpview-marker="' + this.encodedText + '"]' )
409 callback.call( self, editor, this );
415 * Replaces all marker nodes tied to this view instance.
417 replaceMarkers: function() {
418 this.getMarkers( function( editor, node ) {
419 if ( $( node ).text() !== this.text ) {
420 editor.dom.setAttrib( node, 'data-wpview-marker', null );
425 editor.dom.createFragment(
426 '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
427 '<p class="wpview-selection-before">\u00a0</p>' +
428 '<div class="wpview-body" contenteditable="false">' +
429 '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
431 '<p class="wpview-selection-after">\u00a0</p>' +
440 * Removes all marker nodes tied to this view instance.
442 removeMarkers: function() {
443 this.getMarkers( function( editor, node ) {
444 editor.dom.setAttrib( node, 'data-wpview-marker', null );
449 * Sets the content for all view nodes tied to this view instance.
451 * @param {*} content The content to set.
452 * @param {Function} callback A callback. Optional.
453 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
455 setContent: function( content, callback, rendered ) {
456 if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
457 this.setIframes( content.head || '', content.body, callback, rendered );
458 } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
459 this.setIframes( '', content, callback, rendered );
461 this.getNodes( function( editor, node, contentNode ) {
462 content = content.body || content;
464 if ( content.indexOf( '<iframe' ) !== -1 ) {
465 content += '<div class="wpview-overlay"></div>';
468 contentNode.innerHTML = '';
469 contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
471 callback && callback.call( this, editor, node, contentNode );
477 * Sets the content in an iframe for all view nodes tied to this view instance.
479 * @param {String} head HTML string to be added to the head of the document.
480 * @param {String} body HTML string to be added to the body of the document.
481 * @param {Function} callback A callback. Optional.
482 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
484 setIframes: function( head, body, callback, rendered ) {
485 var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
488 this.getNodes( function( editor, node, contentNode ) {
489 var dom = editor.dom,
491 bodyClasses = editor.getBody().className || '',
492 editorHead = editor.getDoc().getElementsByTagName( 'head' )[0];
494 tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
495 if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
496 link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
498 styles += dom.getOuterHTML( link );
502 // Seems the browsers need a bit of time to insert/set the view nodes,
503 // or the iframe will fail especially when switching Text => Visual.
504 setTimeout( function() {
505 var iframe, iframeDoc, observer, i;
507 contentNode.innerHTML = '';
509 iframe = dom.add( contentNode, 'iframe', {
510 /* jshint scripturl: true */
511 src: tinymce.Env.ie ? 'javascript:""' : '',
513 allowTransparency: 'true',
515 'class': 'wpview-sandbox',
522 dom.add( contentNode, 'div', { 'class': 'wpview-overlay' } );
524 iframeDoc = iframe.contentWindow.document;
532 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
537 'background: transparent;' +
541 'body#wpview-iframe-sandbox {' +
542 'background: transparent;' +
543 'padding: 1px 0 !important;' +
544 'margin: -1px 0 0 !important;' +
546 'body#wpview-iframe-sandbox:before,' +
547 'body#wpview-iframe-sandbox:after {' +
553 '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
562 var $iframe, iframeDocHeight;
564 // Make sure the iframe still exists.
565 if ( iframe.contentWindow ) {
566 $iframe = $( iframe );
567 iframeDocHeight = $( iframeDoc.body ).height();
569 if ( $iframe.height() !== iframeDocHeight ) {
570 $iframe.height( iframeDocHeight );
571 editor.nodeChanged();
576 $( iframe.contentWindow ).on( 'load', resize );
578 if ( MutationObserver ) {
579 observer = new MutationObserver( _.debounce( resize, 100 ) );
581 observer.observe( iframeDoc.body, {
587 $( node ).one( 'wp-mce-view-unbind', function() {
588 observer.disconnect();
591 for ( i = 1; i < 6; i++ ) {
592 setTimeout( resize, i * 700 );
596 function classChange() {
597 iframeDoc.body.className = editor.getBody().className;
600 editor.on( 'wp-body-class-change', classChange );
602 $( node ).one( 'wp-mce-view-unbind', function() {
603 editor.off( 'wp-body-class-change', classChange );
606 callback && callback.call( self, editor, node, contentNode );
612 * Sets a loader for all view nodes tied to this view instance.
614 setLoader: function() {
616 '<div class="loading-placeholder">' +
617 '<div class="dashicons dashicons-admin-media"></div>' +
618 '<div class="wpview-loading"><ins></ins></div>' +
624 * Sets an error for all view nodes tied to this view instance.
626 * @param {String} message The error message to set.
627 * @param {String} dashicon A dashicon ID (optional). {@link https://developer.wordpress.org/resource/dashicons/}
629 setError: function( message, dashicon ) {
631 '<div class="wpview-error">' +
632 '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
633 '<p>' + message + '</p>' +
639 * Tries to find a text match in a given string.
641 * @param {String} content The string to scan.
645 match: function( content ) {
646 var match = wp.shortcode.next( this.type, content );
651 content: match.content,
653 shortcode: match.shortcode
660 * Update the text of a given view node.
662 * @param {String} text The new text.
663 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
664 * @param {HTMLElement} node The view node to update.
666 update: function( text, editor, node ) {
667 _.find( views, function( view, type ) {
668 var match = view.prototype.match( text );
671 $( node ).data( 'rendered', false );
672 editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
673 wp.mce.views.createInstance( type, text, match.options ).render();
682 * Remove a given view node from the DOM.
684 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
685 * @param {HTMLElement} node The view node to remove.
687 remove: function( editor, node ) {
688 this.unbindNode.call( this, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
689 $( node ).trigger( 'wp-mce-view-unbind' );
690 editor.dom.remove( node );
694 } )( window, window.wp, window.jQuery );
697 * The WordPress core TinyMCE views.
698 * Views for the gallery, audio, video, playlist and embed shortcodes,
699 * and a view for embeddable URLs.
701 ( function( window, views, $ ) {
702 var postID = $( '#post_ID' ).val() || 0,
703 media, gallery, av, embed;
708 edit: function( text, update ) {
709 var media = wp.media[ this.type ],
710 frame = media.edit( text );
712 this.pausePlayers && this.pausePlayers();
714 _.each( this.state, function( state ) {
715 frame.state( state ).on( 'update', function( selection ) {
716 update( media.shortcode( selection ).string() );
720 frame.on( 'close', function() {
728 gallery = _.extend( {}, media, {
729 state: [ 'gallery-edit' ],
730 template: wp.media.template( 'editor-gallery' ),
732 initialize: function() {
733 var attachments = wp.media.gallery.attachments( this.shortcode, postID ),
734 attrs = this.shortcode.attrs.named,
739 attachments = attachments.toJSON();
741 _.each( attachments, function( attachment ) {
742 if ( attachment.sizes ) {
743 if ( attrs.size && attachment.sizes[ attrs.size ] ) {
744 attachment.thumbnail = attachment.sizes[ attrs.size ];
745 } else if ( attachment.sizes.thumbnail ) {
746 attachment.thumbnail = attachment.sizes.thumbnail;
747 } else if ( attachment.sizes.full ) {
748 attachment.thumbnail = attachment.sizes.full;
753 self.render( self.template( {
754 attachments: attachments,
755 columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns
758 .fail( function( jqXHR, textStatus ) {
759 self.setError( textStatus );
764 av = _.extend( {}, media, {
765 action: 'parse-media-shortcode',
767 initialize: function() {
772 this.shortcode = wp.media.embed.shortcode( {
777 wp.ajax.post( this.action, {
779 type: this.shortcode.tag,
780 shortcode: this.shortcode.string()
782 .done( function( response ) {
783 self.render( response );
785 .fail( function( response ) {
787 self.removeMarkers();
789 self.setError( response.message || response.statusText, 'admin-media' );
793 this.getEditors( function( editor ) {
794 editor.on( 'wpview-selected', function() {
800 pausePlayers: function() {
801 this.getNodes( function( editor, node, content ) {
802 var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
804 if ( win && ( win = win.contentWindow ) && win.mejs ) {
805 _.each( win.mejs.players, function( player ) {
815 embed = _.extend( {}, av, {
816 action: 'parse-embed',
818 edit: function( text, update ) {
819 var media = wp.media.embed,
820 frame = media.edit( text, this.url ),
825 frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
826 if ( url && model.get( 'url' ) ) {
827 frame.state( 'embed' ).metadata = model.toJSON();
831 frame.state( 'embed' ).on( 'select', function() {
832 var data = frame.state( 'embed' ).metadata;
837 update( media.shortcode( data ).string() );
841 frame.on( 'close', function() {
849 views.register( 'gallery', _.extend( {}, gallery ) );
851 views.register( 'audio', _.extend( {}, av, {
852 state: [ 'audio-details' ]
855 views.register( 'video', _.extend( {}, av, {
856 state: [ 'video-details' ]
859 views.register( 'playlist', _.extend( {}, av, {
860 state: [ 'playlist-edit', 'video-playlist-edit' ]
863 views.register( 'embed', _.extend( {}, embed ) );
865 views.register( 'embedURL', _.extend( {}, embed, {
866 match: function( content ) {
867 var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
868 match = re.exec( content );
872 index: match.index + match[1].length,
881 } )( window, window.wp.mce.views, window.jQuery );