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 ) {
80 $( document.body ).addClass( 'modal-open' );
85 window.wpActiveEditor = editorId;
88 if ( ! window.wpActiveEditor ) {
92 this.textarea = $( '#' + window.wpActiveEditor ).get( 0 );
94 if ( typeof tinymce !== 'undefined' ) {
95 ed = tinymce.get( wpActiveEditor );
97 if ( ed && ! ed.isHidden() ) {
103 if ( editor && tinymce.isIE ) {
104 editor.windowManager.bookmark = editor.selection.getBookmark();
108 if ( ! wpLink.isMCE() && document.selection ) {
109 this.textarea.focus();
110 this.range = document.selection.createRange();
114 inputs.backdrop.show();
117 $( document ).trigger( 'wplink-open', inputs.wrap );
121 return editor && ! editor.isHidden();
124 refresh: function() {
125 // Refresh rivers (clear links, check visibility)
126 rivers.search.refresh();
127 rivers.recent.refresh();
129 if ( wpLink.isMCE() ) {
132 wpLink.setDefaultValues();
136 // Close the onscreen keyboard
137 inputs.url.focus().blur();
139 // Focus the URL field and highlight its contents.
140 // If this is moved above the selection changes,
141 // IE will show a flashing cursor over the dialog.
142 inputs.url.focus()[0].select();
145 // Load the most recent results if this is the first time opening the panel.
146 if ( ! rivers.recent.ul.children().length ) {
147 rivers.recent.ajax();
151 mceRefresh: function() {
154 // If link exists, select proper values.
155 if ( e = editor.dom.getParent( editor.selection.getNode(), 'A' ) ) {
156 // Set URL and description.
157 inputs.url.val( editor.dom.getAttrib( e, 'href' ) );
158 inputs.title.val( editor.dom.getAttrib( e, 'title' ) );
159 // Set open in new tab.
160 inputs.openInNewTab.prop( 'checked', ( '_blank' === editor.dom.getAttrib( e, 'target' ) ) );
161 // Update save prompt.
162 inputs.submit.val( wpLinkL10n.update );
164 // If there's no link, set the default values.
166 wpLink.setDefaultValues();
171 $( document.body ).removeClass( 'modal-open' );
173 if ( ! wpLink.isMCE() ) {
174 wpLink.textarea.focus();
176 if ( wpLink.range ) {
177 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
178 wpLink.range.select();
184 inputs.backdrop.hide();
186 $( document ).trigger( 'wplink-close', inputs.wrap );
189 getAttrs: function() {
191 href: inputs.url.val(),
192 title: inputs.title.val(),
193 target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
198 if ( wpLink.isMCE() )
204 htmlUpdate: function() {
205 var attrs, html, begin, end, cursor, title, selection,
206 textarea = wpLink.textarea;
211 attrs = wpLink.getAttrs();
213 // If there's no href, return.
214 if ( ! attrs.href || attrs.href == 'http://' )
218 html = '<a href="' + attrs.href + '"';
221 title = attrs.title.replace( /</g, '<' ).replace( />/g, '>' ).replace( /"/g, '"' );
222 html += ' title="' + title + '"';
225 if ( attrs.target ) {
226 html += ' target="' + attrs.target + '"';
232 if ( document.selection && wpLink.range ) {
234 // Note: If no text is selected, IE will not place the cursor
235 // inside the closing tag.
237 wpLink.range.text = html + wpLink.range.text + '</a>';
238 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
239 wpLink.range.select();
242 } else if ( typeof textarea.selectionStart !== 'undefined' ) {
244 begin = textarea.selectionStart;
245 end = textarea.selectionEnd;
246 selection = textarea.value.substring( begin, end );
247 html = html + selection + '</a>';
248 cursor = begin + html.length;
250 // If no text is selected, place the cursor inside the closing tag.
252 cursor -= '</a>'.length;
254 textarea.value = textarea.value.substring( 0, begin ) + html +
255 textarea.value.substring( end, textarea.value.length );
257 // Update cursor position
258 textarea.selectionStart = textarea.selectionEnd = cursor;
265 mceUpdate: function() {
267 attrs = wpLink.getAttrs();
272 if ( tinymce.isIE ) {
273 editor.selection.moveToBookmark( editor.windowManager.bookmark );
276 link = editor.dom.getParent( editor.selection.getNode(), 'a[href]' );
278 // If the values are empty, unlink and return
279 if ( ! attrs.href || attrs.href == 'http://' ) {
280 editor.execCommand( 'unlink' );
285 editor.dom.setAttribs( link, attrs );
287 editor.execCommand( 'mceInsertLink', false, attrs );
290 // Move the cursor to the end of the selection
291 editor.selection.collapse();
294 updateFields: function( e, li ) {
295 inputs.url.val( li.children( '.item-permalink' ).val() );
296 inputs.title.val( li.hasClass( 'no-title' ) ? '' : li.children( '.item-title' ).text() );
299 setDefaultValues: function() {
300 var selection = editor && editor.selection.getContent(),
301 emailRegexp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
302 urlRegexp = /^(https?|ftp):\/\/[A-Z0-9.-]+\.[A-Z]{2,4}[^ "]*$/i;
304 if ( selection && emailRegexp.test( selection ) ) {
305 // Selection is email address
306 inputs.url.val( 'mailto:' + selection );
307 } else if ( selection && urlRegexp.test( selection ) ) {
309 inputs.url.val( selection.replace( /&|�?38;/gi, '&' ) );
311 // Set URL to default.
312 inputs.url.val( 'http://' );
315 // Set description to default.
316 inputs.title.val( '' );
318 // Update save prompt.
319 inputs.submit.val( wpLinkL10n.save );
322 searchInternalLinks: function() {
323 var t = $( this ), waiting,
326 if ( search.length > 2 ) {
327 rivers.recent.hide();
328 rivers.search.show();
330 // Don't search if the keypress didn't change the title.
331 if ( wpLink.lastSearch == search )
334 wpLink.lastSearch = search;
335 waiting = t.parent().find('.spinner').show();
337 rivers.search.change( search );
338 rivers.search.ajax( function() {
342 rivers.search.hide();
343 rivers.recent.show();
348 rivers.search.next();
349 rivers.recent.next();
353 rivers.search.prev();
354 rivers.recent.prev();
357 keydown: function( event ) {
361 if ( key.ESCAPE === event.keyCode ) {
363 event.stopImmediatePropagation();
364 } else if ( key.TAB === event.keyCode ) {
365 id = event.target.id;
367 // wp-link-submit must always be the last focusable element in the dialog.
368 // following focusable elements will be skipped on keyboard navigation.
369 if ( id === 'wp-link-submit' && ! event.shiftKey ) {
370 inputs.close.focus();
371 event.preventDefault();
372 } else if ( id === 'wp-link-close' && event.shiftKey ) {
373 inputs.submit.focus();
374 event.preventDefault();
378 if ( event.keyCode !== key.UP && event.keyCode !== key.DOWN ) {
382 if ( document.activeElement &&
383 ( document.activeElement.id === 'link-title-field' || document.activeElement.id === 'url-field' ) ) {
387 fn = event.keyCode === key.UP ? 'prev' : 'next';
388 clearInterval( wpLink.keyInterval );
390 wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
391 event.preventDefault();
394 keyup: function( event ) {
395 var key = $.ui.keyCode;
397 if ( event.which === key.UP || event.which === key.DOWN ) {
398 clearInterval( wpLink.keyInterval );
399 event.preventDefault();
403 delayedCallback: function( func, delay ) {
404 var timeoutTriggered, funcTriggered, funcArgs, funcContext;
409 setTimeout( function() {
411 return func.apply( funcContext, funcArgs );
413 timeoutTriggered = true;
417 if ( timeoutTriggered )
418 return func.apply( this, arguments );
420 funcArgs = arguments;
422 funcTriggered = true;
426 toggleInternalLinking: function( event ) {
427 var visible = inputs.wrap.hasClass( 'search-panel-visible' );
429 inputs.wrap.toggleClass( 'search-panel-visible', ! visible );
430 setUserSetting( 'wplink', visible ? '0' : '1' );
431 inputs[ ! visible ? 'search' : 'url' ].focus();
432 event.preventDefault();
436 River = function( element, search ) {
438 this.element = element;
439 this.ul = element.children( 'ul' );
440 this.contentHeight = element.children( '#link-selector-height' );
441 this.waiting = element.find('.river-waiting');
443 this.change( search );
446 $( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
449 element.on( 'click', 'li', function( event ) {
450 self.select( $( this ), event );
454 $.extend( River.prototype, {
455 refresh: function() {
457 this.visible = this.element.is( ':visible' );
460 if ( ! this.visible ) {
468 this.visible = false;
470 // Selects a list item and triggers the river-select event.
471 select: function( li, event ) {
472 var liHeight, elHeight, liTop, elTop;
474 if ( li.hasClass( 'unselectable' ) || li == this.selected )
478 this.selected = li.addClass( 'selected' );
479 // Make sure the element is visible
480 liHeight = li.outerHeight();
481 elHeight = this.element.height();
482 liTop = li.position().top;
483 elTop = this.element.scrollTop();
485 if ( liTop < 0 ) // Make first visible element
486 this.element.scrollTop( elTop + liTop );
487 else if ( liTop + liHeight > elHeight ) // Make last visible element
488 this.element.scrollTop( elTop + liTop - elHeight + liHeight );
490 // Trigger the river-select event
491 this.element.trigger( 'river-select', [ li, event, this ] );
493 deselect: function() {
495 this.selected.removeClass( 'selected' );
496 this.selected = false;
499 if ( ! this.visible )
503 if ( this.selected ) {
504 to = this.selected.prev( 'li' );
510 if ( ! this.visible )
513 var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
517 ajax: function( callback ) {
519 delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
520 response = wpLink.delayedCallback( function( results, params ) {
521 self.process( results, params );
523 callback( results, params );
526 this.query.ajax( response );
528 change: function( search ) {
529 if ( this.query && this._search == search )
532 this._search = search;
533 this.query = new Query( search );
534 this.element.scrollTop( 0 );
536 process: function( results, params ) {
537 var list = '', alt = true, classes = '',
538 firstPage = params.page == 1;
542 list += '<li class="unselectable no-matches-found"><span class="item-title"><em>' +
543 wpLinkL10n.noMatchesFound + '</em></span></li>';
546 $.each( results, function() {
547 classes = alt ? 'alternate' : '';
548 classes += this.title ? '' : ' no-title';
549 list += classes ? '<li class="' + classes + '">' : '<li>';
550 list += '<input type="hidden" class="item-permalink" value="' + this.permalink + '" />';
551 list += '<span class="item-title">';
552 list += this.title ? this.title : wpLinkL10n.noTitle;
553 list += '</span><span class="item-info">' + this.info + '</span></li>';
558 this.ul[ firstPage ? 'html' : 'append' ]( list );
560 maybeLoad: function() {
563 bottom = el.scrollTop() + el.height();
565 if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
568 setTimeout(function() {
569 var newTop = el.scrollTop(),
570 newBottom = newTop + el.height();
572 if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
576 el.scrollTop( newTop + self.waiting.outerHeight() );
578 self.ajax( function() {
581 }, wpLink.timeToTriggerRiver );
585 Query = function( search ) {
587 this.allLoaded = false;
588 this.querying = false;
589 this.search = search;
592 $.extend( Query.prototype, {
594 return ! ( this.querying || this.allLoaded );
596 ajax: function( callback ) {
599 action : 'wp-link-ajax',
601 '_ajax_linking_nonce' : inputs.nonce.val()
605 query.search = this.search;
607 this.querying = true;
609 $.post( ajaxurl, query, function( r ) {
611 self.querying = false;
612 self.allLoaded = ! r;
613 callback( r, query );
618 $( document ).ready( wpLink.init );