Merge "Rank aliases in search in order they appear in the messages file."
[lhc/web/wiklou.git] / resources / src / mediawiki.widgets / mw.widgets.TitleWidget.js
1 /*!
2 * MediaWiki Widgets - TitleWidget class.
3 *
4 * @copyright 2011-2015 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7 ( function ( $, mw ) {
8
9 /**
10 * Mixin for title widgets
11 *
12 * @class
13 * @abstract
14 *
15 * @constructor
16 * @param {Object} [config] Configuration options
17 * @cfg {number} [limit=10] Number of results to show
18 * @cfg {number} [namespace] Namespace to prepend to queries
19 * @cfg {number} [maxLength=255] Maximum query length
20 * @cfg {boolean} [relative=true] If a namespace is set, display titles relative to it
21 * @cfg {boolean} [suggestions=true] Display search suggestions
22 * @cfg {boolean} [showRedirectTargets=true] Show the targets of redirects
23 * @cfg {boolean} [showImages] Show page images
24 * @cfg {boolean} [showDescriptions] Show page descriptions
25 * @cfg {boolean} [excludeCurrentPage] Exclude the current page from suggestions
26 * @cfg {boolean} [validateTitle=true] Whether the input must be a valid title (if set to true,
27 * the widget will marks itself red for invalid inputs, including an empty query).
28 * @cfg {Object} [cache] Result cache which implements a 'set' method, taking keyed values as an argument
29 * @cfg {mw.Api} [api] API object to use, creates a default mw.Api instance if not specified
30 */
31 mw.widgets.TitleWidget = function MwWidgetsTitleWidget( config ) {
32 // Config initialization
33 config = $.extend( {
34 maxLength: 255,
35 limit: 10
36 }, config );
37
38 // Properties
39 this.limit = config.limit;
40 this.maxLength = config.maxLength;
41 this.namespace = config.namespace !== undefined ? config.namespace : null;
42 this.relative = config.relative !== undefined ? config.relative : true;
43 this.suggestions = config.suggestions !== undefined ? config.suggestions : true;
44 this.showRedirectTargets = config.showRedirectTargets !== false;
45 this.showImages = !!config.showImages;
46 this.showDescriptions = !!config.showDescriptions;
47 this.excludeCurrentPage = !!config.excludeCurrentPage;
48 this.validateTitle = config.validateTitle !== undefined ? config.validateTitle : true;
49 this.cache = config.cache;
50 this.api = config.api || new mw.Api();
51
52 // Initialization
53 this.$element.addClass( 'mw-widget-titleWidget' );
54 };
55
56 /* Setup */
57
58 OO.initClass( mw.widgets.TitleWidget );
59
60 /* Static properties */
61
62 mw.widgets.TitleWidget.static.interwikiPrefixesPromiseCache = {};
63
64 /* Methods */
65
66 /**
67 * Get the current value of the search query
68 *
69 * @abstract
70 * @return {string} Search query
71 */
72 mw.widgets.TitleWidget.prototype.getQueryValue = null;
73
74 /**
75 * Get the namespace to prepend to titles in suggestions, if any.
76 *
77 * @return {number|null} Namespace number
78 */
79 mw.widgets.TitleWidget.prototype.getNamespace = function () {
80 return this.namespace;
81 };
82
83 /**
84 * Set the namespace to prepend to titles in suggestions, if any.
85 *
86 * @param {number|null} namespace Namespace number
87 */
88 mw.widgets.TitleWidget.prototype.setNamespace = function ( namespace ) {
89 this.namespace = namespace;
90 };
91
92 mw.widgets.TitleWidget.prototype.getInterwikiPrefixesPromise = function () {
93 var api = this.getApi(),
94 cache = this.constructor.static.interwikiPrefixesPromiseCache,
95 key = api.defaults.ajax.url;
96 if ( !cache.hasOwnProperty( key ) ) {
97 cache[ key ] = api.get( {
98 action: 'query',
99 meta: 'siteinfo',
100 siprop: 'interwikimap'
101 } ).then( function ( data ) {
102 return $.map( data.query.interwikimap, function ( interwiki ) {
103 return interwiki.prefix;
104 } );
105 } );
106 }
107 return cache[ key ];
108 };
109
110 /**
111 * Get a promise which resolves with an API repsonse for suggested
112 * links for the current query.
113 *
114 * @return {jQuery.Promise} Suggestions promise
115 */
116 mw.widgets.TitleWidget.prototype.getSuggestionsPromise = function () {
117 var req,
118 api = this.getApi(),
119 query = this.getQueryValue(),
120 widget = this,
121 promiseAbortObject = { abort: function () {
122 // Do nothing. This is just so OOUI doesn't break due to abort being undefined.
123 } };
124
125 if ( mw.Title.newFromText( query ) ) {
126 return this.getInterwikiPrefixesPromise().then( function ( interwikiPrefixes ) {
127 var params,
128 interwiki = query.substring( 0, query.indexOf( ':' ) );
129 if (
130 interwiki && interwiki !== '' &&
131 interwikiPrefixes.indexOf( interwiki ) !== -1
132 ) {
133 return $.Deferred().resolve( { query: {
134 pages: [ {
135 title: query
136 } ]
137 } } ).promise( promiseAbortObject );
138 } else {
139 params = {
140 action: 'query',
141 prop: [ 'info', 'pageprops' ],
142 generator: 'prefixsearch',
143 gpssearch: query,
144 gpsnamespace: widget.namespace !== null ? widget.namespace : undefined,
145 gpslimit: widget.limit,
146 ppprop: 'disambiguation'
147 };
148 if ( widget.showRedirectTargets ) {
149 params.redirects = true;
150 }
151 if ( widget.showImages ) {
152 params.prop.push( 'pageimages' );
153 params.pithumbsize = 80;
154 params.pilimit = widget.limit;
155 }
156 if ( widget.showDescriptions ) {
157 params.prop.push( 'pageterms' );
158 params.wbptterms = 'description';
159 }
160 req = api.get( params );
161 promiseAbortObject.abort = req.abort.bind( req ); // TODO ew
162 return req.then( function ( ret ) {
163 if ( ret.query === undefined ) {
164 ret = api.get( { action: 'query', titles: query } );
165 promiseAbortObject.abort = ret.abort.bind( ret );
166 }
167 return ret;
168 } );
169 }
170 } ).promise( promiseAbortObject );
171 } else {
172 // Don't send invalid titles to the API.
173 // Just pretend it returned nothing so we can show the 'invalid title' section
174 return $.Deferred().resolve( {} ).promise( promiseAbortObject );
175 }
176 };
177
178 /**
179 * Get the API object for title requests
180 *
181 * @return {mw.Api} MediaWiki API
182 */
183 mw.widgets.TitleWidget.prototype.getApi = function () {
184 return this.api;
185 };
186
187 /**
188 * Get option widgets from the server response
189 *
190 * @param {Object} data Query result
191 * @return {OO.ui.OptionWidget[]} Menu items
192 */
193 mw.widgets.TitleWidget.prototype.getOptionsFromData = function ( data ) {
194 var i, len, index, pageExists, pageExistsExact, suggestionPage, page, redirect, redirects,
195 currentPageName = new mw.Title( mw.config.get( 'wgRelevantPageName' ) ).getPrefixedText(),
196 items = [],
197 titles = [],
198 titleObj = mw.Title.newFromText( this.getQueryValue() ),
199 redirectsTo = {},
200 pageData = {};
201
202 if ( data.redirects ) {
203 for ( i = 0, len = data.redirects.length; i < len; i++ ) {
204 redirect = data.redirects[ i ];
205 redirectsTo[ redirect.to ] = redirectsTo[ redirect.to ] || [];
206 redirectsTo[ redirect.to ].push( redirect.from );
207 }
208 }
209
210 for ( index in data.pages ) {
211 suggestionPage = data.pages[ index ];
212 // When excludeCurrentPage is set, don't list the current page unless the user has type the full title
213 if ( this.excludeCurrentPage && suggestionPage.title === currentPageName && suggestionPage.title !== titleObj.getPrefixedText() ) {
214 continue;
215 }
216 pageData[ suggestionPage.title ] = {
217 known: suggestionPage.known !== undefined,
218 missing: suggestionPage.missing !== undefined,
219 redirect: suggestionPage.redirect !== undefined,
220 disambiguation: OO.getProp( suggestionPage, 'pageprops', 'disambiguation' ) !== undefined,
221 imageUrl: OO.getProp( suggestionPage, 'thumbnail', 'source' ),
222 description: OO.getProp( suggestionPage, 'terms', 'description' ),
223 // Sort index
224 index: suggestionPage.index
225 };
226
227 // Throw away pages from wrong namespaces. This can happen when 'showRedirectTargets' is true
228 // and we encounter a cross-namespace redirect.
229 if ( this.namespace === null || this.namespace === suggestionPage.ns ) {
230 titles.push( suggestionPage.title );
231 }
232
233 redirects = redirectsTo[ suggestionPage.title ] || [];
234 for ( i = 0, len = redirects.length; i < len; i++ ) {
235 pageData[ redirects[ i ] ] = {
236 missing: false,
237 known: true,
238 redirect: true,
239 disambiguation: false,
240 description: mw.msg( 'mw-widgets-titleinput-description-redirect', suggestionPage.title ),
241 // Sort index, just below its target
242 index: suggestionPage.index + 0.5
243 };
244 titles.push( redirects[ i ] );
245 }
246 }
247
248 titles.sort( function ( a, b ) {
249 return pageData[ a ].index - pageData[ b ].index;
250 } );
251
252 // If not found, run value through mw.Title to avoid treating a match as a
253 // mismatch where normalisation would make them matching (bug 48476)
254
255 pageExistsExact = (
256 Object.prototype.hasOwnProperty.call( pageData, this.getQueryValue() ) &&
257 (
258 !pageData[ this.getQueryValue() ].missing ||
259 pageData[ this.getQueryValue() ].known
260 )
261 );
262 pageExists = pageExistsExact || (
263 titleObj &&
264 Object.prototype.hasOwnProperty.call( pageData, titleObj.getPrefixedText() ) &&
265 (
266 !pageData[ titleObj.getPrefixedText() ].missing ||
267 pageData[ titleObj.getPrefixedText() ].known
268 )
269 );
270
271 if ( this.cache ) {
272 this.cache.set( pageData );
273 }
274
275 // Offer the exact text as a suggestion if the page exists
276 if ( pageExists && !pageExistsExact ) {
277 titles.unshift( this.getQueryValue() );
278 }
279
280 for ( i = 0, len = titles.length; i < len; i++ ) {
281 page = pageData[ titles[ i ] ] || {};
282 items.push( new mw.widgets.TitleOptionWidget( this.getOptionWidgetData( titles[ i ], page ) ) );
283 }
284
285 return items;
286 };
287
288 /**
289 * Get menu option widget data from the title and page data
290 *
291 * @param {string} title Title object
292 * @param {Object} data Page data
293 * @return {Object} Data for option widget
294 */
295 mw.widgets.TitleWidget.prototype.getOptionWidgetData = function ( title, data ) {
296 var mwTitle = new mw.Title( title ),
297 description = data.description;
298 if ( data.missing && !description ) {
299 description = mw.msg( 'mw-widgets-titleinput-description-new-page' );
300 }
301 return {
302 data: this.namespace !== null && this.relative ?
303 mwTitle.getRelativeText( this.namespace ) :
304 title,
305 url: mwTitle.getUrl(),
306 imageUrl: this.showImages ? data.imageUrl : null,
307 description: this.showDescriptions ? description : null,
308 missing: data.missing,
309 redirect: data.redirect,
310 disambiguation: data.disambiguation,
311 query: this.getQueryValue()
312 };
313 };
314
315 /**
316 * Get title object corresponding to given value, or #getQueryValue if not given.
317 *
318 * @param {string} [value] Value to get a title for
319 * @return {mw.Title|null} Title object, or null if value is invalid
320 */
321 mw.widgets.TitleWidget.prototype.getTitle = function ( value ) {
322 var title = value !== undefined ? value : this.getQueryValue(),
323 // mw.Title doesn't handle null well
324 titleObj = mw.Title.newFromText( title, this.namespace !== null ? this.namespace : undefined );
325
326 return titleObj;
327 };
328
329 /**
330 * Check if the query is valid
331 *
332 * @return {boolean} The query is valid
333 */
334 mw.widgets.TitleWidget.prototype.isQueryValid = function () {
335 return this.validateTitle ? !!this.getTitle() : true;
336 };
337
338 }( jQuery, mediaWiki ) );