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