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 ) {
331 $( node ).data( 'rendered', true );
332 this.bindNode.call( this, editor, node );
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 ) {
355 this.unbindNode.call( this, editor, node );
360 * Gets all the TinyMCE editor instances that support views.
362 * @param {Function} callback A callback.
364 getEditors: function( callback ) {
365 _.each( tinymce.editors, function( editor ) {
366 if ( editor.plugins.wpview ) {
367 callback.call( this, editor );
373 * Gets all view nodes tied to this view instance.
375 * @param {Function} callback A callback.
376 * @param {Boolean} rendered Get (un)rendered view nodes. Optional.
378 getNodes: function( callback, rendered ) {
379 this.getEditors( function( editor ) {
382 $( editor.getBody() )
383 .find( '[data-wpview-text="' + self.encodedText + '"]' )
384 .filter( function() {
387 if ( rendered == null ) {
391 data = $( this ).data( 'rendered' ) === true;
393 return rendered ? data : ! data;
396 callback.call( self, editor, this, this /* back compat */ );
402 * Gets all marker nodes tied to this view instance.
404 * @param {Function} callback A callback.
406 getMarkers: function( callback ) {
407 this.getEditors( function( editor ) {
410 $( editor.getBody() )
411 .find( '[data-wpview-marker="' + this.encodedText + '"]' )
413 callback.call( self, editor, this );
419 * Replaces all marker nodes tied to this view instance.
421 replaceMarkers: function() {
422 this.getMarkers( function( editor, node ) {
425 if ( ! this.loader && $( node ).text() !== this.text ) {
426 editor.dom.setAttrib( node, 'data-wpview-marker', null );
430 $viewNode = editor.$(
431 '<div class="wpview wpview-wrap" data-wpview-text="' + this.encodedText + '" data-wpview-type="' + this.type + '" contenteditable="false"></div>'
434 editor.$( node ).replaceWith( $viewNode );
439 * Removes all marker nodes tied to this view instance.
441 removeMarkers: function() {
442 this.getMarkers( function( editor, node ) {
443 editor.dom.setAttrib( node, 'data-wpview-marker', null );
448 * Sets the content for all view nodes tied to this view instance.
450 * @param {*} content The content to set.
451 * @param {Function} callback A callback. Optional.
452 * @param {Boolean} rendered Only set for (un)rendered nodes. Optional.
454 setContent: function( content, callback, rendered ) {
455 if ( _.isObject( content ) && content.body.indexOf( '<script' ) !== -1 ) {
456 this.setIframes( content.head || '', content.body, callback, rendered );
457 } else if ( _.isString( content ) && content.indexOf( '<script' ) !== -1 ) {
458 this.setIframes( '', content, callback, rendered );
460 this.getNodes( function( editor, node ) {
461 content = content.body || content;
463 if ( content.indexOf( '<iframe' ) !== -1 ) {
464 content += '<span class="mce-shim"></span>';
467 editor.undoManager.transact( function() {
469 node.appendChild( _.isString( content ) ? editor.dom.createFragment( content ) : content );
470 editor.dom.add( node, 'span', { 'class': 'wpview-end' } );
473 callback && callback.call( this, editor, node );
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 ) {
489 this.getNodes( function( editor, node ) {
490 var dom = editor.dom,
492 bodyClasses = editor.getBody().className || '',
493 editorHead = editor.getDoc().getElementsByTagName( 'head' )[0];
495 tinymce.each( dom.$( 'link[rel="stylesheet"]', editorHead ), function( link ) {
496 if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 &&
497 link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) {
499 styles += dom.getOuterHTML( link );
503 if ( self.iframeHeight ) {
504 dom.add( node, 'span', {
509 height: self.iframeHeight
514 // Seems the browsers need a bit of time to insert/set the view nodes,
515 // or the iframe will fail especially when switching Text => Visual.
516 setTimeout( function() {
517 var iframe, iframeWin, iframeDoc, MutationObserver, observer, i, block;
519 editor.undoManager.transact( function() {
522 iframe = dom.add( node, 'iframe', {
523 /* jshint scripturl: true */
524 src: tinymce.Env.ie ? 'javascript:""' : '',
526 allowTransparency: 'true',
528 'class': 'wpview-sandbox',
533 height: self.iframeHeight
536 dom.add( node, 'span', { 'class': 'mce-shim' } );
537 dom.add( node, 'span', { 'class': 'wpview-end' } );
540 // Bail if the iframe node is not attached to the DOM.
541 // Happens when the view is dragged in the editor.
542 // There is a browser restriction when iframes are moved in the DOM. They get emptied.
543 // The iframe will be rerendered after dropping the view node at the new location.
544 if ( ! iframe.contentWindow ) {
548 iframeWin = iframe.contentWindow;
549 iframeDoc = iframeWin.document;
556 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
561 'background: transparent;' +
565 'body#wpview-iframe-sandbox {' +
566 'background: transparent;' +
567 'padding: 1px 0 !important;' +
568 'margin: -1px 0 0 !important;' +
570 'body#wpview-iframe-sandbox:before,' +
571 'body#wpview-iframe-sandbox:after {' +
577 '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' +
592 // Make sure the iframe still exists.
593 if ( iframe.contentWindow ) {
594 $iframe = $( iframe );
595 self.iframeHeight = $( iframeDoc.body ).height();
597 if ( $iframe.height() !== self.iframeHeight ) {
598 $iframe.height( self.iframeHeight );
599 editor.nodeChanged();
604 if ( self.iframeHeight ) {
607 setTimeout( function() {
613 $( iframeWin ).on( 'load', resize );
615 MutationObserver = iframeWin.MutationObserver || iframeWin.WebKitMutationObserver || iframeWin.MozMutationObserver;
617 if ( MutationObserver ) {
618 observer = new MutationObserver( _.debounce( resize, 100 ) );
620 observer.observe( iframeDoc.body, {
626 for ( i = 1; i < 6; i++ ) {
627 setTimeout( resize, i * 700 );
631 callback && callback.call( self, editor, node );
637 * Sets a loader for all view nodes tied to this view instance.
639 setLoader: function() {
641 '<div class="loading-placeholder">' +
642 '<div class="dashicons dashicons-admin-media"></div>' +
643 '<div class="wpview-loading"><ins></ins></div>' +
649 * Sets an error for all view nodes tied to this view instance.
651 * @param {String} message The error message to set.
652 * @param {String} dashicon A dashicon ID. Optional. {@link https://developer.wordpress.org/resource/dashicons/}
654 setError: function( message, dashicon ) {
656 '<div class="wpview-error">' +
657 '<div class="dashicons dashicons-' + ( dashicon || 'no' ) + '"></div>' +
658 '<p>' + message + '</p>' +
664 * Tries to find a text match in a given string.
666 * @param {String} content The string to scan.
670 match: function( content ) {
671 var match = shortcode.next( this.type, content );
676 content: match.content,
678 shortcode: match.shortcode
685 * Update the text of a given view node.
687 * @param {String} text The new text.
688 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
689 * @param {HTMLElement} node The view node to update.
690 * @param {Boolean} force Recreate the instance. Optional.
692 update: function( text, editor, node, force ) {
693 _.find( views, function( view, type ) {
694 var match = view.prototype.match( text );
697 $( node ).data( 'rendered', false );
698 editor.dom.setAttrib( node, 'data-wpview-text', encodeURIComponent( text ) );
699 wp.mce.views.createInstance( type, text, match.options, force ).render();
708 * Remove a given view node from the DOM.
710 * @param {tinymce.Editor} editor The TinyMCE editor instance the view node is in.
711 * @param {HTMLElement} node The view node to remove.
713 remove: function( editor, node ) {
714 this.unbindNode.call( this, editor, node );
715 editor.dom.remove( node );
719 } )( window, window.wp, window.wp.shortcode, window.jQuery );
722 * The WordPress core TinyMCE views.
723 * Views for the gallery, audio, video, playlist and embed shortcodes,
724 * and a view for embeddable URLs.
726 ( function( window, views, media, $ ) {
727 var base, gallery, av, embed,
728 schema, parser, serializer;
730 function verifyHTML( string ) {
733 if ( ! window.tinymce ) {
734 return string.replace( /<[^>]+>/g, '' );
737 if ( ! string || ( string.indexOf( '<' ) === -1 && string.indexOf( '>' ) === -1 ) ) {
741 schema = schema || new window.tinymce.html.Schema( settings );
742 parser = parser || new window.tinymce.html.DomParser( settings, schema );
743 serializer = serializer || new window.tinymce.html.Serializer( settings, schema );
745 return serializer.serialize( parser.parse( string, { forced_root_block: false } ) );
751 edit: function( text, update ) {
752 var type = this.type,
753 frame = media[ type ].edit( text );
755 this.pausePlayers && this.pausePlayers();
757 _.each( this.state, function( state ) {
758 frame.state( state ).on( 'update', function( selection ) {
759 update( media[ type ].shortcode( selection ).string(), type === 'gallery' );
763 frame.on( 'close', function() {
771 gallery = _.extend( {}, base, {
772 state: [ 'gallery-edit' ],
773 template: media.template( 'editor-gallery' ),
775 initialize: function() {
776 var attachments = media.gallery.attachments( this.shortcode, media.view.settings.post.id ),
777 attrs = this.shortcode.attrs.named,
782 attachments = attachments.toJSON();
784 _.each( attachments, function( attachment ) {
785 if ( attachment.sizes ) {
786 if ( attrs.size && attachment.sizes[ attrs.size ] ) {
787 attachment.thumbnail = attachment.sizes[ attrs.size ];
788 } else if ( attachment.sizes.thumbnail ) {
789 attachment.thumbnail = attachment.sizes.thumbnail;
790 } else if ( attachment.sizes.full ) {
791 attachment.thumbnail = attachment.sizes.full;
796 self.render( self.template( {
797 verifyHTML: verifyHTML,
798 attachments: attachments,
799 columns: attrs.columns ? parseInt( attrs.columns, 10 ) : media.galleryDefaults.columns
802 .fail( function( jqXHR, textStatus ) {
803 self.setError( textStatus );
808 av = _.extend( {}, base, {
809 action: 'parse-media-shortcode',
811 initialize: function() {
816 this.shortcode = media.embed.shortcode( {
821 wp.ajax.post( this.action, {
822 post_ID: media.view.settings.post.id,
823 type: this.shortcode.tag,
824 shortcode: this.shortcode.string()
826 .done( function( response ) {
827 self.render( response );
829 .fail( function( response ) {
832 self.removeMarkers();
834 self.setError( response.message || response.statusText, 'admin-media' );
838 this.getEditors( function( editor ) {
839 editor.on( 'wpview-selected', function() {
845 pausePlayers: function() {
846 this.getNodes( function( editor, node, content ) {
847 var win = $( 'iframe.wpview-sandbox', content ).get( 0 );
849 if ( win && ( win = win.contentWindow ) && win.mejs ) {
850 _.each( win.mejs.players, function( player ) {
860 embed = _.extend( {}, av, {
861 action: 'parse-embed',
863 edit: function( text, update ) {
864 var frame = media.embed.edit( text, this.url ),
869 frame.state( 'embed' ).props.on( 'change:url', function( model, url ) {
870 if ( url && model.get( 'url' ) ) {
871 frame.state( 'embed' ).metadata = model.toJSON();
875 frame.state( 'embed' ).on( 'select', function() {
876 var data = frame.state( 'embed' ).metadata;
881 update( media.embed.shortcode( data ).string() );
885 frame.on( 'close', function() {
893 views.register( 'gallery', _.extend( {}, gallery ) );
895 views.register( 'audio', _.extend( {}, av, {
896 state: [ 'audio-details' ]
899 views.register( 'video', _.extend( {}, av, {
900 state: [ 'video-details' ]
903 views.register( 'playlist', _.extend( {}, av, {
904 state: [ 'playlist-edit', 'video-playlist-edit' ]
907 views.register( 'embed', _.extend( {}, embed ) );
909 views.register( 'embedURL', _.extend( {}, embed, {
910 match: function( content ) {
911 var re = /(^|<p>)(https?:\/\/[^\s"]+?)(<\/p>\s*|$)/gi,
912 match = re.exec( content );
916 index: match.index + match[1].length,
925 } )( window, window.wp.mce.views, window.wp.media, window.jQuery );