1 /* global ajaxurl, tinymce, wpLinkL10n, setUserSetting, wpActiveEditor */
5 var editor, searchTimer, River, Query,
8 isTouch = ( 'ontouchend' in document );
11 timeToTriggerRiver: 150,
12 minRiverAJAXDuration: 200,
13 riverBottomThreshold: 5,
19 inputs.wrap = $('#wp-link-wrap');
20 inputs.dialog = $( '#wp-link' );
21 inputs.backdrop = $( '#wp-link-backdrop' );
22 inputs.submit = $( '#wp-link-submit' );
23 inputs.close = $( '#wp-link-close' );
25 inputs.url = $( '#url-field' );
26 inputs.nonce = $( '#_ajax_linking_nonce' );
28 inputs.title = $( '#link-title-field' );
30 inputs.openInNewTab = $( '#link-target-checkbox' );
31 inputs.search = $( '#search-field' );
33 rivers.search = new River( $( '#search-results' ) );
34 rivers.recent = new River( $( '#most-recent-results' ) );
35 rivers.elements = inputs.dialog.find( '.query-results' );
37 // Get search notice text
38 inputs.queryNotice = $( '#query-notice-message' );
39 inputs.queryNoticeTextDefault = inputs.queryNotice.find( '.query-notice-default' );
40 inputs.queryNoticeTextHint = inputs.queryNotice.find( '.query-notice-hint' );
42 // Bind event handlers
43 inputs.dialog.keydown( wpLink.keydown );
44 inputs.dialog.keyup( wpLink.keyup );
45 inputs.submit.click( function( event ) {
46 event.preventDefault();
49 inputs.close.add( inputs.backdrop ).add( '#wp-link-cancel a' ).click( function( event ) {
50 event.preventDefault();
54 $( '#wp-link-search-toggle' ).on( 'click', wpLink.toggleInternalLinking );
56 rivers.elements.on( 'river-select', wpLink.updateFields );
58 // Display 'hint' message when search field or 'query-results' box are focused
59 inputs.search.on( 'focus.wplink', function() {
60 inputs.queryNoticeTextDefault.hide();
61 inputs.queryNoticeTextHint.removeClass( 'screen-reader-text' ).show();
62 } ).on( 'blur.wplink', function() {
63 inputs.queryNoticeTextDefault.show();
64 inputs.queryNoticeTextHint.addClass( 'screen-reader-text' ).hide();
67 inputs.search.keyup( function() {
70 window.clearTimeout( searchTimer );
71 searchTimer = window.setTimeout( function() {
72 wpLink.searchInternalLinks.call( self );
77 open: function( editorId ) {
83 window.wpActiveEditor = editorId;
86 if ( ! window.wpActiveEditor ) {
90 this.textarea = $( '#' + window.wpActiveEditor ).get( 0 );
92 if ( typeof tinymce !== 'undefined' ) {
93 ed = tinymce.get( wpActiveEditor );
95 if ( ed && ! ed.isHidden() ) {
101 if ( editor && tinymce.isIE ) {
102 editor.windowManager.bookmark = editor.selection.getBookmark();
106 if ( ! wpLink.isMCE() && document.selection ) {
107 this.textarea.focus();
108 this.range = document.selection.createRange();
112 inputs.backdrop.show();
115 $( document ).trigger( 'wplink-open', inputs.wrap );
119 return editor && ! editor.isHidden();
122 refresh: function() {
123 // Refresh rivers (clear links, check visibility)
124 rivers.search.refresh();
125 rivers.recent.refresh();
127 if ( wpLink.isMCE() ) {
130 wpLink.setDefaultValues();
134 // Close the onscreen keyboard
135 inputs.url.focus().blur();
137 // Focus the URL field and highlight its contents.
138 // If this is moved above the selection changes,
139 // IE will show a flashing cursor over the dialog.
140 inputs.url.focus()[0].select();
143 // Load the most recent results if this is the first time opening the panel.
144 if ( ! rivers.recent.ul.children().length ) {
145 rivers.recent.ajax();
149 mceRefresh: function() {
152 // If link exists, select proper values.
153 if ( e = editor.dom.getParent( editor.selection.getNode(), 'A' ) ) {
154 // Set URL and description.
155 inputs.url.val( editor.dom.getAttrib( e, 'href' ) );
156 inputs.title.val( editor.dom.getAttrib( e, 'title' ) );
157 // Set open in new tab.
158 inputs.openInNewTab.prop( 'checked', ( '_blank' === editor.dom.getAttrib( e, 'target' ) ) );
159 // Update save prompt.
160 inputs.submit.val( wpLinkL10n.update );
162 // If there's no link, set the default values.
164 wpLink.setDefaultValues();
169 if ( ! wpLink.isMCE() ) {
170 wpLink.textarea.focus();
172 if ( wpLink.range ) {
173 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
174 wpLink.range.select();
180 inputs.backdrop.hide();
182 $( document ).trigger( 'wplink-close', inputs.wrap );
185 getAttrs: function() {
187 href: inputs.url.val(),
188 title: inputs.title.val(),
189 target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
194 if ( wpLink.isMCE() )
200 htmlUpdate: function() {
201 var attrs, html, begin, end, cursor, title, selection,
202 textarea = wpLink.textarea;
207 attrs = wpLink.getAttrs();
209 // If there's no href, return.
210 if ( ! attrs.href || attrs.href == 'http://' )
214 html = '<a href="' + attrs.href + '"';
217 title = attrs.title.replace( /</g, '<' ).replace( />/g, '>' ).replace( /"/g, '"' );
218 html += ' title="' + title + '"';
221 if ( attrs.target ) {
222 html += ' target="' + attrs.target + '"';
228 if ( document.selection && wpLink.range ) {
230 // Note: If no text is selected, IE will not place the cursor
231 // inside the closing tag.
233 wpLink.range.text = html + wpLink.range.text + '</a>';
234 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
235 wpLink.range.select();
238 } else if ( typeof textarea.selectionStart !== 'undefined' ) {
240 begin = textarea.selectionStart;
241 end = textarea.selectionEnd;
242 selection = textarea.value.substring( begin, end );
243 html = html + selection + '</a>';
244 cursor = begin + html.length;
246 // If no text is selected, place the cursor inside the closing tag.
248 cursor -= '</a>'.length;
250 textarea.value = textarea.value.substring( 0, begin ) + html +
251 textarea.value.substring( end, textarea.value.length );
253 // Update cursor position
254 textarea.selectionStart = textarea.selectionEnd = cursor;
261 mceUpdate: function() {
263 attrs = wpLink.getAttrs();
268 if ( tinymce.isIE ) {
269 editor.selection.moveToBookmark( editor.windowManager.bookmark );
272 link = editor.dom.getParent( editor.selection.getNode(), 'a[href]' );
274 // If the values are empty, unlink and return
275 if ( ! attrs.href || attrs.href == 'http://' ) {
276 editor.execCommand( 'unlink' );
281 editor.dom.setAttribs( link, attrs );
283 editor.execCommand( 'mceInsertLink', false, attrs );
286 // Move the cursor to the end of the selection
287 editor.selection.collapse();
290 updateFields: function( e, li ) {
291 inputs.url.val( li.children( '.item-permalink' ).val() );
292 inputs.title.val( li.hasClass( 'no-title' ) ? '' : li.children( '.item-title' ).text() );
295 setDefaultValues: function() {
296 var selection = editor && editor.selection.getContent(),
297 emailRegexp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
298 urlRegexp = /^(https?|ftp):\/\/[A-Z0-9.-]+\.[A-Z]{2,4}[^ "]*$/i;
300 if ( selection && emailRegexp.test( selection ) ) {
301 // Selection is email address
302 inputs.url.val( 'mailto:' + selection );
303 } else if ( selection && urlRegexp.test( selection ) ) {
305 inputs.url.val( selection.replace( /&|�?38;/gi, '&' ) );
307 // Set URL to default.
308 inputs.url.val( 'http://' );
311 // Set description to default.
312 inputs.title.val( '' );
314 // Update save prompt.
315 inputs.submit.val( wpLinkL10n.save );
318 searchInternalLinks: function() {
319 var t = $( this ), waiting,
322 if ( search.length > 2 ) {
323 rivers.recent.hide();
324 rivers.search.show();
326 // Don't search if the keypress didn't change the title.
327 if ( wpLink.lastSearch == search )
330 wpLink.lastSearch = search;
331 waiting = t.parent().find('.spinner').show();
333 rivers.search.change( search );
334 rivers.search.ajax( function() {
338 rivers.search.hide();
339 rivers.recent.show();
344 rivers.search.next();
345 rivers.recent.next();
349 rivers.search.prev();
350 rivers.recent.prev();
353 keydown: function( event ) {
357 if ( key.ESCAPE === event.keyCode ) {
359 event.stopImmediatePropagation();
360 } else if ( key.TAB === event.keyCode ) {
361 id = event.target.id;
363 // wp-link-submit must always be the last focusable element in the dialog.
364 // following focusable elements will be skipped on keyboard navigation.
365 if ( id === 'wp-link-submit' && ! event.shiftKey ) {
366 inputs.close.focus();
367 event.preventDefault();
368 } else if ( id === 'wp-link-close' && event.shiftKey ) {
369 inputs.submit.focus();
370 event.preventDefault();
374 if ( event.keyCode !== key.UP && event.keyCode !== key.DOWN ) {
378 if ( document.activeElement &&
379 ( document.activeElement.id === 'link-title-field' || document.activeElement.id === 'url-field' ) ) {
383 fn = event.keyCode === key.UP ? 'prev' : 'next';
384 clearInterval( wpLink.keyInterval );
386 wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
387 event.preventDefault();
390 keyup: function( event ) {
391 var key = $.ui.keyCode;
393 if ( event.which === key.UP || event.which === key.DOWN ) {
394 clearInterval( wpLink.keyInterval );
395 event.preventDefault();
399 delayedCallback: function( func, delay ) {
400 var timeoutTriggered, funcTriggered, funcArgs, funcContext;
405 setTimeout( function() {
407 return func.apply( funcContext, funcArgs );
409 timeoutTriggered = true;
413 if ( timeoutTriggered )
414 return func.apply( this, arguments );
416 funcArgs = arguments;
418 funcTriggered = true;
422 toggleInternalLinking: function( event ) {
423 var visible = inputs.wrap.hasClass( 'search-panel-visible' );
425 inputs.wrap.toggleClass( 'search-panel-visible', ! visible );
426 setUserSetting( 'wplink', visible ? '0' : '1' );
427 inputs[ ! visible ? 'search' : 'url' ].focus();
428 event.preventDefault();
432 River = function( element, search ) {
434 this.element = element;
435 this.ul = element.children( 'ul' );
436 this.contentHeight = element.children( '#link-selector-height' );
437 this.waiting = element.find('.river-waiting');
439 this.change( search );
442 $( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
445 element.on( 'click', 'li', function( event ) {
446 self.select( $( this ), event );
450 $.extend( River.prototype, {
451 refresh: function() {
453 this.visible = this.element.is( ':visible' );
456 if ( ! this.visible ) {
464 this.visible = false;
466 // Selects a list item and triggers the river-select event.
467 select: function( li, event ) {
468 var liHeight, elHeight, liTop, elTop;
470 if ( li.hasClass( 'unselectable' ) || li == this.selected )
474 this.selected = li.addClass( 'selected' );
475 // Make sure the element is visible
476 liHeight = li.outerHeight();
477 elHeight = this.element.height();
478 liTop = li.position().top;
479 elTop = this.element.scrollTop();
481 if ( liTop < 0 ) // Make first visible element
482 this.element.scrollTop( elTop + liTop );
483 else if ( liTop + liHeight > elHeight ) // Make last visible element
484 this.element.scrollTop( elTop + liTop - elHeight + liHeight );
486 // Trigger the river-select event
487 this.element.trigger( 'river-select', [ li, event, this ] );
489 deselect: function() {
491 this.selected.removeClass( 'selected' );
492 this.selected = false;
495 if ( ! this.visible )
499 if ( this.selected ) {
500 to = this.selected.prev( 'li' );
506 if ( ! this.visible )
509 var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
513 ajax: function( callback ) {
515 delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
516 response = wpLink.delayedCallback( function( results, params ) {
517 self.process( results, params );
519 callback( results, params );
522 this.query.ajax( response );
524 change: function( search ) {
525 if ( this.query && this._search == search )
528 this._search = search;
529 this.query = new Query( search );
530 this.element.scrollTop( 0 );
532 process: function( results, params ) {
533 var list = '', alt = true, classes = '',
534 firstPage = params.page == 1;
538 list += '<li class="unselectable no-matches-found"><span class="item-title"><em>' +
539 wpLinkL10n.noMatchesFound + '</em></span></li>';
542 $.each( results, function() {
543 classes = alt ? 'alternate' : '';
544 classes += this.title ? '' : ' no-title';
545 list += classes ? '<li class="' + classes + '">' : '<li>';
546 list += '<input type="hidden" class="item-permalink" value="' + this.permalink + '" />';
547 list += '<span class="item-title">';
548 list += this.title ? this.title : wpLinkL10n.noTitle;
549 list += '</span><span class="item-info">' + this.info + '</span></li>';
554 this.ul[ firstPage ? 'html' : 'append' ]( list );
556 maybeLoad: function() {
559 bottom = el.scrollTop() + el.height();
561 if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
564 setTimeout(function() {
565 var newTop = el.scrollTop(),
566 newBottom = newTop + el.height();
568 if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
572 el.scrollTop( newTop + self.waiting.outerHeight() );
574 self.ajax( function() {
577 }, wpLink.timeToTriggerRiver );
581 Query = function( search ) {
583 this.allLoaded = false;
584 this.querying = false;
585 this.search = search;
588 $.extend( Query.prototype, {
590 return ! ( this.querying || this.allLoaded );
592 ajax: function( callback ) {
595 action : 'wp-link-ajax',
597 '_ajax_linking_nonce' : inputs.nonce.val()
601 query.search = this.search;
603 this.querying = true;
605 $.post( ajaxurl, query, function( r ) {
607 self.querying = false;
608 self.allLoaded = ! r;
609 callback( r, query );
614 $( document ).ready( wpLink.init );