SessionManager: Save user name to metadata even if the user doesn't exist locally
[mediawiki.git] / resources / src / mediawiki.widgets / mw.widgets.CategorySelector.js
blobdffcbdda3a75134048c8573f0917c036ae881830
1 /*!
2 * MediaWiki Widgets - CategorySelector class.
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;
11 /**
12 * Category selector widget. Displays an OO.ui.CapsuleMultiSelectWidget
13 * and autocompletes with available categories.
15 * var selector = new mw.widgets.CategorySelector( {
16 * searchTypes: [
17 * mw.widgets.CategorySelector.SearchType.OpenSearch,
18 * mw.widgets.CategorySelector.SearchType.InternalSearch
19 * ]
20 * } );
22 * $( '#content' ).append( selector.$element );
24 * selector.setSearchType( [ mw.widgets.CategorySelector.SearchType.SubCategories ] );
26 * @class mw.widgets.CategorySelector
27 * @uses mw.Api
28 * @extends OO.ui.CapsuleMultiSelectWidget
29 * @mixins OO.ui.mixin.PendingElement
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.
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();
48 // Parent constructor
49 mw.widgets.CategorySelector.parent.call( this, $.extend( true, {}, config, {
50 menu: {
51 filterFromInput: false
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 } ) );
58 // Mixin constructors
59 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$handle } ) );
61 // Event handler to call the autocomplete methods
62 this.$input.on( 'change input cut paste', OO.ui.debounce( this.updateMenuItems.bind( this ), 100 ) );
64 // Initialize
65 this.api = config.api || new mw.Api();
68 /* Setup */
70 OO.inheritClass( CategorySelector, OO.ui.CapsuleMultiSelectWidget );
71 OO.mixinClass( CategorySelector, OO.ui.mixin.PendingElement );
72 CSP = CategorySelector.prototype;
74 /* Methods */
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.
81 * @private
82 * @method
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();
90 // Never show the menu if the input lost focus in the meantime
91 if ( !this.$input.is( ':focus' ) ) {
92 return;
95 // Array of strings of the data of OO.ui.MenuOptionsWidgets
96 existingItems = menu.getItems().map( function ( item ) {
97 return item.data;
98 } );
100 // Remove if items' data already exists
101 filteredItems = items.filter( function ( item ) {
102 return existingItems.indexOf( item ) === -1;
103 } );
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 } );
113 menu.addItems( filteredItems ).toggle( true );
114 }.bind( this ) );
118 * @inheritdoc
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();
127 * Searches for categories based on the input.
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
134 CSP.getNewMenuItems = function ( input ) {
135 var i,
136 promises = [],
137 deferred = $.Deferred();
139 if ( $.trim( input ) === '' ) {
140 deferred.resolve( [] );
141 return deferred.promise();
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 ] ) );
150 this.pushPending();
152 $.when.apply( $, promises ).done( function () {
153 var categoryNames,
154 allData = [],
155 dataSets = Array.prototype.slice.apply( arguments );
157 // Collect values from all results
158 allData = allData.concat.apply( allData, dataSets );
160 categoryNames = allData
161 // Remove duplicates
162 .filter( function ( value, index, self ) {
163 return self.indexOf( value ) === index;
165 // Get Title objects
166 .map( function ( name ) {
167 return mw.Title.newFromText( name );
169 // Keep only titles from 'Category' namespace
170 .filter( function ( title ) {
171 return title && title.getNamespaceId() === NS_CATEGORY;
173 // Convert back to strings, strip 'Category:' prefix
174 .map( function ( title ) {
175 return title.getMainText();
176 } );
178 deferred.resolve( categoryNames );
180 } ).always( this.popPending.bind( this ) );
182 return deferred.promise();
186 * @inheritdoc
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 } );
196 * @inheritdoc
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 );
206 * Validates the values in `this.searchType`.
208 * @private
209 * @return {boolean}
211 CSP.validateSearchTypes = function () {
212 var validSearchTypes = false,
213 searchTypeEnumCount = Object.keys( CategorySelector.SearchType ).length;
215 // Check if all values are in the SearchType enum
216 validSearchTypes = this.searchTypes.every( function ( searchType ) {
217 return searchType > -1 && searchType < searchTypeEnumCount;
218 } );
220 if ( validSearchTypes === false ) {
221 throw new Error( 'Unknown searchType in searchTypes' );
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
229 throw new Error( 'Can\'t have additional search types with CategorySelector.SearchType.SubCategories' );
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
237 throw new Error( 'Can\'t have additional search types with CategorySelector.SearchType.ParentCategories' );
240 return true;
244 * Sets and validates the value of `this.searchType`.
246 * @param {mw.widgets.CategorySelector.SearchType[]} searchTypes
248 CSP.setSearchTypes = function ( searchTypes ) {
249 this.searchTypes = searchTypes;
250 this.validateSearchTypes();
254 * Searches categories based on input and searchType.
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
262 CSP.searchCategories = function ( input, searchType ) {
263 var deferred = $.Deferred();
265 switch ( searchType ) {
266 case CategorySelector.SearchType.OpenSearch:
267 this.api.get( {
268 action: 'opensearch',
269 namespace: NS_CATEGORY,
270 limit: this.limit,
271 search: input
272 } ).done( function ( res ) {
273 var categories = res[ 1 ];
274 deferred.resolve( categories );
275 } ).fail( deferred.reject.bind( deferred ) );
276 break;
278 case CategorySelector.SearchType.InternalSearch:
279 this.api.get( {
280 action: 'query',
281 list: 'allpages',
282 apnamespace: NS_CATEGORY,
283 aplimit: this.limit,
284 apfrom: input,
285 apprefix: input
286 } ).done( function ( res ) {
287 var categories = res.query.allpages.map( function ( page ) {
288 return page.title;
289 } );
290 deferred.resolve( categories );
291 } ).fail( deferred.reject.bind( deferred ) );
292 break;
294 case CategorySelector.SearchType.Exists:
295 if ( input.indexOf( '|' ) > -1 ) {
296 deferred.resolve( [] );
297 break;
300 this.api.get( {
301 action: 'query',
302 prop: 'info',
303 titles: 'Category:' + input
304 } ).done( function ( res ) {
305 var page,
306 categories = [];
308 for ( page in res.query.pages ) {
309 if ( parseInt( page, 10 ) > -1 ) {
310 categories.push( res.query.pages[ page ].title );
314 deferred.resolve( categories );
315 } ).fail( deferred.reject.bind( deferred ) );
316 break;
318 case CategorySelector.SearchType.SubCategories:
319 if ( input.indexOf( '|' ) > -1 ) {
320 deferred.resolve( [] );
321 break;
324 this.api.get( {
325 action: 'query',
326 list: 'categorymembers',
327 cmtype: 'subcat',
328 cmlimit: this.limit,
329 cmtitle: 'Category:' + input
330 } ).done( function ( res ) {
331 var categories = res.query.categorymembers.map( function ( category ) {
332 return category.title;
333 } );
334 deferred.resolve( categories );
335 } ).fail( deferred.reject.bind( deferred ) );
336 break;
338 case CategorySelector.SearchType.ParentCategories:
339 if ( input.indexOf( '|' ) > -1 ) {
340 deferred.resolve( [] );
341 break;
344 this.api.get( {
345 action: 'query',
346 prop: 'categories',
347 cllimit: this.limit,
348 titles: 'Category:' + input
349 } ).done( function ( res ) {
350 var page,
351 categories = [];
353 for ( page in res.query.pages ) {
354 if ( parseInt( page, 10 ) > -1 ) {
355 if ( $.isArray( res.query.pages[ page ].categories ) ) {
356 categories.push.apply( categories, res.query.pages[ page ].categories.map( function ( category ) {
357 return category.title;
358 } ) );
363 deferred.resolve( categories );
364 } ).fail( deferred.reject.bind( deferred ) );
365 break;
367 default:
368 throw new Error( 'Unknown searchType' );
371 return deferred.promise();
375 * @enum mw.widgets.CategorySelector.SearchType
376 * Types of search available.
378 CategorySelector.SearchType = {
379 /** Search using action=opensearch */
380 OpenSearch: 0,
382 /** Search using action=query */
383 InternalSearch: 1,
385 /** Search for existing categories with the exact title */
386 Exists: 2,
388 /** Search only subcategories */
389 SubCategories: 3,
391 /** Search only parent categories */
392 ParentCategories: 4
395 mw.widgets.CategorySelector = CategorySelector;
396 }( jQuery, mediaWiki ) );