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