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