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 // Remove the content of view wrappers from HTML string
156 function emptyViews( content ) {
157 content = content.replace( /<div[^>]+data-wpview-text="([^"]+)"[^>]*>[\s\S]+?wpview-selection-after[^>]+>[^<>]*<\/p>\s*<\/div>/g, function( all, match ) {
158 return '<p>' + window.decodeURIComponent( match ) + '</p>';
161 return content.replace( / data-wpview-marker="[^"]+"/g, '' );
164 // Prevent adding undo levels on changes inside a view wrapper
165 editor.on( 'BeforeAddUndo', function( event ) {
166 if ( event.level.content ) {
167 event.level.content = emptyViews( event.level.content );
171 // When the editor's content changes, scan the new content for
172 // matching view patterns, and transform the matches into
174 editor.on( 'BeforeSetContent', function( event ) {
177 if ( ! event.selection ) {
178 wp.mce.views.unbind();
181 if ( ! event.content ) {
185 if ( ! event.load ) {
187 removeView( selected );
190 node = editor.selection.getNode();
192 if ( node && node !== editor.getBody() && /^\s*https?:\/\/\S+\s*$/i.test( event.content ) ) {
193 // When a url is pasted or inserted, only try to embed it when it is in an empty paragrapgh.
194 node = editor.dom.getParent( node, 'p' );
196 if ( node && /^[\s\uFEFF\u00A0]*$/.test( $( node ).text() || '' ) ) {
197 // Make sure there are no empty inline elements in the <p>
205 event.content = wp.mce.views.setMarkers( event.content );
208 // When pasting strip all tags and check if the string is an URL.
209 // Then replace the pasted content with the cleaned URL.
210 editor.on( 'pastePreProcess', function( event ) {
211 var pastedStr = event.content;
214 pastedStr = tinymce.trim( pastedStr.replace( /<[^>]+>/g, '' ) );
216 if ( /^https?:\/\/\S+$/i.test( pastedStr ) ) {
217 event.content = pastedStr;
222 // When the editor's content has been updated and the DOM has been
223 // processed, render the views in the document.
224 editor.on( 'SetContent', function() {
225 wp.mce.views.render();
228 // Set the cursor before or after a view when clicking next to it.
229 editor.on( 'click', function( event ) {
230 var x = event.clientX,
232 body = editor.getBody(),
233 bodyRect = body.getBoundingClientRect(),
234 first = body.firstChild,
235 last = body.lastChild,
236 firstRect, lastRect, view;
238 if ( ! first || ! last ) {
242 firstRect = first.getBoundingClientRect();
243 lastRect = last.getBoundingClientRect();
245 if ( y < firstRect.top && ( view = getView( first ) ) ) {
246 setViewCursor( true, view );
247 event.preventDefault();
248 } else if ( y > lastRect.bottom && ( view = getView( last ) ) ) {
249 setViewCursor( false, view );
250 event.preventDefault();
251 } else if ( x < bodyRect.left || x > bodyRect.right ) {
252 tinymce.each( editor.dom.select( '.wpview-wrap' ), function( view ) {
253 var rect = view.getBoundingClientRect();
255 if ( y < rect.top ) {
259 if ( y >= rect.top && y <= rect.bottom ) {
260 if ( x < bodyRect.left ) {
261 setViewCursor( true, view );
262 event.preventDefault();
263 } else if ( x > bodyRect.right ) {
264 setViewCursor( false, view );
265 event.preventDefault();
274 editor.on( 'init', function() {
275 var scrolled = false,
276 selection = editor.selection,
277 MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
279 // When a view is selected, ensure content that is being pasted
280 // or inserted is added to a text node (instead of the view).
281 editor.on( 'BeforeSetContent', function() {
283 view = getView( selection.getNode() );
285 // If the selection is not within a view, bail.
290 if ( ! view.nextSibling || getView( view.nextSibling ) ) {
291 // If there are no additional nodes or the next node is a
292 // view, create a text node after the current view.
293 target = editor.getDoc().createTextNode('');
294 editor.dom.insertAfter( target, view );
296 // Otherwise, find the next text node.
297 walker = new TreeWalker( view.nextSibling, view.nextSibling );
298 target = walker.next();
301 // Select the `target` text node.
302 selection.select( target );
303 selection.collapse( true );
306 editor.dom.bind( editor.getDoc(), 'touchmove', function() {
310 editor.on( 'mousedown mouseup click touchend', function( event ) {
311 var view = getView( event.target );
315 // Contain clicks inside the view wrapper
317 event.stopImmediatePropagation();
318 event.preventDefault();
320 if ( event.type === 'touchend' && scrolled ) {
326 // Returning false stops the ugly bars from appearing in IE11 and stops the view being selected as a range in FF.
327 // Unfortunately, it also inhibits the dragging of views to a new location.
330 if ( event.type === 'touchend' || event.type === 'mousedown' ) {
335 if ( event.type === 'touchend' && scrolled ) {
340 if ( MutationObserver ) {
341 new MutationObserver( function() {
342 editor.fire( 'wp-body-class-change' );
344 .observe( editor.getBody(), {
346 attributeFilter: ['class']
351 function resetViews( rootNode ) {
352 // Replace view nodes
353 $( 'div[data-wpview-text]', rootNode ).each( function( i, node ) {
354 var $node = $( node ),
355 text = window.decodeURIComponent( $node.attr( 'data-wpview-text' ) || '' );
357 if ( text && node.parentNode ) {
358 $node.replaceWith( $( editor.dom.create('p') ).text( text ) );
362 // Remove marker attributes
363 $( 'p[data-wpview-marker]', rootNode ).attr( 'data-wpview-marker', null );
366 editor.on( 'PreProcess', function( event ) {
367 // Replace the view nodes with their text in the DOM clone.
368 resetViews( event.node );
371 editor.on( 'hide', function() {
372 // Replace the view nodes with their text directly in the editor body.
373 wp.mce.views.unbind();
375 resetViews( editor.getBody() );
378 // Excludes arrow keys, delete, backspace, enter, space bar.
379 // Ref: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
380 function isSpecialKey( key ) {
381 return ( ( key <= 47 && key !== VK.SPACEBAR && key !== VK.ENTER && key !== VK.DELETE && key !== VK.BACKSPACE && ( key < 37 || key > 40 ) ) ||
382 key >= 224 || // OEM or non-printable
383 ( key >= 144 && key <= 150 ) || // Num Lock, Scroll Lock, OEM
384 ( key >= 91 && key <= 93 ) || // Windows keys
385 ( key >= 112 && key <= 135 ) ); // F keys
388 // (De)select views when arrow keys are used to navigate the content of the editor.
389 editor.on( 'keydown', function( event ) {
390 var key = event.keyCode,
392 selection = editor.selection,
393 node, view, cursorBefore, cursorAfter,
394 range, clonedRange, tempRange;
397 // Ignore key presses that involve the command or control key, but continue when in combination with backspace or v.
398 // Also ignore the F# keys.
399 if ( ( ( event.metaKey || event.ctrlKey ) && key !== VK.BACKSPACE && key !== 86 ) || ( key >= 112 && key <= 123 ) ) {
400 // Remove the view when pressing cmd/ctrl+x on keyup, otherwise the browser can't copy the content.
401 if ( ( event.metaKey || event.ctrlKey ) && key === 88 ) {
407 view = getView( selection.getNode() );
409 // If the caret is not within the selected view, deselect the view and bail.
410 if ( view !== selected ) {
415 if ( key === VK.LEFT ) {
416 setViewCursor( true, view );
417 event.preventDefault();
418 } else if ( key === VK.UP ) {
419 if ( view.previousSibling ) {
420 if ( getView( view.previousSibling ) ) {
421 setViewCursor( true, view.previousSibling );
424 selection.select( view.previousSibling, true );
425 selection.collapse();
428 setViewCursor( true, view );
430 event.preventDefault();
431 } else if ( key === VK.RIGHT ) {
432 setViewCursor( false, view );
433 event.preventDefault();
434 } else if ( key === VK.DOWN ) {
435 if ( view.nextSibling ) {
436 if ( getView( view.nextSibling ) ) {
437 setViewCursor( false, view.nextSibling );
440 selection.setCursorLocation( view.nextSibling, 0 );
443 setViewCursor( false, view );
446 event.preventDefault();
447 // Ignore keys that don't insert anything.
448 } else if ( ! isSpecialKey( key ) ) {
449 removeView( selected );
451 if ( key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE ) {
452 event.preventDefault();
456 if ( event.metaKey || event.ctrlKey || ( key >= 112 && key <= 123 ) ) {
460 node = selection.getNode();
461 lastKeyDownNode = node;
462 view = getView( node );
464 // Make sure we don't delete part of a view.
465 // If the range ends or starts with the view, we'll need to trim it.
466 if ( ! selection.isCollapsed() ) {
467 range = selection.getRng();
469 if ( view = getView( range.endContainer ) ) {
470 clonedRange = range.cloneRange();
471 selection.select( view.previousSibling, true );
472 selection.collapse();
473 tempRange = selection.getRng();
474 clonedRange.setEnd( tempRange.endContainer, tempRange.endOffset );
475 selection.setRng( clonedRange );
476 } else if ( view = getView( range.startContainer ) ) {
477 clonedRange = range.cloneRange();
478 clonedRange.setStart( view.nextSibling, 0 );
479 selection.setRng( clonedRange );
484 // Make sure we don't eat any content.
485 if ( event.keyCode === VK.BACKSPACE ) {
486 if ( editor.dom.isEmpty( node ) ) {
487 if ( view = getView( node.previousSibling ) ) {
488 setViewCursor( false, view );
489 editor.dom.remove( node );
490 event.preventDefault();
492 } else if ( ( range = selection.getRng() ) &&
493 range.startOffset === 0 &&
494 range.endOffset === 0 &&
495 ( view = getView( node.previousSibling ) ) ) {
496 setViewCursor( false, view );
497 event.preventDefault();
503 if ( ! ( ( cursorBefore = dom.hasClass( view, 'wpview-selection-before' ) ) ||
504 ( cursorAfter = dom.hasClass( view, 'wpview-selection-after' ) ) ) ) {
508 if ( isSpecialKey( key ) ) {
513 if ( ( cursorAfter && key === VK.UP ) || ( cursorBefore && key === VK.BACKSPACE ) ) {
514 if ( view.previousSibling ) {
515 if ( getView( view.previousSibling ) ) {
516 setViewCursor( false, view.previousSibling );
518 if ( dom.isEmpty( view.previousSibling ) && key === VK.BACKSPACE ) {
519 dom.remove( view.previousSibling );
521 selection.select( view.previousSibling, true );
522 selection.collapse();
526 setViewCursor( true, view );
528 event.preventDefault();
529 } else if ( cursorAfter && ( key === VK.DOWN || key === VK.RIGHT ) ) {
530 if ( view.nextSibling ) {
531 if ( getView( view.nextSibling ) ) {
532 setViewCursor( key === VK.RIGHT, view.nextSibling );
534 selection.setCursorLocation( view.nextSibling, 0 );
537 event.preventDefault();
538 } else if ( cursorBefore && ( key === VK.UP || key === VK.LEFT ) ) {
539 if ( view.previousSibling ) {
540 if ( getView( view.previousSibling ) ) {
541 setViewCursor( key === VK.UP, view.previousSibling );
543 selection.select( view.previousSibling, true );
544 selection.collapse();
547 event.preventDefault();
548 } else if ( cursorBefore && key === VK.DOWN ) {
549 if ( view.nextSibling ) {
550 if ( getView( view.nextSibling ) ) {
551 setViewCursor( true, view.nextSibling );
553 selection.setCursorLocation( view.nextSibling, 0 );
556 setViewCursor( false, view );
558 event.preventDefault();
559 } else if ( ( cursorAfter && key === VK.LEFT ) || ( cursorBefore && key === VK.RIGHT ) ) {
561 event.preventDefault();
562 } else if ( cursorAfter && key === VK.BACKSPACE ) {
564 event.preventDefault();
565 } else if ( cursorAfter ) {
567 } else if ( cursorBefore ) {
568 handleEnter( view , true, key );
571 if ( key === VK.ENTER ) {
572 event.preventDefault();
577 editor.on( 'keyup', function() {
579 removeView( toRemove );
584 editor.on( 'focus', function() {
588 editor.dom.addClass( editor.getBody(), 'has-focus' );
590 // Edge case: show the fake caret when the editor is focused for the first time
591 // and the first element is a view.
592 if ( firstFocus && ( view = getView( editor.getBody().firstChild ) ) ) {
593 setViewCursor( true, view );
599 editor.on( 'blur', function() {
601 editor.dom.removeClass( editor.getBody(), 'has-focus' );
604 editor.on( 'NodeChange', function( event ) {
605 var dom = editor.dom,
606 views = editor.dom.select( '.wpview-wrap' ),
607 className = event.element.className,
608 view = getView( event.element ),
609 lKDN = lastKeyDownNode;
611 lastKeyDownNode = false;
613 clearInterval( cursorInterval );
615 // This runs a lot and is faster than replacing each class separately
616 tinymce.each( views, function ( view ) {
617 if ( view.className ) {
618 view.className = view.className.replace( / ?\bwpview-(?:selection-before|selection-after|cursor-hide)\b/g, '' );
622 if ( focus && view ) {
623 if ( ( className === 'wpview-selection-before' || className === 'wpview-selection-after' ) &&
624 editor.selection.isCollapsed() ) {
626 setViewCursorTries = 0;
630 // Make sure the cursor arrived in the right node.
631 // This is necessary for Firefox.
632 if ( lKDN === view.previousSibling ) {
633 setViewCursor( true, view );
635 } else if ( lKDN === view.nextSibling ) {
636 setViewCursor( false, view );
640 dom.addClass( view, className );
642 cursorInterval = setInterval( function() {
643 if ( dom.hasClass( view, 'wpview-cursor-hide' ) ) {
644 dom.removeClass( view, 'wpview-cursor-hide' );
646 dom.addClass( view, 'wpview-cursor-hide' );
649 // If the cursor lands anywhere else in the view, set the cursor before it.
650 // Only try this once to prevent a loop. (You never know.)
651 } else if ( ! getParent( event.element, 'wpview-clipboard' ) && ! setViewCursorTries ) {
653 setViewCursorTries++;
654 setViewCursor( true, view );
659 editor.on( 'BeforeExecCommand', function() {
660 var node = editor.selection.getNode(),
663 if ( node && ( ( execCommandBefore = node.className === 'wpview-selection-before' ) || node.className === 'wpview-selection-after' ) && ( view = getView( node ) ) ) {
664 handleEnter( view, execCommandBefore );
665 execCommandView = view;
669 editor.on( 'ExecCommand', function() {
678 if ( execCommandView ) {
679 node = execCommandView[ execCommandBefore ? 'previousSibling' : 'nextSibling' ];
681 if ( node && node.nodeName === 'P' && editor.dom.isEmpty( node ) ) {
682 editor.dom.remove( node );
683 setViewCursor( execCommandBefore, execCommandView );
686 execCommandView = false;
690 editor.on( 'ResolveName', function( event ) {
691 if ( editor.dom.hasClass( event.target, 'wpview-wrap' ) ) {
692 event.name = editor.dom.getAttrib( event.target, 'data-wpview-type' ) || 'wpview';
693 event.stopPropagation();
694 } else if ( getView( event.target ) ) {
695 event.preventDefault();
696 event.stopPropagation();
700 editor.addButton( 'wp_view_edit', {
701 tooltip: 'Edit ', // trailing space is needed, used for context
702 icon: 'dashicon dashicons-edit',
703 onclick: function() {
704 selected && wp.mce.views.edit( editor, selected );
708 editor.addButton( 'wp_view_remove', {
710 icon: 'dashicon dashicons-no',
711 onclick: function() {
712 selected && removeView( selected );
716 editor.once( 'preinit', function() {
717 toolbar = editor.wp._createToolbar( [
723 editor.on( 'wptoolbar', function( event ) {
725 event.element = selected;
726 event.toolbar = toolbar;
731 editor.wp = editor.wp || {};
732 editor.wp.getView = getView;
734 // Keep for back-compat.