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