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