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 );
160 if ( text.indexOf( '[' ) !== -1 && text.indexOf( ']' ) !== -1 ) {
161 // Looks like a shortcode? Remove any line breaks from inside of shortcodes
162 // or autop will replace them with <p> and <br> later and the string won't match.
163 text = text.replace( /\[[^\]]+\]/g, function( match ) {
164 return match.replace( /[\r\n]/g, '' );
169 instance = this.getInstance( text );
176 encodedText = encodeURIComponent( text );
178 options = _.extend( options || {}, {
180 encodedText: encodedText
183 return instances[ encodedText ] = new View( options );
187 * Get a view instance.
189 * @param {(String|HTMLElement)} object The textual representation of the view or the view node.
191 * @return {wp.mce.View} The view instance or undefined.
193 getInstance: function( object ) {
194 if ( typeof object === 'string' ) {
195 return instances[ encodeURIComponent( object ) ];
198 return instances[ $( object ).attr( 'data-wpview-text' ) ];
202 * Given a view node, get the view's text.
204 * @param {HTMLElement} node The view node.
206 * @return {String} The textual representation of the view.
208 getText: function( node ) {
209 return decodeURIComponent( $( node ).attr( 'data-wpview-text' ) || '' );
213 * Renders all view nodes that are not yet rendered.
215 * @param {Boolean} force Rerender all view nodes.
217 render: function( force ) {
218 _.each( instances, function( instance ) {
219 instance.render( null, force );
224 * Update the text of a given view node.
226 * @param {String} text The new text.
227 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
228 * @param {HTMLElement} node The view node to update.
229 * @param {Boolean} force Recreate the instance. Optional.
231 update: function( text, editor, node, force ) {
232 var instance = this.getInstance( node );
235 instance.update( text, editor, node, force );
240 * Renders any editing interface based on the view type.
242 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
243 * @param {HTMLElement} node The view node to edit.
245 edit: function( editor, node ) {
246 var instance = this.getInstance( node );
248 if ( instance && instance.edit ) {
249 instance.edit( instance.text, function( text, force ) {
250 instance.update( text, editor, node, force );
256 * Remove a given view node from the DOM.
258 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
259 * @param {HTMLElement} node The view node to remove.
261 remove: function( editor, node ) {
262 var instance = this.getInstance( node );
265 instance.remove( editor, node );
271 * A Backbone-like View constructor intended for use when rendering a TinyMCE View.
272 * The main difference is that the TinyMCE View is not tied to a particular DOM node.
274 * @param {Object} options Options.
276 wp.mce.View = function( options ) {
277 _.extend( this, options );
281 wp.mce.View.extend = Backbone.View.extend;
283 _.extend( wp.mce.View.prototype, {
293 * Whether or not to display a loader.
300 * Runs after the view instance is created.
302 initialize: function() {},
305 * Returns the content to render in the view node.
309 getContent: function() {
314 * Renders all view nodes tied to this view instance that are not yet rendered.
316 * @param {String} content The content to render. Optional.
317 * @param {Boolean} force Rerender all view nodes tied to this view instance. Optional.
319 render: function( content, force ) {
320 if ( content != null ) {
321 this.content = content;
324 content = this.getContent();
326 // If there's nothing to render an no loader needs to be shown, stop.
327 if ( ! this.loader && ! content ) {
331 // We're about to rerender all views of this instance, so unbind rendered views.
332 force && this.unbind();
334 // Replace any left over markers.
335 this.replaceMarkers();
338 this.setContent( content, function( editor, node ) {
339 $( node ).data( 'rendered', true );
340 this.bindNode.call( this, editor, node );
341 }, force ? null : false );
348 * Binds a given node after its content is added to the DOM.
350 bindNode: function() {},
353 * Unbinds a given node before its content is removed from the DOM.
355 unbindNode: function() {},
358 * Unbinds all view nodes tied to this view instance.
359 * Runs before their content is removed from the DOM.
362 this.getNodes( function( editor, node ) {
363 this.unbindNode.call( this, editor, node );
368 * Gets all the TinyMCE editor instances that support views.
370 * @param {Function} callback A callback.
372 getEditors: function( callback ) {
373 _.each( tinymce.editors, function( editor ) {
374 if ( editor.plugins.wpview ) {
375 callback.call( this, editor );
381 * Gets all view nodes tied to this view instance.
383 * @param {Function} callback A callback.
384 * @param {Boolean} rendered Get (un)rendered view nodes. Optional.
386 getNodes: function( callback, rendered ) {
387 this.getEditors( function( editor ) {
390 $( editor.getBody() )
391 .find( '[data-wpview-text="' + self.encodedText + '"]' )
392 .filter( function() {
395 if ( rendered == null ) {
399 data = $( this ).data( 'rendered' ) === true;
401 return rendered ? data : ! data;
404 callback.call( self, editor, this, this /* back compat */ );
410 * Gets all marker nodes tied to this view instance.
412 * @param {Function} callback A callback.
414 getMarkers: function( callback ) {
415 this.getEditors( function( editor ) {
418 $( editor.getBody() )
419 .find( '[data-wpview-marker="' + this.encodedText + '"]' )
421 callback.call( self, editor, this );
427 * Replaces all marker nodes tied to this view instance.
429 replaceMarkers: function() {
430 this.getMarkers( function( editor, node ) {
433 if ( ! this.loader && $( node ).text() !== this.text ) {
434 editor.dom.setAttrib( node, 'data-wpview-marker', null );
438 $viewNode = editor.$(
439 '<div class="wpview wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '" contenteditable="false"></div>'
442 editor.$( node ).replaceWith( $viewNode );
447 * Removes all marker nodes tied to this view instance.
449 removeMarkers: function() {
450 this.getMarkers( function( editor, node ) {
451 editor.dom.setAttrib( node, 'data-wpview-marker', null );
456 * Sets the content for all view nodes tied to this view instance.
458 * @param {*} content The content to set.
459 * @param {Function} callback A callback. Optional.
460 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
462 setContent: function( content, callback, rendered ) {
463 if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
464 this.setIframes( content.head || '', content.body, callback, rendered );
465 } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
466 this.setIframes( '', content, callback, rendered );
468 this.getNodes( function( editor, node ) {
469 content = content.body || content;
471 if ( content.indexOf( '<iframe' ) !== -1 ) {
472 content += '<span class="mce-shim"></span>';
475 editor.undoManager.transact( function() {
477 node.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
478 editor.dom.add( node, 'span', { 'class': 'wpview-end' } );
481 callback && callback.call( this, editor, node );
487 * Sets the content in an iframe for all view nodes tied to this view instance.
489 * @param {String} head HTML string to be added to the head of the document.
490 * @param {String} body HTML string to be added to the body of the document.
491 * @param {Function} callback A callback. Optional.
492 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
494 setIframes: function( head, body, callback, rendered ) {
497 this.getNodes( function( editor, node ) {
498 var dom = editor.dom,
500 bodyClasses = editor.getBody().className || '',
501 editorHead = editor.getDoc().getElementsByTagName( 'head' )[0],
502 iframe, iframeWin, iframeDoc, MutationObserver, observer, i, block;
504 tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
505 if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
506 link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
508 styles += dom.getOuterHTML( link );
512 if ( self.iframeHeight ) {
513 dom.add( node, 'span', {
518 height: self.iframeHeight
523 editor.undoManager.transact( function() {
526 iframe = dom.add( node, 'iframe', {
527 /* jshint scripturl: true */
528 src: tinymce.Env.ie ? 'javascript:""' : '',
530 allowTransparency: 'true',
532 'class': 'wpview-sandbox',
537 height: self.iframeHeight
540 dom.add( node, 'span', { 'class': 'mce-shim' } );
541 dom.add( node, 'span', { 'class': 'wpview-end' } );
544 // Bail if the iframe node is not attached to the DOM.
545 // Happens when the view is dragged in the editor.
546 // There is a browser restriction when iframes are moved in the DOM. They get emptied.
547 // The iframe will be rerendered after dropping the view node at the new location.
548 if ( ! iframe.contentWindow ) {
552 iframeWin = iframe.contentWindow;
553 iframeDoc = iframeWin.document;
560 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
565 'background: transparent;' +
569 'body#wpview-iframe-sandbox {' +
570 'background: transparent;' +
571 'padding: 1px 0 !important;' +
572 'margin: -1px 0 0 !important;' +
574 'body#wpview-iframe-sandbox:before,' +
575 'body#wpview-iframe-sandbox:after {' +
581 '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
596 // Make sure the iframe still exists.
597 if ( iframe.contentWindow ) {
598 $iframe = $( iframe );
599 self.iframeHeight = $( iframeDoc.body ).height();
601 if ( $iframe.height() !== self.iframeHeight ) {
602 $iframe.height( self.iframeHeight );
603 editor.nodeChanged();
608 if ( self.iframeHeight ) {
611 setTimeout( function() {
618 $( node ).data( 'rendered', null );
620 setTimeout( function() {
621 wp.mce.views.render();
625 $( iframeWin ).on( 'load', resize ).on( 'unload', reload );
627 MutationObserver = iframeWin.MutationObserver || iframeWin.WebKitMutationObserver || iframeWin.MozMutationObserver;
629 if ( MutationObserver ) {
630 observer = new MutationObserver( _.debounce( resize, 100 ) );
632 observer.observe( iframeDoc.body, {
638 for ( i = 1; i < 6; i++ ) {
639 setTimeout( resize, i * 700 );
643 callback && callback.call( self, editor, node );
648 * Sets a loader for all view nodes tied to this view instance.
650 setLoader: function( dashicon ) {
652 '<div class="loading-placeholder">' +
653 '<div class="dashicons dashicons-' + ( dashicon || 'admin-media' ) + '"></div>' +
654 '<div class="wpview-loading"><ins></ins></div>' +
660 * Sets an error for all view nodes tied to this view instance.
662 * @param {String} message The error message to set.
663 * @param {String} dashicon A dashicon ID. Optional. {@link https://developer.wordpress.org/resource/dashicons/}
665 setError: function( message, dashicon ) {
667 '<div class="wpview-error">' +
668 '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
669 '<p>' + message + '</p>' +
675 * Tries to find a text match in a given string.
677 * @param {String} content The string to scan.
681 match: function( content ) {
682 var match = shortcode.next( this.type, content );
687 content: match.content,
689 shortcode: match.shortcode
696 * Update the text of a given view node.
698 * @param {String} text The new text.
699 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
700 * @param {HTMLElement} node The view node to update.
701 * @param {Boolean} force Recreate the instance. Optional.
703 update: function( text, editor, node, force ) {
704 _.find( views, function( view, type ) {
705 var match = view.prototype.match( text );
708 $( node ).data( 'rendered', false );
709 editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
710 wp.mce.views.createInstance( type, text, match.options, force ).render();
719 * Remove a given view node from the DOM.
721 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
722 * @param {HTMLElement} node The view node to remove.
724 remove: function( editor, node ) {
725 this.unbindNode.call( this, editor, node );
726 editor.dom.remove( node );
730 } )( window, window.wp, window.wp.shortcode, window.jQuery );
733 * The WordPress core TinyMCE views.
734 * Views for the gallery, audio, video, playlist and embed shortcodes,
735 * and a view for embeddable URLs.
737 ( function( window, views, media, $ ) {
738 var base, gallery, av, embed,
739 schema, parser, serializer;
741 function verifyHTML( string ) {
744 if ( ! window.tinymce ) {
745 return string.replace( /<[^>]+>/g, '' );
748 if ( ! string || ( string.indexOf( '<' ) === -1 && string.indexOf( '>' ) === -1 ) ) {
752 schema = schema || new window.tinymce.html.Schema( settings );
753 parser = parser || new window.tinymce.html.DomParser( settings, schema );
754 serializer = serializer || new window.tinymce.html.Serializer( settings, schema );
756 return serializer.serialize( parser.parse( string, { forced_root_block: false } ) );
762 edit: function( text, update ) {
763 var type = this.type,
764 frame = media[ type ].edit( text );
766 this.pausePlayers && this.pausePlayers();
768 _.each( this.state, function( state ) {
769 frame.state( state ).on( 'update', function( selection ) {
770 update( media[ type ].shortcode( selection ).string(), type === 'gallery' );
774 frame.on( 'close', function() {
782 gallery = _.extend( {}, base, {
783 state: [ 'gallery-edit' ],
784 template: media.template( 'editor-gallery' ),
786 initialize: function() {
787 var attachments = media.gallery.attachments( this.shortcode, media.view.settings.post.id ),
788 attrs = this.shortcode.attrs.named,
793 attachments = attachments.toJSON();
795 _.each( attachments, function( attachment ) {
796 if ( attachment.sizes ) {
797 if ( attrs.size && attachment.sizes[ attrs.size ] ) {
798 attachment.thumbnail = attachment.sizes[ attrs.size ];
799 } else if ( attachment.sizes.thumbnail ) {
800 attachment.thumbnail = attachment.sizes.thumbnail;
801 } else if ( attachment.sizes.full ) {
802 attachment.thumbnail = attachment.sizes.full;
807 self.render( self.template( {
808 verifyHTML: verifyHTML,
809 attachments: attachments,
810 columns: attrs.columns ? parseInt( attrs.columns, 10 ) : media.galleryDefaults.columns
813 .fail( function( jqXHR, textStatus ) {
814 self.setError( textStatus );
819 av = _.extend( {}, base, {
820 action: 'parse-media-shortcode',
822 initialize: function() {
827 this.shortcode = media.embed.shortcode( {
832 wp.ajax.post( this.action, {
833 post_ID: media.view.settings.post.id,
834 type: this.shortcode.tag,
835 shortcode: this.shortcode.string()
837 .done( function( response ) {
838 self.render( response );
840 .fail( function( response ) {
843 self.removeMarkers();
845 self.setError( response.message || response.statusText, 'admin-media' );
849 this.getEditors( function( editor ) {
850 editor.on( 'wpview-selected', function() {
856 pausePlayers: function() {
857 this.getNodes( function( editor, node, content ) {
858 var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
860 if ( win && ( win = win.contentWindow ) && win.mejs ) {
861 _.each( win.mejs.players, function( player ) {
871 embed = _.extend( {}, av, {
872 action: 'parse-embed',
874 edit: function( text, update ) {
875 var frame = media.embed.edit( text, this.url ),
880 frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
881 if ( url && model.get( 'url' ) ) {
882 frame.state( 'embed' ).metadata = model.toJSON();
886 frame.state( 'embed' ).on( 'select', function() {
887 var data = frame.state( 'embed' ).metadata;
892 update( media.embed.shortcode( data ).string() );
896 frame.on( 'close', function() {
904 views.register( 'gallery', _.extend( {}, gallery ) );
906 views.register( 'audio', _.extend( {}, av, {
907 state: [ 'audio-details' ]
910 views.register( 'video', _.extend( {}, av, {
911 state: [ 'video-details' ]
914 views.register( 'playlist', _.extend( {}, av, {
915 state: [ 'playlist-edit', 'video-playlist-edit' ]
918 views.register( 'embed', _.extend( {}, embed ) );
920 views.register( 'embedURL', _.extend( {}, embed, {
921 match: function( content ) {
922 var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
923 match = re.exec( content );
927 index: match.index + match[1].length,
936 } )( window, window.wp.mce.views, window.wp.media, window.jQuery );