]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/wplink.js
WordPress 4.0.1
[autoinstalls/wordpress.git] / wp-includes / js / wplink.js
1 /* global ajaxurl, tinymce, wpLinkL10n, setUserSetting, wpActiveEditor */
2 var wpLink;
3
4 ( function( $ ) {
5         var editor, searchTimer, River, Query,
6                 inputs = {},
7                 rivers = {},
8                 isTouch = ( 'ontouchend' in document );
9
10         wpLink = {
11                 timeToTriggerRiver: 150,
12                 minRiverAJAXDuration: 200,
13                 riverBottomThreshold: 5,
14                 keySensitivity: 100,
15                 lastSearch: '',
16                 textarea: '',
17
18                 init: function() {
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' );
24                         // URL
25                         inputs.url = $( '#url-field' );
26                         inputs.nonce = $( '#_ajax_linking_nonce' );
27                         // Secondary options
28                         inputs.title = $( '#link-title-field' );
29                         // Advanced Options
30                         inputs.openInNewTab = $( '#link-target-checkbox' );
31                         inputs.search = $( '#search-field' );
32                         // Build Rivers
33                         rivers.search = new River( $( '#search-results' ) );
34                         rivers.recent = new River( $( '#most-recent-results' ) );
35                         rivers.elements = inputs.dialog.find( '.query-results' );
36
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' );
41
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();
47                                 wpLink.update();
48                         });
49                         inputs.close.add( inputs.backdrop ).add( '#wp-link-cancel a' ).click( function( event ) {
50                                 event.preventDefault();
51                                 wpLink.close();
52                         });
53
54                         $( '#wp-link-search-toggle' ).on( 'click', wpLink.toggleInternalLinking );
55
56                         rivers.elements.on( 'river-select', wpLink.updateFields );
57
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();
65                         } );
66
67                         inputs.search.keyup( function() {
68                                 var self = this;
69
70                                 window.clearTimeout( searchTimer );
71                                 searchTimer = window.setTimeout( function() {
72                                         wpLink.searchInternalLinks.call( self );
73                                 }, 500 );
74                         });
75                 },
76
77                 open: function( editorId ) {
78                         var ed;
79
80                         wpLink.range = null;
81
82                         if ( editorId ) {
83                                 window.wpActiveEditor = editorId;
84                         }
85
86                         if ( ! window.wpActiveEditor ) {
87                                 return;
88                         }
89
90                         this.textarea = $( '#' + window.wpActiveEditor ).get( 0 );
91
92                         if ( typeof tinymce !== 'undefined' ) {
93                                 ed = tinymce.get( wpActiveEditor );
94
95                                 if ( ed && ! ed.isHidden() ) {
96                                         editor = ed;
97                                 } else {
98                                         editor = null;
99                                 }
100
101                                 if ( editor && tinymce.isIE ) {
102                                         editor.windowManager.bookmark = editor.selection.getBookmark();
103                                 }
104                         }
105
106                         if ( ! wpLink.isMCE() && document.selection ) {
107                                 this.textarea.focus();
108                                 this.range = document.selection.createRange();
109                         }
110
111                         inputs.wrap.show();
112                         inputs.backdrop.show();
113
114                         wpLink.refresh();
115                         $( document ).trigger( 'wplink-open', inputs.wrap );
116                 },
117
118                 isMCE: function() {
119                         return editor && ! editor.isHidden();
120                 },
121
122                 refresh: function() {
123                         // Refresh rivers (clear links, check visibility)
124                         rivers.search.refresh();
125                         rivers.recent.refresh();
126
127                         if ( wpLink.isMCE() ) {
128                                 wpLink.mceRefresh();
129                         } else {
130                                 wpLink.setDefaultValues();
131                         }
132
133                         if ( isTouch ) {
134                                 // Close the onscreen keyboard
135                                 inputs.url.focus().blur();
136                         } else {
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();
141                         }
142
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();
146                         }
147                 },
148
149                 mceRefresh: function() {
150                         var e;
151
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 );
161
162                         // If there's no link, set the default values.
163                         } else {
164                                 wpLink.setDefaultValues();
165                         }
166                 },
167
168                 close: function() {
169                         if ( ! wpLink.isMCE() ) {
170                                 wpLink.textarea.focus();
171
172                                 if ( wpLink.range ) {
173                                         wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
174                                         wpLink.range.select();
175                                 }
176                         } else {
177                                 editor.focus();
178                         }
179
180                         inputs.backdrop.hide();
181                         inputs.wrap.hide();
182                         $( document ).trigger( 'wplink-close', inputs.wrap );
183                 },
184
185                 getAttrs: function() {
186                         return {
187                                 href: inputs.url.val(),
188                                 title: inputs.title.val(),
189                                 target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
190                         };
191                 },
192
193                 update: function() {
194                         if ( wpLink.isMCE() )
195                                 wpLink.mceUpdate();
196                         else
197                                 wpLink.htmlUpdate();
198                 },
199
200                 htmlUpdate: function() {
201                         var attrs, html, begin, end, cursor, title, selection,
202                                 textarea = wpLink.textarea;
203
204                         if ( ! textarea )
205                                 return;
206
207                         attrs = wpLink.getAttrs();
208
209                         // If there's no href, return.
210                         if ( ! attrs.href || attrs.href == 'http://' )
211                                 return;
212
213                         // Build HTML
214                         html = '<a href="' + attrs.href + '"';
215
216                         if ( attrs.title ) {
217                                 title = attrs.title.replace( /</g, '&lt;' ).replace( />/g, '&gt;' ).replace( /"/g, '&quot;' );
218                                 html += ' title="' + title + '"';
219                         }
220
221                         if ( attrs.target ) {
222                                 html += ' target="' + attrs.target + '"';
223                         }
224
225                         html += '>';
226
227                         // Insert HTML
228                         if ( document.selection && wpLink.range ) {
229                                 // IE
230                                 // Note: If no text is selected, IE will not place the cursor
231                                 //       inside the closing tag.
232                                 textarea.focus();
233                                 wpLink.range.text = html + wpLink.range.text + '</a>';
234                                 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
235                                 wpLink.range.select();
236
237                                 wpLink.range = null;
238                         } else if ( typeof textarea.selectionStart !== 'undefined' ) {
239                                 // W3C
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;
245
246                                 // If no text is selected, place the cursor inside the closing tag.
247                                 if ( begin == end )
248                                         cursor -= '</a>'.length;
249
250                                 textarea.value = textarea.value.substring( 0, begin ) + html +
251                                         textarea.value.substring( end, textarea.value.length );
252
253                                 // Update cursor position
254                                 textarea.selectionStart = textarea.selectionEnd = cursor;
255                         }
256
257                         wpLink.close();
258                         textarea.focus();
259                 },
260
261                 mceUpdate: function() {
262                         var link,
263                                 attrs = wpLink.getAttrs();
264
265                         wpLink.close();
266                         editor.focus();
267
268                         if ( tinymce.isIE ) {
269                                 editor.selection.moveToBookmark( editor.windowManager.bookmark );
270                         }
271
272                         link = editor.dom.getParent( editor.selection.getNode(), 'a[href]' );
273
274                         // If the values are empty, unlink and return
275                         if ( ! attrs.href || attrs.href == 'http://' ) {
276                                 editor.execCommand( 'unlink' );
277                                 return;
278                         }
279
280                         if ( link ) {
281                                 editor.dom.setAttribs( link, attrs );
282                         } else {
283                                 editor.execCommand( 'mceInsertLink', false, attrs );
284                         }
285
286                         // Move the cursor to the end of the selection
287                         editor.selection.collapse();
288                 },
289
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() );
293                 },
294
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;
299
300                         if ( selection && emailRegexp.test( selection ) ) {
301                                 // Selection is email address
302                                 inputs.url.val( 'mailto:' + selection );
303                         } else if ( selection && urlRegexp.test( selection ) ) {
304                                 // Selection is URL
305                                 inputs.url.val( selection.replace( /&amp;|&#0?38;/gi, '&' ) );
306                         } else {
307                                 // Set URL to default.
308                                 inputs.url.val( 'http://' );
309                         }
310
311                         // Set description to default.
312                         inputs.title.val( '' );
313
314                         // Update save prompt.
315                         inputs.submit.val( wpLinkL10n.save );
316                 },
317
318                 searchInternalLinks: function() {
319                         var t = $( this ), waiting,
320                                 search = t.val();
321
322                         if ( search.length > 2 ) {
323                                 rivers.recent.hide();
324                                 rivers.search.show();
325
326                                 // Don't search if the keypress didn't change the title.
327                                 if ( wpLink.lastSearch == search )
328                                         return;
329
330                                 wpLink.lastSearch = search;
331                                 waiting = t.parent().find('.spinner').show();
332
333                                 rivers.search.change( search );
334                                 rivers.search.ajax( function() {
335                                         waiting.hide();
336                                 });
337                         } else {
338                                 rivers.search.hide();
339                                 rivers.recent.show();
340                         }
341                 },
342
343                 next: function() {
344                         rivers.search.next();
345                         rivers.recent.next();
346                 },
347
348                 prev: function() {
349                         rivers.search.prev();
350                         rivers.recent.prev();
351                 },
352
353                 keydown: function( event ) {
354                         var fn, id,
355                                 key = $.ui.keyCode;
356
357                         if ( key.ESCAPE === event.keyCode ) {
358                                 wpLink.close();
359                                 event.stopImmediatePropagation();
360                         } else if ( key.TAB === event.keyCode ) {
361                                 id = event.target.id;
362
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();
371                                 }
372                         }
373
374                         if ( event.keyCode !== key.UP && event.keyCode !== key.DOWN ) {
375                                 return;
376                         }
377
378                         if ( document.activeElement &&
379                                 ( document.activeElement.id === 'link-title-field' || document.activeElement.id === 'url-field' ) ) {
380                                 return;
381                         }
382
383                         fn = event.keyCode === key.UP ? 'prev' : 'next';
384                         clearInterval( wpLink.keyInterval );
385                         wpLink[ fn ]();
386                         wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
387                         event.preventDefault();
388                 },
389
390                 keyup: function( event ) {
391                         var key = $.ui.keyCode;
392
393                         if ( event.which === key.UP || event.which === key.DOWN ) {
394                                 clearInterval( wpLink.keyInterval );
395                                 event.preventDefault();
396                         }
397                 },
398
399                 delayedCallback: function( func, delay ) {
400                         var timeoutTriggered, funcTriggered, funcArgs, funcContext;
401
402                         if ( ! delay )
403                                 return func;
404
405                         setTimeout( function() {
406                                 if ( funcTriggered )
407                                         return func.apply( funcContext, funcArgs );
408                                 // Otherwise, wait.
409                                 timeoutTriggered = true;
410                         }, delay );
411
412                         return function() {
413                                 if ( timeoutTriggered )
414                                         return func.apply( this, arguments );
415                                 // Otherwise, wait.
416                                 funcArgs = arguments;
417                                 funcContext = this;
418                                 funcTriggered = true;
419                         };
420                 },
421
422                 toggleInternalLinking: function( event ) {
423                         var visible = inputs.wrap.hasClass( 'search-panel-visible' );
424
425                         inputs.wrap.toggleClass( 'search-panel-visible', ! visible );
426                         setUserSetting( 'wplink', visible ? '0' : '1' );
427                         inputs[ ! visible ? 'search' : 'url' ].focus();
428                         event.preventDefault();
429                 }
430         };
431
432         River = function( element, search ) {
433                 var self = this;
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');
438
439                 this.change( search );
440                 this.refresh();
441
442                 $( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
443                         self.maybeLoad();
444                 });
445                 element.on( 'click', 'li', function( event ) {
446                         self.select( $( this ), event );
447                 });
448         };
449
450         $.extend( River.prototype, {
451                 refresh: function() {
452                         this.deselect();
453                         this.visible = this.element.is( ':visible' );
454                 },
455                 show: function() {
456                         if ( ! this.visible ) {
457                                 this.deselect();
458                                 this.element.show();
459                                 this.visible = true;
460                         }
461                 },
462                 hide: function() {
463                         this.element.hide();
464                         this.visible = false;
465                 },
466                 // Selects a list item and triggers the river-select event.
467                 select: function( li, event ) {
468                         var liHeight, elHeight, liTop, elTop;
469
470                         if ( li.hasClass( 'unselectable' ) || li == this.selected )
471                                 return;
472
473                         this.deselect();
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();
480
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 );
485
486                         // Trigger the river-select event
487                         this.element.trigger( 'river-select', [ li, event, this ] );
488                 },
489                 deselect: function() {
490                         if ( this.selected )
491                                 this.selected.removeClass( 'selected' );
492                         this.selected = false;
493                 },
494                 prev: function() {
495                         if ( ! this.visible )
496                                 return;
497
498                         var to;
499                         if ( this.selected ) {
500                                 to = this.selected.prev( 'li' );
501                                 if ( to.length )
502                                         this.select( to );
503                         }
504                 },
505                 next: function() {
506                         if ( ! this.visible )
507                                 return;
508
509                         var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
510                         if ( to.length )
511                                 this.select( to );
512                 },
513                 ajax: function( callback ) {
514                         var self = this,
515                                 delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
516                                 response = wpLink.delayedCallback( function( results, params ) {
517                                         self.process( results, params );
518                                         if ( callback )
519                                                 callback( results, params );
520                                 }, delay );
521
522                         this.query.ajax( response );
523                 },
524                 change: function( search ) {
525                         if ( this.query && this._search == search )
526                                 return;
527
528                         this._search = search;
529                         this.query = new Query( search );
530                         this.element.scrollTop( 0 );
531                 },
532                 process: function( results, params ) {
533                         var list = '', alt = true, classes = '',
534                                 firstPage = params.page == 1;
535
536                         if ( ! results ) {
537                                 if ( firstPage ) {
538                                         list += '<li class="unselectable no-matches-found"><span class="item-title"><em>' +
539                                                 wpLinkL10n.noMatchesFound + '</em></span></li>';
540                                 }
541                         } else {
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>';
550                                         alt = ! alt;
551                                 });
552                         }
553
554                         this.ul[ firstPage ? 'html' : 'append' ]( list );
555                 },
556                 maybeLoad: function() {
557                         var self = this,
558                                 el = this.element,
559                                 bottom = el.scrollTop() + el.height();
560
561                         if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
562                                 return;
563
564                         setTimeout(function() {
565                                 var newTop = el.scrollTop(),
566                                         newBottom = newTop + el.height();
567
568                                 if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
569                                         return;
570
571                                 self.waiting.show();
572                                 el.scrollTop( newTop + self.waiting.outerHeight() );
573
574                                 self.ajax( function() {
575                                         self.waiting.hide();
576                                 });
577                         }, wpLink.timeToTriggerRiver );
578                 }
579         });
580
581         Query = function( search ) {
582                 this.page = 1;
583                 this.allLoaded = false;
584                 this.querying = false;
585                 this.search = search;
586         };
587
588         $.extend( Query.prototype, {
589                 ready: function() {
590                         return ! ( this.querying || this.allLoaded );
591                 },
592                 ajax: function( callback ) {
593                         var self = this,
594                                 query = {
595                                         action : 'wp-link-ajax',
596                                         page : this.page,
597                                         '_ajax_linking_nonce' : inputs.nonce.val()
598                                 };
599
600                         if ( this.search )
601                                 query.search = this.search;
602
603                         this.querying = true;
604
605                         $.post( ajaxurl, query, function( r ) {
606                                 self.page++;
607                                 self.querying = false;
608                                 self.allLoaded = ! r;
609                                 callback( r, query );
610                         }, 'json' );
611                 }
612         });
613
614         $( document ).ready( wpLink.init );
615 })( jQuery );