4 * WordPress View plugin.
6 tinymce.PluginManager.add( 'wpview', function( editor ) {
10 TreeWalker = tinymce.dom.TreeWalker,
13 _noop = function() { return false; },
14 isios = /iPad|iPod|iPhone/.test( navigator.userAgent ),
15 cursorInterval, lastKeyDownNode, setViewCursorTries, focus, execCommandView;
17 function getView( node ) {
18 return getParent( node, 'wpview-wrap' );
22 * Returns the node or a parent of the node that has the passed className.
23 * Doing this directly is about 40% faster
25 function getParent( node, className ) {
26 while ( node && node.parentNode ) {
27 if ( node.className && ( ' ' + node.className + ' ' ).indexOf( ' ' + className + ' ' ) !== -1 ) {
31 node = node.parentNode;
38 * Get the text/shortcode string for a view.
40 * @param view The view wrapper's node
41 * @returns string The text/shoercode string of the view
43 function getViewText( view ) {
44 if ( view = getView( view ) ) {
45 return window.decodeURIComponent( editor.dom.getAttrib( view, 'data-wpview-text' ) || '' );
52 * Set the view's original text/shortcode string
54 * @param view The view wrapper's HTML id or node
55 * @param text The text string to be set
57 function setViewText( view, text ) {
58 view = getView( view );
61 editor.dom.setAttrib( view, 'data-wpview-text', window.encodeURIComponent( text || '' ) );
68 function _stop( event ) {
69 event.stopPropagation();
72 function setViewCursor( before, view ) {
73 var location = before ? 'before' : 'after',
74 offset = before ? 0 : 1;
76 editor.selection.setCursorLocation( editor.dom.select( '.wpview-selection-' + location, view )[0], offset );
80 function handleEnter( view, before, key ) {
82 padNode = dom.create( 'p' );
84 if ( ! ( Env.ie && Env.ie < 11 ) ) {
85 padNode.innerHTML = '<br data-mce-bogus="1">';
89 view.parentNode.insertBefore( padNode, view );
91 dom.insertAfter( padNode, view );
96 if ( before && key === VK.ENTER ) {
97 setViewCursor( before, view );
99 editor.selection.setCursorLocation( padNode, 0 );
102 editor.nodeChanged();
105 function removeView( view ) {
106 // TODO: trigger an event to run a clean up function.
107 // Maybe `jQuery( view ).trigger( 'remove' );`?
108 editor.undoManager.transact( function() {
110 editor.dom.remove( view );
114 function select( viewNode ) {
118 // Bail if node is already selected.
119 if ( ! viewNode || viewNode === selected ) {
123 // Make sure that the editor is focused.
124 // It is possible that the editor is not focused when the mouse event fires
125 // without focus, the selection will not work properly.
126 editor.getBody().focus();
130 dom.setAttrib( viewNode, 'data-mce-selected', 1 );
132 clipboard = dom.create( 'div', {
133 'class': 'wpview-clipboard',
134 'contenteditable': 'true'
135 }, getViewText( viewNode ) );
137 editor.dom.select( '.wpview-body', viewNode )[0].appendChild( clipboard );
139 // Both of the following are necessary to prevent manipulating the selection/focus
140 dom.bind( clipboard, 'beforedeactivate focusin focusout', _stop );
141 dom.bind( selected, 'beforedeactivate focusin focusout', _stop );
143 // select the hidden div
145 editor.selection.select( clipboard );
147 editor.selection.select( clipboard, true );
150 editor.nodeChanged();
151 editor.fire( 'wpview-selected', viewNode );
155 * Deselect a selected view and remove clipboard
157 function deselect() {
162 clipboard = editor.dom.select( '.wpview-clipboard', selected )[0];
163 dom.unbind( clipboard );
164 dom.remove( clipboard );
166 dom.unbind( selected, 'beforedeactivate focusin focusout click mouseup', _stop );
167 dom.setAttrib( selected, 'data-mce-selected', null );
173 // Check if the `wp.mce` API exists.
174 if ( typeof wp === 'undefined' || ! wp.mce ) {
182 // Remove the content of view wrappers from HTML string
183 function emptyViews( content ) {
184 return content.replace(/<div[^>]+data-wpview-text=\"([^"]+)"[^>]*>[\s\S]+?wpview-selection-after[^>]+>(?: |\u00a0)*<\/p><\/div>/g, '$1' );
187 // Prevent adding undo levels on changes inside a view wrapper
188 editor.on( 'BeforeAddUndo', function( event ) {
189 if ( event.lastLevel && emptyViews( event.level.content ) === emptyViews( event.lastLevel.content ) ) {
190 event.preventDefault();
194 // When the editor's content changes, scan the new content for
195 // matching view patterns, and transform the matches into
197 editor.on( 'BeforeSetContent', function( event ) {
200 if ( ! event.content ) {
205 removeView( selected );
208 node = editor.selection.getNode();
210 // When a url is pasted, only try to embed it when pasted in an empty paragrapgh.
211 if ( event.content.match( /^\s*(https?:\/\/[^\s"]+)\s*$/i ) &&
212 ( node.nodeName !== 'P' || node.parentNode !== editor.getBody() || ! editor.dom.isEmpty( node ) ) ) {
216 event.content = wp.mce.views.toViews( event.content );
219 // When the editor's content has been updated and the DOM has been
220 // processed, render the views in the document.
221 editor.on( 'SetContent', function() {
222 wp.mce.views.render();
225 // Set the cursor before or after a view when clicking next to it.
226 editor.on( 'click', function( event ) {
227 var x = event.clientX,
229 body = editor.getBody(),
230 bodyRect = body.getBoundingClientRect(),
231 first = body.firstChild,
232 firstRect = first.getBoundingClientRect(),
233 last = body.lastChild,
234 lastRect = last.getBoundingClientRect(),
237 if ( y < firstRect.top && ( view = getView( first ) ) ) {
238 setViewCursor( true, view );
239 event.preventDefault();
240 } else if ( y > lastRect.bottom && ( view = getView( last ) ) ) {
241 setViewCursor( false, view );
242 event.preventDefault();
244 tinymce.each( editor.dom.select( '.wpview-wrap' ), function( view ) {
245 var rect = view.getBoundingClientRect();
247 if ( y >= rect.top && y <= rect.bottom ) {
248 if ( x < bodyRect.left ) {
249 setViewCursor( true, view );
250 event.preventDefault();
251 } else if ( x > bodyRect.right ) {
252 setViewCursor( false, view );
253 event.preventDefault();
261 editor.on( 'init', function() {
262 var scrolled = false,
263 selection = editor.selection,
264 MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
266 // When a view is selected, ensure content that is being pasted
267 // or inserted is added to a text node (instead of the view).
268 editor.on( 'BeforeSetContent', function() {
270 view = getView( selection.getNode() );
272 // If the selection is not within a view, bail.
277 if ( ! view.nextSibling || getView( view.nextSibling ) ) {
278 // If there are no additional nodes or the next node is a
279 // view, create a text node after the current view.
280 target = editor.getDoc().createTextNode('');
281 editor.dom.insertAfter( target, view );
283 // Otherwise, find the next text node.
284 walker = new TreeWalker( view.nextSibling, view.nextSibling );
285 target = walker.next();
288 // Select the `target` text node.
289 selection.select( target );
290 selection.collapse( true );
293 editor.dom.bind( editor.getDoc(), 'touchmove', function() {
297 editor.on( 'mousedown mouseup click touchend', function( event ) {
298 var view = getView( event.target );
302 // Contain clicks inside the view wrapper
304 event.stopImmediatePropagation();
305 event.preventDefault();
307 if ( ( event.type === 'touchend' || event.type === 'mousedown' ) && ! event.metaKey && ! event.ctrlKey ) {
308 if ( editor.dom.hasClass( event.target, 'edit' ) ) {
309 wp.mce.views.edit( view );
312 } else if ( editor.dom.hasClass( event.target, 'remove' ) ) {
318 if ( event.type === 'touchend' && scrolled ) {
324 // Returning false stops the ugly bars from appearing in IE11 and stops the view being selected as a range in FF.
325 // Unfortunately, it also inhibits the dragging of views to a new location.
328 if ( event.type === 'touchend' || event.type === 'mousedown' ) {
333 if ( event.type === 'touchend' && scrolled ) {
338 if ( MutationObserver ) {
339 new MutationObserver( function() {
340 editor.fire( 'wp-body-class-change' );
342 .observe( editor.getBody(), {
344 attributeFilter: ['class']
349 editor.on( 'PreProcess', function( event ) {
350 // Empty the wpview wrap nodes
351 tinymce.each( editor.dom.select( 'div[data-wpview-text]', event.node ), function( node ) {
352 node.textContent = node.innerText = '\u00a0';
356 editor.on( 'PostProcess', function( event ) {
357 if ( event.content ) {
358 event.content = event.content.replace( /<div [^>]*?data-wpview-text="([^"]*)"[^>]*>[\s\S]*?<\/div>/g, function( match, shortcode ) {
360 return '<p>' + window.decodeURIComponent( shortcode ) + '</p>';
362 return ''; // If error, remove the view wrapper
367 // Excludes arrow keys, delete, backspace, enter, space bar.
368 // Ref: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
369 function isSpecialKey( key ) {
370 return ( ( key <= 47 && key !== VK.SPACEBAR && key !== VK.ENTER && key !== VK.DELETE && key !== VK.BACKSPACE && ( key < 37 || key > 40 ) ) ||
371 key >= 224 || // OEM or non-printable
372 ( key >= 144 && key <= 150 ) || // Num Lock, Scroll Lock, OEM
373 ( key >= 91 && key <= 93 ) || // Windows keys
374 ( key >= 112 && key <= 135 ) ); // F keys
377 // (De)select views when arrow keys are used to navigate the content of the editor.
378 editor.on( 'keydown', function( event ) {
379 var key = event.keyCode,
381 selection = editor.selection,
382 node, view, cursorBefore, cursorAfter,
383 range, clonedRange, tempRange;
386 // Ignore key presses that involve the command or control key, but continue when in combination with backspace or v.
387 // Also ignore the F# keys.
388 if ( ( ( event.metaKey || event.ctrlKey ) && key !== VK.BACKSPACE && key !== 86 ) || ( key >= 112 && key <= 123 ) ) {
389 // Remove the view when pressing cmd/ctrl+x on keyup, otherwise the browser can't copy the content.
390 if ( ( event.metaKey || event.ctrlKey ) && key === 88 ) {
396 view = getView( selection.getNode() );
398 // If the caret is not within the selected view, deselect the view and bail.
399 if ( view !== selected ) {
404 if ( key === VK.LEFT ) {
405 setViewCursor( true, view );
406 event.preventDefault();
407 } else if ( key === VK.UP ) {
408 if ( view.previousSibling ) {
409 if ( getView( view.previousSibling ) ) {
410 setViewCursor( true, view.previousSibling );
413 selection.select( view.previousSibling, true );
414 selection.collapse();
417 setViewCursor( true, view );
419 event.preventDefault();
420 } else if ( key === VK.RIGHT ) {
421 setViewCursor( false, view );
422 event.preventDefault();
423 } else if ( key === VK.DOWN ) {
424 if ( view.nextSibling ) {
425 if ( getView( view.nextSibling ) ) {
426 setViewCursor( false, view.nextSibling );
429 selection.setCursorLocation( view.nextSibling, 0 );
432 setViewCursor( false, view );
435 event.preventDefault();
436 // Ignore keys that don't insert anything.
437 } else if ( ! isSpecialKey( key ) ) {
438 removeView( selected );
440 if ( key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE ) {
441 event.preventDefault();
445 if ( event.metaKey || event.ctrlKey || ( key >= 112 && key <= 123 ) ) {
449 node = selection.getNode();
450 lastKeyDownNode = node;
451 view = getView( node );
453 // Make sure we don't delete part of a view.
454 // If the range ends or starts with the view, we'll need to trim it.
455 if ( ! selection.isCollapsed() ) {
456 range = selection.getRng();
458 if ( view = getView( range.endContainer ) ) {
459 clonedRange = range.cloneRange();
460 selection.select( view.previousSibling, true );
461 selection.collapse();
462 tempRange = selection.getRng();
463 clonedRange.setEnd( tempRange.endContainer, tempRange.endOffset );
464 selection.setRng( clonedRange );
465 } else if ( view = getView( range.startContainer ) ) {
466 clonedRange = range.cloneRange();
467 clonedRange.setStart( view.nextSibling, 0 );
468 selection.setRng( clonedRange );
473 // Make sure we don't eat any content.
474 if ( event.keyCode === VK.BACKSPACE ) {
475 if ( editor.dom.isEmpty( node ) ) {
476 if ( view = getView( node.previousSibling ) ) {
477 setViewCursor( false, view );
478 editor.dom.remove( node );
479 event.preventDefault();
481 } else if ( ( range = selection.getRng() ) &&
482 range.startOffset === 0 &&
483 range.endOffset === 0 &&
484 ( view = getView( node.previousSibling ) ) ) {
485 setViewCursor( false, view );
486 event.preventDefault();
492 if ( ! ( ( cursorBefore = dom.hasClass( view, 'wpview-selection-before' ) ) ||
493 ( cursorAfter = dom.hasClass( view, 'wpview-selection-after' ) ) ) ) {
497 if ( isSpecialKey( key ) ) {
502 if ( ( cursorAfter && key === VK.UP ) || ( cursorBefore && key === VK.BACKSPACE ) ) {
503 if ( view.previousSibling ) {
504 if ( getView( view.previousSibling ) ) {
505 setViewCursor( false, view.previousSibling );
507 if ( dom.isEmpty( view.previousSibling ) && key === VK.BACKSPACE ) {
508 dom.remove( view.previousSibling );
510 selection.select( view.previousSibling, true );
511 selection.collapse();
515 setViewCursor( true, view );
517 event.preventDefault();
518 } else if ( cursorAfter && ( key === VK.DOWN || key === VK.RIGHT ) ) {
519 if ( view.nextSibling ) {
520 if ( getView( view.nextSibling ) ) {
521 setViewCursor( key === VK.RIGHT, view.nextSibling );
523 selection.setCursorLocation( view.nextSibling, 0 );
526 event.preventDefault();
527 } else if ( cursorBefore && ( key === VK.UP || key === VK.LEFT ) ) {
528 if ( view.previousSibling ) {
529 if ( getView( view.previousSibling ) ) {
530 setViewCursor( key === VK.UP, view.previousSibling );
532 selection.select( view.previousSibling, true );
533 selection.collapse();
536 event.preventDefault();
537 } else if ( cursorBefore && key === VK.DOWN ) {
538 if ( view.nextSibling ) {
539 if ( getView( view.nextSibling ) ) {
540 setViewCursor( true, view.nextSibling );
542 selection.setCursorLocation( view.nextSibling, 0 );
545 setViewCursor( false, view );
547 event.preventDefault();
548 } else if ( ( cursorAfter && key === VK.LEFT ) || ( cursorBefore && key === VK.RIGHT ) ) {
550 event.preventDefault();
551 } else if ( cursorAfter && key === VK.BACKSPACE ) {
553 event.preventDefault();
554 } else if ( cursorAfter ) {
556 } else if ( cursorBefore ) {
557 handleEnter( view , true, key );
560 if ( key === VK.ENTER ) {
561 event.preventDefault();
566 editor.on( 'keyup', function() {
568 removeView( toRemove );
573 editor.on( 'focus', function() {
577 editor.dom.addClass( editor.getBody(), 'has-focus' );
579 // Edge case: show the fake caret when the editor is focused for the first time
580 // and the first element is a view.
581 if ( firstFocus && ( view = getView( editor.getBody().firstChild ) ) ) {
582 setViewCursor( true, view );
588 editor.on( 'blur', function() {
590 editor.dom.removeClass( editor.getBody(), 'has-focus' );
593 editor.on( 'NodeChange', function( event ) {
594 var dom = editor.dom,
595 views = editor.dom.select( '.wpview-wrap' ),
596 className = event.element.className,
597 view = getView( event.element ),
598 lKDN = lastKeyDownNode;
600 lastKeyDownNode = false;
602 clearInterval( cursorInterval );
604 // This runs a lot and is faster than replacing each class separately
605 tinymce.each( views, function ( view ) {
606 if ( view.className ) {
607 view.className = view.className.replace( / ?\bwpview-(?:selection-before|selection-after|cursor-hide)\b/g, '' );
611 if ( focus && view ) {
612 if ( ( className === 'wpview-selection-before' || className === 'wpview-selection-after' ) &&
613 editor.selection.isCollapsed() ) {
615 setViewCursorTries = 0;
619 // Make sure the cursor arrived in the right node.
620 // This is necessary for Firefox.
621 if ( lKDN === view.previousSibling ) {
622 setViewCursor( true, view );
624 } else if ( lKDN === view.nextSibling ) {
625 setViewCursor( false, view );
629 dom.addClass( view, className );
631 cursorInterval = setInterval( function() {
632 if ( dom.hasClass( view, 'wpview-cursor-hide' ) ) {
633 dom.removeClass( view, 'wpview-cursor-hide' );
635 dom.addClass( view, 'wpview-cursor-hide' );
638 // If the cursor lands anywhere else in the view, set the cursor before it.
639 // Only try this once to prevent a loop. (You never know.)
640 } else if ( ! getParent( event.element, 'wpview-clipboard' ) && ! setViewCursorTries ) {
642 setViewCursorTries++;
643 setViewCursor( true, view );
648 editor.on( 'BeforeExecCommand', function() {
649 var node = editor.selection.getNode(),
652 if ( node && ( node.className === 'wpview-selection-before' || node.className === 'wpview-selection-after' ) && ( view = getView( node ) ) ) {
654 execCommandView = view;
658 editor.on( 'ExecCommand', function() {
667 if ( execCommandView ) {
668 node = execCommandView.nextSibling;
670 if ( node && node.nodeName === 'P' && editor.dom.isEmpty( node ) ) {
671 editor.dom.remove( node );
672 setViewCursor( false, execCommandView );
675 execCommandView = false;
679 editor.on( 'ResolveName', function( event ) {
680 if ( editor.dom.hasClass( event.target, 'wpview-wrap' ) ) {
681 event.name = editor.dom.getAttrib( event.target, 'data-wpview-type' ) || 'wpview';
682 event.stopPropagation();
683 } else if ( getView( event.target ) ) {
684 event.preventDefault();
685 event.stopPropagation();
690 getViewText: getViewText,
691 setViewText: setViewText,