jquery.textSelection: Move copyright comments to the top of the file
[lhc/web/wiklou.git] / resources / src / jquery / jquery.textSelection.js
1 /**
2 * These plugins provide extra functionality for interaction with textareas.
3 *
4 * - encapsulateSelection: Ported from skins/common/edit.js by Trevor Parscal
5 * © 2009 Wikimedia Foundation (GPLv2) - http://www.wikimedia.org
6 * - getCaretPosition, scrollToCaretPosition: Ported from Wikia's LinkSuggest extension
7 * https://github.com/Wikia/app/blob/c0cd8b763/extensions/wikia/LinkSuggest/js/jquery.wikia.linksuggest.js
8 * © 2010 Inez Korczyński (korczynski@gmail.com) & Jesús Martínez Novo (martineznovo@gmail.com) (GPLv2)
9 */
10 ( function ( $ ) {
11 $.fn.textSelection = function ( command, options ) {
12 var fn,
13 alternateFn,
14 retval;
15
16 fn = {
17 /**
18 * Get the contents of the textarea
19 *
20 * @return {string}
21 */
22 getContents: function () {
23 return this.val();
24 },
25 /**
26 * Set the contents of the textarea, replacing anything that was there before
27 *
28 * @param {string} content
29 */
30 setContents: function ( content ) {
31 this.val( content );
32 },
33 /**
34 * Get the currently selected text in this textarea.
35 *
36 * @return {string}
37 */
38 getSelection: function () {
39 var retval,
40 el = this.get( 0 );
41
42 if ( !el || $( el ).is( ':hidden' ) ) {
43 retval = '';
44 } else if ( el.selectionStart || el.selectionStart === 0 ) {
45 retval = el.value.substring( el.selectionStart, el.selectionEnd );
46 }
47
48 return retval;
49 },
50 /**
51 * Inserts text at the beginning and end of a text selection, optionally
52 * inserting text at the caret when selection is empty.
53 *
54 * @param {Object} options Options
55 * FIXME document the options parameters
56 * @return {jQuery}
57 */
58 encapsulateSelection: function ( options ) {
59 return this.each( function () {
60 var selText, scrollTop, insertText,
61 isSample, startPos, endPos,
62 pre = options.pre,
63 post = options.post;
64
65 /**
66 * Check if the selected text is the same as the insert text
67 */
68 function checkSelectedText() {
69 if ( !selText ) {
70 selText = options.peri;
71 isSample = true;
72 } else if ( options.replace ) {
73 selText = options.peri;
74 } else {
75 while ( selText.charAt( selText.length - 1 ) === ' ' ) {
76 // Exclude ending space char
77 selText = selText.slice( 0, -1 );
78 post += ' ';
79 }
80 while ( selText.charAt( 0 ) === ' ' ) {
81 // Exclude prepending space char
82 selText = selText.slice( 1 );
83 pre = ' ' + pre;
84 }
85 }
86 }
87
88 /**
89 * Do the splitlines stuff.
90 *
91 * Wrap each line of the selected text with pre and post
92 *
93 * @param {string} selText Selected text
94 * @param {string} pre Text before
95 * @param {string} post Text after
96 * @return {string} Wrapped text
97 */
98 function doSplitLines( selText, pre, post ) {
99 var i,
100 insertText = '',
101 selTextArr = selText.split( '\n' );
102 for ( i = 0; i < selTextArr.length; i++ ) {
103 insertText += pre + selTextArr[ i ] + post;
104 if ( i !== selTextArr.length - 1 ) {
105 insertText += '\n';
106 }
107 }
108 return insertText;
109 }
110
111 isSample = false;
112 // Do nothing if display none
113 if ( this.style.display !== 'none' ) {
114 if ( this.selectionStart || this.selectionStart === 0 ) {
115 $( this ).focus();
116 if ( options.selectionStart !== undefined ) {
117 $( this ).textSelection( 'setSelection', { start: options.selectionStart, end: options.selectionEnd } );
118 }
119
120 selText = $( this ).textSelection( 'getSelection' );
121 startPos = this.selectionStart;
122 endPos = this.selectionEnd;
123 scrollTop = this.scrollTop;
124 checkSelectedText();
125 if (
126 options.selectionStart !== undefined &&
127 endPos - startPos !== options.selectionEnd - options.selectionStart
128 ) {
129 // This means there is a difference in the selection range returned by browser and what we passed.
130 // This happens for Chrome in the case of composite characters. Ref bug #30130
131 // Set the startPos to the correct position.
132 startPos = options.selectionStart;
133 }
134
135 insertText = pre + selText + post;
136 if ( options.splitlines ) {
137 insertText = doSplitLines( selText, pre, post );
138 }
139 if ( options.ownline ) {
140 if ( startPos !== 0 && this.value.charAt( startPos - 1 ) !== '\n' && this.value.charAt( startPos - 1 ) !== '\r' ) {
141 insertText = '\n' + insertText;
142 pre += '\n';
143 }
144 if ( this.value.charAt( endPos ) !== '\n' && this.value.charAt( endPos ) !== '\r' ) {
145 insertText += '\n';
146 post += '\n';
147 }
148 }
149 this.value = this.value.slice( 0, startPos ) + insertText +
150 this.value.slice( endPos );
151 // Setting this.value scrolls the textarea to the top, restore the scroll position
152 this.scrollTop = scrollTop;
153 if ( window.opera ) {
154 pre = pre.replace( /\r?\n/g, '\r\n' );
155 selText = selText.replace( /\r?\n/g, '\r\n' );
156 post = post.replace( /\r?\n/g, '\r\n' );
157 }
158 if ( isSample && options.selectPeri && ( !options.splitlines || ( options.splitlines && selText.indexOf( '\n' ) === -1 ) ) ) {
159 this.selectionStart = startPos + pre.length;
160 this.selectionEnd = startPos + pre.length + selText.length;
161 } else {
162 this.selectionStart = startPos + insertText.length;
163 this.selectionEnd = this.selectionStart;
164 }
165 }
166 }
167 $( this ).trigger( 'encapsulateSelection', [ options.pre, options.peri, options.post, options.ownline,
168 options.replace, options.splitlines ] );
169 } );
170 },
171 /**
172 * Get the position (in resolution of bytes not necessarily characters)
173 * in a textarea
174 *
175 * @param {Object} options Options
176 * FIXME document the options parameters
177 * @return {number} Position
178 */
179 getCaretPosition: function ( options ) {
180 function getCaret( e ) {
181 var caretPos = 0,
182 endPos = 0;
183
184 if ( e && ( e.selectionStart || e.selectionStart === 0 ) ) {
185 caretPos = e.selectionStart;
186 endPos = e.selectionEnd;
187 }
188 return options.startAndEnd ? [ caretPos, endPos ] : caretPos;
189 }
190 return getCaret( this.get( 0 ) );
191 },
192 /**
193 * @param {Object} options options
194 * FIXME document the options parameters
195 * @return {jQuery}
196 */
197 setSelection: function ( options ) {
198 return this.each( function () {
199 // Do nothing if hidden
200 if ( !$( this ).is( ':hidden' ) ) {
201 if ( this.selectionStart || this.selectionStart === 0 ) {
202 // Opera 9.0 doesn't allow setting selectionStart past
203 // selectionEnd; any attempts to do that will be ignored
204 // Make sure to set them in the right order
205 if ( options.start > this.selectionEnd ) {
206 this.selectionEnd = options.end;
207 this.selectionStart = options.start;
208 } else {
209 this.selectionStart = options.start;
210 this.selectionEnd = options.end;
211 }
212 }
213 }
214 } );
215 },
216 /**
217 * Scroll a textarea to the current cursor position. You can set the cursor
218 * position with setSelection()
219 *
220 * @param {Object} options options
221 * @cfg {boolean} [force=false] Whether to force a scroll even if the caret position
222 * is already visible.
223 * FIXME document the options parameters
224 * @return {jQuery}
225 */
226 scrollToCaretPosition: function ( options ) {
227 function getLineLength( e ) {
228 return Math.floor( e.scrollWidth / ( $.client.profile().platform === 'linux' ? 7 : 8 ) );
229 }
230 function getCaretScrollPosition( e ) {
231 // FIXME: This functions sucks and is off by a few lines most
232 // of the time. It should be replaced by something decent.
233 var i, j,
234 nextSpace,
235 text = e.value.replace( /\r/g, '' ),
236 caret = $( e ).textSelection( 'getCaretPosition' ),
237 lineLength = getLineLength( e ),
238 row = 0,
239 charInLine = 0,
240 lastSpaceInLine = 0;
241
242 for ( i = 0; i < caret; i++ ) {
243 charInLine++;
244 if ( text.charAt( i ) === ' ' ) {
245 lastSpaceInLine = charInLine;
246 } else if ( text.charAt( i ) === '\n' ) {
247 lastSpaceInLine = 0;
248 charInLine = 0;
249 row++;
250 }
251 if ( charInLine > lineLength ) {
252 if ( lastSpaceInLine > 0 ) {
253 charInLine = charInLine - lastSpaceInLine;
254 lastSpaceInLine = 0;
255 row++;
256 }
257 }
258 }
259 nextSpace = 0;
260 for ( j = caret; j < caret + lineLength; j++ ) {
261 if (
262 text.charAt( j ) === ' ' ||
263 text.charAt( j ) === '\n' ||
264 caret === text.length
265 ) {
266 nextSpace = j;
267 break;
268 }
269 }
270 if ( nextSpace > lineLength && caret <= lineLength ) {
271 charInLine = caret - lastSpaceInLine;
272 row++;
273 }
274 return ( $.client.profile().platform === 'mac' ? 13 : ( $.client.profile().platform === 'linux' ? 15 : 16 ) ) * row;
275 }
276 return this.each( function () {
277 var scroll;
278 // Do nothing if hidden
279 if ( !$( this ).is( ':hidden' ) ) {
280 if ( this.selectionStart || this.selectionStart === 0 ) {
281 scroll = getCaretScrollPosition( this );
282 if ( options.force || scroll < $( this ).scrollTop() ||
283 scroll > $( this ).scrollTop() + $( this ).height() ) {
284 $( this ).scrollTop( scroll );
285 }
286 }
287 }
288 $( this ).trigger( 'scrollToPosition' );
289 } );
290 }
291 };
292
293 alternateFn = $( this ).data( 'jquery.textSelection' );
294
295 // Apply defaults
296 switch ( command ) {
297 // case 'getContents': // no params
298 // case 'setContents': // no params with defaults
299 // case 'getSelection': // no params
300 case 'encapsulateSelection':
301 options = $.extend( {
302 pre: '', // Text to insert before the cursor/selection
303 peri: '', // Text to insert between pre and post and select afterwards
304 post: '', // Text to insert after the cursor/selection
305 ownline: false, // Put the inserted text on a line of its own
306 replace: false, // If there is a selection, replace it with peri instead of leaving it alone
307 selectPeri: true, // Select the peri text if it was inserted (but not if there was a selection and replace==false, or if splitlines==true)
308 splitlines: false, // If multiple lines are selected, encapsulate each line individually
309 selectionStart: undefined, // Position to start selection at
310 selectionEnd: undefined // Position to end selection at. Defaults to start
311 }, options );
312 break;
313 case 'getCaretPosition':
314 options = $.extend( {
315 // Return [start, end] instead of just start
316 startAndEnd: false
317 }, options );
318 break;
319 case 'setSelection':
320 options = $.extend( {
321 // Position to start selection at
322 start: undefined,
323 // Position to end selection at. Defaults to start
324 end: undefined
325 }, options );
326
327 if ( options.end === undefined ) {
328 options.end = options.start;
329 }
330 break;
331 case 'scrollToCaretPosition':
332 options = $.extend( {
333 force: false // Force a scroll even if the caret position is already visible
334 }, options );
335 break;
336 case 'register':
337 if ( alternateFn ) {
338 throw new Error( 'Another textSelection API was already registered' );
339 }
340 $( this ).data( 'jquery.textSelection', options );
341 // No need to update alternateFn as this command only stores the options.
342 // A command that uses it will set it again.
343 return;
344 case 'unregister':
345 $( this ).removeData( 'jquery.textSelection' );
346 return;
347 }
348
349 retval = ( alternateFn && alternateFn[ command ] || fn[ command ] ).call( this, options );
350
351 return retval;
352 };
353
354 }( jQuery ) );