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