3 ( function( $, wpLinkL10n, wp ) {
4 var editor, searchTimer, River, Query, correctedURL, linkNode,
5 emailRegexp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
6 urlRegexp = /^(https?|ftp):\/\/[A-Z0-9.-]+\.[A-Z]{2,4}[^ "]*$/i,
9 isTouch = ( 'ontouchend' in document );
12 return linkNode || editor.dom.getParent( editor.selection.getNode(), 'a[href]' );
16 timeToTriggerRiver: 150,
17 minRiverAJAXDuration: 200,
18 riverBottomThreshold: 5,
24 inputs.wrap = $('#wp-link-wrap');
25 inputs.dialog = $( '#wp-link' );
26 inputs.backdrop = $( '#wp-link-backdrop' );
27 inputs.submit = $( '#wp-link-submit' );
28 inputs.close = $( '#wp-link-close' );
31 inputs.text = $( '#wp-link-text' );
32 inputs.url = $( '#wp-link-url' );
33 inputs.nonce = $( '#_ajax_linking_nonce' );
34 inputs.openInNewTab = $( '#wp-link-target' );
35 inputs.search = $( '#wp-link-search' );
38 rivers.search = new River( $( '#search-results' ) );
39 rivers.recent = new River( $( '#most-recent-results' ) );
40 rivers.elements = inputs.dialog.find( '.query-results' );
42 // Get search notice text
43 inputs.queryNotice = $( '#query-notice-message' );
44 inputs.queryNoticeTextDefault = inputs.queryNotice.find( '.query-notice-default' );
45 inputs.queryNoticeTextHint = inputs.queryNotice.find( '.query-notice-hint' );
47 // Bind event handlers
48 inputs.dialog.keydown( wpLink.keydown );
49 inputs.dialog.keyup( wpLink.keyup );
50 inputs.submit.click( function( event ) {
51 event.preventDefault();
55 inputs.close.add( inputs.backdrop ).add( '#wp-link-cancel button' ).click( function( event ) {
56 event.preventDefault();
60 rivers.elements.on( 'river-select', wpLink.updateFields );
62 // Display 'hint' message when search field or 'query-results' box are focused
63 inputs.search.on( 'focus.wplink', function() {
64 inputs.queryNoticeTextDefault.hide();
65 inputs.queryNoticeTextHint.removeClass( 'screen-reader-text' ).show();
66 } ).on( 'blur.wplink', function() {
67 inputs.queryNoticeTextDefault.show();
68 inputs.queryNoticeTextHint.addClass( 'screen-reader-text' ).hide();
71 inputs.search.on( 'keyup input', function() {
72 window.clearTimeout( searchTimer );
73 searchTimer = window.setTimeout( function() {
74 wpLink.searchInternalLinks();
78 inputs.url.on( 'paste', function() {
79 setTimeout( wpLink.correctURL, 0 );
82 inputs.url.on( 'blur', wpLink.correctURL );
85 // If URL wasn't corrected last time and doesn't start with http:, https:, ? # or /, prepend http://
86 correctURL: function () {
87 var url = $.trim( inputs.url.val() );
89 if ( url && correctedURL !== url && ! /^(?:[a-z]+:|#|\?|\.|\/)/.test( url ) ) {
90 inputs.url.val( 'http://' + url );
95 open: function( editorId, url, text, node ) {
97 $body = $( document.body );
99 $body.addClass( 'modal-open' );
105 window.wpActiveEditor = editorId;
108 if ( ! window.wpActiveEditor ) {
112 this.textarea = $( '#' + window.wpActiveEditor ).get( 0 );
114 if ( typeof window.tinymce !== 'undefined' ) {
115 // Make sure the link wrapper is the last element in the body,
116 // or the inline editor toolbar may show above the backdrop.
117 $body.append( inputs.backdrop, inputs.wrap );
119 ed = window.tinymce.get( window.wpActiveEditor );
121 if ( ed && ! ed.isHidden() ) {
127 if ( editor && window.tinymce.isIE ) {
128 editor.windowManager.wplinkBookmark = editor.selection.getBookmark();
132 if ( ! wpLink.isMCE() && document.selection ) {
133 this.textarea.focus();
134 this.range = document.selection.createRange();
138 inputs.backdrop.show();
140 wpLink.refresh( url, text );
142 $( document ).trigger( 'wplink-open', inputs.wrap );
146 return editor && ! editor.isHidden();
149 refresh: function( url, text ) {
152 // Refresh rivers (clear links, check visibility)
153 rivers.search.refresh();
154 rivers.recent.refresh();
156 if ( wpLink.isMCE() ) {
157 wpLink.mceRefresh( url, text );
159 // For the Text editor the "Link text" field is always shown
160 if ( ! inputs.wrap.hasClass( 'has-text-field' ) ) {
161 inputs.wrap.addClass( 'has-text-field' );
164 if ( document.selection ) {
166 linkText = document.selection.createRange().text || text || '';
167 } else if ( typeof this.textarea.selectionStart !== 'undefined' &&
168 ( this.textarea.selectionStart !== this.textarea.selectionEnd ) ) {
170 text = this.textarea.value.substring( this.textarea.selectionStart, this.textarea.selectionEnd ) || text || '';
173 inputs.text.val( text );
174 wpLink.setDefaultValues();
178 // Close the onscreen keyboard
179 inputs.url.focus().blur();
181 // Focus the URL field and highlight its contents.
182 // If this is moved above the selection changes,
183 // IE will show a flashing cursor over the dialog.
184 window.setTimeout( function() {
185 inputs.url[0].select();
190 // Load the most recent results if this is the first time opening the panel.
191 if ( ! rivers.recent.ul.children().length ) {
192 rivers.recent.ajax();
195 correctedURL = inputs.url.val().replace( /^http:\/\//, '' );
198 hasSelectedText: function( linkNode ) {
199 var node, nodes, i, html = editor.selection.getContent();
201 // Partial html and not a fully selected anchor element
202 if ( /</.test( html ) && ( ! /^<a [^>]+>[^<]+<\/a>$/.test( html ) || html.indexOf('href=') === -1 ) ) {
207 nodes = linkNode.childNodes;
209 if ( nodes.length === 0 ) {
213 for ( i = nodes.length - 1; i >= 0; i-- ) {
216 if ( node.nodeType != 3 && ! window.tinymce.dom.BookmarkManager.isBookmarkNode( node ) ) {
225 mceRefresh: function( searchStr, text ) {
227 linkNode = getLink(),
228 onlyText = this.hasSelectedText( linkNode );
231 linkText = linkNode.innerText || linkNode.textContent;
232 href = editor.dom.getAttrib( linkNode, 'href' );
234 if ( ! $.trim( linkText ) ) {
235 linkText = text || '';
238 if ( searchStr && ( urlRegexp.test( searchStr ) || emailRegexp.test( searchStr ) ) ) {
242 if ( href !== '_wp_link_placeholder' ) {
243 inputs.url.val( href );
244 inputs.openInNewTab.prop( 'checked', '_blank' === editor.dom.getAttrib( linkNode, 'target' ) );
245 inputs.submit.val( wpLinkL10n.update );
247 this.setDefaultValues( linkText );
250 if ( searchStr && searchStr !== href ) {
251 // The user has typed something in the inline dialog. Trigger a search with it.
252 inputs.search.val( searchStr );
254 inputs.search.val( '' );
257 // Always reset the search
258 window.setTimeout( function() {
259 wpLink.searchInternalLinks();
262 linkText = editor.selection.getContent({ format: 'text' }) || text || '';
263 this.setDefaultValues( linkText );
267 inputs.text.val( linkText );
268 inputs.wrap.addClass( 'has-text-field' );
270 inputs.text.val( '' );
271 inputs.wrap.removeClass( 'has-text-field' );
275 close: function( reset ) {
276 $( document.body ).removeClass( 'modal-open' );
278 if ( reset !== 'noReset' ) {
279 if ( ! wpLink.isMCE() ) {
280 wpLink.textarea.focus();
282 if ( wpLink.range ) {
283 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
284 wpLink.range.select();
287 if ( editor.plugins.wplink ) {
288 editor.plugins.wplink.close();
295 inputs.backdrop.hide();
298 correctedURL = false;
300 $( document ).trigger( 'wplink-close', inputs.wrap );
303 getAttrs: function() {
307 href: $.trim( inputs.url.val() ),
308 target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
312 buildHtml: function(attrs) {
313 var html = '<a href="' + attrs.href + '"';
315 if ( attrs.target ) {
316 html += ' target="' + attrs.target + '"';
323 if ( wpLink.isMCE() ) {
330 htmlUpdate: function() {
331 var attrs, text, html, begin, end, cursor, selection,
332 textarea = wpLink.textarea;
338 attrs = wpLink.getAttrs();
339 text = inputs.text.val();
341 // If there's no href, return.
342 if ( ! attrs.href ) {
346 html = wpLink.buildHtml(attrs);
349 if ( document.selection && wpLink.range ) {
351 // Note: If no text is selected, IE will not place the cursor
352 // inside the closing tag.
354 wpLink.range.text = html + ( text || wpLink.range.text ) + '</a>';
355 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
356 wpLink.range.select();
359 } else if ( typeof textarea.selectionStart !== 'undefined' ) {
361 begin = textarea.selectionStart;
362 end = textarea.selectionEnd;
363 selection = text || textarea.value.substring( begin, end );
364 html = html + selection + '</a>';
365 cursor = begin + html.length;
367 // If no text is selected, place the cursor inside the closing tag.
368 if ( begin === end && ! selection ) {
373 textarea.value.substring( 0, begin ) +
375 textarea.value.substring( end, textarea.value.length )
378 // Update cursor position
379 textarea.selectionStart = textarea.selectionEnd = cursor;
385 // Audible confirmation message when a link has been inserted in the Editor.
386 wp.a11y.speak( wpLinkL10n.linkInserted );
389 mceUpdate: function() {
390 var attrs = wpLink.getAttrs(),
393 if ( window.tinymce.isIE && editor.windowManager.wplinkBookmark ) {
394 editor.selection.moveToBookmark( editor.windowManager.wplinkBookmark );
395 editor.windowManager.wplinkBookmark = null;
398 if ( ! attrs.href ) {
399 editor.execCommand( 'unlink' );
406 if ( inputs.wrap.hasClass( 'has-text-field' ) ) {
407 text = inputs.text.val() || attrs.href;
412 if ( 'innerText' in link ) {
413 link.innerText = text;
415 link.textContent = text;
419 // Not editing any more
420 attrs['data-wplink-edit'] = null;
421 editor.dom.setAttribs( link, attrs );
424 editor.selection.setNode( editor.dom.create( 'a', attrs, editor.dom.encode( text ) ) );
426 editor.execCommand( 'mceInsertLink', false, attrs );
430 wpLink.close( 'noReset' );
432 editor.nodeChanged();
434 // Audible confirmation message when a link has been inserted in the Editor.
435 wp.a11y.speak( wpLinkL10n.linkInserted );
438 updateFields: function( e, li ) {
439 inputs.url.val( li.children( '.item-permalink' ).val() );
442 getUrlFromSelection: function( selection ) {
444 if ( this.isMCE() ) {
445 selection = editor.selection.getContent({ format: 'text' });
446 } else if ( document.selection && wpLink.range ) {
447 selection = wpLink.range.text;
448 } else if ( typeof this.textarea.selectionStart !== 'undefined' ) {
449 selection = this.textarea.value.substring( this.textarea.selectionStart, this.textarea.selectionEnd );
453 selection = $.trim( selection );
455 if ( selection && emailRegexp.test( selection ) ) {
456 // Selection is email address
457 return 'mailto:' + selection;
458 } else if ( selection && urlRegexp.test( selection ) ) {
460 return selection.replace( /&|�?38;/gi, '&' );
466 setDefaultValues: function( selection ) {
467 inputs.url.val( this.getUrlFromSelection( selection ) );
469 // Empty the search field and swap the "rivers".
470 inputs.search.val('');
471 wpLink.searchInternalLinks();
473 // Update save prompt.
474 inputs.submit.val( wpLinkL10n.save );
477 searchInternalLinks: function() {
479 search = inputs.search.val() || '';
481 if ( search.length > 2 ) {
482 rivers.recent.hide();
483 rivers.search.show();
485 // Don't search if the keypress didn't change the title.
486 if ( wpLink.lastSearch == search )
489 wpLink.lastSearch = search;
490 waiting = inputs.search.parent().find( '.spinner' ).addClass( 'is-active' );
492 rivers.search.change( search );
493 rivers.search.ajax( function() {
494 waiting.removeClass( 'is-active' );
497 rivers.search.hide();
498 rivers.recent.show();
503 rivers.search.next();
504 rivers.recent.next();
508 rivers.search.prev();
509 rivers.recent.prev();
512 keydown: function( event ) {
516 if ( 27 === event.keyCode ) {
518 event.stopImmediatePropagation();
520 } else if ( 9 === event.keyCode ) {
521 id = event.target.id;
523 // wp-link-submit must always be the last focusable element in the dialog.
524 // following focusable elements will be skipped on keyboard navigation.
525 if ( id === 'wp-link-submit' && ! event.shiftKey ) {
526 inputs.close.focus();
527 event.preventDefault();
528 } else if ( id === 'wp-link-close' && event.shiftKey ) {
529 inputs.submit.focus();
530 event.preventDefault();
534 // Up Arrow and Down Arrow keys.
535 if ( 38 !== event.keyCode && 40 !== event.keyCode ) {
539 if ( document.activeElement &&
540 ( document.activeElement.id === 'link-title-field' || document.activeElement.id === 'url-field' ) ) {
545 fn = 38 === event.keyCode ? 'prev' : 'next';
546 clearInterval( wpLink.keyInterval );
548 wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
549 event.preventDefault();
552 keyup: function( event ) {
553 // Up Arrow and Down Arrow keys.
554 if ( 38 === event.keyCode || 40 === event.keyCode ) {
555 clearInterval( wpLink.keyInterval );
556 event.preventDefault();
560 delayedCallback: function( func, delay ) {
561 var timeoutTriggered, funcTriggered, funcArgs, funcContext;
566 setTimeout( function() {
568 return func.apply( funcContext, funcArgs );
570 timeoutTriggered = true;
574 if ( timeoutTriggered )
575 return func.apply( this, arguments );
577 funcArgs = arguments;
579 funcTriggered = true;
584 River = function( element, search ) {
586 this.element = element;
587 this.ul = element.children( 'ul' );
588 this.contentHeight = element.children( '#link-selector-height' );
589 this.waiting = element.find('.river-waiting');
591 this.change( search );
594 $( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
597 element.on( 'click', 'li', function( event ) {
598 self.select( $( this ), event );
602 $.extend( River.prototype, {
603 refresh: function() {
605 this.visible = this.element.is( ':visible' );
608 if ( ! this.visible ) {
616 this.visible = false;
618 // Selects a list item and triggers the river-select event.
619 select: function( li, event ) {
620 var liHeight, elHeight, liTop, elTop;
622 if ( li.hasClass( 'unselectable' ) || li == this.selected )
626 this.selected = li.addClass( 'selected' );
627 // Make sure the element is visible
628 liHeight = li.outerHeight();
629 elHeight = this.element.height();
630 liTop = li.position().top;
631 elTop = this.element.scrollTop();
633 if ( liTop < 0 ) // Make first visible element
634 this.element.scrollTop( elTop + liTop );
635 else if ( liTop + liHeight > elHeight ) // Make last visible element
636 this.element.scrollTop( elTop + liTop - elHeight + liHeight );
638 // Trigger the river-select event
639 this.element.trigger( 'river-select', [ li, event, this ] );
641 deselect: function() {
643 this.selected.removeClass( 'selected' );
644 this.selected = false;
647 if ( ! this.visible )
651 if ( this.selected ) {
652 to = this.selected.prev( 'li' );
658 if ( ! this.visible )
661 var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
665 ajax: function( callback ) {
667 delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
668 response = wpLink.delayedCallback( function( results, params ) {
669 self.process( results, params );
671 callback( results, params );
674 this.query.ajax( response );
676 change: function( search ) {
677 if ( this.query && this._search == search )
680 this._search = search;
681 this.query = new Query( search );
682 this.element.scrollTop( 0 );
684 process: function( results, params ) {
685 var list = '', alt = true, classes = '',
686 firstPage = params.page == 1;
690 list += '<li class="unselectable no-matches-found"><span class="item-title"><em>' +
691 wpLinkL10n.noMatchesFound + '</em></span></li>';
694 $.each( results, function() {
695 classes = alt ? 'alternate' : '';
696 classes += this.title ? '' : ' no-title';
697 list += classes ? '<li class="' + classes + '">' : '<li>';
698 list += '<input type="hidden" class="item-permalink" value="' + this.permalink + '" />';
699 list += '<span class="item-title">';
700 list += this.title ? this.title : wpLinkL10n.noTitle;
701 list += '</span><span class="item-info">' + this.info + '</span></li>';
706 this.ul[ firstPage ? 'html' : 'append' ]( list );
708 maybeLoad: function() {
711 bottom = el.scrollTop() + el.height();
713 if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
716 setTimeout(function() {
717 var newTop = el.scrollTop(),
718 newBottom = newTop + el.height();
720 if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
723 self.waiting.addClass( 'is-active' );
724 el.scrollTop( newTop + self.waiting.outerHeight() );
726 self.ajax( function() {
727 self.waiting.removeClass( 'is-active' );
729 }, wpLink.timeToTriggerRiver );
733 Query = function( search ) {
735 this.allLoaded = false;
736 this.querying = false;
737 this.search = search;
740 $.extend( Query.prototype, {
742 return ! ( this.querying || this.allLoaded );
744 ajax: function( callback ) {
747 action : 'wp-link-ajax',
749 '_ajax_linking_nonce' : inputs.nonce.val()
753 query.search = this.search;
755 this.querying = true;
757 $.post( window.ajaxurl, query, function( r ) {
759 self.querying = false;
760 self.allLoaded = ! r;
761 callback( r, query );
766 $( document ).ready( wpLink.init );
767 })( jQuery, window.wpLinkL10n, window.wp );