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