4 * The TinyMCE view API.
6 * Note: this API is "experimental" meaning that it will probably change
7 * in the next few releases based on feedback from 3.9.0.
8 * If you decide to use it, please follow the development closely.
12 * |- registered view constructor (type)
13 * | |- view instance (unique text)
25 ( function( window, wp, shortcode, $ ) {
31 wp.mce = wp.mce || {};
36 * A set of utilities that simplifies adding custom UI within a TinyMCE editor.
37 * At its core, it serves as a series of converters, transforming text to a
38 * custom UI, and back again.
43 * Registers a new view type.
45 * @param {String} type The view type.
46 * @param {Object} extend An object to extend wp.mce.View.prototype with.
48 register: function( type, extend ) {
49 views[ type ] = wp.mce.View.extend( _.extend( extend, { type: type } ) );
53 * Unregisters a view type.
55 * @param {String} type The view type.
57 unregister: function( type ) {
62 * Returns the settings of a view type.
64 * @param {String} type The view type.
66 * @return {Function} The view constructor.
68 get: function( type ) {
73 * Unbinds all view nodes.
74 * Runs before removing all view nodes from the DOM.
77 _.each( instances, function( instance ) {
83 * Scans a given string for each view's pattern,
84 * replacing any matches with markers,
85 * and creates a new instance for every match.
87 * @param {String} content The string to scan.
89 * @return {String} The string with markers.
91 setMarkers: function( content ) {
92 var pieces = [ { content: content } ],
96 _.each( views, function( view, type ) {
97 current = pieces.slice();
100 _.each( current, function( piece ) {
101 var remaining = piece.content,
104 // Ignore processed pieces, but retain their location.
105 if ( piece.processed ) {
106 pieces.push( piece );
110 // Iterate through the string progressively matching views
111 // and slicing the string as we go.
112 while ( remaining && ( result = view.prototype.match( remaining ) ) ) {
113 // Any text before the match becomes an unprocessed piece.
114 if ( result.index ) {
115 pieces.push( { content: remaining.substring( 0, result.index ) } );
118 instance = self.createInstance( type, result.content, result.options );
119 text = instance.loader ? '.' : instance.text;
121 // Add the processed piece for the match.
123 content: instance.ignore ? text : '<p data-wpview-marker="' + instance.encodedText + '">' + text + '</p>',
127 // Update the remaining content.
128 remaining = remaining.slice( result.index + result.content.length );
131 // There are no additional matches.
132 // If any content remains, add it as an unprocessed piece.
134 pieces.push( { content: remaining } );
139 content = _.pluck( pieces, 'content' ).join( '' );
140 return content.replace( /<p>\s*<p data-wpview-marker=/g, '<p data-wpview-marker=' ).replace( /<\/p>\s*<\/p>/g, '</p>' );
144 * Create a view instance.
146 * @param {String} type The view type.
147 * @param {String} text The textual representation of the view.
148 * @param {Object} options Options.
149 * @param {Boolean} force Recreate the instance. Optional.
151 * @return {wp.mce.View} The view instance.
153 createInstance: function( type, text, options, force ) {
154 var View = this.get( type ),
158 text = tinymce.DOM.decode( text );
161 instance = this.getInstance( text );
168 encodedText = encodeURIComponent( text );
170 options = _.extend( options || {}, {
172 encodedText: encodedText
175 return instances[ encodedText ] = new View( options );
179 * Get a view instance.
181 * @param {(String|HTMLElement)} object The textual representation of the view or the view node.
183 * @return {wp.mce.View} The view instance or undefined.
185 getInstance: function( object ) {
186 if ( typeof object === 'string' ) {
187 return instances[ encodeURIComponent( object ) ];
190 return instances[ $( object ).attr( 'data-wpview-text' ) ];
194 * Given a view node, get the view's text.
196 * @param {HTMLElement} node The view node.
198 * @return {String} The textual representation of the view.
200 getText: function( node ) {
201 return decodeURIComponent( $( node ).attr( 'data-wpview-text' ) || '' );
205 * Renders all view nodes that are not yet rendered.
207 * @param {Boolean} force Rerender all view nodes.
209 render: function( force ) {
210 _.each( instances, function( instance ) {
211 instance.render( force );
216 * Update the text of a given view node.
218 * @param {String} text The new text.
219 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
220 * @param {HTMLElement} node The view node to update.
221 * @param {Boolean} force Recreate the instance. Optional.
223 update: function( text, editor, node, force ) {
224 var instance = this.getInstance( node );
227 instance.update( text, editor, node, force );
232 * Renders any editing interface based on the view type.
234 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
235 * @param {HTMLElement} node The view node to edit.
237 edit: function( editor, node ) {
238 var instance = this.getInstance( node );
240 if ( instance && instance.edit ) {
241 instance.edit( instance.text, function( text, force ) {
242 instance.update( text, editor, node, force );
248 * Remove a given view node from the DOM.
250 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
251 * @param {HTMLElement} node The view node to remove.
253 remove: function( editor, node ) {
254 var instance = this.getInstance( node );
257 instance.remove( editor, node );
263 * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
264 * The main difference is that the TinyMCE View is not tied to a particular DOM node.
266 * @param {Object} options Options.
268 wp.mce.View = function( options ) {
269 _.extend( this, options );
273 wp.mce.View.extend = Backbone.View.extend;
275 _.extend( wp.mce.View.prototype, {
285 * Whether or not to display a loader.
292 * Runs after the view instance is created.
294 initialize: function() {},
297 * Retuns the content to render in the view node.
301 getContent: function() {
306 * Renders all view nodes tied to this view instance that are not yet rendered.
308 * @param {String} content The content to render. Optional.
309 * @param {Boolean} force Rerender all view nodes tied to this view instance. Optional.
311 render: function( content, force ) {
312 if ( content != null ) {
313 this.content = content;
316 content = this.getContent();
318 // If there's nothing to render an no loader needs to be shown, stop.
319 if ( ! this.loader && ! content ) {
323 // We're about to rerender all views of this instance, so unbind rendered views.
324 force && this.unbind();
326 // Replace any left over markers.
327 this.replaceMarkers();
330 this.setContent( content, function( editor, node, contentNode ) {
331 $( node ).data( 'rendered', true );
332 this.bindNode.call( this, editor, node, contentNode );
333 }, force ? null : false );
340 * Binds a given node after its content is added to the DOM.
342 bindNode: function() {},
345 * Unbinds a given node before its content is removed from the DOM.
347 unbindNode: function() {},
350 * Unbinds all view nodes tied to this view instance.
351 * Runs before their content is removed from the DOM.
354 this.getNodes( function( editor, node, contentNode ) {
355 this.unbindNode.call( this, editor, node, contentNode );
356 $( node ).trigger( 'wp-mce-view-unbind' );
361 * Gets all the TinyMCE editor instances that support views.
363 * @param {Function} callback A callback.
365 getEditors: function( callback ) {
366 _.each( tinymce.editors, function( editor ) {
367 if ( editor.plugins.wpview ) {
368 callback.call( this, editor );
374 * Gets all view nodes tied to this view instance.
376 * @param {Function} callback A callback.
377 * @param {Boolean} rendered Get (un)rendered view nodes. Optional.
379 getNodes: function( callback, rendered ) {
380 this.getEditors( function( editor ) {
383 $( editor.getBody() )
384 .find( '[data-wpview-text="' + self.encodedText + '"]' )
385 .filter( function() {
388 if ( rendered == null ) {
392 data = $( this ).data( 'rendered' ) === true;
394 return rendered ? data : ! data;
397 callback.call( self, editor, this, $( this ).find( '.wpview-content' ).get( 0 ) );
403 * Gets all marker nodes tied to this view instance.
405 * @param {Function} callback A callback.
407 getMarkers: function( callback ) {
408 this.getEditors( function( editor ) {
411 $( editor.getBody() )
412 .find( '[data-wpview-marker="' + this.encodedText + '"]' )
414 callback.call( self, editor, this );
420 * Replaces all marker nodes tied to this view instance.
422 replaceMarkers: function() {
423 this.getMarkers( function( editor, node ) {
424 var selected = node === editor.selection.getNode(),
427 if ( ! this.loader && $( node ).text() !== this.text ) {
428 editor.dom.setAttrib( node, 'data-wpview-marker', null );
432 $viewNode = editor.$(
433 '<div class="wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '">' +
434 '<p class="wpview-selection-before">\u00a0</p>' +
435 '<div class="wpview-body" contenteditable="false">' +
436 '<div class="wpview-content wpview-type-' + this.type + '"></div>' +
438 '<p class="wpview-selection-after">\u00a0</p>' +
442 editor.$( node ).replaceWith( $viewNode );
445 editor.wp.setViewCursor( false, $viewNode[0] );
451 * Removes all marker nodes tied to this view instance.
453 removeMarkers: function() {
454 this.getMarkers( function( editor, node ) {
455 editor.dom.setAttrib( node, 'data-wpview-marker', null );
460 * Sets the content for all view nodes tied to this view instance.
462 * @param {*} content The content to set.
463 * @param {Function} callback A callback. Optional.
464 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
466 setContent: function( content, callback, rendered ) {
467 if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
468 this.setIframes( content.head || '', content.body, callback, rendered );
469 } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
470 this.setIframes( '', content, callback, rendered );
472 this.getNodes( function( editor, node, contentNode ) {
473 content = content.body || content;
475 if ( content.indexOf( '<iframe' ) !== -1 ) {
476 content += '<div class="wpview-overlay"></div>';
479 contentNode.innerHTML = '';
480 contentNode.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
482 callback && callback.call( this, editor, node, contentNode );
488 * Sets the content in an iframe for all view nodes tied to this view instance.
490 * @param {String} head HTML string to be added to the head of the document.
491 * @param {String} body HTML string to be added to the body of the document.
492 * @param {Function} callback A callback. Optional.
493 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
495 setIframes: function( head, body, callback, rendered ) {
496 var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
499 this.getNodes( function( editor, node, contentNode ) {
500 var dom = editor.dom,
502 bodyClasses = editor.getBody().className || '',
503 editorHead = editor.getDoc().getElementsByTagName( 'head' )[0];
505 tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
506 if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
507 link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
509 styles += dom.getOuterHTML( link );
513 if ( self.iframeHeight ) {
514 dom.add( contentNode, 'div', { style: {
516 height: self.iframeHeight
520 // Seems the browsers need a bit of time to insert/set the view nodes,
521 // or the iframe will fail especially when switching Text => Visual.
522 setTimeout( function() {
523 var iframe, iframeDoc, observer, i, block;
525 contentNode.innerHTML = '';
527 iframe = dom.add( contentNode, 'iframe', {
528 /* jshint scripturl: true */
529 src: tinymce.Env.ie ? 'javascript:""' : '',
531 allowTransparency: 'true',
533 'class': 'wpview-sandbox',
538 height: self.iframeHeight
541 dom.add( contentNode, 'div', { 'class': 'wpview-overlay' } );
543 iframeDoc = iframe.contentWindow.document;
551 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
556 'background: transparent;' +
560 'body#wpview-iframe-sandbox {' +
561 'background: transparent;' +
562 'padding: 1px 0 !important;' +
563 'margin: -1px 0 0 !important;' +
565 'body#wpview-iframe-sandbox:before,' +
566 'body#wpview-iframe-sandbox:after {' +
572 '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
587 // Make sure the iframe still exists.
588 if ( iframe.contentWindow ) {
589 $iframe = $( iframe );
590 self.iframeHeight = $( iframeDoc.body ).height();
592 if ( $iframe.height() !== self.iframeHeight ) {
593 $iframe.height( self.iframeHeight );
594 editor.nodeChanged();
599 if ( self.iframeHeight ) {
602 setTimeout( function() {
608 $( iframe.contentWindow ).on( 'load', resize );
610 if ( MutationObserver ) {
611 observer = new MutationObserver( _.debounce( resize, 100 ) );
613 observer.observe( iframeDoc.body, {
619 $( node ).one( 'wp-mce-view-unbind', function() {
620 observer.disconnect();
623 for ( i = 1; i < 6; i++ ) {
624 setTimeout( resize, i * 700 );
628 function classChange() {
629 iframeDoc.body.className = editor.getBody().className;
632 editor.on( 'wp-body-class-change', classChange );
634 $( node ).one( 'wp-mce-view-unbind', function() {
635 editor.off( 'wp-body-class-change', classChange );
638 callback && callback.call( self, editor, node, contentNode );
644 * Sets a loader for all view nodes tied to this view instance.
646 setLoader: function() {
648 '<div class="loading-placeholder">' +
649 '<div class="dashicons dashicons-admin-media"></div>' +
650 '<div class="wpview-loading"><ins></ins></div>' +
656 * Sets an error for all view nodes tied to this view instance.
658 * @param {String} message The error message to set.
659 * @param {String} dashicon A dashicon ID. Optional. {@link https://developer.wordpress.org/resource/dashicons/}
661 setError: function( message, dashicon ) {
663 '<div class="wpview-error">' +
664 '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
665 '<p>' + message + '</p>' +
671 * Tries to find a text match in a given string.
673 * @param {String} content The string to scan.
677 match: function( content ) {
678 var match = shortcode.next( this.type, content );
683 content: match.content,
685 shortcode: match.shortcode
692 * Update the text of a given view node.
694 * @param {String} text The new text.
695 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
696 * @param {HTMLElement} node The view node to update.
697 * @param {Boolean} force Recreate the instance. Optional.
699 update: function( text, editor, node, force ) {
700 _.find( views, function( view, type ) {
701 var match = view.prototype.match( text );
704 $( node ).data( 'rendered', false );
705 editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
706 wp.mce.views.createInstance( type, text, match.options, force ).render();
715 * Remove a given view node from the DOM.
717 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
718 * @param {HTMLElement} node The view node to remove.
720 remove: function( editor, node ) {
721 this.unbindNode.call( this, editor, node, $( node ).find( '.wpview-content' ).get( 0 ) );
722 $( node ).trigger( 'wp-mce-view-unbind' );
723 editor.dom.remove( node );
727 } )( window, window.wp, window.wp.shortcode, window.jQuery );
730 * The WordPress core TinyMCE views.
731 * Views for the gallery, audio, video, playlist and embed shortcodes,
732 * and a view for embeddable URLs.
734 ( function( window, views, media, $ ) {
735 var base, gallery, av, embed,
736 schema, parser, serializer;
738 function verifyHTML( string ) {
741 if ( ! window.tinymce ) {
742 return string.replace( /<[^>]+>/g, '' );
745 if ( ! string || ( string.indexOf( '<' ) === -1 && string.indexOf( '>' ) === -1 ) ) {
749 schema = schema || new window.tinymce.html.Schema( settings );
750 parser = parser || new window.tinymce.html.DomParser( settings, schema );
751 serializer = serializer || new window.tinymce.html.Serializer( settings, schema );
753 return serializer.serialize( parser.parse( string, { forced_root_block: false } ) );
759 edit: function( text, update ) {
760 var type = this.type,
761 frame = media[ type ].edit( text );
763 this.pausePlayers && this.pausePlayers();
765 _.each( this.state, function( state ) {
766 frame.state( state ).on( 'update', function( selection ) {
767 update( media[ type ].shortcode( selection ).string(), type === 'gallery' );
771 frame.on( 'close', function() {
779 gallery = _.extend( {}, base, {
780 state: [ 'gallery-edit' ],
781 template: media.template( 'editor-gallery' ),
783 initialize: function() {
784 var attachments = media.gallery.attachments( this.shortcode, media.view.settings.post.id ),
785 attrs = this.shortcode.attrs.named,
790 attachments = attachments.toJSON();
792 _.each( attachments, function( attachment ) {
793 if ( attachment.sizes ) {
794 if ( attrs.size && attachment.sizes[ attrs.size ] ) {
795 attachment.thumbnail = attachment.sizes[ attrs.size ];
796 } else if ( attachment.sizes.thumbnail ) {
797 attachment.thumbnail = attachment.sizes.thumbnail;
798 } else if ( attachment.sizes.full ) {
799 attachment.thumbnail = attachment.sizes.full;
804 self.render( self.template( {
805 verifyHTML: verifyHTML,
806 attachments: attachments,
807 columns: attrs.columns ? parseInt( attrs.columns, 10 ) : media.galleryDefaults.columns
810 .fail( function( jqXHR, textStatus ) {
811 self.setError( textStatus );
816 av = _.extend( {}, base, {
817 action: 'parse-media-shortcode',
819 initialize: function() {
824 this.shortcode = media.embed.shortcode( {
829 wp.ajax.post( this.action, {
830 post_ID: media.view.settings.post.id,
831 type: this.shortcode.tag,
832 shortcode: this.shortcode.string()
834 .done( function( response ) {
835 self.render( response );
837 .fail( function( response ) {
840 self.removeMarkers();
842 self.setError( response.message || response.statusText, 'admin-media' );
846 this.getEditors( function( editor ) {
847 editor.on( 'wpview-selected', function() {
853 pausePlayers: function() {
854 this.getNodes( function( editor, node, content ) {
855 var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
857 if ( win && ( win = win.contentWindow ) && win.mejs ) {
858 _.each( win.mejs.players, function( player ) {
868 embed = _.extend( {}, av, {
869 action: 'parse-embed',
871 edit: function( text, update ) {
872 var frame = media.embed.edit( text, this.url ),
877 frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
878 if ( url && model.get( 'url' ) ) {
879 frame.state( 'embed' ).metadata = model.toJSON();
883 frame.state( 'embed' ).on( 'select', function() {
884 var data = frame.state( 'embed' ).metadata;
889 update( media.embed.shortcode( data ).string() );
893 frame.on( 'close', function() {
901 views.register( 'gallery', _.extend( {}, gallery ) );
903 views.register( 'audio', _.extend( {}, av, {
904 state: [ 'audio-details' ]
907 views.register( 'video', _.extend( {}, av, {
908 state: [ 'video-details' ]
911 views.register( 'playlist', _.extend( {}, av, {
912 state: [ 'playlist-edit', 'video-playlist-edit' ]
915 views.register( 'embed', _.extend( {}, embed ) );
917 views.register( 'embedURL', _.extend( {}, embed, {
918 match: function( content ) {
919 var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
920 match = re.exec( content );
924 index: match.index + match[1].length,
933 } )( window, window.wp.mce.views, window.wp.media, window.jQuery );