Fix noglobals exceptions from QUnit
[mediawiki.git] / resources / jquery / jquery.textSelection.js
blob5b3c833c76234ec3a1796888c78d69952ea06228
1 /**
2  * These plugins provide extra functionality for interaction with textareas.
3  */
4 ( function( $ ) {
5 $.fn.textSelection = function( command, options ) {
7 /**
8  * Helper function to get an IE TextRange object for an element
9  */
10 function rangeForElementIE( e ) {
11         if ( e.nodeName.toLowerCase() == 'input' ) {
12                 return e.createTextRange();
13         } else {
14                 var sel = document.body.createTextRange();
15                 sel.moveToElementText( e );
16                 return sel;
17         }
20 var fn = {
21 /**
22  * Get the contents of the textarea
23  */
24 getContents: function() {
25         return this.val();
27 /**
28  * Get the currently selected text in this textarea. Will focus the textarea
29  * in some browsers (IE/Opera)
30  */
31 getSelection: function() {
32         var e = this.get( 0 );
33         var retval = '';
34         if ( $(e).is( ':hidden' ) ) {
35                 // Do nothing
36         } else if ( document.selection && document.selection.createRange ) {
37                 e.focus();
38                 var range = document.selection.createRange();
39                 retval = range.text;
40         } else if ( e.selectionStart || e.selectionStart == '0' ) {
41                 retval = e.value.substring( e.selectionStart, e.selectionEnd );
42         }
43         return retval;
45 /**
46  * Ported from skins/common/edit.js by Trevor Parscal
47  * (c) 2009 Wikimedia Foundation (GPLv2) - http://www.wikimedia.org
48  *
49  * Inserts text at the begining and end of a text selection, optionally
50  * inserting text at the caret when selection is empty.
51  *
52  * @fixme document the options parameters
53  */
54 encapsulateSelection: function( options ) {
55         return this.each( function() {
56                 var pre = options.pre, post = options.post;
57                 
58                 /**
59                  * Check if the selected text is the same as the insert text
60                  */
61                 function checkSelectedText() {
62                         if ( !selText ) {
63                                 selText = options.peri;
64                                 isSample = true;
65                         } else if ( options.replace ) {
66                                 selText = options.peri;
67                         } else {
68                                 while ( selText.charAt( selText.length - 1 ) == ' ' ) {
69                                         // Exclude ending space char
70                                         selText = selText.substring( 0, selText.length - 1 );
71                                         post += ' ';
72                                 }
73                                 while ( selText.charAt( 0 ) == ' ' ) {
74                                         // Exclude prepending space char
75                                         selText = selText.substring( 1, selText.length );
76                                         pre = ' ' + pre;
77                                 }
78                         }
79                 }
80                 
81                 /**
82                  * Do the splitlines stuff.
83                  * 
84                  * Wrap each line of the selected text with pre and post
85                  */
86                 function doSplitLines( selText, pre, post ) {
87                         var insertText = '';
88                         var selTextArr = selText.split( '\n' );
89                         for ( var i = 0; i < selTextArr.length; i++ ) {
90                                 insertText += pre + selTextArr[i] + post;
91                                 if ( i != selTextArr.length - 1 ) {
92                                         insertText += '\n';
93                                 }
94                         }
95                         return insertText;
96                 }
97                 
98                 var isSample = false;
99                 if ( this.style.display == 'none' ) {
100                         // Do nothing
101                 } else if ( this.selectionStart || this.selectionStart == '0' ) {
102                         // Mozilla/Opera
103                         $(this).focus();
104                         var selText = $(this).textSelection( 'getSelection' );
105                         var startPos = this.selectionStart;
106                         var endPos = this.selectionEnd;
107                         var scrollTop = this.scrollTop;
108                         checkSelectedText();
109                         
110                         var insertText = pre + selText  + post;
111                         if ( options.splitlines ) {
112                                 insertText = doSplitLines( selText, pre, post );
113                         }
114                         if ( options.ownline ) {
115                                 if ( startPos != 0 && this.value.charAt( startPos - 1 ) != "\n" && this.value.charAt( startPos - 1 ) != "\r" ) {
116                                         insertText = "\n" + insertText;
117                                         pre += "\n";
118                                 }
119                                 if ( this.value.charAt( endPos ) != "\n" && this.value.charAt( endPos ) != "\r" ) {
120                                         insertText += "\n";
121                                         post += "\n";
122                                 }
123                         }
124                         this.value = this.value.substring( 0, startPos ) + insertText +
125                                 this.value.substring( endPos, this.value.length );
126                         // Setting this.value scrolls the textarea to the top, restore the scroll position
127                         this.scrollTop = scrollTop;
128                         if ( window.opera ) {
129                                 pre = pre.replace( /\r?\n/g, "\r\n" );
130                                 selText = selText.replace( /\r?\n/g, "\r\n" );
131                                 post = post.replace( /\r?\n/g, "\r\n" );
132                         }
133                         if ( isSample && options.selectPeri && !options.splitlines ) {
134                                 this.selectionStart = startPos + pre.length;
135                                 this.selectionEnd = startPos + pre.length + selText.length;
136                         } else {
137                                 this.selectionStart = startPos + insertText.length;
138                                 this.selectionEnd = this.selectionStart;
139                         }
140                 } else if ( document.selection && document.selection.createRange ) {
141                         // IE
142                         $(this).focus();
143                         if ( context ) {
144                                 context.fn.restoreCursorAndScrollTop();
145                         }
146                         var selText = $(this).textSelection( 'getSelection' );
147                         var scrollTop = this.scrollTop;
148                         var range = document.selection.createRange();
149                         
150                         checkSelectedText();
151                         var insertText = pre + selText  + post;
152                         if ( options.splitlines ) {
153                                 insertText = doSplitLines( selText, pre, post );
154                         }
155                         if ( options.ownline && range.moveStart ) {
156                                 var range2 = document.selection.createRange();
157                                 range2.collapse();
158                                 range2.moveStart( 'character', -1 );
159                                 // FIXME: Which check is correct?
160                                 if ( range2.text != "\r" && range2.text != "\n" && range2.text != "" ) {
161                                         insertText = "\n" + insertText;
162                                         pre += "\n";
163                                 }
164                                 var range3 = document.selection.createRange();
165                                 range3.collapse( false );
166                                 range3.moveEnd( 'character', 1 );
167                                 if ( range3.text != "\r" && range3.text != "\n" && range3.text != "" ) {
168                                         insertText += "\n";
169                                         post += "\n";
170                                 }
171                         }
172                         
173                         range.text = insertText;
174                         if ( isSample && options.selectPeri && range.moveStart ) {
175                                 range.moveStart( 'character', - post.length - selText.length );
176                                 range.moveEnd( 'character', - post.length );
177                         }
178                         range.select();
179                         // Restore the scroll position
180                         this.scrollTop = scrollTop;
181                 }
182                 $(this).trigger( 'encapsulateSelection', [ options.pre, options.peri, options.post, options.ownline,
183                         options.replace, options.spitlines ] );
184         });
187  * Ported from Wikia's LinkSuggest extension
188  * https://svn.wikia-code.com/wikia/trunk/extensions/wikia/LinkSuggest
189  * Some code copied from
190  * http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/
192  * Get the position (in resolution of bytes not nessecarily characters)
193  * in a textarea
195  * @fixme document the options parameters
196  */
197  getCaretPosition: function( options ) {
198         function getCaret( e ) {
199                 var caretPos = 0, endPos = 0;
200                 if ( $.browser.msie ) {
201                         // IE Support
202                         var preFinished = false;
203                         var periFinished = false;
204                         var postFinished = false;
205                         var preText, rawPreText, periText;
206                         var rawPeriText, postText, rawPostText;
207                         // Create range containing text in the selection
208                         var periRange = document.selection.createRange().duplicate();
209                         // Create range containing text before the selection
210                         var preRange = rangeForElementIE( e );
211                         // Move the end where we need it
212                         preRange.setEndPoint("EndToStart", periRange);
213                         // Create range containing text after the selection
214                         var postRange = rangeForElementIE( e );
215                         // Move the start where we need it
216                         postRange.setEndPoint("StartToEnd", periRange);
217                         // Load the text values we need to compare
218                         preText = rawPreText = preRange.text;
219                         periText = rawPeriText = periRange.text;
220                         postText = rawPostText = postRange.text;
221                         /*
222                          * Check each range for trimmed newlines by shrinking the range by 1
223                          * character and seeing if the text property has changed. If it has
224                          * not changed then we know that IE has trimmed a \r\n from the end.
225                          */
226                         do {
227                                 if ( !preFinished ) {
228                                         if ( preRange.compareEndPoints( "StartToEnd", preRange ) == 0 ) {
229                                                 preFinished = true;
230                                         } else {
231                                                 preRange.moveEnd( "character", -1 );
232                                                 if ( preRange.text == preText ) {
233                                                         rawPreText += "\r\n";
234                                                 } else {
235                                                         preFinished = true;
236                                                 }
237                                         }
238                                 }
239                                 if ( !periFinished ) {
240                                         if ( periRange.compareEndPoints( "StartToEnd", periRange ) == 0 ) {
241                                                 periFinished = true;
242                                         } else {
243                                                 periRange.moveEnd( "character", -1 );
244                                                 if ( periRange.text == periText ) {
245                                                         rawPeriText += "\r\n";
246                                                 } else {
247                                                         periFinished = true;
248                                                 }
249                                         }
250                                 }
251                                 if ( !postFinished ) {
252                                         if ( postRange.compareEndPoints("StartToEnd", postRange) == 0 ) {
253                                                 postFinished = true;
254                                         } else {
255                                                 postRange.moveEnd( "character", -1 );
256                                                 if ( postRange.text == postText ) {
257                                                         rawPostText += "\r\n";
258                                                 } else {
259                                                         postFinished = true;
260                                                 }
261                                         }
262                                 }
263                         } while ( ( !preFinished || !periFinished || !postFinished ) );
264                         caretPos = rawPreText.replace( /\r\n/g, "\n" ).length;
265                         endPos = caretPos + rawPeriText.replace( /\r\n/g, "\n" ).length;
266                 } else if ( e.selectionStart || e.selectionStart == '0' ) {
267                         // Firefox support
268                         caretPos = e.selectionStart;
269                         endPos = e.selectionEnd;
270                 }
271                 return options.startAndEnd ? [ caretPos, endPos ] : caretPos;
272         }
273         return getCaret( this.get( 0 ) );
276  * @fixme document the options parameters
277  */
278 setSelection: function( options ) {
279         return this.each( function() {
280                 if ( $(this).is( ':hidden' ) ) {
281                         // Do nothing
282                 } else if ( this.selectionStart || this.selectionStart == '0' ) {
283                         // Opera 9.0 doesn't allow setting selectionStart past
284                         // selectionEnd; any attempts to do that will be ignored
285                         // Make sure to set them in the right order
286                         if ( options.start > this.selectionEnd ) {
287                                 this.selectionEnd = options.end;
288                                 this.selectionStart = options.start;
289                         } else {
290                                 this.selectionStart = options.start;
291                                 this.selectionEnd = options.end;
292                         }
293                 } else if ( document.body.createTextRange ) {
294                         var selection = rangeForElementIE( this );
295                         var length = this.value.length;
296                         // IE doesn't count \n when computing the offset, so we won't either
297                         var newLines = this.value.match( /\n/g );
298                         if ( newLines ) length = length - newLines.length;
299                         selection.moveStart( 'character', options.start );
300                         selection.moveEnd( 'character', -length + options.end );
301                         
302                         // This line can cause an error under certain circumstances (textarea empty, no selection)
303                         // Silence that error
304                         try {
305                                 selection.select();
306                         } catch( e ) { }
307                 }
308         });
311  * Ported from Wikia's LinkSuggest extension
312  * https://svn.wikia-code.com/wikia/trunk/extensions/wikia/LinkSuggest
314  * Scroll a textarea to the current cursor position. You can set the cursor
315  * position with setSelection()
316  * @param options boolean Whether to force a scroll even if the caret position
317  *  is already visible. Defaults to false
319  * @fixme document the options parameters (function body suggests options.force is a boolean, not options itself)
320  */
321 scrollToCaretPosition: function( options ) {
322         function getLineLength( e ) {
323                 return Math.floor( e.scrollWidth / ( $.client.profile().platform == 'linux' ? 7 : 8 ) );
324         }
325         function getCaretScrollPosition( e ) {
326                 // FIXME: This functions sucks and is off by a few lines most
327                 // of the time. It should be replaced by something decent.
328                 var text = e.value.replace( /\r/g, "" );
329                 var caret = $( e ).textSelection( 'getCaretPosition' );
330                 var lineLength = getLineLength( e );
331                 var row = 0;
332                 var charInLine = 0;
333                 var lastSpaceInLine = 0;
334                 for ( i = 0; i < caret; i++ ) {
335                         charInLine++;
336                         if ( text.charAt( i ) == " " ) {
337                                 lastSpaceInLine = charInLine;
338                         } else if ( text.charAt( i ) == "\n" ) {
339                                 lastSpaceInLine = 0;
340                                 charInLine = 0;
341                                 row++;
342                         }
343                         if ( charInLine > lineLength ) {
344                                 if ( lastSpaceInLine > 0 ) {
345                                         charInLine = charInLine - lastSpaceInLine;
346                                         lastSpaceInLine = 0;
347                                         row++;
348                                 }
349                         }
350                 }
351                 var nextSpace = 0;
352                 for ( j = caret; j < caret + lineLength; j++ ) {
353                         if (
354                                 text.charAt( j ) == " " ||
355                                 text.charAt( j ) == "\n" ||
356                                 caret == text.length
357                         ) {
358                                 nextSpace = j;
359                                 break;
360                         }
361                 }
362                 if ( nextSpace > lineLength && caret <= lineLength ) {
363                         charInLine = caret - lastSpaceInLine;
364                         row++;
365                 }
366                 return ( $.client.profile().platform == 'mac' ? 13 : ( $.client.profile().platform == 'linux' ? 15 : 16 ) ) * row;
367         }
368         return this.each(function() {
369                 if ( $(this).is( ':hidden' ) ) {
370                         // Do nothing
371                 } else if ( this.selectionStart || this.selectionStart == '0' ) {
372                         // Mozilla
373                         var scroll = getCaretScrollPosition( this );
374                         if ( options.force || scroll < $(this).scrollTop() ||
375                                         scroll > $(this).scrollTop() + $(this).height() )
376                                 $(this).scrollTop( scroll );
377                 } else if ( document.selection && document.selection.createRange ) {
378                         // IE / Opera
379                         /*
380                          * IE automatically scrolls the selected text to the
381                          * bottom of the textarea at range.select() time, except
382                          * if it was already in view and the cursor position
383                          * wasn't changed, in which case it does nothing. To
384                          * cover that case, we'll force it to act by moving one
385                          * character back and forth.
386                          */
387                         var range = document.body.createTextRange();
388                         var savedRange = document.selection.createRange();
389                         var pos = $(this).textSelection( 'getCaretPosition' );
390                         var oldScrollTop = this.scrollTop;
391                         range.moveToElementText( this );
392                         range.collapse();
393                         range.move( 'character', pos + 1);
394                         range.select();
395                         if ( this.scrollTop != oldScrollTop )
396                                 this.scrollTop += range.offsetTop;
397                         else if ( options.force ) {
398                                 range.move( 'character', -1 );
399                                 range.select();
400                         }
401                         savedRange.select();
402                 }
403                 $(this).trigger( 'scrollToPosition' );
404         } );
407         // Apply defaults
408         switch ( command ) {
409                 //case 'getContents': // no params
410                 //case 'setContents': // no params with defaults
411                 //case 'getSelection': // no params
412                 case 'encapsulateSelection':
413                         options = $.extend( {
414                                 'pre': '', // Text to insert before the cursor/selection
415                                 'peri': '', // Text to insert between pre and post and select afterwards
416                                 'post': '', // Text to insert after the cursor/selection
417                                 'ownline': false, // Put the inserted text on a line of its own
418                                 'replace': false, // If there is a selection, replace it with peri instead of leaving it alone
419                                 'selectPeri': true, // Select the peri text if it was inserted (but not if there was a selection and replace==false, or if splitlines==true)
420                                 'splitlines': false // If multiple lines are selected, encapsulate each line individually
421                         }, options );
422                         break;
423                 case 'getCaretPosition':
424                         options = $.extend( {
425                                 'startAndEnd': false // Return [start, end] instead of just start
426                         }, options );
427                         // FIXME: We may not need character position-based functions if we insert markers in the right places
428                         break;
429                 case 'setSelection':
430                         options = $.extend( {
431                                 'start': undefined, // Position to start selection at
432                                 'end': undefined, // Position to end selection at. Defaults to start
433                                 'startContainer': undefined, // Element to start selection in (iframe only)
434                                 'endContainer': undefined // Element to end selection in (iframe only). Defaults to startContainer
435                         }, options );
436                         if ( options.end === undefined )
437                                 options.end = options.start;
438                         if ( options.endContainer == undefined )
439                                 options.endContainer = options.startContainer;
440                         // FIXME: We may not need character position-based functions if we insert markers in the right places
441                         break;
442                 case 'scrollToCaretPosition':
443                         options = $.extend( {
444                                 'force': false // Force a scroll even if the caret position is already visible
445                         }, options );
446                         break;
447         }
448         var context = $(this).data( 'wikiEditor-context' );
449         var hasIframe = typeof context !== 'undefined' && context && typeof context.$iframe !== 'undefined';
450         
451         // IE selection restore voodoo
452         var needSave = false;
453         if ( hasIframe && context.savedSelection !== null ) {
454                 context.fn.restoreSelection();
455                 needSave = true;
456         }
457         var retval = ( hasIframe ? context.fn : fn )[command].call( this, options );
458         if ( hasIframe && needSave ) {
459                 context.fn.saveSelection();
460         }
461         return retval;
463 } )( jQuery );