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.CapsuleMultiselectWidget
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.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.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
.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
.CapsuleMultiselectWidget
);
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
.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
.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 ( $.trim( input
) === '' ) {
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.createItemWidget = function ( data
) {
192 var title
= mw
.Title
.makeTitle( NS_CATEGORY
, data
);
196 return new mw
.widgets
.CategoryCapsuleItemWidget( {
197 apiUrl
: this.api
.apiUrl
|| undefined,
205 mw
.widgets
.CategoryMultiselectWidget
.prototype.findItemFromData = function ( data
) {
206 // This is a bit of a hack... We have to canonicalize the data in the same way that
207 // #createItemWidget and CategoryCapsuleItemWidget will do, otherwise we won't find duplicates.
208 var title
= mw
.Title
.makeTitle( NS_CATEGORY
, data
);
212 return OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData
.call( this, title
.getMainText() );
216 * Validates the values in `this.searchType`.
221 mw
.widgets
.CategoryMultiselectWidget
.prototype.validateSearchTypes = function () {
222 var validSearchTypes
= false,
223 searchTypeEnumCount
= Object
.keys( mw
.widgets
.CategoryMultiselectWidget
.SearchType
).length
;
225 // Check if all values are in the SearchType enum
226 validSearchTypes
= this.searchTypes
.every( function ( searchType
) {
227 return searchType
> -1 && searchType
< searchTypeEnumCount
;
230 if ( validSearchTypes
=== false ) {
231 throw new Error( 'Unknown searchType in searchTypes' );
234 // If the searchTypes has mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories
235 // it can be the only search type.
236 if ( this.searchTypes
.indexOf( mw
.widgets
.CategoryMultiselectWidget
.SearchType
.SubCategories
) > -1 &&
237 this.searchTypes
.length
> 1
239 throw new Error( 'Can\'t have additional search types with mw.widgets.CategoryMultiselectWidget.SearchType.SubCategories' );
242 // If the searchTypes has mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories
243 // it can be the only search type.
244 if ( this.searchTypes
.indexOf( mw
.widgets
.CategoryMultiselectWidget
.SearchType
.ParentCategories
) > -1 &&
245 this.searchTypes
.length
> 1
247 throw new Error( 'Can\'t have additional search types with mw.widgets.CategoryMultiselectWidget.SearchType.ParentCategories' );
254 * Sets and validates the value of `this.searchType`.
256 * @param {mw.widgets.CategoryMultiselectWidget.SearchType[]} searchTypes
258 mw
.widgets
.CategoryMultiselectWidget
.prototype.setSearchTypes = function ( searchTypes
) {
259 this.searchTypes
= searchTypes
;
260 this.validateSearchTypes();
264 * Searches categories based on input and searchType.
268 * @param {string} input The input used to prefix search categories
269 * @param {mw.widgets.CategoryMultiselectWidget.SearchType} searchType
270 * @return {jQuery.Promise} Resolves with an array of categories
272 mw
.widgets
.CategoryMultiselectWidget
.prototype.searchCategories = function ( input
, searchType
) {
273 var deferred
= $.Deferred(),
274 cacheKey
= input
+ searchType
.toString();
277 if ( hasOwn
.call( this.searchCache
, cacheKey
) ) {
278 return this.searchCache
[ cacheKey
];
281 switch ( searchType
) {
282 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.OpenSearch
:
285 action
: 'opensearch',
286 namespace: NS_CATEGORY
,
289 } ).done( function ( res
) {
290 var categories
= res
[ 1 ];
291 deferred
.resolve( categories
);
292 } ).fail( deferred
.reject
.bind( deferred
) );
295 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.InternalSearch
:
300 apnamespace
: NS_CATEGORY
,
304 } ).done( function ( res
) {
305 var categories
= res
.query
.allpages
.map( function ( page
) {
308 deferred
.resolve( categories
);
309 } ).fail( deferred
.reject
.bind( deferred
) );
312 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.Exists
:
313 if ( input
.indexOf( '|' ) > -1 ) {
314 deferred
.resolve( [] );
322 titles
: 'Category:' + input
323 } ).done( function ( res
) {
326 $.each( res
.query
.pages
, function ( index
, page
) {
327 if ( !page
.missing
) {
328 categories
.push( page
.title
);
332 deferred
.resolve( categories
);
333 } ).fail( deferred
.reject
.bind( deferred
) );
336 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.SubCategories
:
337 if ( input
.indexOf( '|' ) > -1 ) {
338 deferred
.resolve( [] );
345 list
: 'categorymembers',
348 cmtitle
: 'Category:' + input
349 } ).done( function ( res
) {
350 var categories
= res
.query
.categorymembers
.map( function ( category
) {
351 return category
.title
;
353 deferred
.resolve( categories
);
354 } ).fail( deferred
.reject
.bind( deferred
) );
357 case mw
.widgets
.CategoryMultiselectWidget
.SearchType
.ParentCategories
:
358 if ( input
.indexOf( '|' ) > -1 ) {
359 deferred
.resolve( [] );
368 titles
: 'Category:' + input
369 } ).done( function ( res
) {
372 $.each( res
.query
.pages
, function ( index
, page
) {
373 if ( !page
.missing
&& Array
.isArray( page
.categories
) ) {
374 categories
.push
.apply( categories
, page
.categories
.map( function ( category
) {
375 return category
.title
;
380 deferred
.resolve( categories
);
381 } ).fail( deferred
.reject
.bind( deferred
) );
385 throw new Error( 'Unknown searchType' );
389 this.searchCache
[ cacheKey
] = deferred
.promise();
391 return deferred
.promise();
395 * @enum mw.widgets.CategoryMultiselectWidget.SearchType
396 * Types of search available.
398 mw
.widgets
.CategoryMultiselectWidget
.SearchType
= {
399 /** Search using action=opensearch */
402 /** Search using action=query */
405 /** Search for existing categories with the exact title */
408 /** Search only subcategories */
411 /** Search only parent categories */
415 // For backwards compatibility. See T161285.
416 mw
.widgets
.CategorySelector
= mw
.widgets
.CategoryMultiselectWidget
;
417 }( jQuery
, mediaWiki
) );