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