]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/wplink.js
WordPress 4.2.5
[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, correctedURL,
6                 inputs = {},
7                 rivers = {},
8                 isTouch = ( 'ontouchend' in document );
9
10         function getLink() {
11                 return editor.dom.getParent( editor.selection.getNode(), 'a' );
12         }
13
14         wpLink = {
15                 timeToTriggerRiver: 150,
16                 minRiverAJAXDuration: 200,
17                 riverBottomThreshold: 5,
18                 keySensitivity: 100,
19                 lastSearch: '',
20                 textarea: '',
21
22                 init: function() {
23                         inputs.wrap = $('#wp-link-wrap');
24                         inputs.dialog = $( '#wp-link' );
25                         inputs.backdrop = $( '#wp-link-backdrop' );
26                         inputs.submit = $( '#wp-link-submit' );
27                         inputs.close = $( '#wp-link-close' );
28
29                         // Input
30                         inputs.text = $( '#wp-link-text' );
31                         inputs.url = $( '#wp-link-url' );
32                         inputs.nonce = $( '#_ajax_linking_nonce' );
33                         inputs.openInNewTab = $( '#wp-link-target' );
34                         inputs.search = $( '#wp-link-search' );
35
36                         // Build Rivers
37                         rivers.search = new River( $( '#search-results' ) );
38                         rivers.recent = new River( $( '#most-recent-results' ) );
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' );
45
46                         // Bind event handlers
47                         inputs.dialog.keydown( wpLink.keydown );
48                         inputs.dialog.keyup( wpLink.keyup );
49                         inputs.submit.click( function( event ) {
50                                 event.preventDefault();
51                                 wpLink.update();
52                         });
53                         inputs.close.add( inputs.backdrop ).add( '#wp-link-cancel a' ).click( function( event ) {
54                                 event.preventDefault();
55                                 wpLink.close();
56                         });
57
58                         $( '#wp-link-search-toggle' ).on( 'click', wpLink.toggleInternalLinking );
59
60                         rivers.elements.on( 'river-select', wpLink.updateFields );
61
62                         // Display 'hint' message when search field or 'query-results' box are focused
63                         inputs.search.on( 'focus.wplink', function() {
64                                 inputs.queryNoticeTextDefault.hide();
65                                 inputs.queryNoticeTextHint.removeClass( 'screen-reader-text' ).show();
66                         } ).on( 'blur.wplink', function() {
67                                 inputs.queryNoticeTextDefault.show();
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
101                         wpLink.range = null;
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
127                         if ( ! wpLink.isMCE() && document.selection ) {
128                                 this.textarea.focus();
129                                 this.range = document.selection.createRange();
130                         }
131
132                         inputs.wrap.show();
133                         inputs.backdrop.show();
134
135                         wpLink.refresh();
136
137                         $( document ).trigger( 'wplink-open', inputs.wrap );
138                 },
139
140                 isMCE: function() {
141                         return editor && ! editor.isHidden();
142                 },
143
144                 refresh: function() {
145                         var text = '';
146
147                         // Refresh rivers (clear links, check visibility)
148                         rivers.search.refresh();
149                         rivers.recent.refresh();
150
151                         if ( wpLink.isMCE() ) {
152                                 wpLink.mceRefresh();
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 );
169                                 wpLink.setDefaultValues();
170                         }
171
172                         if ( isTouch ) {
173                                 // Close the onscreen keyboard
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
182                         // Load the most recent results if this is the first time opening the panel.
183                         if ( ! rivers.recent.ul.children().length ) {
184                                 rivers.recent.ajax();
185                         }
186
187                         correctedURL = inputs.url.val().replace( /^http:\/\//, '' );
188                 },
189
190                 hasSelectedText: function( linkNode ) {
191                         var html = editor.selection.getContent();
192
193                         // Partial html and not a fully selected anchor element
194                         if ( /</.test( html ) && ( ! /^<a [^>]+>[^<]+<\/a>$/.test( html ) || html.indexOf('href=') === -1 ) ) {
195                                 return false;
196                         }
197
198                         if ( linkNode ) {
199                                 var nodes = linkNode.childNodes, i;
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' ) );
225                                 inputs.submit.val( wpLinkL10n.update );
226                         } else {
227                                 text = editor.selection.getContent({ format: 'text' });
228                                 this.setDefaultValues();
229                         }
230
231                         if ( onlyText ) {
232                                 inputs.text.val( text || '' );
233                                 inputs.wrap.addClass( 'has-text-field' );
234                         } else {
235                                 inputs.text.val( '' );
236                                 inputs.wrap.removeClass( 'has-text-field' );
237                         }
238                 },
239
240                 close: function() {
241                         $( document.body ).removeClass( 'modal-open' );
242
243                         if ( ! wpLink.isMCE() ) {
244                                 wpLink.textarea.focus();
245
246                                 if ( wpLink.range ) {
247                                         wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
248                                         wpLink.range.select();
249                                 }
250                         } else {
251                                 editor.focus();
252                         }
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() {
263                         return {
264                                 href: $.trim( inputs.url.val() ),
265                                 target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
266                         };
267                 },
268
269                 update: function() {
270                         if ( wpLink.isMCE() ) {
271                                 wpLink.mceUpdate();
272                         } else {
273                                 wpLink.htmlUpdate();
274                         }
275                 },
276
277                 htmlUpdate: function() {
278                         var attrs, text, html, begin, end, cursor, selection,
279                                 textarea = wpLink.textarea;
280
281                         if ( ! textarea ) {
282                                 return;
283                         }
284
285                         attrs = wpLink.getAttrs();
286                         text = inputs.text.val();
287
288                         // If there's no href, return.
289                         if ( ! attrs.href ) {
290                                 return;
291                         }
292
293                         // Build HTML
294                         html = '<a href="' + attrs.href + '"';
295
296                         if ( attrs.target ) {
297                                 html += ' target="' + attrs.target + '"';
298                         }
299
300                         html += '>';
301
302                         // Insert HTML
303                         if ( document.selection && wpLink.range ) {
304                                 // IE
305                                 // Note: If no text is selected, IE will not place the cursor
306                                 //       inside the closing tag.
307                                 textarea.focus();
308                                 wpLink.range.text = html + ( text || wpLink.range.text ) + '</a>';
309                                 wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
310                                 wpLink.range.select();
311
312                                 wpLink.range = null;
313                         } else if ( typeof textarea.selectionStart !== 'undefined' ) {
314                                 // W3C
315                                 begin = textarea.selectionStart;
316                                 end = textarea.selectionEnd;
317                                 selection = text || textarea.value.substring( begin, end );
318                                 html = html + selection + '</a>';
319                                 cursor = begin + html.length;
320
321                                 // If no text is selected, place the cursor inside the closing tag.
322                                 if ( begin === end && ! selection ) {
323                                         cursor -= 4;
324                                 }
325
326                                 textarea.value = (
327                                         textarea.value.substring( 0, begin ) +
328                                         html +
329                                         textarea.value.substring( end, textarea.value.length )
330                                 );
331
332                                 // Update cursor position
333                                 textarea.selectionStart = textarea.selectionEnd = cursor;
334                         }
335
336                         wpLink.close();
337                         textarea.focus();
338                 },
339
340                 mceUpdate: function() {
341                         var attrs = wpLink.getAttrs(),
342                                 link, text;
343
344                         wpLink.close();
345                         editor.focus();
346
347                         if ( tinymce.isIE ) {
348                                 editor.selection.moveToBookmark( editor.windowManager.bookmark );
349                         }
350
351                         if ( ! attrs.href ) {
352                                 editor.execCommand( 'unlink' );
353                                 return;
354                         }
355
356                         link = getLink();
357                         text = inputs.text.val();
358
359                         if ( link ) {
360                                 if ( text ) {
361                                         if ( 'innerText' in link ) {
362                                                 link.innerText = text;
363                                         } else {
364                                                 link.textContent = text;
365                                         }
366                                 }
367
368                                 editor.dom.setAttribs( link, attrs );
369                         } else {
370                                 if ( text ) {
371                                         editor.selection.setNode( editor.dom.create( 'a', attrs, text ) );
372                                 } else {
373                                         editor.execCommand( 'mceInsertLink', false, attrs );
374                                 }
375                         }
376                 },
377
378                 updateFields: function( e, li ) {
379                         inputs.url.val( li.children( '.item-permalink' ).val() );
380                 },
381
382                 setDefaultValues: function() {
383                         var selection,
384                                 emailRegexp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
385                                 urlRegexp = /^(https?|ftp):\/\/[A-Z0-9.-]+\.[A-Z]{2,4}[^ "]*$/i;
386
387                         if ( this.isMCE() ) {
388                                 selection = editor.selection.getContent();
389                         } else if ( document.selection && wpLink.range ) {
390                                 selection = wpLink.range.text;
391                         } else if ( typeof this.textarea.selectionStart !== 'undefined' ) {
392                                 selection = this.textarea.value.substring( this.textarea.selectionStart, this.textarea.selectionEnd );
393                         }
394
395                         if ( selection && emailRegexp.test( selection ) ) {
396                                 // Selection is email address
397                                 inputs.url.val( 'mailto:' + selection );
398                         } else if ( selection && urlRegexp.test( selection ) ) {
399                                 // Selection is URL
400                                 inputs.url.val( selection.replace( /&amp;|&#0?38;/gi, '&' ) );
401                         } else {
402                                 // Set URL to default.
403                                 inputs.url.val( '' );
404                         }
405
406                         // Update save prompt.
407                         inputs.submit.val( wpLinkL10n.save );
408                 },
409
410                 searchInternalLinks: function() {
411                         var t = $( this ), waiting,
412                                 search = t.val();
413
414                         if ( search.length > 2 ) {
415                                 rivers.recent.hide();
416                                 rivers.search.show();
417
418                                 // Don't search if the keypress didn't change the title.
419                                 if ( wpLink.lastSearch == search )
420                                         return;
421
422                                 wpLink.lastSearch = search;
423                                 waiting = t.parent().find( '.spinner' ).addClass( 'is-active' );
424
425                                 rivers.search.change( search );
426                                 rivers.search.ajax( function() {
427                                         waiting.removeClass( 'is-active' );
428                                 });
429                         } else {
430                                 rivers.search.hide();
431                                 rivers.recent.show();
432                         }
433                 },
434
435                 next: function() {
436                         rivers.search.next();
437                         rivers.recent.next();
438                 },
439
440                 prev: function() {
441                         rivers.search.prev();
442                         rivers.recent.prev();
443                 },
444
445                 keydown: function( event ) {
446                         var fn, id,
447                                 key = $.ui.keyCode;
448
449                         if ( key.ESCAPE === event.keyCode ) {
450                                 wpLink.close();
451                                 event.stopImmediatePropagation();
452                         } else if ( key.TAB === event.keyCode ) {
453                                 id = event.target.id;
454
455                                 // wp-link-submit must always be the last focusable element in the dialog.
456                                 // following focusable elements will be skipped on keyboard navigation.
457                                 if ( id === 'wp-link-submit' && ! event.shiftKey ) {
458                                         inputs.close.focus();
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 );
479                         event.preventDefault();
480                 },
481
482                 keyup: function( event ) {
483                         var key = $.ui.keyCode;
484
485                         if ( event.which === key.UP || event.which === key.DOWN ) {
486                                 clearInterval( wpLink.keyInterval );
487                                 event.preventDefault();
488                         }
489                 },
490
491                 delayedCallback: function( func, delay ) {
492                         var timeoutTriggered, funcTriggered, funcArgs, funcContext;
493
494                         if ( ! delay )
495                                 return func;
496
497                         setTimeout( function() {
498                                 if ( funcTriggered )
499                                         return func.apply( funcContext, funcArgs );
500                                 // Otherwise, wait.
501                                 timeoutTriggered = true;
502                         }, delay );
503
504                         return function() {
505                                 if ( timeoutTriggered )
506                                         return func.apply( this, arguments );
507                                 // Otherwise, wait.
508                                 funcArgs = arguments;
509                                 funcContext = this;
510                                 funcTriggered = true;
511                         };
512                 },
513
514                 toggleInternalLinking: function( event ) {
515                         var visible = inputs.wrap.hasClass( 'search-panel-visible' );
516
517                         inputs.wrap.toggleClass( 'search-panel-visible', ! visible );
518                         setUserSetting( 'wplink', visible ? '0' : '1' );
519                         inputs[ ! visible ? 'search' : 'url' ].focus();
520                         event.preventDefault();
521                 }
522         };
523
524         River = function( element, search ) {
525                 var self = this;
526                 this.element = element;
527                 this.ul = element.children( 'ul' );
528                 this.contentHeight = element.children( '#link-selector-height' );
529                 this.waiting = element.find('.river-waiting');
530
531                 this.change( search );
532                 this.refresh();
533
534                 $( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
535                         self.maybeLoad();
536                 });
537                 element.on( 'click', 'li', function( event ) {
538                         self.select( $( this ), event );
539                 });
540         };
541
542         $.extend( River.prototype, {
543                 refresh: function() {
544                         this.deselect();
545                         this.visible = this.element.is( ':visible' );
546                 },
547                 show: function() {
548                         if ( ! this.visible ) {
549                                 this.deselect();
550                                 this.element.show();
551                                 this.visible = true;
552                         }
553                 },
554                 hide: function() {
555                         this.element.hide();
556                         this.visible = false;
557                 },
558                 // Selects a list item and triggers the river-select event.
559                 select: function( li, event ) {
560                         var liHeight, elHeight, liTop, elTop;
561
562                         if ( li.hasClass( 'unselectable' ) || li == this.selected )
563                                 return;
564
565                         this.deselect();
566                         this.selected = li.addClass( 'selected' );
567                         // Make sure the element is visible
568                         liHeight = li.outerHeight();
569                         elHeight = this.element.height();
570                         liTop = li.position().top;
571                         elTop = this.element.scrollTop();
572
573                         if ( liTop < 0 ) // Make first visible element
574                                 this.element.scrollTop( elTop + liTop );
575                         else if ( liTop + liHeight > elHeight ) // Make last visible element
576                                 this.element.scrollTop( elTop + liTop - elHeight + liHeight );
577
578                         // Trigger the river-select event
579                         this.element.trigger( 'river-select', [ li, event, this ] );
580                 },
581                 deselect: function() {
582                         if ( this.selected )
583                                 this.selected.removeClass( 'selected' );
584                         this.selected = false;
585                 },
586                 prev: function() {
587                         if ( ! this.visible )
588                                 return;
589
590                         var to;
591                         if ( this.selected ) {
592                                 to = this.selected.prev( 'li' );
593                                 if ( to.length )
594                                         this.select( to );
595                         }
596                 },
597                 next: function() {
598                         if ( ! this.visible )
599                                 return;
600
601                         var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
602                         if ( to.length )
603                                 this.select( to );
604                 },
605                 ajax: function( callback ) {
606                         var self = this,
607                                 delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
608                                 response = wpLink.delayedCallback( function( results, params ) {
609                                         self.process( results, params );
610                                         if ( callback )
611                                                 callback( results, params );
612                                 }, delay );
613
614                         this.query.ajax( response );
615                 },
616                 change: function( search ) {
617                         if ( this.query && this._search == search )
618                                 return;
619
620                         this._search = search;
621                         this.query = new Query( search );
622                         this.element.scrollTop( 0 );
623                 },
624                 process: function( results, params ) {
625                         var list = '', alt = true, classes = '',
626                                 firstPage = params.page == 1;
627
628                         if ( ! results ) {
629                                 if ( firstPage ) {
630                                         list += '<li class="unselectable no-matches-found"><span class="item-title"><em>' +
631                                                 wpLinkL10n.noMatchesFound + '</em></span></li>';
632                                 }
633                         } else {
634                                 $.each( results, function() {
635                                         classes = alt ? 'alternate' : '';
636                                         classes += this.title ? '' : ' no-title';
637                                         list += classes ? '<li class="' + classes + '">' : '<li>';
638                                         list += '<input type="hidden" class="item-permalink" value="' + this.permalink + '" />';
639                                         list += '<span class="item-title">';
640                                         list += this.title ? this.title : wpLinkL10n.noTitle;
641                                         list += '</span><span class="item-info">' + this.info + '</span></li>';
642                                         alt = ! alt;
643                                 });
644                         }
645
646                         this.ul[ firstPage ? 'html' : 'append' ]( list );
647                 },
648                 maybeLoad: function() {
649                         var self = this,
650                                 el = this.element,
651                                 bottom = el.scrollTop() + el.height();
652
653                         if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
654                                 return;
655
656                         setTimeout(function() {
657                                 var newTop = el.scrollTop(),
658                                         newBottom = newTop + el.height();
659
660                                 if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
661                                         return;
662
663                                 self.waiting.addClass( 'is-active' );
664                                 el.scrollTop( newTop + self.waiting.outerHeight() );
665
666                                 self.ajax( function() {
667                                         self.waiting.removeClass( 'is-active' );
668                                 });
669                         }, wpLink.timeToTriggerRiver );
670                 }
671         });
672
673         Query = function( search ) {
674                 this.page = 1;
675                 this.allLoaded = false;
676                 this.querying = false;
677                 this.search = search;
678         };
679
680         $.extend( Query.prototype, {
681                 ready: function() {
682                         return ! ( this.querying || this.allLoaded );
683                 },
684                 ajax: function( callback ) {
685                         var self = this,
686                                 query = {
687                                         action : 'wp-link-ajax',
688                                         page : this.page,
689                                         '_ajax_linking_nonce' : inputs.nonce.val()
690                                 };
691
692                         if ( this.search )
693                                 query.search = this.search;
694
695                         this.querying = true;
696
697                         $.post( ajaxurl, query, function( r ) {
698                                 self.page++;
699                                 self.querying = false;
700                                 self.allLoaded = ! r;
701                                 callback( r, query );
702                         }, 'json' );
703                 }
704         });
705
706         $( document ).ready( wpLink.init );
707 })( jQuery );