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']
352 // Empty the wpview wrap and marker nodes
353 function emptyViewNodes( rootNode ) {
354 $( 'div[data-wpview-text], p[data-wpview-marker]', rootNode ).each( function( i, node ) {
355 node.innerHTML = '.';
359 // Run that before the DOM cleanup
360 editor.on( 'PreProcess', function( event ) {
361 emptyViewNodes( event.node );
364 editor.on( 'hide', function() {
365 wp.mce.views.unbind();
370 editor.on( 'PostProcess', function( event ) {
371 if ( event.content ) {
372 event.content = event.content.replace( /<div [^>]*?data-wpview-text="([^"]+)"[^>]*>[\s\S]*?<\/div>/g, resetViewsCallback )
373 .replace( /<p [^>]*?data-wpview-marker="([^"]+)"[^>]*>[\s\S]*?<\/p>/g, resetViewsCallback );
377 // Excludes arrow keys, delete, backspace, enter, space bar.
378 // Ref: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
379 function isSpecialKey( key ) {
380 return ( ( key <= 47 && key !== VK.SPACEBAR && key !== VK.ENTER && key !== VK.DELETE && key !== VK.BACKSPACE && ( key < 37 || key > 40 ) ) ||
381 key >= 224 || // OEM or non-printable
382 ( key >= 144 && key <= 150 ) || // Num Lock, Scroll Lock, OEM
383 ( key >= 91 && key <= 93 ) || // Windows keys
384 ( key >= 112 && key <= 135 ) ); // F keys
387 // (De)select views when arrow keys are used to navigate the content of the editor.
388 editor.on( 'keydown', function( event ) {
389 var key = event.keyCode,
391 selection = editor.selection,
392 node, view, cursorBefore, cursorAfter,
393 range, clonedRange, tempRange;
396 // Ignore key presses that involve the command or control key, but continue when in combination with backspace or v.
397 // Also ignore the F# keys.
398 if ( ( ( event.metaKey || event.ctrlKey ) && key !== VK.BACKSPACE && key !== 86 ) || ( key >= 112 && key <= 123 ) ) {
399 // Remove the view when pressing cmd/ctrl+x on keyup, otherwise the browser can't copy the content.
400 if ( ( event.metaKey || event.ctrlKey ) && key === 88 ) {
406 view = getView( selection.getNode() );
408 // If the caret is not within the selected view, deselect the view and bail.
409 if ( view !== selected ) {
414 if ( key === VK.LEFT ) {
415 setViewCursor( true, view );
416 event.preventDefault();
417 } else if ( key === VK.UP ) {
418 if ( view.previousSibling ) {
419 if ( getView( view.previousSibling ) ) {
420 setViewCursor( true, view.previousSibling );
423 selection.select( view.previousSibling, true );
424 selection.collapse();
427 setViewCursor( true, view );
429 event.preventDefault();
430 } else if ( key === VK.RIGHT ) {
431 setViewCursor( false, view );
432 event.preventDefault();
433 } else if ( key === VK.DOWN ) {
434 if ( view.nextSibling ) {
435 if ( getView( view.nextSibling ) ) {
436 setViewCursor( false, view.nextSibling );
439 selection.setCursorLocation( view.nextSibling, 0 );
442 setViewCursor( false, view );
445 event.preventDefault();
446 // Ignore keys that don't insert anything.
447 } else if ( ! isSpecialKey( key ) ) {
448 removeView( selected );
450 if ( key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE ) {
451 event.preventDefault();
455 if ( event.metaKey || event.ctrlKey || ( key >= 112 && key <= 123 ) ) {
459 node = selection.getNode();
460 lastKeyDownNode = node;
461 view = getView( node );
463 // Make sure we don't delete part of a view.
464 // If the range ends or starts with the view, we'll need to trim it.
465 if ( ! selection.isCollapsed() ) {
466 range = selection.getRng();
468 if ( view = getView( range.endContainer ) ) {
469 clonedRange = range.cloneRange();
470 selection.select( view.previousSibling, true );
471 selection.collapse();
472 tempRange = selection.getRng();
473 clonedRange.setEnd( tempRange.endContainer, tempRange.endOffset );
474 selection.setRng( clonedRange );
475 } else if ( view = getView( range.startContainer ) ) {
476 clonedRange = range.cloneRange();
477 clonedRange.setStart( view.nextSibling, 0 );
478 selection.setRng( clonedRange );
483 // Make sure we don't eat any content.
484 if ( event.keyCode === VK.BACKSPACE ) {
485 if ( editor.dom.isEmpty( node ) ) {
486 if ( view = getView( node.previousSibling ) ) {
487 setViewCursor( false, view );
488 editor.dom.remove( node );
489 event.preventDefault();
491 } else if ( ( range = selection.getRng() ) &&
492 range.startOffset === 0 &&
493 range.endOffset === 0 &&
494 ( view = getView( node.previousSibling ) ) ) {
495 setViewCursor( false, view );
496 event.preventDefault();
502 if ( ! ( ( cursorBefore = dom.hasClass( view, 'wpview-selection-before' ) ) ||
503 ( cursorAfter = dom.hasClass( view, 'wpview-selection-after' ) ) ) ) {
507 if ( isSpecialKey( key ) ) {
512 if ( ( cursorAfter && key === VK.UP ) || ( cursorBefore && key === VK.BACKSPACE ) ) {
513 if ( view.previousSibling ) {
514 if ( getView( view.previousSibling ) ) {
515 setViewCursor( false, view.previousSibling );
517 if ( dom.isEmpty( view.previousSibling ) && key === VK.BACKSPACE ) {
518 dom.remove( view.previousSibling );
520 selection.select( view.previousSibling, true );
521 selection.collapse();
525 setViewCursor( true, view );
527 event.preventDefault();
528 } else if ( cursorAfter && ( key === VK.DOWN || key === VK.RIGHT ) ) {
529 if ( view.nextSibling ) {
530 if ( getView( view.nextSibling ) ) {
531 setViewCursor( key === VK.RIGHT, view.nextSibling );
533 selection.setCursorLocation( view.nextSibling, 0 );
536 event.preventDefault();
537 } else if ( cursorBefore && ( key === VK.UP || key === VK.LEFT ) ) {
538 if ( view.previousSibling ) {
539 if ( getView( view.previousSibling ) ) {
540 setViewCursor( key === VK.UP, view.previousSibling );
542 selection.select( view.previousSibling, true );
543 selection.collapse();
546 event.preventDefault();
547 } else if ( cursorBefore && key === VK.DOWN ) {
548 if ( view.nextSibling ) {
549 if ( getView( view.nextSibling ) ) {
550 setViewCursor( true, view.nextSibling );
552 selection.setCursorLocation( view.nextSibling, 0 );
555 setViewCursor( false, view );
557 event.preventDefault();
558 } else if ( ( cursorAfter && key === VK.LEFT ) || ( cursorBefore && key === VK.RIGHT ) ) {
560 event.preventDefault();
561 } else if ( cursorAfter && key === VK.BACKSPACE ) {
563 event.preventDefault();
564 } else if ( cursorAfter ) {
566 } else if ( cursorBefore ) {
567 handleEnter( view , true, key );
570 if ( key === VK.ENTER ) {
571 event.preventDefault();
576 editor.on( 'keyup', function() {
578 removeView( toRemove );
583 editor.on( 'focus', function() {
587 editor.dom.addClass( editor.getBody(), 'has-focus' );
589 // Edge case: show the fake caret when the editor is focused for the first time
590 // and the first element is a view.
591 if ( firstFocus && ( view = getView( editor.getBody().firstChild ) ) ) {
592 setViewCursor( true, view );
598 editor.on( 'blur', function() {
600 editor.dom.removeClass( editor.getBody(), 'has-focus' );
603 editor.on( 'NodeChange', function( event ) {
604 var dom = editor.dom,
605 views = editor.dom.select( '.wpview-wrap' ),
606 className = event.element.className,
607 view = getView( event.element ),
608 lKDN = lastKeyDownNode;
610 lastKeyDownNode = false;
612 clearInterval( cursorInterval );
614 // This runs a lot and is faster than replacing each class separately
615 tinymce.each( views, function ( view ) {
616 if ( view.className ) {
617 view.className = view.className.replace( / ?\bwpview-(?:selection-before|selection-after|cursor-hide)\b/g, '' );
621 if ( focus && view ) {
622 if ( ( className === 'wpview-selection-before' || className === 'wpview-selection-after' ) &&
623 editor.selection.isCollapsed() ) {
625 setViewCursorTries = 0;
629 // Make sure the cursor arrived in the right node.
630 // This is necessary for Firefox.
631 if ( lKDN === view.previousSibling ) {
632 setViewCursor( true, view );
634 } else if ( lKDN === view.nextSibling ) {
635 setViewCursor( false, view );
639 dom.addClass( view, className );
641 cursorInterval = setInterval( function() {
642 if ( dom.hasClass( view, 'wpview-cursor-hide' ) ) {
643 dom.removeClass( view, 'wpview-cursor-hide' );
645 dom.addClass( view, 'wpview-cursor-hide' );
648 // If the cursor lands anywhere else in the view, set the cursor before it.
649 // Only try this once to prevent a loop. (You never know.)
650 } else if ( ! getParent( event.element, 'wpview-clipboard' ) && ! setViewCursorTries ) {
652 setViewCursorTries++;
653 setViewCursor( true, view );
658 editor.on( 'BeforeExecCommand', function() {
659 var node = editor.selection.getNode(),
662 if ( node && ( ( execCommandBefore = node.className === 'wpview-selection-before' ) || node.className === 'wpview-selection-after' ) && ( view = getView( node ) ) ) {
663 handleEnter( view, execCommandBefore );
664 execCommandView = view;
668 editor.on( 'ExecCommand', function() {
677 if ( execCommandView ) {
678 node = execCommandView[ execCommandBefore ? 'previousSibling' : 'nextSibling' ];
680 if ( node && node.nodeName === 'P' && editor.dom.isEmpty( node ) ) {
681 editor.dom.remove( node );
682 setViewCursor( execCommandBefore, execCommandView );
685 execCommandView = false;
689 editor.on( 'ResolveName', function( event ) {
690 if ( editor.dom.hasClass( event.target, 'wpview-wrap' ) ) {
691 event.name = editor.dom.getAttrib( event.target, 'data-wpview-type' ) || 'wpview';
692 event.stopPropagation();
693 } else if ( getView( event.target ) ) {
694 event.preventDefault();
695 event.stopPropagation();
699 editor.addButton( 'wp_view_edit', {
700 tooltip: 'Edit ', // trailing space is needed, used for context
701 icon: 'dashicon dashicons-edit',
702 onclick: function() {
703 selected && wp.mce.views.edit( editor, selected );
707 editor.addButton( 'wp_view_remove', {
709 icon: 'dashicon dashicons-no',
710 onclick: function() {
711 selected && removeView( selected );
715 editor.once( 'preinit', function() {
716 toolbar = editor.wp._createToolbar( [
722 editor.on( 'wptoolbar', function( event ) {
724 event.element = selected;
725 event.toolbar = toolbar;
730 editor.wp = editor.wp || {};
731 editor.wp.getView = getView;
732 editor.wp.setViewCursor = setViewCursor;
734 // Keep for back-compat.