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
9 NS_CATEGORY
= mw
.config
.get( 'wgNamespaceIds' ).category
;
12 * Category selector widget. Displays an OO.ui.CapsuleMultiSelectWidget
13 * and autocompletes with available categories.
15 * var selector = new mw.widgets.CategorySelector( {
17 * mw.widgets.CategorySelector.SearchType.OpenSearch,
18 * mw.widgets.CategorySelector.SearchType.InternalSearch
22 * $( '#content' ).append( selector.$element );
24 * selector.setSearchType( [ mw.widgets.CategorySelector.SearchType.SubCategories ] );
26 * @class mw.widgets.CategorySelector
28 * @extends OO.ui.CapsuleMultiSelectWidget
29 * @mixins OO.ui.mixin.PendingElement
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
42 searchTypes
: [ CategorySelector
.SearchType
.OpenSearch
]
44 this.limit
= config
.limit
;
45 this.searchTypes
= config
.searchTypes
;
46 this.validateSearchTypes();
49 mw
.widgets
.CategorySelector
.parent
.call( this, $.extend( true, {}, config
, {
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
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 ) );
65 this.api
= config
.api
|| new mw
.Api();
70 OO
.inheritClass( CategorySelector
, OO
.ui
.CapsuleMultiSelectWidget
);
71 OO
.mixinClass( CategorySelector
, OO
.ui
.mixin
.PendingElement
);
72 CSP
= CategorySelector
.prototype;
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.
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' ) ) {
95 // Array of strings of the data of OO.ui.MenuOptionsWidgets
96 existingItems
= menu
.getItems().map( function ( item
) {
100 // Remove if items' data already exists
101 filteredItems
= items
.filter( function ( item
) {
102 return existingItems
.indexOf( item
) === -1;
105 // Map to an array of OO.ui.MenuOptionWidgets
106 filteredItems
= filteredItems
.map( function ( item
) {
107 return new OO
.ui
.MenuOptionWidget( {
113 menu
.addItems( filteredItems
).toggle( true );
120 CSP
.clearInput = function () {
121 CategorySelector
.parent
.prototype.clearInput
.call( this );
122 // Abort all pending requests, we won't need their results
127 * Searches for categories based on the input.
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
) {
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
146 for ( i
= 0; i
< this.searchTypes
.length
; i
++ ) {
147 promises
.push( this.searchCategories( input
, this.searchTypes
[ i
] ) );
152 $.when
.apply( $, promises
).done( function () {
155 dataSets
= Array
.prototype.slice
.apply( arguments
);
157 // Collect values from all results
158 allData
= allData
.concat
.apply( allData
, dataSets
);
160 categoryNames
= allData
162 .filter( function ( value
, index
, self
) {
163 return self
.indexOf( value
) === index
;
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();
178 deferred
.resolve( categoryNames
);
180 } ).always( this.popPending
.bind( this ) );
182 return deferred
.promise();
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
)
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`.
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
;
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' );
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.
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
:
268 action
: 'opensearch',
269 namespace: NS_CATEGORY
,
272 } ).done( function ( res
) {
273 var categories
= res
[ 1 ];
274 deferred
.resolve( categories
);
275 } ).fail( deferred
.reject
.bind( deferred
) );
278 case CategorySelector
.SearchType
.InternalSearch
:
282 apnamespace
: NS_CATEGORY
,
286 } ).done( function ( res
) {
287 var categories
= res
.query
.allpages
.map( function ( page
) {
290 deferred
.resolve( categories
);
291 } ).fail( deferred
.reject
.bind( deferred
) );
294 case CategorySelector
.SearchType
.Exists
:
295 if ( input
.indexOf( '|' ) > -1 ) {
296 deferred
.resolve( [] );
303 titles
: 'Category:' + input
304 } ).done( function ( res
) {
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
) );
318 case CategorySelector
.SearchType
.SubCategories
:
319 if ( input
.indexOf( '|' ) > -1 ) {
320 deferred
.resolve( [] );
326 list
: 'categorymembers',
329 cmtitle
: 'Category:' + input
330 } ).done( function ( res
) {
331 var categories
= res
.query
.categorymembers
.map( function ( category
) {
332 return category
.title
;
334 deferred
.resolve( categories
);
335 } ).fail( deferred
.reject
.bind( deferred
) );
338 case CategorySelector
.SearchType
.ParentCategories
:
339 if ( input
.indexOf( '|' ) > -1 ) {
340 deferred
.resolve( [] );
348 titles
: 'Category:' + input
349 } ).done( function ( res
) {
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
;
363 deferred
.resolve( categories
);
364 } ).fail( deferred
.reject
.bind( deferred
) );
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 */
382 /** Search using action=query */
385 /** Search for existing categories with the exact title */
388 /** Search only subcategories */
391 /** Search only parent categories */
395 mw
.widgets
.CategorySelector
= CategorySelector
;
396 }( jQuery
, mediaWiki
) );