4 * WordPress View plugin.
6 tinymce.PluginManager.add( 'wpview', function( editor ) {
11 TreeWalker = tinymce.dom.TreeWalker,
14 _noop = function() { return false; },
15 isios = /iPad|iPod|iPhone/.test( navigator.userAgent ),
24 function getView( node ) {
25 return getParent( node, 'wpview-wrap' );
29 * Returns the node or a parent of the node that has the passed className.
30 * Doing this directly is about 40% faster
32 function getParent( node, className ) {
33 while ( node && node.parentNode ) {
34 if ( node.className && ( ' ' + node.className + ' ' ).indexOf( ' ' + className + ' ' ) !== -1 ) {
38 node = node.parentNode;
44 function _stop( event ) {
45 event.stopPropagation();
48 function setViewCursor( before, view ) {
49 var location = before ? 'before' : 'after',
50 offset = before ? 0 : 1;
52 editor.selection.setCursorLocation( editor.dom.select( '.wpview-selection-' + location, view )[0], offset );
56 function handleEnter( view, before, key ) {
58 padNode = dom.create( 'p' );
60 if ( ! ( Env.ie && Env.ie < 11 ) ) {
61 padNode.innerHTML = '<br data-mce-bogus="1">';
65 view.parentNode.insertBefore( padNode, view );
67 dom.insertAfter( padNode, view );
72 if ( before && key === VK.ENTER ) {
73 setViewCursor( before, view );
75 editor.selection.setCursorLocation( padNode, 0 );
81 function removeView( view ) {
82 editor.undoManager.transact( function() {
84 wp.mce.views.remove( editor, view );
88 function select( viewNode ) {
96 if ( viewNode !== selected ) {
97 // Make sure that the editor is focused.
98 // It is possible that the editor is not focused when the mouse event fires
99 // without focus, the selection will not work properly.
100 editor.getBody().focus();
104 dom.setAttrib( viewNode, 'data-mce-selected', 1 );
106 clipboard = dom.create( 'div', {
107 'class': 'wpview-clipboard',
108 'contenteditable': 'true'
109 }, wp.mce.views.getText( viewNode ) );
111 editor.dom.select( '.wpview-body', viewNode )[0].appendChild( clipboard );
113 // Both of the following are necessary to prevent manipulating the selection/focus
114 dom.bind( clipboard, 'beforedeactivate focusin focusout', _stop );
115 dom.bind( selected, 'beforedeactivate focusin focusout', _stop );
117 // select the hidden div
119 editor.selection.select( clipboard );
121 editor.selection.select( clipboard, true );
125 editor.nodeChanged();
126 editor.fire( 'wpview-selected', viewNode );
130 * Deselect a selected view and remove clipboard
132 function deselect() {
137 clipboard = editor.dom.select( '.wpview-clipboard', selected )[0];
138 dom.unbind( clipboard );
139 dom.remove( clipboard );
141 dom.unbind( selected, 'beforedeactivate focusin focusout click mouseup', _stop );
142 dom.setAttrib( selected, 'data-mce-selected', null );
148 // Check if the `wp.mce` API exists.
149 if ( typeof wp === 'undefined' || ! wp.mce ) {
155 function resetViewsCallback( match, viewText ) {
156 return '<p>' + window.decodeURIComponent( viewText ) + '</p>';
159 // Replace the view tags with the view string
160 function resetViews( content ) {
161 return content.replace( /<div[^>]+data-wpview-text="([^"]+)"[^>]*>(?:[\s\S]+?wpview-selection-after[^>]+>[^<>]*<\/p>\s*|\.)<\/div>/g, resetViewsCallback )
162 .replace( /<p [^>]*?data-wpview-marker="([^"]+)"[^>]*>[\s\S]*?<\/p>/g, resetViewsCallback );
165 // Prevent adding undo levels on changes inside a view wrapper
166 editor.on( 'BeforeAddUndo', function( event ) {
167 if ( event.level.content ) {
168 event.level.content = resetViews( event.level.content );
172 // When the editor's content changes, scan the new content for
173 // matching view patterns, and transform the matches into
175 editor.on( 'BeforeSetContent', function( event ) {
178 if ( ! event.selection ) {
179 wp.mce.views.unbind();
182 if ( ! event.content ) {
186 if ( ! event.load ) {
188 removeView( selected );
191 node = editor.selection.getNode();
193 if ( node && node !== editor.getBody() && /^\s*https?:\/\/\S+\s*$/i.test( event.content ) ) {
194 // When a url is pasted or inserted, only try to embed it when it is in an empty paragrapgh.
195 node = editor.dom.getParent( node, 'p' );
197 if ( node && /^[\s\uFEFF\u00A0]*$/.test( $( node ).text() || '' ) ) {
198 // Make sure there are no empty inline elements in the <p>
206 event.content = wp.mce.views.setMarkers( event.content );
209 // When pasting strip all tags and check if the string is an URL.
210 // Then replace the pasted content with the cleaned URL.
211 editor.on( 'pastePreProcess', function( event ) {
212 var pastedStr = event.content;
215 pastedStr = tinymce.trim( pastedStr.replace( /<[^>]+>/g, '' ) );
217 if ( /^https?:\/\/\S+$/i.test( pastedStr ) ) {
218 event.content = pastedStr;
223 // When the editor's content has been updated and the DOM has been
224 // processed, render the views in the document.
225 editor.on( 'SetContent', function() {
226 wp.mce.views.render();
229 // Set the cursor before or after a view when clicking next to it.
230 editor.on( 'click', function( event ) {
231 var x = event.clientX,
233 body = editor.getBody(),
234 bodyRect = body.getBoundingClientRect(),
235 first = body.firstChild,
236 last = body.lastChild,
237 firstRect, lastRect, view;
239 if ( ! first || ! last ) {
243 firstRect = first.getBoundingClientRect();
244 lastRect = last.getBoundingClientRect();
246 if ( y < firstRect.top && ( view = getView( first ) ) ) {
247 setViewCursor( true, view );
248 event.preventDefault();
249 } else if ( y > lastRect.bottom && ( view = getView( last ) ) ) {
250 setViewCursor( false, view );
251 event.preventDefault();
252 } else if ( x < bodyRect.left || x > bodyRect.right ) {
253 tinymce.each( editor.dom.select( '.wpview-wrap' ), function( view ) {
254 var rect = view.getBoundingClientRect();
256 if ( y < rect.top ) {
260 if ( y >= rect.top && y <= rect.bottom ) {
261 if ( x < bodyRect.left ) {
262 setViewCursor( true, view );
263 event.preventDefault();
264 } else if ( x > bodyRect.right ) {
265 setViewCursor( false, view );
266 event.preventDefault();
275 editor.on( 'init', function() {
276 var scrolled = false,
277 selection = editor.selection,
278 MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
280 // When a view is selected, ensure content that is being pasted
281 // or inserted is added to a text node (instead of the view).
282 editor.on( 'BeforeSetContent', function() {
284 view = getView( selection.getNode() );
286 // If the selection is not within a view, bail.
291 if ( ! view.nextSibling || getView( view.nextSibling ) ) {
292 // If there are no additional nodes or the next node is a
293 // view, create a text node after the current view.
294 target = editor.getDoc().createTextNode('');
295 editor.dom.insertAfter( target, view );
297 // Otherwise, find the next text node.
298 walker = new TreeWalker( view.nextSibling, view.nextSibling );
299 target = walker.next();
302 // Select the `target` text node.
303 selection.select( target );
304 selection.collapse( true );
307 editor.dom.bind( editor.getDoc(), 'touchmove', function() {
311 editor.on( 'mousedown mouseup click touchend', function( event ) {
312 var view = getView( event.target );
316 // Contain clicks inside the view wrapper
318 event.stopImmediatePropagation();
319 event.preventDefault();
321 if ( event.type === 'touchend' && scrolled ) {
327 // Returning false stops the ugly bars from appearing in IE11 and stops the view being selected as a range in FF.
328 // Unfortunately, it also inhibits the dragging of views to a new location.
331 if ( event.type === 'touchend' || event.type === 'mousedown' ) {
336 if ( event.type === 'touchend' && scrolled ) {
341 if ( MutationObserver ) {
342 new MutationObserver( function() {
343 editor.fire( 'wp-body-class-change' );
345 .observe( editor.getBody(), {
347 attributeFilter: ['class']
351 if ( tinymce.Env.ie ) {
352 // Prevent resize handles in newer IE
353 editor.dom.bind( editor.getBody(), 'controlselect mscontrolselect', function( event ) {
354 if ( getView( event.target ) ) {
355 event.preventDefault();
361 // Empty the wpview wrap and marker nodes
362 function emptyViewNodes( rootNode ) {
363 $( 'div[data-wpview-text], p[data-wpview-marker]', rootNode ).each( function( i, node ) {
364 node.innerHTML = '.';
368 // Run that before the DOM cleanup
369 editor.on( 'PreProcess', function( event ) {
370 emptyViewNodes( event.node );
373 editor.on( 'hide', function() {
374 wp.mce.views.unbind();
379 editor.on( 'PostProcess', function( event ) {
380 if ( event.content ) {
381 event.content = event.content.replace( /<div [^>]*?data-wpview-text="([^"]+)"[^>]*>[\s\S]*?<\/div>/g, resetViewsCallback )
382 .replace( /<p [^>]*?data-wpview-marker="([^"]+)"[^>]*>[\s\S]*?<\/p>/g, resetViewsCallback );
386 // Excludes arrow keys, delete, backspace, enter, space bar.
387 // Ref: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
388 function isSpecialKey( key ) {
389 return ( ( key <= 47 && key !== VK.SPACEBAR && key !== VK.ENTER && key !== VK.DELETE && key !== VK.BACKSPACE && ( key < 37 || key > 40 ) ) ||
390 key >= 224 || // OEM or non-printable
391 ( key >= 144 && key <= 150 ) || // Num Lock, Scroll Lock, OEM
392 ( key >= 91 && key <= 93 ) || // Windows keys
393 ( key >= 112 && key <= 135 ) ); // F keys
396 // (De)select views when arrow keys are used to navigate the content of the editor.
397 editor.on( 'keydown', function( event ) {
398 var key = event.keyCode,
400 selection = editor.selection,
401 node, view, cursorBefore, cursorAfter,
402 range, clonedRange, tempRange;
405 // Ignore key presses that involve the command or control key, but continue when in combination with backspace or v.
406 // Also ignore the F# keys.
407 if ( ( ( event.metaKey || event.ctrlKey ) && key !== VK.BACKSPACE && key !== 86 ) || ( key >= 112 && key <= 123 ) ) {
408 // Remove the view when pressing cmd/ctrl+x on keyup, otherwise the browser can't copy the content.
409 if ( ( event.metaKey || event.ctrlKey ) && key === 88 ) {
415 view = getView( selection.getNode() );
417 // If the caret is not within the selected view, deselect the view and bail.
418 if ( view !== selected ) {
423 if ( key === VK.LEFT ) {
424 setViewCursor( true, view );
425 event.preventDefault();
426 } else if ( key === VK.UP ) {
427 if ( view.previousSibling ) {
428 if ( getView( view.previousSibling ) ) {
429 setViewCursor( true, view.previousSibling );
432 selection.select( view.previousSibling, true );
433 selection.collapse();
436 setViewCursor( true, view );
438 event.preventDefault();
439 } else if ( key === VK.RIGHT ) {
440 setViewCursor( false, view );
441 event.preventDefault();
442 } else if ( key === VK.DOWN ) {
443 if ( view.nextSibling ) {
444 if ( getView( view.nextSibling ) ) {
445 setViewCursor( false, view.nextSibling );
448 selection.setCursorLocation( view.nextSibling, 0 );
451 setViewCursor( false, view );
454 event.preventDefault();
455 // Ignore keys that don't insert anything.
456 } else if ( ! isSpecialKey( key ) ) {
457 removeView( selected );
459 if ( key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE ) {
460 event.preventDefault();
464 if ( event.metaKey || event.ctrlKey || ( key >= 112 && key <= 123 ) ) {
468 node = selection.getNode();
469 lastKeyDownNode = node;
470 view = getView( node );
472 // Make sure we don't delete part of a view.
473 // If the range ends or starts with the view, we'll need to trim it.
474 if ( ! selection.isCollapsed() ) {
475 range = selection.getRng();
477 if ( view = getView( range.endContainer ) ) {
478 clonedRange = range.cloneRange();
479 selection.select( view.previousSibling, true );
480 selection.collapse();
481 tempRange = selection.getRng();
482 clonedRange.setEnd( tempRange.endContainer, tempRange.endOffset );
483 selection.setRng( clonedRange );
484 } else if ( view = getView( range.startContainer ) ) {
485 clonedRange = range.cloneRange();
486 clonedRange.setStart( view.nextSibling, 0 );
487 selection.setRng( clonedRange );
492 // Make sure we don't eat any content.
493 if ( event.keyCode === VK.BACKSPACE ) {
494 if ( editor.dom.isEmpty( node ) ) {
495 if ( view = getView( node.previousSibling ) ) {
496 setViewCursor( false, view );
497 editor.dom.remove( node );
498 event.preventDefault();
500 } else if ( ( range = selection.getRng() ) &&
501 range.startOffset === 0 &&
502 range.endOffset === 0 &&
503 ( view = getView( node.previousSibling ) ) ) {
504 setViewCursor( false, view );
505 event.preventDefault();
511 if ( ! ( ( cursorBefore = dom.hasClass( view, 'wpview-selection-before' ) ) ||
512 ( cursorAfter = dom.hasClass( view, 'wpview-selection-after' ) ) ) ) {
516 if ( isSpecialKey( key ) ) {
521 if ( ( cursorAfter && key === VK.UP ) || ( cursorBefore && key === VK.BACKSPACE ) ) {
522 if ( view.previousSibling ) {
523 if ( getView( view.previousSibling ) ) {
524 setViewCursor( false, view.previousSibling );
526 if ( dom.isEmpty( view.previousSibling ) && key === VK.BACKSPACE ) {
527 dom.remove( view.previousSibling );
529 selection.select( view.previousSibling, true );
530 selection.collapse();
534 setViewCursor( true, view );
536 event.preventDefault();
537 } else if ( cursorAfter && ( key === VK.DOWN || key === VK.RIGHT ) ) {
538 if ( view.nextSibling ) {
539 if ( getView( view.nextSibling ) ) {
540 setViewCursor( key === VK.RIGHT, view.nextSibling );
542 selection.setCursorLocation( view.nextSibling, 0 );
545 event.preventDefault();
546 } else if ( cursorBefore && ( key === VK.UP || key === VK.LEFT ) ) {
547 if ( view.previousSibling ) {
548 if ( getView( view.previousSibling ) ) {
549 setViewCursor( key === VK.UP, view.previousSibling );
551 selection.select( view.previousSibling, true );
552 selection.collapse();
555 event.preventDefault();
556 } else if ( cursorBefore && key === VK.DOWN ) {
557 if ( view.nextSibling ) {
558 if ( getView( view.nextSibling ) ) {
559 setViewCursor( true, view.nextSibling );
561 selection.setCursorLocation( view.nextSibling, 0 );
564 setViewCursor( false, view );
566 event.preventDefault();
567 } else if ( ( cursorAfter && key === VK.LEFT ) || ( cursorBefore && key === VK.RIGHT ) ) {
569 event.preventDefault();
570 } else if ( cursorAfter && key === VK.BACKSPACE ) {
572 event.preventDefault();
573 } else if ( cursorAfter ) {
575 } else if ( cursorBefore ) {
576 handleEnter( view , true, key );
579 if ( key === VK.ENTER ) {
580 event.preventDefault();
585 editor.on( 'keyup', function() {
587 removeView( toRemove );
592 editor.on( 'focus', function() {
596 editor.dom.addClass( editor.getBody(), 'has-focus' );
598 // Edge case: show the fake caret when the editor is focused for the first time
599 // and the first element is a view.
600 if ( firstFocus && ( view = getView( editor.getBody().firstChild ) ) ) {
601 setViewCursor( true, view );
607 editor.on( 'blur', function() {
609 editor.dom.removeClass( editor.getBody(), 'has-focus' );
612 editor.on( 'NodeChange', function( event ) {
613 var dom = editor.dom,
614 views = editor.dom.select( '.wpview-wrap' ),
615 className = event.element.className,
616 view = getView( event.element ),
617 lKDN = lastKeyDownNode;
619 lastKeyDownNode = false;
621 clearInterval( cursorInterval );
623 // This runs a lot and is faster than replacing each class separately
624 tinymce.each( views, function ( view ) {
625 if ( view.className ) {
626 view.className = view.className.replace( / ?\bwpview-(?:selection-before|selection-after|cursor-hide)\b/g, '' );
630 if ( focus && view ) {
631 if ( ( className === 'wpview-selection-before' || className === 'wpview-selection-after' ) &&
632 editor.selection.isCollapsed() ) {
634 setViewCursorTries = 0;
638 // Make sure the cursor arrived in the right node.
639 // This is necessary for Firefox.
640 if ( lKDN === view.previousSibling ) {
641 setViewCursor( true, view );
643 } else if ( lKDN === view.nextSibling ) {
644 setViewCursor( false, view );
648 dom.addClass( view, className );
650 cursorInterval = setInterval( function() {
651 if ( dom.hasClass( view, 'wpview-cursor-hide' ) ) {
652 dom.removeClass( view, 'wpview-cursor-hide' );
654 dom.addClass( view, 'wpview-cursor-hide' );
657 // If the cursor lands anywhere else in the view, set the cursor before it.
658 // Only try this once to prevent a loop. (You never know.)
659 } else if ( ! getParent( event.element, 'wpview-clipboard' ) && ! setViewCursorTries ) {
661 setViewCursorTries++;
662 setViewCursor( true, view );
667 editor.on( 'BeforeExecCommand', function() {
668 var node = editor.selection.getNode(),
671 if ( node && ( ( execCommandBefore = node.className === 'wpview-selection-before' ) || node.className === 'wpview-selection-after' ) && ( view = getView( node ) ) ) {
672 handleEnter( view, execCommandBefore );
673 execCommandView = view;
677 editor.on( 'ExecCommand', function() {
686 if ( execCommandView ) {
687 node = execCommandView[ execCommandBefore ? 'previousSibling' : 'nextSibling' ];
689 if ( node && node.nodeName === 'P' && editor.dom.isEmpty( node ) ) {
690 editor.dom.remove( node );
691 setViewCursor( execCommandBefore, execCommandView );
694 execCommandView = false;
698 editor.on( 'ResolveName', function( event ) {
699 if ( editor.dom.hasClass( event.target, 'wpview-wrap' ) ) {
700 event.name = editor.dom.getAttrib( event.target, 'data-wpview-type' ) || 'wpview';
701 event.stopPropagation();
702 } else if ( getView( event.target ) ) {
703 event.preventDefault();
704 event.stopPropagation();
708 editor.addButton( 'wp_view_edit', {
709 tooltip: 'Edit ', // trailing space is needed, used for context
710 icon: 'dashicon dashicons-edit',
711 onclick: function() {
712 selected && wp.mce.views.edit( editor, selected );
716 editor.addButton( 'wp_view_remove', {
718 icon: 'dashicon dashicons-no',
719 onclick: function() {
720 selected && removeView( selected );
724 editor.once( 'preinit', function() {
725 if ( editor.wp && editor.wp._createToolbar ) {
726 toolbar = editor.wp._createToolbar( [
733 editor.on( 'wptoolbar', function( event ) {
735 event.element = selected;
736 event.toolbar = toolbar;
741 editor.wp = editor.wp || {};
742 editor.wp.getView = getView;
743 editor.wp.setViewCursor = setViewCursor;
745 // Keep for back-compat.