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