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