7fdef257d324f62a29f06aae3db13a06c6436b02
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 * mw.loader.using( 'mediawiki.widgets.CategorySelector', function () {
16 * var selector = new mw.widgets.CategorySelector( {
18 * mw.widgets.CategorySelector.SearchType.OpenSearch,
19 * mw.widgets.CategorySelector.SearchType.InternalSearch
23 * $( 'body' ).append( selector.$element );
25 * selector.setSearchTypes( [ mw.widgets.CategorySelector.SearchType.SubCategories ] );
28 * @class mw.widgets.CategorySelector
30 * @extends OO.ui.CapsuleMultiselectWidget
31 * @mixins OO.ui.mixin.PendingElement
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.CategorySelector.SearchType[]} [searchTypes=[mw.widgets.CategorySelector.SearchType.OpenSearch]]
38 * Default search API to use when searching.
40 function CategorySelector( config
) {
41 // Config initialization
44 searchTypes
: [ CategorySelector
.SearchType
.OpenSearch
]
46 this.limit
= config
.limit
;
47 this.searchTypes
= config
.searchTypes
;
48 this.validateSearchTypes();
51 mw
.widgets
.CategorySelector
.parent
.call( this, $.extend( true, {}, config
, {
53 filterFromInput
: false
55 // This allows the user to both select non-existent categories, and prevents the selector from
56 // being wiped from #onMenuItemsChange when we change the available options in the dropdown
61 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$handle
} ) );
63 // Event handler to call the autocomplete methods
64 this.$input
.on( 'change input cut paste', OO
.ui
.debounce( this.updateMenuItems
.bind( this ), 100 ) );
67 this.api
= config
.api
|| new mw
.Api();
72 OO
.inheritClass( CategorySelector
, OO
.ui
.CapsuleMultiselectWidget
);
73 OO
.mixinClass( CategorySelector
, OO
.ui
.mixin
.PendingElement
);
74 CSP
= CategorySelector
.prototype;
79 * Gets new items based on the input by calling
80 * {@link #getNewMenuItems getNewItems} and updates the menu
81 * after removing duplicates based on the data value.
86 CSP
.updateMenuItems = function () {
87 this.getMenu().clearItems();
88 this.getNewMenuItems( this.$input
.val() ).then( function ( items
) {
89 var existingItems
, filteredItems
,
90 menu
= this.getMenu();
92 // Never show the menu if the input lost focus in the meantime
93 if ( !this.$input
.is( ':focus' ) ) {
97 // Array of strings of the data of OO.ui.MenuOptionsWidgets
98 existingItems
= menu
.getItems().map( function ( item
) {
102 // Remove if items' data already exists
103 filteredItems
= items
.filter( function ( item
) {
104 return existingItems
.indexOf( item
) === -1;
107 // Map to an array of OO.ui.MenuOptionWidgets
108 filteredItems
= filteredItems
.map( function ( item
) {
109 return new OO
.ui
.MenuOptionWidget( {
115 menu
.addItems( filteredItems
).toggle( true );
122 CSP
.clearInput = function () {
123 CategorySelector
.parent
.prototype.clearInput
.call( this );
124 // Abort all pending requests, we won't need their results
129 * Searches for categories based on the input.
133 * @param {string} input The input used to prefix search categories
134 * @return {jQuery.Promise} Resolves with an array of categories
136 CSP
.getNewMenuItems = function ( input
) {
139 deferred
= $.Deferred();
141 if ( $.trim( input
) === '' ) {
142 deferred
.resolve( [] );
143 return deferred
.promise();
146 // Abort all pending requests, we won't need their results
148 for ( i
= 0; i
< this.searchTypes
.length
; i
++ ) {
149 promises
.push( this.searchCategories( input
, this.searchTypes
[ i
] ) );
154 $.when
.apply( $, promises
).done( function () {
157 dataSets
= Array
.prototype.slice
.apply( arguments
);
159 // Collect values from all results
160 allData
= allData
.concat
.apply( allData
, dataSets
);
162 categoryNames
= allData
164 .filter( function ( value
, index
, self
) {
165 return self
.indexOf( value
) === index
;
168 .map( function ( name
) {
169 return mw
.Title
.newFromText( name
);
171 // Keep only titles from 'Category' namespace
172 .filter( function ( title
) {
173 return title
&& title
.getNamespaceId() === NS_CATEGORY
;
175 // Convert back to strings, strip 'Category:' prefix
176 .map( function ( title
) {
177 return title
.getMainText();
180 deferred
.resolve( categoryNames
);
182 } ).always( this.popPending
.bind( this ) );
184 return deferred
.promise();
190 CSP
.createItemWidget = function ( data
) {
191 var title
= mw
.Title
.makeTitle( NS_CATEGORY
, data
);
195 return new mw
.widgets
.CategoryCapsuleItemWidget( {
196 apiUrl
: this.api
.apiUrl
|| undefined,
204 CSP
.getItemFromData = function ( data
) {
205 // This is a bit of a hack... We have to canonicalize the data in the same way that
206 // #createItemWidget and CategoryCapsuleItemWidget will do, otherwise we won't find duplicates.
207 var title
= mw
.Title
.makeTitle( NS_CATEGORY
, data
);
211 return OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData
.call( this, title
.getMainText() );
215 * Validates the values in `this.searchType`.
220 CSP
.validateSearchTypes = function () {
221 var validSearchTypes
= false,
222 searchTypeEnumCount
= Object
.keys( CategorySelector
.SearchType
).length
;
224 // Check if all values are in the SearchType enum
225 validSearchTypes
= this.searchTypes
.every( function ( searchType
) {
226 return searchType
> -1 && searchType
< searchTypeEnumCount
;
229 if ( validSearchTypes
=== false ) {
230 throw new Error( 'Unknown searchType in searchTypes' );
233 // If the searchTypes has CategorySelector.SearchType.SubCategories
234 // it can be the only search type.
235 if ( this.searchTypes
.indexOf( CategorySelector
.SearchType
.SubCategories
) > -1 &&
236 this.searchTypes
.length
> 1
238 throw new Error( 'Can\'t have additional search types with CategorySelector.SearchType.SubCategories' );
241 // If the searchTypes has CategorySelector.SearchType.ParentCategories
242 // it can be the only search type.
243 if ( this.searchTypes
.indexOf( CategorySelector
.SearchType
.ParentCategories
) > -1 &&
244 this.searchTypes
.length
> 1
246 throw new Error( 'Can\'t have additional search types with CategorySelector.SearchType.ParentCategories' );
253 * Sets and validates the value of `this.searchType`.
255 * @param {mw.widgets.CategorySelector.SearchType[]} searchTypes
257 CSP
.setSearchTypes = function ( searchTypes
) {
258 this.searchTypes
= searchTypes
;
259 this.validateSearchTypes();
263 * Searches categories based on input and searchType.
267 * @param {string} input The input used to prefix search categories
268 * @param {mw.widgets.CategorySelector.SearchType} searchType
269 * @return {jQuery.Promise} Resolves with an array of categories
271 CSP
.searchCategories = function ( input
, searchType
) {
272 var deferred
= $.Deferred();
274 switch ( searchType
) {
275 case CategorySelector
.SearchType
.OpenSearch
:
278 action
: 'opensearch',
279 namespace: NS_CATEGORY
,
282 } ).done( function ( res
) {
283 var categories
= res
[ 1 ];
284 deferred
.resolve( categories
);
285 } ).fail( deferred
.reject
.bind( deferred
) );
288 case CategorySelector
.SearchType
.InternalSearch
:
293 apnamespace
: NS_CATEGORY
,
297 } ).done( function ( res
) {
298 var categories
= res
.query
.allpages
.map( function ( page
) {
301 deferred
.resolve( categories
);
302 } ).fail( deferred
.reject
.bind( deferred
) );
305 case CategorySelector
.SearchType
.Exists
:
306 if ( input
.indexOf( '|' ) > -1 ) {
307 deferred
.resolve( [] );
315 titles
: 'Category:' + input
316 } ).done( function ( res
) {
319 $.each( res
.query
.pages
, function ( index
, page
) {
320 if ( !page
.missing
) {
321 categories
.push( page
.title
);
325 deferred
.resolve( categories
);
326 } ).fail( deferred
.reject
.bind( deferred
) );
329 case CategorySelector
.SearchType
.SubCategories
:
330 if ( input
.indexOf( '|' ) > -1 ) {
331 deferred
.resolve( [] );
338 list
: 'categorymembers',
341 cmtitle
: 'Category:' + input
342 } ).done( function ( res
) {
343 var categories
= res
.query
.categorymembers
.map( function ( category
) {
344 return category
.title
;
346 deferred
.resolve( categories
);
347 } ).fail( deferred
.reject
.bind( deferred
) );
350 case CategorySelector
.SearchType
.ParentCategories
:
351 if ( input
.indexOf( '|' ) > -1 ) {
352 deferred
.resolve( [] );
361 titles
: 'Category:' + input
362 } ).done( function ( res
) {
365 $.each( res
.query
.pages
, function ( index
, page
) {
366 if ( !page
.missing
) {
367 if ( $.isArray( page
.categories
) ) {
368 categories
.push
.apply( categories
, page
.categories
.map( function ( category
) {
369 return category
.title
;
375 deferred
.resolve( categories
);
376 } ).fail( deferred
.reject
.bind( deferred
) );
380 throw new Error( 'Unknown searchType' );
383 return deferred
.promise();
387 * @enum mw.widgets.CategorySelector.SearchType
388 * Types of search available.
390 CategorySelector
.SearchType
= {
391 /** Search using action=opensearch */
394 /** Search using action=query */
397 /** Search for existing categories with the exact title */
400 /** Search only subcategories */
403 /** Search only parent categories */
407 mw
.widgets
.CategorySelector
= CategorySelector
;
408 }( jQuery
, mediaWiki
) );