Merge "resources: Strip '$' and 'mw' from file closures"
[lhc/web/wiklou.git] / resources / src / mediawiki.widgets / mw.widgets.CategoryMultiselectWidget.js
1 /*!
2 * MediaWiki Widgets - CategoryMultiselectWidget class.
3 *
4 * @copyright 2011-2015 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7 ( function () {
8 var hasOwn = Object.prototype.hasOwnProperty,
9 NS_CATEGORY = mw.config.get( 'wgNamespaceIds' ).category;
10
11 /**
12 * Category selector widget. Displays an OO.ui.MenuTagMultiselectWidget
13 * and autocompletes with available categories.
14 *
15 * mw.loader.using( 'mediawiki.widgets.CategoryMultiselectWidget', function () {
16 * var selector = new mw.widgets.CategoryMultiselectWidget( {
17 * searchTypes: [
18 * mw.widgets.CategoryMultiselectWidget.SearchType.OpenSearch,
19 * mw.widgets.CategoryMultiselectWidget.SearchType.InternalSearch
20 * ]
21 * } );
22 *
23 * $( 'body' ).append( selector.$element );
24 *
25 * selector.setSearchTypes( [ mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories ] );
26 * } );
27 *
28 * @class mw.widgets.CategoryMultiselectWidget
29 * @uses mw.Api
30 * @extends OO.ui.MenuTagMultiselectWidget
31 * @mixins OO.ui.mixin.PendingElement
32 *
33 * @constructor
34 * @param {Object} [config] Configuration options
35 * @cfg {mw.Api} [api] Instance of mw.Api (or subclass thereof) to use for queries
36 * @cfg {number} [limit=10] Maximum number of results to load
37 * @cfg {mw.widgets.CategoryMultiselectWidget.SearchType[]} [searchTypes=[mw.widgets.CategoryMultiselectWidget.SearchType.OpenSearch]]
38 * Default search API to use when searching.
39 */
40 mw.widgets.CategoryMultiselectWidget = function MWCategoryMultiselectWidget( config ) {
41 // Config initialization
42 config = $.extend( {
43 limit: 10,
44 searchTypes: [ mw.widgets.CategoryMultiselectWidget.SearchType.OpenSearch ]
45 }, config );
46 this.limit = config.limit;
47 this.searchTypes = config.searchTypes;
48 this.validateSearchTypes();
49
50 // Parent constructor
51 mw.widgets.CategoryMultiselectWidget.parent.call( this, $.extend( true, {}, config, {
52 menu: {
53 filterFromInput: false
54 },
55 placeholder: mw.msg( 'mw-widgets-categoryselector-add-category-placeholder' ),
56 // This allows the user to both select non-existent categories, and prevents the selector from
57 // being wiped from #onMenuItemsChange when we change the available options in the dropdown
58 allowArbitrary: true
59 } ) );
60
61 // Mixin constructors
62 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$handle } ) );
63
64 // Event handler to call the autocomplete methods
65 this.input.$input.on( 'change input cut paste', OO.ui.debounce( this.updateMenuItems.bind( this ), 100 ) );
66
67 // Initialize
68 this.api = config.api || new mw.Api();
69 this.searchCache = {};
70 };
71
72 /* Setup */
73
74 OO.inheritClass( mw.widgets.CategoryMultiselectWidget, OO.ui.MenuTagMultiselectWidget );
75 OO.mixinClass( mw.widgets.CategoryMultiselectWidget, OO.ui.mixin.PendingElement );
76
77 /* Methods */
78
79 /**
80 * Gets new items based on the input by calling
81 * {@link #getNewMenuItems getNewItems} and updates the menu
82 * after removing duplicates based on the data value.
83 *
84 * @private
85 * @method
86 */
87 mw.widgets.CategoryMultiselectWidget.prototype.updateMenuItems = function () {
88 this.getMenu().clearItems();
89 this.getNewMenuItems( this.input.$input.val() ).then( function ( items ) {
90 var existingItems, filteredItems,
91 menu = this.getMenu();
92
93 // Never show the menu if the input lost focus in the meantime
94 if ( !this.input.$input.is( ':focus' ) ) {
95 return;
96 }
97
98 // Array of strings of the data of OO.ui.MenuOptionsWidgets
99 existingItems = menu.getItems().map( function ( item ) {
100 return item.data;
101 } );
102
103 // Remove if items' data already exists
104 filteredItems = items.filter( function ( item ) {
105 return existingItems.indexOf( item ) === -1;
106 } );
107
108 // Map to an array of OO.ui.MenuOptionWidgets
109 filteredItems = filteredItems.map( function ( item ) {
110 return new OO.ui.MenuOptionWidget( {
111 data: item,
112 label: item
113 } );
114 } );
115
116 menu.addItems( filteredItems ).toggle( true );
117 }.bind( this ) );
118 };
119
120 /**
121 * @inheritdoc
122 */
123 mw.widgets.CategoryMultiselectWidget.prototype.clearInput = function () {
124 mw.widgets.CategoryMultiselectWidget.parent.prototype.clearInput.call( this );
125 // Abort all pending requests, we won't need their results
126 this.api.abort();
127 };
128
129 /**
130 * Searches for categories based on the input.
131 *
132 * @private
133 * @method
134 * @param {string} input The input used to prefix search categories
135 * @return {jQuery.Promise} Resolves with an array of categories
136 */
137 mw.widgets.CategoryMultiselectWidget.prototype.getNewMenuItems = function ( input ) {
138 var i,
139 promises = [],
140 deferred = $.Deferred();
141
142 if ( input.trim() === '' ) {
143 deferred.resolve( [] );
144 return deferred.promise();
145 }
146
147 // Abort all pending requests, we won't need their results
148 this.api.abort();
149 for ( i = 0; i < this.searchTypes.length; i++ ) {
150 promises.push( this.searchCategories( input, this.searchTypes[ i ] ) );
151 }
152
153 this.pushPending();
154
155 $.when.apply( $, promises ).done( function () {
156 var categoryNames,
157 allData = [],
158 dataSets = Array.prototype.slice.apply( arguments );
159
160 // Collect values from all results
161 allData = allData.concat.apply( allData, dataSets );
162
163 categoryNames = allData
164 // Remove duplicates
165 .filter( function ( value, index, self ) {
166 return self.indexOf( value ) === index;
167 } )
168 // Get Title objects
169 .map( function ( name ) {
170 return mw.Title.newFromText( name );
171 } )
172 // Keep only titles from 'Category' namespace
173 .filter( function ( title ) {
174 return title && title.getNamespaceId() === NS_CATEGORY;
175 } )
176 // Convert back to strings, strip 'Category:' prefix
177 .map( function ( title ) {
178 return title.getMainText();
179 } );
180
181 deferred.resolve( categoryNames );
182
183 } ).always( this.popPending.bind( this ) );
184
185 return deferred.promise();
186 };
187
188 /**
189 * @inheritdoc
190 */
191 mw.widgets.CategoryMultiselectWidget.prototype.createTagItemWidget = function ( data ) {
192 var title = mw.Title.makeTitle( NS_CATEGORY, data );
193
194 return new mw.widgets.CategoryTagItemWidget( {
195 apiUrl: this.api.apiUrl || undefined,
196 title: title
197 } );
198 };
199
200 /**
201 * @inheritdoc
202 */
203 mw.widgets.CategoryMultiselectWidget.prototype.findItemFromData = function ( data ) {
204 // This is a bit of a hack... We have to canonicalize the data in the same way that
205 // #createItemWidget and CategoryTagItemWidget will do, otherwise we won't find duplicates.
206 var title = mw.Title.makeTitle( NS_CATEGORY, data );
207 if ( !title ) {
208 return null;
209 }
210 return OO.ui.mixin.GroupElement.prototype.findItemFromData.call( this, title.getMainText() );
211 };
212
213 /**
214 * Validates the values in `this.searchType`.
215 *
216 * @private
217 * @return {boolean}
218 */
219 mw.widgets.CategoryMultiselectWidget.prototype.validateSearchTypes = function () {
220 var validSearchTypes = false,
221 searchTypeEnumCount = Object.keys( mw.widgets.CategoryMultiselectWidget.SearchType ).length;
222
223 // Check if all values are in the SearchType enum
224 validSearchTypes = this.searchTypes.every( function ( searchType ) {
225 return searchType > -1 && searchType < searchTypeEnumCount;
226 } );
227
228 if ( validSearchTypes === false ) {
229 throw new Error( 'Unknown searchType in searchTypes' );
230 }
231
232 // If the searchTypes has mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories
233 // it can be the only search type.
234 if ( this.searchTypes.indexOf( mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories ) > -1 &&
235 this.searchTypes.length > 1
236 ) {
237 throw new Error( 'Can\'t have additional search types with mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories' );
238 }
239
240 // If the searchTypes has mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories
241 // it can be the only search type.
242 if ( this.searchTypes.indexOf( mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories ) > -1 &&
243 this.searchTypes.length > 1
244 ) {
245 throw new Error( 'Can\'t have additional search types with mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories' );
246 }
247
248 return true;
249 };
250
251 /**
252 * Sets and validates the value of `this.searchType`.
253 *
254 * @param {mw.widgets.CategoryMultiselectWidget.SearchType[]} searchTypes
255 */
256 mw.widgets.CategoryMultiselectWidget.prototype.setSearchTypes = function ( searchTypes ) {
257 this.searchTypes = searchTypes;
258 this.validateSearchTypes();
259 };
260
261 /**
262 * Searches categories based on input and searchType.
263 *
264 * @private
265 * @method
266 * @param {string} input The input used to prefix search categories
267 * @param {mw.widgets.CategoryMultiselectWidget.SearchType} searchType
268 * @return {jQuery.Promise} Resolves with an array of categories
269 */
270 mw.widgets.CategoryMultiselectWidget.prototype.searchCategories = function ( input, searchType ) {
271 var deferred = $.Deferred(),
272 cacheKey = input + searchType.toString();
273
274 // Check cache
275 if ( hasOwn.call( this.searchCache, cacheKey ) ) {
276 return this.searchCache[ cacheKey ];
277 }
278
279 switch ( searchType ) {
280 case mw.widgets.CategoryMultiselectWidget.SearchType.OpenSearch:
281 this.api.get( {
282 formatversion: 2,
283 action: 'opensearch',
284 namespace: NS_CATEGORY,
285 limit: this.limit,
286 search: input
287 } ).done( function ( res ) {
288 var categories = res[ 1 ];
289 deferred.resolve( categories );
290 } ).fail( deferred.reject.bind( deferred ) );
291 break;
292
293 case mw.widgets.CategoryMultiselectWidget.SearchType.InternalSearch:
294 this.api.get( {
295 formatversion: 2,
296 action: 'query',
297 list: 'allpages',
298 apnamespace: NS_CATEGORY,
299 aplimit: this.limit,
300 apfrom: input,
301 apprefix: input
302 } ).done( function ( res ) {
303 var categories = res.query.allpages.map( function ( page ) {
304 return page.title;
305 } );
306 deferred.resolve( categories );
307 } ).fail( deferred.reject.bind( deferred ) );
308 break;
309
310 case mw.widgets.CategoryMultiselectWidget.SearchType.Exists:
311 if ( input.indexOf( '|' ) > -1 ) {
312 deferred.resolve( [] );
313 break;
314 }
315
316 this.api.get( {
317 formatversion: 2,
318 action: 'query',
319 prop: 'info',
320 titles: 'Category:' + input
321 } ).done( function ( res ) {
322 var categories = [];
323
324 res.query.pages.forEach( function ( page ) {
325 if ( !page.missing ) {
326 categories.push( page.title );
327 }
328 } );
329
330 deferred.resolve( categories );
331 } ).fail( deferred.reject.bind( deferred ) );
332 break;
333
334 case mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories:
335 if ( input.indexOf( '|' ) > -1 ) {
336 deferred.resolve( [] );
337 break;
338 }
339
340 this.api.get( {
341 formatversion: 2,
342 action: 'query',
343 list: 'categorymembers',
344 cmtype: 'subcat',
345 cmlimit: this.limit,
346 cmtitle: 'Category:' + input
347 } ).done( function ( res ) {
348 var categories = res.query.categorymembers.map( function ( category ) {
349 return category.title;
350 } );
351 deferred.resolve( categories );
352 } ).fail( deferred.reject.bind( deferred ) );
353 break;
354
355 case mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories:
356 if ( input.indexOf( '|' ) > -1 ) {
357 deferred.resolve( [] );
358 break;
359 }
360
361 this.api.get( {
362 formatversion: 2,
363 action: 'query',
364 prop: 'categories',
365 cllimit: this.limit,
366 titles: 'Category:' + input
367 } ).done( function ( res ) {
368 var categories = [];
369
370 res.query.pages.forEach( function ( page ) {
371 if ( !page.missing && Array.isArray( page.categories ) ) {
372 categories.push.apply( categories, page.categories.map( function ( category ) {
373 return category.title;
374 } ) );
375 }
376 } );
377
378 deferred.resolve( categories );
379 } ).fail( deferred.reject.bind( deferred ) );
380 break;
381
382 default:
383 throw new Error( 'Unknown searchType' );
384 }
385
386 // Cache the result
387 this.searchCache[ cacheKey ] = deferred.promise();
388
389 return deferred.promise();
390 };
391
392 /**
393 * @enum mw.widgets.CategoryMultiselectWidget.SearchType
394 * Types of search available.
395 */
396 mw.widgets.CategoryMultiselectWidget.SearchType = {
397 /** Search using action=opensearch */
398 OpenSearch: 0,
399
400 /** Search using action=query */
401 InternalSearch: 1,
402
403 /** Search for existing categories with the exact title */
404 Exists: 2,
405
406 /** Search only subcategories */
407 SubCategories: 3,
408
409 /** Search only parent categories */
410 ParentCategories: 4
411 };
412 }() );