Merge "Split DateInputWidget & CalendarWidget into a separate ResourceLoader module"
[lhc/web/wiklou.git] / resources / src / mediawiki / api / category.js
1 /**
2 * @class mw.Api.plugin.category
3 */
4 ( function ( mw, $ ) {
5
6 $.extend( mw.Api.prototype, {
7 /**
8 * Determine if a category exists.
9 *
10 * @param {mw.Title|string} title
11 * @return {jQuery.Promise}
12 * @return {Function} return.done
13 * @return {boolean} return.done.isCategory Whether the category exists.
14 */
15 isCategory: function ( title ) {
16 var apiPromise = this.get( {
17 prop: 'categoryinfo',
18 titles: String( title )
19 } );
20
21 return apiPromise
22 .then( function ( data ) {
23 var exists = false;
24 if ( data.query && data.query.pages ) {
25 $.each( data.query.pages, function ( id, page ) {
26 if ( page.categoryinfo ) {
27 exists = true;
28 }
29 } );
30 }
31 return exists;
32 } )
33 .promise( { abort: apiPromise.abort } );
34 },
35
36 /**
37 * Get a list of categories that match a certain prefix.
38 *
39 * E.g. given "Foo", return "Food", "Foolish people", "Foosball tables"...
40 *
41 * @param {string} prefix Prefix to match.
42 * @return {jQuery.Promise}
43 * @return {Function} return.done
44 * @return {string[]} return.done.categories Matched categories
45 */
46 getCategoriesByPrefix: function ( prefix ) {
47 // Fetch with allpages to only get categories that have a corresponding description page.
48 var apiPromise = this.get( {
49 list: 'allpages',
50 apprefix: prefix,
51 apnamespace: mw.config.get( 'wgNamespaceIds' ).category
52 } );
53
54 return apiPromise
55 .then( function ( data ) {
56 var texts = [];
57 if ( data.query && data.query.allpages ) {
58 $.each( data.query.allpages, function ( i, category ) {
59 texts.push( new mw.Title( category.title ).getMainText() );
60 } );
61 }
62 return texts;
63 } )
64 .promise( { abort: apiPromise.abort } );
65 },
66
67 /**
68 * Get the categories that a particular page on the wiki belongs to.
69 *
70 * @param {mw.Title|string} title
71 * @return {jQuery.Promise}
72 * @return {Function} return.done
73 * @return {boolean|mw.Title[]} return.done.categories List of category titles or false
74 * if title was not found.
75 */
76 getCategories: function ( title ) {
77 var apiPromise = this.get( {
78 prop: 'categories',
79 titles: String( title )
80 } );
81
82 return apiPromise
83 .then( function ( data ) {
84 var titles = false;
85 if ( data.query && data.query.pages ) {
86 $.each( data.query.pages, function ( id, page ) {
87 if ( page.categories ) {
88 if ( titles === false ) {
89 titles = [];
90 }
91 $.each( page.categories, function ( i, cat ) {
92 titles.push( new mw.Title( cat.title ) );
93 } );
94 }
95 } );
96 }
97 return titles;
98 } )
99 .promise( { abort: apiPromise.abort } );
100 }
101 } );
102
103 /**
104 * @class mw.Api
105 * @mixins mw.Api.plugin.category
106 */
107
108 }( mediaWiki, jQuery ) );