5fe094ff63e0e087370f61f510857580e89599ca
[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 // Cache client-side for a day since this info is mostly static
102 maxage: 60 * 60 * 24,
103 smaxage: 60 * 60 * 24,
104 // Workaround T97096 by setting uselang=content
105 uselang: 'content'
106 } ).then( function ( data ) {
107 return $.map( data.query.interwikimap, function ( interwiki ) {
108 return interwiki.prefix;
109 } );
110 } );
111 }
112 return cache[ key ];
113 };
114
115 /**
116 * Get a promise which resolves with an API repsonse for suggested
117 * links for the current query.
118 *
119 * @return {jQuery.Promise} Suggestions promise
120 */
121 mw.widgets.TitleWidget.prototype.getSuggestionsPromise = function () {
122 var req,
123 api = this.getApi(),
124 query = this.getQueryValue(),
125 widget = this,
126 promiseAbortObject = { abort: function () {
127 // Do nothing. This is just so OOUI doesn't break due to abort being undefined.
128 } };
129
130 if ( mw.Title.newFromText( query ) ) {
131 return this.getInterwikiPrefixesPromise().then( function ( interwikiPrefixes ) {
132 var interwiki = query.substring( 0, query.indexOf( ':' ) );
133 if (
134 interwiki && interwiki !== '' &&
135 interwikiPrefixes.indexOf( interwiki ) !== -1
136 ) {
137 return $.Deferred().resolve( { query: {
138 pages: [ {
139 title: query
140 } ]
141 } } ).promise( promiseAbortObject );
142 } else {
143 req = api.get( widget.getApiParams( query ) );
144 promiseAbortObject.abort = req.abort.bind( req ); // TODO ew
145 return req.then( function ( ret ) {
146 if ( ret.query === undefined ) {
147 ret = api.get( { action: 'query', titles: query } );
148 promiseAbortObject.abort = ret.abort.bind( ret );
149 }
150 return ret;
151 } );
152 }
153 } ).promise( promiseAbortObject );
154 } else {
155 // Don't send invalid titles to the API.
156 // Just pretend it returned nothing so we can show the 'invalid title' section
157 return $.Deferred().resolve( {} ).promise( promiseAbortObject );
158 }
159 };
160
161 /**
162 * Get API params for a given query
163 *
164 * @param {string} query User query
165 * @return {Object} API params
166 */
167 mw.widgets.TitleWidget.prototype.getApiParams = function ( query ) {
168 var params = {
169 action: 'query',
170 prop: [ 'info', 'pageprops' ],
171 generator: 'prefixsearch',
172 gpssearch: query,
173 gpsnamespace: this.namespace !== null ? this.namespace : undefined,
174 gpslimit: this.limit,
175 ppprop: 'disambiguation'
176 };
177 if ( this.showRedirectTargets ) {
178 params.redirects = true;
179 }
180 if ( this.showImages ) {
181 params.prop.push( 'pageimages' );
182 params.pithumbsize = 80;
183 params.pilimit = this.limit;
184 }
185 if ( this.showDescriptions ) {
186 params.prop.push( 'pageterms' );
187 params.wbptterms = 'description';
188 }
189 return params;
190 };
191
192 /**
193 * Get the API object for title requests
194 *
195 * @return {mw.Api} MediaWiki API
196 */
197 mw.widgets.TitleWidget.prototype.getApi = function () {
198 return this.api;
199 };
200
201 /**
202 * Get option widgets from the server response
203 *
204 * @param {Object} data Query result
205 * @return {OO.ui.OptionWidget[]} Menu items
206 */
207 mw.widgets.TitleWidget.prototype.getOptionsFromData = function ( data ) {
208 var i, len, index, pageExists, pageExistsExact, suggestionPage, page, redirect, redirects,
209 currentPageName = new mw.Title( mw.config.get( 'wgRelevantPageName' ) ).getPrefixedText(),
210 items = [],
211 titles = [],
212 titleObj = mw.Title.newFromText( this.getQueryValue() ),
213 redirectsTo = {},
214 pageData = {};
215
216 if ( data.redirects ) {
217 for ( i = 0, len = data.redirects.length; i < len; i++ ) {
218 redirect = data.redirects[ i ];
219 redirectsTo[ redirect.to ] = redirectsTo[ redirect.to ] || [];
220 redirectsTo[ redirect.to ].push( redirect.from );
221 }
222 }
223
224 for ( index in data.pages ) {
225 suggestionPage = data.pages[ index ];
226 // When excludeCurrentPage is set, don't list the current page unless the user has type the full title
227 if ( this.excludeCurrentPage && suggestionPage.title === currentPageName && suggestionPage.title !== titleObj.getPrefixedText() ) {
228 continue;
229 }
230 pageData[ suggestionPage.title ] = {
231 known: suggestionPage.known !== undefined,
232 missing: suggestionPage.missing !== undefined,
233 redirect: suggestionPage.redirect !== undefined,
234 disambiguation: OO.getProp( suggestionPage, 'pageprops', 'disambiguation' ) !== undefined,
235 imageUrl: OO.getProp( suggestionPage, 'thumbnail', 'source' ),
236 description: OO.getProp( suggestionPage, 'terms', 'description' ),
237 // Sort index
238 index: suggestionPage.index,
239 originalData: suggestionPage
240 };
241
242 // Throw away pages from wrong namespaces. This can happen when 'showRedirectTargets' is true
243 // and we encounter a cross-namespace redirect.
244 if ( this.namespace === null || this.namespace === suggestionPage.ns ) {
245 titles.push( suggestionPage.title );
246 }
247
248 redirects = redirectsTo[ suggestionPage.title ] || [];
249 for ( i = 0, len = redirects.length; i < len; i++ ) {
250 pageData[ redirects[ i ] ] = {
251 missing: false,
252 known: true,
253 redirect: true,
254 disambiguation: false,
255 description: mw.msg( 'mw-widgets-titleinput-description-redirect', suggestionPage.title ),
256 // Sort index, just below its target
257 index: suggestionPage.index + 0.5,
258 originalData: suggestionPage
259 };
260 titles.push( redirects[ i ] );
261 }
262 }
263
264 titles.sort( function ( a, b ) {
265 return pageData[ a ].index - pageData[ b ].index;
266 } );
267
268 // If not found, run value through mw.Title to avoid treating a match as a
269 // mismatch where normalisation would make them matching (T50476)
270
271 pageExistsExact = (
272 Object.prototype.hasOwnProperty.call( pageData, this.getQueryValue() ) &&
273 (
274 !pageData[ this.getQueryValue() ].missing ||
275 pageData[ this.getQueryValue() ].known
276 )
277 );
278 pageExists = pageExistsExact || (
279 titleObj &&
280 Object.prototype.hasOwnProperty.call( pageData, titleObj.getPrefixedText() ) &&
281 (
282 !pageData[ titleObj.getPrefixedText() ].missing ||
283 pageData[ titleObj.getPrefixedText() ].known
284 )
285 );
286
287 if ( this.cache ) {
288 this.cache.set( pageData );
289 }
290
291 // Offer the exact text as a suggestion if the page exists
292 if ( pageExists && !pageExistsExact ) {
293 titles.unshift( this.getQueryValue() );
294 }
295
296 for ( i = 0, len = titles.length; i < len; i++ ) {
297 page = pageData[ titles[ i ] ] || {};
298 items.push( this.createOptionWidget( this.getOptionWidgetData( titles[ i ], page ) ) );
299 }
300
301 return items;
302 };
303
304 /**
305 * Create a menu option widget with specified data
306 *
307 * @param {Object} data Data for option widget
308 * @return {OO.ui.MenuOptionWidget} Data for option widget
309 */
310 mw.widgets.TitleWidget.prototype.createOptionWidget = function ( data ) {
311 return new mw.widgets.TitleOptionWidget( data );
312 };
313
314 /**
315 * Get menu option widget data from the title and page data
316 *
317 * @param {string} title Title object
318 * @param {Object} data Page data
319 * @return {Object} Data for option widget
320 */
321 mw.widgets.TitleWidget.prototype.getOptionWidgetData = function ( title, data ) {
322 var mwTitle = new mw.Title( title ),
323 description = data.description;
324 if ( data.missing && !description ) {
325 description = mw.msg( 'mw-widgets-titleinput-description-new-page' );
326 }
327 return {
328 data: this.namespace !== null && this.relative ?
329 mwTitle.getRelativeText( this.namespace ) :
330 title,
331 url: mwTitle.getUrl(),
332 showImages: this.showImages,
333 imageUrl: this.showImages ? data.imageUrl : null,
334 description: this.showDescriptions ? description : null,
335 missing: data.missing,
336 redirect: data.redirect,
337 disambiguation: data.disambiguation,
338 query: this.getQueryValue()
339 };
340 };
341
342 /**
343 * Get title object corresponding to given value, or #getQueryValue if not given.
344 *
345 * @param {string} [value] Value to get a title for
346 * @return {mw.Title|null} Title object, or null if value is invalid
347 */
348 mw.widgets.TitleWidget.prototype.getTitle = function ( value ) {
349 var title = value !== undefined ? value : this.getQueryValue(),
350 // mw.Title doesn't handle null well
351 titleObj = mw.Title.newFromText( title, this.namespace !== null ? this.namespace : undefined );
352
353 return titleObj;
354 };
355
356 /**
357 * Check if the query is valid
358 *
359 * @return {boolean} The query is valid
360 */
361 mw.widgets.TitleWidget.prototype.isQueryValid = function () {
362 return this.validateTitle ? !!this.getTitle() : true;
363 };
364
365 }( jQuery, mediaWiki ) );