summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/UniversalLanguageSelector/lib/jquery.uls/src/jquery.uls.languagefilter.js
blob: cdc96c6fd535ea2f20b4f784a4f773cf0ff4784f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
 * jQuery language filter plugin.
 *
 * Copyright (C) 2012 Alolita Sharma, Amir Aharoni, Arun Ganesh, Brandon Harris,
 * Niklas Laxström, Pau Giner, Santhosh Thottingal, Siebrand Mazeland and other
 * contributors. See CREDITS for a list.
 *
 * UniversalLanguageSelector is dual licensed GPLv2 or later and MIT. You don't
 * have to do anything special to choose one license or the other and you don't
 * have to notify anyone which license you are using. You are free to use
 * UniversalLanguageSelector in commercial projects as long as the copyright
 * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details.
 *
 * @file
 * @ingroup Extensions
 * @licence GNU General Public Licence 2.0 or later
 * @licence MIT License
 */

/**
 * Usage: $( 'inputbox' ).languagefilter();
 * The values for autocompletion is from the options.languages or options.searchAPI.
 */
( function ( $ ) {
	'use strict';

	var LanguageFilter;

	/**
	 * Check if a prefix is visually prefix of a string
	 *
	 * @param {string} prefix
	 * @param {string} string
	 * @return {boolean}
	 */
	function isVisualPrefix( prefix, string ) {
		// Pre-base vowel signs of Indic languages. A vowel sign is called pre-base if
		// consonant + vowel becomes [vowel][consonant] when rendered. Eg: ക + െ => കെ
		var prebases = 'െേൈൊോൌெேைொோௌେୈୋୌિਿिিেৈোৌෙේෛොෝෞ';
		return prebases.indexOf( string[ prefix.length ] ) <= 0;
	}

	LanguageFilter = function ( element, options ) {
		this.$element = $( element );
		this.options = $.extend( {}, $.fn.languagefilter.defaults, options );
		this.$element.addClass( 'languagefilter' );
		this.resultCount = 0;
		this.$suggestion = this.$element.siblings( '.' + this.$element.data( 'suggestion' ) );
		this.$clear = this.$element.siblings( '.' + this.$element.data( 'clear' ) );
		this.selectedLanguage = null;
		this.init();
		this.listen();
	};

	LanguageFilter.prototype = {
		init: function () {
			this.search();
		},

		listen: function () {
			this.$element.on( 'keydown', this.keypress.bind( this ) );
			this.$element.on( 'input', $.fn.uls.debounce( this.onInputChange.bind( this ), 300 ) );

			if ( this.$clear.length ) {
				this.$clear.on( 'click', this.clear.bind( this ) );
			}

			this.toggleClear();
		},

		onInputChange: function () {
			this.selectedLanguage = null;

			if ( !this.$element.val() ) {
				this.clear();
			} else {
				this.options.lcd.empty();
				this.search();
			}

			this.toggleClear();
		},

		keypress: function ( e ) {
			var suggestion, query;

			switch ( e.keyCode ) {
				case 9: // Tab -> Autocomplete
					suggestion = this.$suggestion.val();

					if ( suggestion && suggestion !== this.$element.val() ) {
						this.$element.val( suggestion );
						e.preventDefault();
						e.stopPropagation();
					}
					break;
				case 13: // Enter
					if ( !this.options.onSelect ) {
						break;
					}

					// Avoid bubbling this 'enter' to background page elements
					e.preventDefault();
					e.stopPropagation();

					query = $.trim( this.$element.val() ).toLowerCase();

					if ( this.selectedLanguage ) {
						// this.selectLanguage will be populated from a matching search
						this.options.onSelect( this.selectedLanguage );
					} else if ( this.options.languages[ query ] ) {
						// Search is yet to happen (in timeout delay),
						// but we have a matching language code.
						this.options.onSelect( query );
					}

					break;
			}
		},

		/**
		 * Clears the current search removing
		 * clear buttons and suggestions.
		 */
		deactivate: function () {
			this.$element.val( '' );

			if ( !$.fn.uls.Constructor.prototype.isMobile() ) {
				this.$element.focus();
			}

			this.toggleClear();
			this.autofill();
		},

		/**
		 * Clears the search and shows all languages
		 */
		clear: function () {
			this.deactivate();
			this.search();
		},

		/**
		 * Toggles the visibility of clear icon depending
		 * on whether there is anything to clear.
		 */
		toggleClear: function () {
			if ( !this.$clear.length ) {
				return;
			}

			if ( this.$element.val() ) {
				this.$clear.show();
			} else {
				this.$clear.hide();
			}
		},

		search: function () {
			var languages = Object.keys( this.options.languages ),
				results = [],
				query = $.trim( this.$element.val() ).toLowerCase();

			if ( query === '' ) {
				this.options.lcd.setGroupByRegionOverride( null );
				this.resultHandler( query, languages );
				return;
			}

			this.options.lcd.setGroupByRegionOverride( false );
			// Local search results
			results = languages.filter( function ( langCode ) {
				return this.filter( langCode, query );
			}.bind( this ) );

			// Use the searchAPI if available, assuming that it has superior search results.
			if ( this.options.searchAPI ) {
				this.searchAPI( query )
					.done( this.resultHandler.bind( this ) )
					.fail( this.resultHandler.bind( this, query, results, undefined ) );
			} else {
				this.resultHandler( query, results );
			}
		},

		searchAPI: function ( query ) {
			return $.get( this.options.searchAPI, { search: query } ).then( function ( result ) {
				var autofillLabel,
					results = [];

				$.each( result.languagesearch, function ( apiCode, name ) {
					var code, redirect;

					if ( this.options.languages[ apiCode ] ) {
						code = apiCode;
					} else {
						redirect = $.uls.data.isRedirect( apiCode );
						if ( !redirect || !this.options.languages[ redirect ] ) {
							return;
						}
						code = redirect;
					}

					// Because of the redirect checking above, we might get duplicates.
					// For example if API returns both `sr` and `sr-cyrl`, the former
					// could get mapped to `sr-cyrl` and then we would have it twice.
					// The exact cases when this happens of course depends on what is in
					// options.languages, which might contain redirects such as `sr`. In
					// this case we only show `sr` if no other variants are there.
					// This also protects against broken search APIs returning duplicate
					// results, although that is not happening in practice.
					if ( results.indexOf( code ) === -1 ) {
						autofillLabel = autofillLabel || name;
						results.push( code );
					}
				}.bind( this ) );

				return $.Deferred().resolve( query, results, autofillLabel );
			}.bind( this ) );
		},

		/**
		 * Handler method to be called once search is over.
		 * Based on search result triggers resultsfound or noresults events
		 * @param {string} query
		 * @param {string[]} results
		 * @param {string} [autofillLabel]
		 */
		resultHandler: function ( query, results, autofillLabel ) {
			if ( results.length === 0 ) {
				this.$suggestion.val( '' );
				this.$element.trigger(
					'noresults.uls',
					{
						query: query,
						ulsPurpose: this.options.ulsPurpose
					}
				);
				return;
			}

			if ( query ) {
				this.selectedLanguage = results[ 0 ];
				this.autofill( results[ 0 ], autofillLabel );
			}

			results.map( this.render.bind( this ) );
			this.$element.trigger( 'resultsfound.uls', [ query, results.length ] );
		},

		autofill: function ( langCode, languageName ) {
			var autonym, userInput, suggestion;

			if ( !this.$suggestion.length ) {
				return;
			}

			if ( !this.$element.val() ) {
				this.$suggestion.val( '' );
				return;
			}

			languageName = languageName || this.options.languages[ langCode ];

			if ( !languageName ) {
				return;
			}

			userInput = this.$element.val();
			suggestion = userInput +
				languageName.substring( userInput.length, languageName.length );

			if ( suggestion.toLowerCase() !== languageName.toLowerCase() ) {
				// see if it was autonym match
				autonym = $.uls.data.getAutonym( langCode ) || '';
				suggestion = userInput + autonym.substring( userInput.length, autonym.length );

				if ( suggestion !== autonym ) {
					// Give up. It may be an ISO/script code match.
					suggestion = '';
				}
			}

			// Make sure that it is a visual prefix.
			if ( !isVisualPrefix( userInput, suggestion ) ) {
				suggestion = '';
			}

			this.$suggestion.val( suggestion );
		},

		render: function ( langCode ) {
			return this.options.lcd.append( langCode );
		},

		escapeRegex: function ( value ) {
			return value.replace( /[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&' );
		},

		/**
		 * A search match happens if any of the following passes:
		 * a) Language name in current user interface language
		 * 'starts with' search string.
		 * b) Language autonym 'starts with' search string.
		 * c) ISO 639 code match with search string.
		 * d) ISO 15924 code for the script match the search string.
		 * @param {string} langCode
		 * @param {string} searchTerm
		 * @return {boolean}
		 */
		filter: function ( langCode, searchTerm ) {
			// FIXME script is ISO 15924 code. We might need actual name of script.
			var matcher = new RegExp( '^' + this.escapeRegex( searchTerm ), 'i' ),
				languageName = this.options.languages[ langCode ];

			return matcher.test( languageName ) ||
				matcher.test( $.uls.data.getAutonym( langCode ) ) ||
				matcher.test( langCode ) ||
				matcher.test( $.uls.data.getScript( langCode ) );
		}
	};

	$.fn.languagefilter = function ( option ) {
		return this.each( function () {
			var $this = $( this ),
				data = $this.data( 'languagefilter' ),
				options = typeof option === 'object' && option;

			if ( !data ) {
				$this.data( 'languagefilter', ( data = new LanguageFilter( this, options ) ) );
			}

			if ( typeof option === 'string' ) {
				data[ option ]();
			}
		} );
	};

	$.fn.languagefilter.defaults = {
		// LanguageCategoryDisplay
		lcd: undefined,
		// URL to which we append query parameter with the query value
		searchAPI: undefined,
		// What is this ULS used for.
		// Should be set for distinguishing between different instances of ULS
		// in the same application.
		ulsPurpose: '',
		// Object of language tags to language names
		languages: [],
		// Callback function when language is selected
		onSelect: undefined
	};

	$.fn.languagefilter.Constructor = LanguageFilter;

}( jQuery ) );