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