use __call() to instantly have some new fresh helpers
[mediawiki.git] / resources / jquery / jquery.textSelection.js
blob443722f2dfe5a988d6a76952c6e76259d4b3ec5b
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 ( this.selectionStart || this.selectionStart == '0' ) {
135                         // Mozilla/Opera
136                         $(this).focus();
137                         if ( options.selectionStart !== undefined ) {
138                                 $(this).textSelection( 'setSelection', { 'start': options.selectionStart, 'end': options.selectionEnd } );
139                         }
140                         
141                         var selText = $(this).textSelection( 'getSelection' );
142                         var startPos = this.selectionStart;
143                         var endPos = this.selectionEnd;
144                         var scrollTop = this.scrollTop;
145                         checkSelectedText();
146                         if ( options.selectionStart !== undefined
147                                         && endPos - startPos != options.selectionEnd - options.selectionStart )
148                         {
149                                 // This means there is a difference in the selection range returned by browser and what we passed.
150                                 // This happens for Chrome in the case of composite characters. Ref bug #30130
151                                 // Set the startPos to the correct position.
152                                 startPos = options.selectionStart;
153                         }
155                         var insertText = pre + selText + post;
156                         if ( options.splitlines ) {
157                                 insertText = doSplitLines( selText, pre, post );
158                         }
159                         if ( options.ownline ) {
160                                 if ( startPos != 0 && this.value.charAt( startPos - 1 ) != "\n" && this.value.charAt( startPos - 1 ) != "\r" ) {
161                                         insertText = "\n" + insertText;
162                                         pre += "\n";
163                                 }
164                                 if ( this.value.charAt( endPos ) != "\n" && this.value.charAt( endPos ) != "\r" ) {
165                                         insertText += "\n";
166                                         post += "\n";
167                                 }
168                         }
169                         this.value = this.value.substring( 0, startPos ) + insertText +
170                                 this.value.substring( endPos, this.value.length );
171                         // Setting this.value scrolls the textarea to the top, restore the scroll position
172                         this.scrollTop = scrollTop;
173                         if ( window.opera ) {
174                                 pre = pre.replace( /\r?\n/g, "\r\n" );
175                                 selText = selText.replace( /\r?\n/g, "\r\n" );
176                                 post = post.replace( /\r?\n/g, "\r\n" );
177                         }
178                         if ( isSample && options.selectPeri && !options.splitlines ) {
179                                 this.selectionStart = startPos + pre.length;
180                                 this.selectionEnd = startPos + pre.length + selText.length;
181                         } else {
182                                 this.selectionStart = startPos + insertText.length;
183                                 this.selectionEnd = this.selectionStart;
184                         }
185                 } else if ( document.selection && document.selection.createRange ) {
186                         // IE
187                         activateElementOnIE( this );
188                         if ( context ) {
189                                 context.fn.restoreCursorAndScrollTop();
190                         }
191                         if ( options.selectionStart !== undefined ) {
192                                 $(this).textSelection( 'setSelection', { 'start': options.selectionStart, 'end': options.selectionEnd } );
193                         }
194                         
195                         var selText = $(this).textSelection( 'getSelection' );
196                         var scrollTop = this.scrollTop;
197                         var range = document.selection.createRange();
199                         checkSelectedText();
200                         var insertText = pre + selText + post;
201                         if ( options.splitlines ) {
202                                 insertText = doSplitLines( selText, pre, post );
203                         }
204                         if ( options.ownline && range.moveStart ) {
205                                 var range2 = document.selection.createRange();
206                                 range2.collapse();
207                                 range2.moveStart( 'character', -1 );
208                                 // FIXME: Which check is correct?
209                                 if ( range2.text != "\r" && range2.text != "\n" && range2.text != "" ) {
210                                         insertText = "\n" + insertText;
211                                         pre += "\n";
212                                 }
213                                 var range3 = document.selection.createRange();
214                                 range3.collapse( false );
215                                 range3.moveEnd( 'character', 1 );
216                                 if ( range3.text != "\r" && range3.text != "\n" && range3.text != "" ) {
217                                         insertText += "\n";
218                                         post += "\n";
219                                 }
220                         }
222                         range.text = insertText;
223                         if ( isSample && options.selectPeri && range.moveStart ) {
224                                 range.moveStart( 'character', - post.length - selText.length );
225                                 range.moveEnd( 'character', - post.length );
226                         }
227                         range.select();
228                         // Restore the scroll position
229                         this.scrollTop = scrollTop;
230                 }
231                 $(this).trigger( 'encapsulateSelection', [ options.pre, options.peri, options.post, options.ownline,
232                         options.replace, options.spitlines ] );
233         });
236  * Ported from Wikia's LinkSuggest extension
237  * https://svn.wikia-code.com/wikia/trunk/extensions/wikia/LinkSuggest
238  * Some code copied from
239  * http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/
241  * Get the position (in resolution of bytes not nessecarily characters)
242  * in a textarea
244  * Will focus the textarea in some browsers (IE/Opera)
246  * @fixme document the options parameters
247  */
248  getCaretPosition: function( options ) {
249         function getCaret( e ) {
250                 var caretPos = 0, endPos = 0;
251                 if ( document.selection && document.selection.createRange ) {
252                         // IE doesn't properly report non-selected caret position through
253                         // the selection ranges when textarea isn't focused. This can
254                         // lead to saving a bogus empty selection, which then screws up
255                         // whatever we do later (bug 31847).
256                         activateElementOnIE( e );
258                         // IE Support
259                         var preFinished = false;
260                         var periFinished = false;
261                         var postFinished = false;
262                         var preText, rawPreText, periText;
263                         var rawPeriText, postText, rawPostText;
264                         // Create range containing text in the selection
265                         var periRange = document.selection.createRange().duplicate();
266                         // Create range containing text before the selection
267                         var preRange = rangeForElementIE( e );
268                         // Move the end where we need it
269                         preRange.setEndPoint("EndToStart", periRange);
270                         // Create range containing text after the selection
271                         var postRange = rangeForElementIE( e );
272                         // Move the start where we need it
273                         postRange.setEndPoint("StartToEnd", periRange);
274                         // Load the text values we need to compare
275                         preText = rawPreText = preRange.text;
276                         periText = rawPeriText = periRange.text;
277                         postText = rawPostText = postRange.text;
278                         /*
279                          * Check each range for trimmed newlines by shrinking the range by 1
280                          * character and seeing if the text property has changed. If it has
281                          * not changed then we know that IE has trimmed a \r\n from the end.
282                          */
283                         do {
284                                 if ( !preFinished ) {
285                                         if ( preRange.compareEndPoints( "StartToEnd", preRange ) == 0 ) {
286                                                 preFinished = true;
287                                         } else {
288                                                 preRange.moveEnd( "character", -1 );
289                                                 if ( preRange.text == preText ) {
290                                                         rawPreText += "\r\n";
291                                                 } else {
292                                                         preFinished = true;
293                                                 }
294                                         }
295                                 }
296                                 if ( !periFinished ) {
297                                         if ( periRange.compareEndPoints( "StartToEnd", periRange ) == 0 ) {
298                                                 periFinished = true;
299                                         } else {
300                                                 periRange.moveEnd( "character", -1 );
301                                                 if ( periRange.text == periText ) {
302                                                         rawPeriText += "\r\n";
303                                                 } else {
304                                                         periFinished = true;
305                                                 }
306                                         }
307                                 }
308                                 if ( !postFinished ) {
309                                         if ( postRange.compareEndPoints("StartToEnd", postRange) == 0 ) {
310                                                 postFinished = true;
311                                         } else {
312                                                 postRange.moveEnd( "character", -1 );
313                                                 if ( postRange.text == postText ) {
314                                                         rawPostText += "\r\n";
315                                                 } else {
316                                                         postFinished = true;
317                                                 }
318                                         }
319                                 }
320                         } while ( ( !preFinished || !periFinished || !postFinished ) );
321                         caretPos = rawPreText.replace( /\r\n/g, "\n" ).length;
322                         endPos = caretPos + rawPeriText.replace( /\r\n/g, "\n" ).length;
323                 } else if ( e.selectionStart || e.selectionStart == '0' ) {
324                         // Firefox support
325                         caretPos = e.selectionStart;
326                         endPos = e.selectionEnd;
327                 }
328                 return options.startAndEnd ? [ caretPos, endPos ] : caretPos;
329         }
330         return getCaret( this.get( 0 ) );
333  * @fixme document the options parameters
334  */
335 setSelection: function( options ) {
336         return this.each( function() {
337                 if ( $(this).is( ':hidden' ) ) {
338                         // Do nothing
339                 } else if ( this.selectionStart || this.selectionStart == '0' ) {
340                         // Opera 9.0 doesn't allow setting selectionStart past
341                         // selectionEnd; any attempts to do that will be ignored
342                         // Make sure to set them in the right order
343                         if ( options.start > this.selectionEnd ) {
344                                 this.selectionEnd = options.end;
345                                 this.selectionStart = options.start;
346                         } else {
347                                 this.selectionStart = options.start;
348                                 this.selectionEnd = options.end;
349                         }
350                 } else if ( document.body.createTextRange ) {
351                         var selection = rangeForElementIE( this );
352                         var length = this.value.length;
353                         // IE doesn't count \n when computing the offset, so we won't either
354                         var newLines = this.value.match( /\n/g );
355                         if ( newLines ) length = length - newLines.length;
356                         selection.moveStart( 'character', options.start );
357                         selection.moveEnd( 'character', -length + options.end );
359                         // This line can cause an error under certain circumstances (textarea empty, no selection)
360                         // Silence that error
361                         try {
362                                 selection.select();
363                         } catch( e ) { }
364                 }
365         });
368  * Ported from Wikia's LinkSuggest extension
369  * https://svn.wikia-code.com/wikia/trunk/extensions/wikia/LinkSuggest
371  * Scroll a textarea to the current cursor position. You can set the cursor
372  * position with setSelection()
373  * @param options boolean Whether to force a scroll even if the caret position
374  *  is already visible. Defaults to false
376  * @fixme document the options parameters (function body suggests options.force is a boolean, not options itself)
377  */
378 scrollToCaretPosition: function( options ) {
379         function getLineLength( e ) {
380                 return Math.floor( e.scrollWidth / ( $.client.profile().platform == 'linux' ? 7 : 8 ) );
381         }
382         function getCaretScrollPosition( e ) {
383                 // FIXME: This functions sucks and is off by a few lines most
384                 // of the time. It should be replaced by something decent.
385                 var text = e.value.replace( /\r/g, "" );
386                 var caret = $( e ).textSelection( 'getCaretPosition' );
387                 var lineLength = getLineLength( e );
388                 var row = 0;
389                 var charInLine = 0;
390                 var lastSpaceInLine = 0;
391                 for ( i = 0; i < caret; i++ ) {
392                         charInLine++;
393                         if ( text.charAt( i ) == " " ) {
394                                 lastSpaceInLine = charInLine;
395                         } else if ( text.charAt( i ) == "\n" ) {
396                                 lastSpaceInLine = 0;
397                                 charInLine = 0;
398                                 row++;
399                         }
400                         if ( charInLine > lineLength ) {
401                                 if ( lastSpaceInLine > 0 ) {
402                                         charInLine = charInLine - lastSpaceInLine;
403                                         lastSpaceInLine = 0;
404                                         row++;
405                                 }
406                         }
407                 }
408                 var nextSpace = 0;
409                 for ( j = caret; j < caret + lineLength; j++ ) {
410                         if (
411                                 text.charAt( j ) == " " ||
412                                 text.charAt( j ) == "\n" ||
413                                 caret == text.length
414                         ) {
415                                 nextSpace = j;
416                                 break;
417                         }
418                 }
419                 if ( nextSpace > lineLength && caret <= lineLength ) {
420                         charInLine = caret - lastSpaceInLine;
421                         row++;
422                 }
423                 return ( $.client.profile().platform == 'mac' ? 13 : ( $.client.profile().platform == 'linux' ? 15 : 16 ) ) * row;
424         }
425         return this.each(function() {
426                 if ( $(this).is( ':hidden' ) ) {
427                         // Do nothing
428                 } else if ( this.selectionStart || this.selectionStart == '0' ) {
429                         // Mozilla
430                         var scroll = getCaretScrollPosition( this );
431                         if ( options.force || scroll < $(this).scrollTop() ||
432                                         scroll > $(this).scrollTop() + $(this).height() )
433                                 $(this).scrollTop( scroll );
434                 } else if ( document.selection && document.selection.createRange ) {
435                         // IE / Opera
436                         /*
437                          * IE automatically scrolls the selected text to the
438                          * bottom of the textarea at range.select() time, except
439                          * if it was already in view and the cursor position
440                          * wasn't changed, in which case it does nothing. To
441                          * cover that case, we'll force it to act by moving one
442                          * character back and forth.
443                          */
444                         var range = document.body.createTextRange();
445                         var savedRange = document.selection.createRange();
446                         var pos = $(this).textSelection( 'getCaretPosition' );
447                         var oldScrollTop = this.scrollTop;
448                         range.moveToElementText( this );
449                         range.collapse();
450                         range.move( 'character', pos + 1);
451                         range.select();
452                         if ( this.scrollTop != oldScrollTop )
453                                 this.scrollTop += range.offsetTop;
454                         else if ( options.force ) {
455                                 range.move( 'character', -1 );
456                                 range.select();
457                         }
458                         savedRange.select();
459                 }
460                 $(this).trigger( 'scrollToPosition' );
461         } );
464         // Apply defaults
465         switch ( command ) {
466                 //case 'getContents': // no params
467                 //case 'setContents': // no params with defaults
468                 //case 'getSelection': // no params
469                 case 'encapsulateSelection':
470                         options = $.extend( {
471                                 'pre': '', // Text to insert before the cursor/selection
472                                 'peri': '', // Text to insert between pre and post and select afterwards
473                                 'post': '', // Text to insert after the cursor/selection
474                                 'ownline': false, // Put the inserted text on a line of its own
475                                 'replace': false, // If there is a selection, replace it with peri instead of leaving it alone
476                                 'selectPeri': true, // Select the peri text if it was inserted (but not if there was a selection and replace==false, or if splitlines==true)
477                                 'splitlines': false, // If multiple lines are selected, encapsulate each line individually
478                                 'selectionStart': undefined, // Position to start selection at
479                                 'selectionEnd': undefined // Position to end selection at. Defaults to start
480                         }, options );
481                         break;
482                 case 'getCaretPosition':
483                         options = $.extend( {
484                                 'startAndEnd': false // Return [start, end] instead of just start
485                         }, options );
486                         // FIXME: We may not need character position-based functions if we insert markers in the right places
487                         break;
488                 case 'setSelection':
489                         options = $.extend( {
490                                 'start': undefined, // Position to start selection at
491                                 'end': undefined, // Position to end selection at. Defaults to start
492                                 'startContainer': undefined, // Element to start selection in (iframe only)
493                                 'endContainer': undefined // Element to end selection in (iframe only). Defaults to startContainer
494                         }, options );
495                         if ( options.end === undefined )
496                                 options.end = options.start;
497                         if ( options.endContainer == undefined )
498                                 options.endContainer = options.startContainer;
499                         // FIXME: We may not need character position-based functions if we insert markers in the right places
500                         break;
501                 case 'scrollToCaretPosition':
502                         options = $.extend( {
503                                 'force': false // Force a scroll even if the caret position is already visible
504                         }, options );
505                         break;
506         }
507         var context = $(this).data( 'wikiEditor-context' );
508         var hasIframe = typeof context !== 'undefined' && context && typeof context.$iframe !== 'undefined';
510         // IE selection restore voodoo
511         var needSave = false;
512         if ( hasIframe && context.savedSelection !== null ) {
513                 context.fn.restoreSelection();
514                 needSave = true;
515         }
516         var retval = ( hasIframe ? context.fn : fn )[command].call( this, options );
517         if ( hasIframe && needSave ) {
518                 context.fn.saveSelection();
519         }
520         return retval;
522 } )( jQuery );