2 * MediaWiki Widgets - CategoryMultiselectWidget class.
4 * @copyright 2011-2015 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
8 var hasOwn
= Object
.prototype.hasOwnProperty
,
9 NS_CATEGORY
= mw
.config
.get( 'wgNamespaceIds' ).category
;
12 * Category selector widget. Displays an OO.ui.MenuTagMultiselectWidget
13 * and autocompletes with available categories.
15 * mw.loader.using( 'mediawiki.widgets.CategoryMultiselectWidget', function () {
16 * var selector = new mw.widgets.CategoryMultiselectWidget( {
18 * mw.widgets.CategoryMultiselectWidget.SearchType.OpenSearch,
19 * mw.widgets.CategoryMultiselectWidget.SearchType.InternalSearch
23 * $( 'body' ).append( selector.$element );
25 * selector.setSearchTypes( [ mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories ] );
28 * @class mw.widgets.CategoryMultiselectWidget
30 * @extends OO.ui.MenuTagMultiselectWidget
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.CategoryMultiselectWidget.SearchType[]} [searchTypes=[mw.widgets.CategoryMultiselectWidget.SearchType.OpenSearch]]
38 * Default search API to use when searching.
40 mw
.widgets
.CategoryMultiselectWidget
= function MWCategoryMultiselectWidget( config
) {
41 // Config initialization
44 searchTypes
: [ mw
.widgets
.CategoryMultiselectWidget
.SearchType
.OpenSearch
]
46 this.limit
= config
.limit
;
47 this.searchTypes
= config
.searchTypes
;
48 this.validateSearchTypes();
51 mw
.widgets
.CategoryMultiselectWidget
.parent
.call( this, $.extend( true, {}, config
, {
53 filterFromInput
: false
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
62 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$handle
} ) );
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 ) );
68 this.api
= config
.api
|| new mw
.Api();
69 this.searchCache
= {};
74 OO
.inheritClass( mw
.widgets
.CategoryMultiselectWidget
, OO
.ui
.MenuTagMultiselectWidget
);
75 OO
.mixinClass( mw
.widgets
.CategoryMultiselectWidget
, OO
.ui
.mixin
.PendingElement
);
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.
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();
93 // Never show the menu if the input lost focus in the meantime
94 if ( !this.input
.$input
.is( ':focus' ) ) {
98 // Array of strings of the data of OO.ui.MenuOptionsWidgets
99 existingItems
= menu
.getItems().map( function ( item
) {
103 // Remove if items' data already exists
104 filteredItems
= items
.filter( function ( item
) {
105 return existingItems
.indexOf( item
) === -1;
108 // Map to an array of OO.ui.MenuOptionWidgets
109 filteredItems
= filteredItems
.map( function ( item
) {
110 return new OO
.ui
.MenuOptionWidget( {
116 menu
.addItems( filteredItems
).toggle( true );
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
130 * Searches for categories based on the input.
134 * @param {string} input The input used to prefix search categories
135 * @return {jQuery.Promise} Resolves with an array of categories
137 mw
.widgets
.CategoryMultiselectWidget
.prototype.getNewMenuItems = function ( input
) {
140 deferred
= $.Deferred();
142 if ( input
.trim() === '' ) {
143 deferred
.resolve( [] );
144 return deferred
.promise();
147 // Abort all pending requests, we won't need their results
149 for ( i
= 0; i
< this.searchTypes
.length
; i
++ ) {
150 promises
.push( this.searchCategories( input
, this.searchTypes
[ i
] ) );
155 $.when
.apply( $, promises
).done( function () {
158 dataSets
= Array
.prototype.slice
.apply( arguments
);
160 // Collect values from all results
161 allData
= allData
.concat
.apply( allData
, dataSets
);
163 categoryNames
= allData
165 .filter( function ( value
, index
, self
) {
166 return self
.indexOf( value
) === index
;
169 .map( function ( name
) {
170 return mw
.Title
.newFromText( name
);
172 // Keep only titles from 'Category' namespace
173 .filter( function ( title
) {
174 return title
&& title
.getNamespaceId() === NS_CATEGORY
;
176 // Convert back to strings, strip 'Category:' prefix
177 .map( function ( title
) {
178 return title
.getMainText();
181 deferred
.resolve( categoryNames
);
183 } ).always( this.popPending
.bind( this ) );
185 return deferred
.promise();
191 mw
.widgets
.CategoryMultiselectWidget
.prototype.createTagItemWidget = function ( data
) {
192 var title
= mw
.Title
.makeTitle( NS_CATEGORY
, data
);
194 return new mw
.widgets
.CategoryTagItemWidget( {
195 apiUrl
: this.api
.apiUrl
|| undefined,
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
);
210 return OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData
.call( this, title
.getMainText() );
214 * Validates the values in `this.searchType`.
219 mw
.widgets
.CategoryMultiselectWidget
.prototype.validateSearchTypes = function () {
220 var validSearchTypes
= false,
221 searchTypeEnumCount
= Object
.keys( mw
.widgets
.CategoryMultiselectWidget
.SearchType
).length
;
223 // Check if all values are in the SearchType enum
224 validSearchTypes
= this.searchTypes
.every( function ( searchType
) {
225 return searchType
> -1 && searchType
< searchTypeEnumCount
;
228 if ( validSearchTypes
=== false ) {
229 throw new Error( 'Unknown searchType in searchTypes' );
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
237 throw new Error( 'Can\'t have additional search types with mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories' );
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
245 throw new Error( 'Can\'t have additional search types with mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories' );
252 * Sets and validates the value of `this.searchType`.
254 * @param {mw.widgets.CategoryMultiselectWidget.SearchType[]} searchTypes
256 mw
.widgets
.CategoryMultiselectWidget
.prototype.setSearchTypes = function ( searchTypes
) {
257 this.searchTypes
= searchTypes
;
258 this.validateSearchTypes();
262 * Searches categories based on input and searchType.
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
270 mw
.widgets
.CategoryMultiselectWidget
.prototype.searchCategories = function ( input
, searchType
) {
271 var deferred
= $.Deferred(),
272 cacheKey
= input
+ searchType
.toString();
275 if ( hasOwn
.call( this.searchCache
, cacheKey
) ) {
276 return this.searchCache
[ cacheKey
];
279 switch ( searchType
) {
280 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.OpenSearch
:
283 action
: 'opensearch',
284 namespace: NS_CATEGORY
,
287 } ).done( function ( res
) {
288 var categories
= res
[ 1 ];
289 deferred
.resolve( categories
);
290 } ).fail( deferred
.reject
.bind( deferred
) );
293 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.InternalSearch
:
298 apnamespace
: NS_CATEGORY
,
302 } ).done( function ( res
) {
303 var categories
= res
.query
.allpages
.map( function ( page
) {
306 deferred
.resolve( categories
);
307 } ).fail( deferred
.reject
.bind( deferred
) );
310 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.Exists
:
311 if ( input
.indexOf( '|' ) > -1 ) {
312 deferred
.resolve( [] );
320 titles
: 'Category:' + input
321 } ).done( function ( res
) {
324 $.each( res
.query
.pages
, function ( index
, page
) {
325 if ( !page
.missing
) {
326 categories
.push( page
.title
);
330 deferred
.resolve( categories
);
331 } ).fail( deferred
.reject
.bind( deferred
) );
334 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.SubCategories
:
335 if ( input
.indexOf( '|' ) > -1 ) {
336 deferred
.resolve( [] );
343 list
: 'categorymembers',
346 cmtitle
: 'Category:' + input
347 } ).done( function ( res
) {
348 var categories
= res
.query
.categorymembers
.map( function ( category
) {
349 return category
.title
;
351 deferred
.resolve( categories
);
352 } ).fail( deferred
.reject
.bind( deferred
) );
355 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.ParentCategories
:
356 if ( input
.indexOf( '|' ) > -1 ) {
357 deferred
.resolve( [] );
366 titles
: 'Category:' + input
367 } ).done( function ( res
) {
370 $.each( res
.query
.pages
, function ( index
, page
) {
371 if ( !page
.missing
&& Array
.isArray( page
.categories
) ) {
372 categories
.push
.apply( categories
, page
.categories
.map( function ( category
) {
373 return category
.title
;
378 deferred
.resolve( categories
);
379 } ).fail( deferred
.reject
.bind( deferred
) );
383 throw new Error( 'Unknown searchType' );
387 this.searchCache
[ cacheKey
] = deferred
.promise();
389 return deferred
.promise();
393 * @enum mw.widgets.CategoryMultiselectWidget.SearchType
394 * Types of search available.
396 mw
.widgets
.CategoryMultiselectWidget
.SearchType
= {
397 /** Search using action=opensearch */
400 /** Search using action=query */
403 /** Search for existing categories with the exact title */
406 /** Search only subcategories */
409 /** Search only parent categories */
412 }( jQuery
, mediaWiki
) );