wp/wp-includes/js/wplink.js
changeset 5 5e2f62d02dcd
parent 0 d970ebf37754
child 7 cf61fcea0001
equal deleted inserted replaced
4:346c88efed21 5:5e2f62d02dcd
       
     1 /* global ajaxurl, tinymce, wpLinkL10n, setUserSetting, wpActiveEditor */
     1 var wpLink;
     2 var wpLink;
     2 
     3 
     3 (function($){
     4 ( function( $ ) {
     4 	var inputs = {}, rivers = {}, ed, River, Query;
     5 	var editor, searchTimer, River, Query, correctedURL,
       
     6 		inputs = {},
       
     7 		rivers = {},
       
     8 		isTouch = ( 'ontouchend' in document );
       
     9 
       
    10 	function getLink() {
       
    11 		return editor.dom.getParent( editor.selection.getNode(), 'a' );
       
    12 	}
     5 
    13 
     6 	wpLink = {
    14 	wpLink = {
     7 		timeToTriggerRiver: 150,
    15 		timeToTriggerRiver: 150,
     8 		minRiverAJAXDuration: 200,
    16 		minRiverAJAXDuration: 200,
     9 		riverBottomThreshold: 5,
    17 		riverBottomThreshold: 5,
    10 		keySensitivity: 100,
    18 		keySensitivity: 100,
    11 		lastSearch: '',
    19 		lastSearch: '',
    12 		textarea: '',
    20 		textarea: '',
    13 
    21 
    14 		init : function() {
    22 		init: function() {
    15 			inputs.dialog = $('#wp-link');
    23 			inputs.wrap = $('#wp-link-wrap');
    16 			inputs.submit = $('#wp-link-submit');
    24 			inputs.dialog = $( '#wp-link' );
    17 			// URL
    25 			inputs.backdrop = $( '#wp-link-backdrop' );
    18 			inputs.url = $('#url-field');
    26 			inputs.submit = $( '#wp-link-submit' );
    19 			inputs.nonce = $('#_ajax_linking_nonce');
    27 			inputs.close = $( '#wp-link-close' );
    20 			// Secondary options
    28 
    21 			inputs.title = $('#link-title-field');
    29 			// Input
    22 			// Advanced Options
    30 			inputs.text = $( '#wp-link-text' );
    23 			inputs.openInNewTab = $('#link-target-checkbox');
    31 			inputs.url = $( '#wp-link-url' );
    24 			inputs.search = $('#search-field');
    32 			inputs.nonce = $( '#_ajax_linking_nonce' );
       
    33 			inputs.openInNewTab = $( '#wp-link-target' );
       
    34 			inputs.search = $( '#wp-link-search' );
       
    35 
    25 			// Build Rivers
    36 			// Build Rivers
    26 			rivers.search = new River( $('#search-results') );
    37 			rivers.search = new River( $( '#search-results' ) );
    27 			rivers.recent = new River( $('#most-recent-results') );
    38 			rivers.recent = new River( $( '#most-recent-results' ) );
    28 			rivers.elements = $('.query-results', inputs.dialog);
    39 			rivers.elements = inputs.dialog.find( '.query-results' );
       
    40 
       
    41 			// Get search notice text
       
    42 			inputs.queryNotice = $( '#query-notice-message' );
       
    43 			inputs.queryNoticeTextDefault = inputs.queryNotice.find( '.query-notice-default' );
       
    44 			inputs.queryNoticeTextHint = inputs.queryNotice.find( '.query-notice-hint' );
    29 
    45 
    30 			// Bind event handlers
    46 			// Bind event handlers
    31 			inputs.dialog.keydown( wpLink.keydown );
    47 			inputs.dialog.keydown( wpLink.keydown );
    32 			inputs.dialog.keyup( wpLink.keyup );
    48 			inputs.dialog.keyup( wpLink.keyup );
    33 			inputs.submit.click( function(e){
    49 			inputs.submit.click( function( event ) {
    34 				e.preventDefault();
    50 				event.preventDefault();
    35 				wpLink.update();
    51 				wpLink.update();
    36 			});
    52 			});
    37 			$('#wp-link-cancel').click( function(e){
    53 			inputs.close.add( inputs.backdrop ).add( '#wp-link-cancel a' ).click( function( event ) {
    38 				e.preventDefault();
    54 				event.preventDefault();
    39 				wpLink.close();
    55 				wpLink.close();
    40 			});
    56 			});
    41 			$('#internal-toggle').click( wpLink.toggleInternalLinking );
    57 
    42 
    58 			$( '#wp-link-search-toggle' ).on( 'click', wpLink.toggleInternalLinking );
    43 			rivers.elements.bind('river-select', wpLink.updateFields );
    59 
    44 
    60 			rivers.elements.on( 'river-select', wpLink.updateFields );
    45 			inputs.search.keyup( wpLink.searchInternalLinks );
    61 
    46 
    62 			// Display 'hint' message when search field or 'query-results' box are focused
    47 			inputs.dialog.bind('wpdialogrefresh', wpLink.refresh);
    63 			inputs.search.on( 'focus.wplink', function() {
    48 			inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen);
    64 				inputs.queryNoticeTextDefault.hide();
    49 			inputs.dialog.bind('wpdialogclose', wpLink.onClose);
    65 				inputs.queryNoticeTextHint.removeClass( 'screen-reader-text' ).show();
    50 		},
    66 			} ).on( 'blur.wplink', function() {
    51 
    67 				inputs.queryNoticeTextDefault.show();
    52 		beforeOpen : function() {
    68 				inputs.queryNoticeTextHint.addClass( 'screen-reader-text' ).hide();
       
    69 			} );
       
    70 
       
    71 			inputs.search.keyup( function() {
       
    72 				var self = this;
       
    73 
       
    74 				window.clearTimeout( searchTimer );
       
    75 				searchTimer = window.setTimeout( function() {
       
    76 					wpLink.searchInternalLinks.call( self );
       
    77 				}, 500 );
       
    78 			});
       
    79 
       
    80 			function correctURL() {
       
    81 				var url = $.trim( inputs.url.val() );
       
    82 
       
    83 				if ( url && correctedURL !== url && ! /^(?:[a-z]+:|#|\?|\.|\/)/.test( url ) ) {
       
    84 					inputs.url.val( 'http://' + url );
       
    85 					correctedURL = url;
       
    86 				}
       
    87 			}
       
    88 
       
    89 			inputs.url.on( 'paste', function() {
       
    90 				setTimeout( correctURL, 0 );
       
    91 			} );
       
    92 
       
    93 			inputs.url.on( 'blur', correctURL );
       
    94 		},
       
    95 
       
    96 		open: function( editorId ) {
       
    97 			var ed;
       
    98 
       
    99 			$( document.body ).addClass( 'modal-open' );
       
   100 
    53 			wpLink.range = null;
   101 			wpLink.range = null;
    54 
   102 
       
   103 			if ( editorId ) {
       
   104 				window.wpActiveEditor = editorId;
       
   105 			}
       
   106 
       
   107 			if ( ! window.wpActiveEditor ) {
       
   108 				return;
       
   109 			}
       
   110 
       
   111 			this.textarea = $( '#' + window.wpActiveEditor ).get( 0 );
       
   112 
       
   113 			if ( typeof tinymce !== 'undefined' ) {
       
   114 				ed = tinymce.get( wpActiveEditor );
       
   115 
       
   116 				if ( ed && ! ed.isHidden() ) {
       
   117 					editor = ed;
       
   118 				} else {
       
   119 					editor = null;
       
   120 				}
       
   121 
       
   122 				if ( editor && tinymce.isIE ) {
       
   123 					editor.windowManager.bookmark = editor.selection.getBookmark();
       
   124 				}
       
   125 			}
       
   126 
    55 			if ( ! wpLink.isMCE() && document.selection ) {
   127 			if ( ! wpLink.isMCE() && document.selection ) {
    56 				wpLink.textarea.focus();
   128 				this.textarea.focus();
    57 				wpLink.range = document.selection.createRange();
   129 				this.range = document.selection.createRange();
    58 			}
   130 			}
    59 		},
   131 
    60 
   132 			inputs.wrap.show();
    61 		open : function() {
   133 			inputs.backdrop.show();
    62 			if ( !wpActiveEditor )
   134 
    63 				return;
   135 			wpLink.refresh();
    64 
   136 
    65 			this.textarea = $('#'+wpActiveEditor).get(0);
   137 			$( document ).trigger( 'wplink-open', inputs.wrap );
    66 
   138 		},
    67 			// Initialize the dialog if necessary (html mode).
   139 
    68 			if ( ! inputs.dialog.data('wpdialog') ) {
   140 		isMCE: function() {
    69 				inputs.dialog.wpdialog({
   141 			return editor && ! editor.isHidden();
    70 					title: wpLinkL10n.title,
   142 		},
    71 					width: 480,
   143 
    72 					height: 'auto',
   144 		refresh: function() {
    73 					modal: true,
   145 			var text = '';
    74 					dialogClass: 'wp-dialog'
   146 
    75 				});
       
    76 			}
       
    77 
       
    78 			inputs.dialog.wpdialog('open');
       
    79 		},
       
    80 
       
    81 		isMCE : function() {
       
    82 			return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden();
       
    83 		},
       
    84 
       
    85 		refresh : function() {
       
    86 			// Refresh rivers (clear links, check visibility)
   147 			// Refresh rivers (clear links, check visibility)
    87 			rivers.search.refresh();
   148 			rivers.search.refresh();
    88 			rivers.recent.refresh();
   149 			rivers.recent.refresh();
    89 
   150 
    90 			if ( wpLink.isMCE() )
   151 			if ( wpLink.isMCE() ) {
    91 				wpLink.mceRefresh();
   152 				wpLink.mceRefresh();
    92 			else
   153 			} else {
       
   154 				// For the Text editor the "Link text" field is always shown
       
   155 				if ( ! inputs.wrap.hasClass( 'has-text-field' ) ) {
       
   156 					inputs.wrap.addClass( 'has-text-field' );
       
   157 				}
       
   158 
       
   159 				if ( document.selection ) {
       
   160 					// Old IE
       
   161 					text = document.selection.createRange().text || '';
       
   162 				} else if ( typeof this.textarea.selectionStart !== 'undefined' &&
       
   163 					( this.textarea.selectionStart !== this.textarea.selectionEnd ) ) {
       
   164 					// W3C
       
   165 					text = this.textarea.value.substring( this.textarea.selectionStart, this.textarea.selectionEnd ) || '';
       
   166 				}
       
   167 
       
   168 				inputs.text.val( text );
    93 				wpLink.setDefaultValues();
   169 				wpLink.setDefaultValues();
    94 
   170 			}
    95 			// Focus the URL field and highlight its contents.
   171 
    96 			//     If this is moved above the selection changes,
   172 			if ( isTouch ) {
    97 			//     IE will show a flashing cursor over the dialog.
   173 				// Close the onscreen keyboard
    98 			inputs.url.focus()[0].select();
   174 				inputs.url.focus().blur();
       
   175 			} else {
       
   176 				// Focus the URL field and highlight its contents.
       
   177 				// If this is moved above the selection changes,
       
   178 				// IE will show a flashing cursor over the dialog.
       
   179 				inputs.url.focus()[0].select();
       
   180 			}
       
   181 
    99 			// Load the most recent results if this is the first time opening the panel.
   182 			// Load the most recent results if this is the first time opening the panel.
   100 			if ( ! rivers.recent.ul.children().length )
   183 			if ( ! rivers.recent.ul.children().length ) {
   101 				rivers.recent.ajax();
   184 				rivers.recent.ajax();
   102 		},
   185 			}
   103 
   186 
   104 		mceRefresh : function() {
   187 			correctedURL = inputs.url.val().replace( /^http:\/\//, '' );
   105 			var e;
   188 		},
   106 			ed = tinyMCEPopup.editor;
   189 
   107 
   190 		hasSelectedText: function( linkNode ) {
   108 			tinyMCEPopup.restoreSelection();
   191 			var html = editor.selection.getContent();
   109 
   192 
   110 			// If link exists, select proper values.
   193 			// Partial html and not a fully selected anchor element
   111 			if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) {
   194 			if ( /</.test( html ) && ( ! /^<a [^>]+>[^<]+<\/a>$/.test( html ) || html.indexOf('href=') === -1 ) ) {
   112 				// Set URL and description.
   195 				return false;
   113 				inputs.url.val( ed.dom.getAttrib(e, 'href') );
   196 			}
   114 				inputs.title.val( ed.dom.getAttrib(e, 'title') );
   197 
   115 				// Set open in new tab.
   198 			if ( linkNode ) {
   116 				inputs.openInNewTab.prop('checked', ( "_blank" == ed.dom.getAttrib( e, 'target' ) ) );
   199 				var nodes = linkNode.childNodes, i;
   117 				// Update save prompt.
   200 
       
   201 				if ( nodes.length === 0 ) {
       
   202 					return false;
       
   203 				}
       
   204 
       
   205 				for ( i = nodes.length - 1; i >= 0; i-- ) {
       
   206 					if ( nodes[i].nodeType != 3 ) {
       
   207 						return false;
       
   208 					}
       
   209 				}
       
   210 			}
       
   211 
       
   212 			return true;
       
   213 		},
       
   214 
       
   215 		mceRefresh: function() {
       
   216 			var text,
       
   217 				selectedNode = editor.selection.getNode(),
       
   218 				linkNode = editor.dom.getParent( selectedNode, 'a[href]' ),
       
   219 				onlyText = this.hasSelectedText( linkNode );
       
   220 
       
   221 			if ( linkNode ) {
       
   222 				text = linkNode.innerText || linkNode.textContent;
       
   223 				inputs.url.val( editor.dom.getAttrib( linkNode, 'href' ) );
       
   224 				inputs.openInNewTab.prop( 'checked', '_blank' === editor.dom.getAttrib( linkNode, 'target' ) );
   118 				inputs.submit.val( wpLinkL10n.update );
   225 				inputs.submit.val( wpLinkL10n.update );
   119 
   226 			} else {
   120 			// If there's no link, set the default values.
   227 				text = editor.selection.getContent({ format: 'text' });
   121 			} else {
   228 				this.setDefaultValues();
   122 				wpLink.setDefaultValues();
   229 			}
   123 			}
   230 
   124 		},
   231 			if ( onlyText ) {
   125 
   232 				inputs.text.val( text || '' );
   126 		close : function() {
   233 				inputs.wrap.addClass( 'has-text-field' );
   127 			if ( wpLink.isMCE() )
   234 			} else {
   128 				tinyMCEPopup.close();
   235 				inputs.text.val( '' );
   129 			else
   236 				inputs.wrap.removeClass( 'has-text-field' );
   130 				inputs.dialog.wpdialog('close');
   237 			}
   131 		},
   238 		},
   132 
   239 
   133 		onClose: function() {
   240 		close: function() {
       
   241 			$( document.body ).removeClass( 'modal-open' );
       
   242 
   134 			if ( ! wpLink.isMCE() ) {
   243 			if ( ! wpLink.isMCE() ) {
   135 				wpLink.textarea.focus();
   244 				wpLink.textarea.focus();
       
   245 
   136 				if ( wpLink.range ) {
   246 				if ( wpLink.range ) {
   137 					wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
   247 					wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
   138 					wpLink.range.select();
   248 					wpLink.range.select();
   139 				}
   249 				}
   140 			}
   250 			} else {
   141 		},
   251 				editor.focus();
   142 
   252 			}
   143 		getAttrs : function() {
   253 
       
   254 			inputs.backdrop.hide();
       
   255 			inputs.wrap.hide();
       
   256 
       
   257 			correctedURL = false;
       
   258 
       
   259 			$( document ).trigger( 'wplink-close', inputs.wrap );
       
   260 		},
       
   261 
       
   262 		getAttrs: function() {
   144 			return {
   263 			return {
   145 				href : inputs.url.val(),
   264 				href: $.trim( inputs.url.val() ),
   146 				title : inputs.title.val(),
   265 				target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
   147 				target : inputs.openInNewTab.prop('checked') ? '_blank' : ''
       
   148 			};
   266 			};
   149 		},
   267 		},
   150 
   268 
   151 		update : function() {
   269 		update: function() {
   152 			if ( wpLink.isMCE() )
   270 			if ( wpLink.isMCE() ) {
   153 				wpLink.mceUpdate();
   271 				wpLink.mceUpdate();
   154 			else
   272 			} else {
   155 				wpLink.htmlUpdate();
   273 				wpLink.htmlUpdate();
   156 		},
   274 			}
   157 
   275 		},
   158 		htmlUpdate : function() {
   276 
   159 			var attrs, html, begin, end, cursor,
   277 		htmlUpdate: function() {
       
   278 			var attrs, text, html, begin, end, cursor, selection,
   160 				textarea = wpLink.textarea;
   279 				textarea = wpLink.textarea;
   161 
   280 
   162 			if ( ! textarea )
   281 			if ( ! textarea ) {
   163 				return;
   282 				return;
       
   283 			}
   164 
   284 
   165 			attrs = wpLink.getAttrs();
   285 			attrs = wpLink.getAttrs();
       
   286 			text = inputs.text.val();
   166 
   287 
   167 			// If there's no href, return.
   288 			// If there's no href, return.
   168 			if ( ! attrs.href || attrs.href == 'http://' )
   289 			if ( ! attrs.href ) {
   169 				return;
   290 				return;
       
   291 			}
   170 
   292 
   171 			// Build HTML
   293 			// Build HTML
   172 			html = '<a href="' + attrs.href + '"';
   294 			html = '<a href="' + attrs.href + '"';
   173 
   295 
   174 			if ( attrs.title )
   296 			if ( attrs.target ) {
   175 				html += ' title="' + attrs.title + '"';
       
   176 			if ( attrs.target )
       
   177 				html += ' target="' + attrs.target + '"';
   297 				html += ' target="' + attrs.target + '"';
       
   298 			}
   178 
   299 
   179 			html += '>';
   300 			html += '>';
   180 
   301 
   181 			// Insert HTML
   302 			// Insert HTML
   182 			if ( document.selection && wpLink.range ) {
   303 			if ( document.selection && wpLink.range ) {
   183 				// IE
   304 				// IE
   184 				// Note: If no text is selected, IE will not place the cursor
   305 				// Note: If no text is selected, IE will not place the cursor
   185 				//       inside the closing tag.
   306 				//       inside the closing tag.
   186 				textarea.focus();
   307 				textarea.focus();
   187 				wpLink.range.text = html + wpLink.range.text + '</a>';
   308 				wpLink.range.text = html + ( text || wpLink.range.text ) + '</a>';
   188 				wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
   309 				wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
   189 				wpLink.range.select();
   310 				wpLink.range.select();
   190 
   311 
   191 				wpLink.range = null;
   312 				wpLink.range = null;
   192 			} else if ( typeof textarea.selectionStart !== 'undefined' ) {
   313 			} else if ( typeof textarea.selectionStart !== 'undefined' ) {
   193 				// W3C
   314 				// W3C
   194 				begin       = textarea.selectionStart;
   315 				begin = textarea.selectionStart;
   195 				end         = textarea.selectionEnd;
   316 				end = textarea.selectionEnd;
   196 				selection   = textarea.value.substring( begin, end );
   317 				selection = text || textarea.value.substring( begin, end );
   197 				html        = html + selection + '</a>';
   318 				html = html + selection + '</a>';
   198 				cursor      = begin + html.length;
   319 				cursor = begin + html.length;
   199 
   320 
   200 				// If no next is selected, place the cursor inside the closing tag.
   321 				// If no text is selected, place the cursor inside the closing tag.
   201 				if ( begin == end )
   322 				if ( begin === end && ! selection ) {
   202 					cursor -= '</a>'.length;
   323 					cursor -= 4;
   203 
   324 				}
   204 				textarea.value = textarea.value.substring( 0, begin )
   325 
   205 				               + html
   326 				textarea.value = (
   206 				               + textarea.value.substring( end, textarea.value.length );
   327 					textarea.value.substring( 0, begin ) +
       
   328 					html +
       
   329 					textarea.value.substring( end, textarea.value.length )
       
   330 				);
   207 
   331 
   208 				// Update cursor position
   332 				// Update cursor position
   209 				textarea.selectionStart = textarea.selectionEnd = cursor;
   333 				textarea.selectionStart = textarea.selectionEnd = cursor;
   210 			}
   334 			}
   211 
   335 
   212 			wpLink.close();
   336 			wpLink.close();
   213 			textarea.focus();
   337 			textarea.focus();
   214 		},
   338 		},
   215 
   339 
   216 		mceUpdate : function() {
   340 		mceUpdate: function() {
   217 			var ed = tinyMCEPopup.editor,
   341 			var attrs = wpLink.getAttrs(),
   218 				attrs = wpLink.getAttrs(),
   342 				link, text;
   219 				e, b;
   343 
   220 
   344 			wpLink.close();
   221 			tinyMCEPopup.restoreSelection();
   345 			editor.focus();
   222 			e = ed.dom.getParent(ed.selection.getNode(), 'A');
   346 
   223 
   347 			if ( tinymce.isIE ) {
   224 			// If the values are empty, unlink and return
   348 				editor.selection.moveToBookmark( editor.windowManager.bookmark );
   225 			if ( ! attrs.href || attrs.href == 'http://' ) {
   349 			}
   226 				if ( e ) {
   350 
   227 					b = ed.selection.getBookmark();
   351 			if ( ! attrs.href ) {
   228 					ed.dom.remove(e, 1);
   352 				editor.execCommand( 'unlink' );
   229 					ed.selection.moveToBookmark(b);
   353 				return;
   230 					tinyMCEPopup.execCommand("mceEndUndoLevel");
   354 			}
   231 					wpLink.close();
   355 
   232 				}
   356 			link = getLink();
   233 				return;
   357 			text = inputs.text.val();
   234 			}
   358 
   235 
   359 			if ( link ) {
   236 			if (e == null) {
   360 				if ( text ) {
   237 				ed.getDoc().execCommand("unlink", false, null);
   361 					if ( 'innerText' in link ) {
   238 				tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1});
   362 						link.innerText = text;
   239 
   363 					} else {
   240 				tinymce.each(ed.dom.select("a"), function(n) {
   364 						link.textContent = text;
   241 					if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
       
   242 						e = n;
       
   243 						ed.dom.setAttribs(e, attrs);
       
   244 					}
   365 					}
   245 				});
   366 				}
   246 
   367 
   247 				// Sometimes WebKit lets a user create a link where
   368 				editor.dom.setAttribs( link, attrs );
   248 				// they shouldn't be able to. In this case, CreateLink
   369 			} else {
   249 				// injects "#mce_temp_url#" into their content. Fix it.
   370 				if ( text ) {
   250 				if ( tinymce.isWebKit && $(e).text() == '#mce_temp_url#' ) {
   371 					editor.selection.setNode( editor.dom.create( 'a', attrs, text ) );
   251 					ed.dom.remove(e);
   372 				} else {
   252 					e = null;
   373 					editor.execCommand( 'mceInsertLink', false, attrs );
   253 				}
   374 				}
   254 			} else {
   375 			}
   255 				ed.dom.setAttribs(e, attrs);
   376 		},
   256 			}
   377 
   257 
   378 		updateFields: function( e, li ) {
   258 			// Move the caret if selection was not an image.
   379 			inputs.url.val( li.children( '.item-permalink' ).val() );
   259 			if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) {
   380 		},
   260 				ed.selection.select(e);
   381 
   261 				ed.selection.collapse(0);
   382 		setDefaultValues: function() {
   262 				tinyMCEPopup.storeSelection();
   383 			var selection,
   263 			}
   384 				emailRegexp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
   264 
   385 				urlRegexp = /^(https?|ftp):\/\/[A-Z0-9.-]+\.[A-Z]{2,4}[^ "]*$/i;
   265 			ed.execCommand("mceEndUndoLevel");
   386 
   266 			wpLink.close();
   387 			if ( this.isMCE() ) {
   267 			ed.focus();
   388 				selection = editor.selection.getContent();
   268 		},
   389 			} else if ( document.selection && wpLink.range ) {
   269 
   390 				selection = wpLink.range.text;
   270 		updateFields : function( e, li, originalEvent ) {
   391 			} else if ( typeof this.textarea.selectionStart !== 'undefined' ) {
   271 			inputs.url.val( li.children('.item-permalink').val() );
   392 				selection = this.textarea.value.substring( this.textarea.selectionStart, this.textarea.selectionEnd );
   272 			inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() );
   393 			}
   273 			if ( originalEvent && originalEvent.type == "click" )
   394 
   274 				inputs.url.focus();
   395 			if ( selection && emailRegexp.test( selection ) ) {
   275 		},
   396 				// Selection is email address
   276 		setDefaultValues : function() {
   397 				inputs.url.val( 'mailto:' + selection );
   277 			// Set URL and description to defaults.
   398 			} else if ( selection && urlRegexp.test( selection ) ) {
   278 			// Leave the new tab setting as-is.
   399 				// Selection is URL
   279 			inputs.url.val('http://');
   400 				inputs.url.val( selection.replace( /&amp;|&#0?38;/gi, '&' ) );
   280 			inputs.title.val('');
   401 			} else {
       
   402 				// Set URL to default.
       
   403 				inputs.url.val( '' );
       
   404 			}
   281 
   405 
   282 			// Update save prompt.
   406 			// Update save prompt.
   283 			inputs.submit.val( wpLinkL10n.save );
   407 			inputs.submit.val( wpLinkL10n.save );
   284 		},
   408 		},
   285 
   409 
   286 		searchInternalLinks : function() {
   410 		searchInternalLinks: function() {
   287 			var t = $(this), waiting,
   411 			var t = $( this ), waiting,
   288 				search = t.val();
   412 				search = t.val();
   289 
   413 
   290 			if ( search.length > 2 ) {
   414 			if ( search.length > 2 ) {
   291 				rivers.recent.hide();
   415 				rivers.recent.hide();
   292 				rivers.search.show();
   416 				rivers.search.show();
   294 				// Don't search if the keypress didn't change the title.
   418 				// Don't search if the keypress didn't change the title.
   295 				if ( wpLink.lastSearch == search )
   419 				if ( wpLink.lastSearch == search )
   296 					return;
   420 					return;
   297 
   421 
   298 				wpLink.lastSearch = search;
   422 				wpLink.lastSearch = search;
   299 				waiting = t.parent().find('.spinner').show();
   423 				waiting = t.parent().find( '.spinner' ).addClass( 'is-active' );
   300 
   424 
   301 				rivers.search.change( search );
   425 				rivers.search.change( search );
   302 				rivers.search.ajax( function(){ waiting.hide(); });
   426 				rivers.search.ajax( function() {
       
   427 					waiting.removeClass( 'is-active' );
       
   428 				});
   303 			} else {
   429 			} else {
   304 				rivers.search.hide();
   430 				rivers.search.hide();
   305 				rivers.recent.show();
   431 				rivers.recent.show();
   306 			}
   432 			}
   307 		},
   433 		},
   308 
   434 
   309 		next : function() {
   435 		next: function() {
   310 			rivers.search.next();
   436 			rivers.search.next();
   311 			rivers.recent.next();
   437 			rivers.recent.next();
   312 		},
   438 		},
   313 		prev : function() {
   439 
       
   440 		prev: function() {
   314 			rivers.search.prev();
   441 			rivers.search.prev();
   315 			rivers.recent.prev();
   442 			rivers.recent.prev();
   316 		},
   443 		},
   317 
   444 
   318 		keydown : function( event ) {
   445 		keydown: function( event ) {
   319 			var fn, key = $.ui.keyCode;
   446 			var fn, id,
   320 
   447 				key = $.ui.keyCode;
   321 			switch( event.which ) {
   448 
   322 				case key.UP:
   449 			if ( key.ESCAPE === event.keyCode ) {
   323 					fn = 'prev';
   450 				wpLink.close();
   324 				case key.DOWN:
   451 				event.stopImmediatePropagation();
   325 					fn = fn || 'next';
   452 			} else if ( key.TAB === event.keyCode ) {
   326 					clearInterval( wpLink.keyInterval );
   453 				id = event.target.id;
   327 					wpLink[ fn ]();
   454 
   328 					wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
   455 				// wp-link-submit must always be the last focusable element in the dialog.
   329 					break;
   456 				// following focusable elements will be skipped on keyboard navigation.
   330 				default:
   457 				if ( id === 'wp-link-submit' && ! event.shiftKey ) {
   331 					return;
   458 					inputs.close.focus();
   332 			}
   459 					event.preventDefault();
       
   460 				} else if ( id === 'wp-link-close' && event.shiftKey ) {
       
   461 					inputs.submit.focus();
       
   462 					event.preventDefault();
       
   463 				}
       
   464 			}
       
   465 
       
   466 			if ( event.keyCode !== key.UP && event.keyCode !== key.DOWN ) {
       
   467 				return;
       
   468 			}
       
   469 
       
   470 			if ( document.activeElement &&
       
   471 				( document.activeElement.id === 'link-title-field' || document.activeElement.id === 'url-field' ) ) {
       
   472 				return;
       
   473 			}
       
   474 
       
   475 			fn = event.keyCode === key.UP ? 'prev' : 'next';
       
   476 			clearInterval( wpLink.keyInterval );
       
   477 			wpLink[ fn ]();
       
   478 			wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
   333 			event.preventDefault();
   479 			event.preventDefault();
   334 		},
   480 		},
       
   481 
   335 		keyup: function( event ) {
   482 		keyup: function( event ) {
   336 			var key = $.ui.keyCode;
   483 			var key = $.ui.keyCode;
   337 
   484 
   338 			switch( event.which ) {
   485 			if ( event.which === key.UP || event.which === key.DOWN ) {
   339 				case key.ESCAPE:
   486 				clearInterval( wpLink.keyInterval );
   340 					event.stopImmediatePropagation();
   487 				event.preventDefault();
   341 					if ( ! $(document).triggerHandler( 'wp_CloseOnEscape', [{ event: event, what: 'wplink', cb: wpLink.close }] ) )
   488 			}
   342 						wpLink.close();
   489 		},
   343 
   490 
   344 					return false;
   491 		delayedCallback: function( func, delay ) {
   345 					break;
       
   346 				case key.UP:
       
   347 				case key.DOWN:
       
   348 					clearInterval( wpLink.keyInterval );
       
   349 					break;
       
   350 				default:
       
   351 					return;
       
   352 			}
       
   353 			event.preventDefault();
       
   354 		},
       
   355 
       
   356 		delayedCallback : function( func, delay ) {
       
   357 			var timeoutTriggered, funcTriggered, funcArgs, funcContext;
   492 			var timeoutTriggered, funcTriggered, funcArgs, funcContext;
   358 
   493 
   359 			if ( ! delay )
   494 			if ( ! delay )
   360 				return func;
   495 				return func;
   361 
   496 
   362 			setTimeout( function() {
   497 			setTimeout( function() {
   363 				if ( funcTriggered )
   498 				if ( funcTriggered )
   364 					return func.apply( funcContext, funcArgs );
   499 					return func.apply( funcContext, funcArgs );
   365 				// Otherwise, wait.
   500 				// Otherwise, wait.
   366 				timeoutTriggered = true;
   501 				timeoutTriggered = true;
   367 			}, delay);
   502 			}, delay );
   368 
   503 
   369 			return function() {
   504 			return function() {
   370 				if ( timeoutTriggered )
   505 				if ( timeoutTriggered )
   371 					return func.apply( this, arguments );
   506 					return func.apply( this, arguments );
   372 				// Otherwise, wait.
   507 				// Otherwise, wait.
   374 				funcContext = this;
   509 				funcContext = this;
   375 				funcTriggered = true;
   510 				funcTriggered = true;
   376 			};
   511 			};
   377 		},
   512 		},
   378 
   513 
   379 		toggleInternalLinking : function( event ) {
   514 		toggleInternalLinking: function( event ) {
   380 			var panel = $('#search-panel'),
   515 			var visible = inputs.wrap.hasClass( 'search-panel-visible' );
   381 				widget = inputs.dialog.wpdialog('widget'),
   516 
   382 				// We're about to toggle visibility; it's currently the opposite
   517 			inputs.wrap.toggleClass( 'search-panel-visible', ! visible );
   383 				visible = !panel.is(':visible'),
   518 			setUserSetting( 'wplink', visible ? '0' : '1' );
   384 				win = $(window);
   519 			inputs[ ! visible ? 'search' : 'url' ].focus();
   385 
       
   386 			$(this).toggleClass('toggle-arrow-active', visible);
       
   387 
       
   388 			inputs.dialog.height('auto');
       
   389 			panel.slideToggle( 300, function() {
       
   390 				setUserSetting('wplink', visible ? '1' : '0');
       
   391 				inputs[ visible ? 'search' : 'url' ].focus();
       
   392 
       
   393 				// Move the box if the box is now expanded, was opened in a collapsed state,
       
   394 				// and if it needs to be moved. (Judged by bottom not being positive or
       
   395 				// bottom being smaller than top.)
       
   396 				var scroll = win.scrollTop(),
       
   397 					top = widget.offset().top,
       
   398 					bottom = top + widget.outerHeight(),
       
   399 					diff = bottom - win.height();
       
   400 
       
   401 				if ( diff > scroll ) {
       
   402 					widget.animate({'top': diff < top ?  top - diff : scroll }, 200);
       
   403 				}
       
   404 			});
       
   405 			event.preventDefault();
   520 			event.preventDefault();
   406 		}
   521 		}
   407 	}
   522 	};
   408 
   523 
   409 	River = function( element, search ) {
   524 	River = function( element, search ) {
   410 		var self = this;
   525 		var self = this;
   411 		this.element = element;
   526 		this.element = element;
   412 		this.ul = element.children('ul');
   527 		this.ul = element.children( 'ul' );
       
   528 		this.contentHeight = element.children( '#link-selector-height' );
   413 		this.waiting = element.find('.river-waiting');
   529 		this.waiting = element.find('.river-waiting');
   414 
   530 
   415 		this.change( search );
   531 		this.change( search );
   416 		this.refresh();
   532 		this.refresh();
   417 
   533 
   418 		element.scroll( function(){ self.maybeLoad(); });
   534 		$( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
   419 		element.delegate('li', 'click', function(e){ self.select( $(this), e ); });
   535 			self.maybeLoad();
       
   536 		});
       
   537 		element.on( 'click', 'li', function( event ) {
       
   538 			self.select( $( this ), event );
       
   539 		});
   420 	};
   540 	};
   421 
   541 
   422 	$.extend( River.prototype, {
   542 	$.extend( River.prototype, {
   423 		refresh: function() {
   543 		refresh: function() {
   424 			this.deselect();
   544 			this.deselect();
   425 			this.visible = this.element.is(':visible');
   545 			this.visible = this.element.is( ':visible' );
   426 		},
   546 		},
   427 		show: function() {
   547 		show: function() {
   428 			if ( ! this.visible ) {
   548 			if ( ! this.visible ) {
   429 				this.deselect();
   549 				this.deselect();
   430 				this.element.show();
   550 				this.element.show();
   437 		},
   557 		},
   438 		// Selects a list item and triggers the river-select event.
   558 		// Selects a list item and triggers the river-select event.
   439 		select: function( li, event ) {
   559 		select: function( li, event ) {
   440 			var liHeight, elHeight, liTop, elTop;
   560 			var liHeight, elHeight, liTop, elTop;
   441 
   561 
   442 			if ( li.hasClass('unselectable') || li == this.selected )
   562 			if ( li.hasClass( 'unselectable' ) || li == this.selected )
   443 				return;
   563 				return;
   444 
   564 
   445 			this.deselect();
   565 			this.deselect();
   446 			this.selected = li.addClass('selected');
   566 			this.selected = li.addClass( 'selected' );
   447 			// Make sure the element is visible
   567 			// Make sure the element is visible
   448 			liHeight = li.outerHeight();
   568 			liHeight = li.outerHeight();
   449 			elHeight = this.element.height();
   569 			elHeight = this.element.height();
   450 			liTop = li.position().top;
   570 			liTop = li.position().top;
   451 			elTop = this.element.scrollTop();
   571 			elTop = this.element.scrollTop();
   454 				this.element.scrollTop( elTop + liTop );
   574 				this.element.scrollTop( elTop + liTop );
   455 			else if ( liTop + liHeight > elHeight ) // Make last visible element
   575 			else if ( liTop + liHeight > elHeight ) // Make last visible element
   456 				this.element.scrollTop( elTop + liTop - elHeight + liHeight );
   576 				this.element.scrollTop( elTop + liTop - elHeight + liHeight );
   457 
   577 
   458 			// Trigger the river-select event
   578 			// Trigger the river-select event
   459 			this.element.trigger('river-select', [ li, event, this ]);
   579 			this.element.trigger( 'river-select', [ li, event, this ] );
   460 		},
   580 		},
   461 		deselect: function() {
   581 		deselect: function() {
   462 			if ( this.selected )
   582 			if ( this.selected )
   463 				this.selected.removeClass('selected');
   583 				this.selected.removeClass( 'selected' );
   464 			this.selected = false;
   584 			this.selected = false;
   465 		},
   585 		},
   466 		prev: function() {
   586 		prev: function() {
   467 			if ( ! this.visible )
   587 			if ( ! this.visible )
   468 				return;
   588 				return;
   469 
   589 
   470 			var to;
   590 			var to;
   471 			if ( this.selected ) {
   591 			if ( this.selected ) {
   472 				to = this.selected.prev('li');
   592 				to = this.selected.prev( 'li' );
   473 				if ( to.length )
   593 				if ( to.length )
   474 					this.select( to );
   594 					this.select( to );
   475 			}
   595 			}
   476 		},
   596 		},
   477 		next: function() {
   597 		next: function() {
   478 			if ( ! this.visible )
   598 			if ( ! this.visible )
   479 				return;
   599 				return;
   480 
   600 
   481 			var to = this.selected ? this.selected.next('li') : $('li:not(.unselectable):first', this.element);
   601 			var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
   482 			if ( to.length )
   602 			if ( to.length )
   483 				this.select( to );
   603 				this.select( to );
   484 		},
   604 		},
   485 		ajax: function( callback ) {
   605 		ajax: function( callback ) {
   486 			var self = this,
   606 			var self = this,
   497 			if ( this.query && this._search == search )
   617 			if ( this.query && this._search == search )
   498 				return;
   618 				return;
   499 
   619 
   500 			this._search = search;
   620 			this._search = search;
   501 			this.query = new Query( search );
   621 			this.query = new Query( search );
   502 			this.element.scrollTop(0);
   622 			this.element.scrollTop( 0 );
   503 		},
   623 		},
   504 		process: function( results, params ) {
   624 		process: function( results, params ) {
   505 			var list = '', alt = true, classes = '',
   625 			var list = '', alt = true, classes = '',
   506 				firstPage = params.page == 1;
   626 				firstPage = params.page == 1;
   507 
   627 
   508 			if ( !results ) {
   628 			if ( ! results ) {
   509 				if ( firstPage ) {
   629 				if ( firstPage ) {
   510 					list += '<li class="unselectable"><span class="item-title"><em>'
   630 					list += '<li class="unselectable no-matches-found"><span class="item-title"><em>' +
   511 					+ wpLinkL10n.noMatchesFound
   631 						wpLinkL10n.noMatchesFound + '</em></span></li>';
   512 					+ '</em></span></li>';
       
   513 				}
   632 				}
   514 			} else {
   633 			} else {
   515 				$.each( results, function() {
   634 				$.each( results, function() {
   516 					classes = alt ? 'alternate' : '';
   635 					classes = alt ? 'alternate' : '';
   517 					classes += this['title'] ? '' : ' no-title';
   636 					classes += this.title ? '' : ' no-title';
   518 					list += classes ? '<li class="' + classes + '">' : '<li>';
   637 					list += classes ? '<li class="' + classes + '">' : '<li>';
   519 					list += '<input type="hidden" class="item-permalink" value="' + this['permalink'] + '" />';
   638 					list += '<input type="hidden" class="item-permalink" value="' + this.permalink + '" />';
   520 					list += '<span class="item-title">';
   639 					list += '<span class="item-title">';
   521 					list += this['title'] ? this['title'] : wpLinkL10n.noTitle;
   640 					list += this.title ? this.title : wpLinkL10n.noTitle;
   522 					list += '</span><span class="item-info">' + this['info'] + '</span></li>';
   641 					list += '</span><span class="item-info">' + this.info + '</span></li>';
   523 					alt = ! alt;
   642 					alt = ! alt;
   524 				});
   643 				});
   525 			}
   644 			}
   526 
   645 
   527 			this.ul[ firstPage ? 'html' : 'append' ]( list );
   646 			this.ul[ firstPage ? 'html' : 'append' ]( list );
   529 		maybeLoad: function() {
   648 		maybeLoad: function() {
   530 			var self = this,
   649 			var self = this,
   531 				el = this.element,
   650 				el = this.element,
   532 				bottom = el.scrollTop() + el.height();
   651 				bottom = el.scrollTop() + el.height();
   533 
   652 
   534 			if ( ! this.query.ready() || bottom < this.ul.height() - wpLink.riverBottomThreshold )
   653 			if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
   535 				return;
   654 				return;
   536 
   655 
   537 			setTimeout(function() {
   656 			setTimeout(function() {
   538 				var newTop = el.scrollTop(),
   657 				var newTop = el.scrollTop(),
   539 					newBottom = newTop + el.height();
   658 					newBottom = newTop + el.height();
   540 
   659 
   541 				if ( ! self.query.ready() || newBottom < self.ul.height() - wpLink.riverBottomThreshold )
   660 				if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
   542 					return;
   661 					return;
   543 
   662 
   544 				self.waiting.show();
   663 				self.waiting.addClass( 'is-active' );
   545 				el.scrollTop( newTop + self.waiting.outerHeight() );
   664 				el.scrollTop( newTop + self.waiting.outerHeight() );
   546 
   665 
   547 				self.ajax( function() { self.waiting.hide(); });
   666 				self.ajax( function() {
       
   667 					self.waiting.removeClass( 'is-active' );
       
   668 				});
   548 			}, wpLink.timeToTriggerRiver );
   669 			}, wpLink.timeToTriggerRiver );
   549 		}
   670 		}
   550 	});
   671 	});
   551 
   672 
   552 	Query = function( search ) {
   673 	Query = function( search ) {
   556 		this.search = search;
   677 		this.search = search;
   557 	};
   678 	};
   558 
   679 
   559 	$.extend( Query.prototype, {
   680 	$.extend( Query.prototype, {
   560 		ready: function() {
   681 		ready: function() {
   561 			return !( this.querying || this.allLoaded );
   682 			return ! ( this.querying || this.allLoaded );
   562 		},
   683 		},
   563 		ajax: function( callback ) {
   684 		ajax: function( callback ) {
   564 			var self = this,
   685 			var self = this,
   565 				query = {
   686 				query = {
   566 					action : 'wp-link-ajax',
   687 					action : 'wp-link-ajax',
   571 			if ( this.search )
   692 			if ( this.search )
   572 				query.search = this.search;
   693 				query.search = this.search;
   573 
   694 
   574 			this.querying = true;
   695 			this.querying = true;
   575 
   696 
   576 			$.post( ajaxurl, query, function(r) {
   697 			$.post( ajaxurl, query, function( r ) {
   577 				self.page++;
   698 				self.page++;
   578 				self.querying = false;
   699 				self.querying = false;
   579 				self.allLoaded = !r;
   700 				self.allLoaded = ! r;
   580 				callback( r, query );
   701 				callback( r, query );
   581 			}, "json" );
   702 			}, 'json' );
   582 		}
   703 		}
   583 	});
   704 	});
   584 
   705 
   585 	$(document).ready( wpLink.init );
   706 	$( document ).ready( wpLink.init );
   586 })(jQuery);
   707 })( jQuery );