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