Debian Codegraph @

resources/src/mediawiki.widgets/mw.widgets.TitleWidget.js

raw symbols SCIP
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 () {
8 const hasOwn = Object.prototype.hasOwnProperty;
9
10 /**
11 * @classdesc Mixin for title widgets.
12 *
13 * @class
14 * @abstract
15 *
16 * @constructor
17 * @description Create an instance of `mw.widgets.TitleWidget`.
18 * @param {Object} [config] Configuration options
19 * @param {number} [config.limit=10] Number of results to show
20 * @param {number} [config.namespace] Namespace to prepend to queries
21 * @param {number} [config.maxLength=255] Maximum query length
22 * @param {boolean} [config.relative=true] If a namespace is set, display titles relative to it
23 * @param {boolean} [config.suggestions=true] Display search suggestions
24 * @param {boolean} [config.showRedirectTargets=true] Show the targets of redirects
25 * @param {boolean} [config.showImages=false] Show page images
26 * @param {boolean} [config.showDescriptions=false] Show page descriptions
27 * @param {boolean} [config.showDisambigsLast=false] Show disambiguation pages as the last results
28 * @param {boolean} [config.showMissing] Show the user's input as a missing page when a page with this
29 * exact name doesn't exist. Disabled by default when the namespace option is used, otherwise
30 * enabled by default.
31 * @param {boolean} [config.showInterwikis=false] Show pages with a valid interwiki prefix
32 * @param {boolean} [config.searchFragments=false] Search for hash fragments on a specific page when typed
33 * @param {boolean} [config.addQueryInput=true] Add exact user's input query to results
34 * @param {boolean} [config.excludeCurrentPage=false] Exclude the current page from suggestions
35 * @param {boolean} [config.excludeDynamicNamespaces=false] Exclude pages whose namespace is negative
36 * @param {boolean} [config.validateTitle=true] Whether the input must be a valid title
37 * @param {boolean} [config.required=false] Whether the input must not be empty
38 * @param {boolean} [config.highlightSearchQuery=true] Highlight the partial query the user used for this title
39 * @param {Object} [config.cache] Result cache which implements a 'set' method, taking keyed values as an argument
40 * @param {mw.Api} [config.api] API object to use, creates a default mw.Api instance if not specified
41 */
42 mw.widgets.TitleWidget = function MwWidgetsTitleWidget( config ) {
43 // Config initialization
44 config = Object.assign( {
45 maxLength: 255,
46 limit: 10
47 }, config );
48
49 // Properties
50 this.limit = config.limit;
51 this.maxLength = config.maxLength;
52 this.namespace = config.namespace !== undefined ? config.namespace : null;
53 this.relative = config.relative !== undefined ? config.relative : true;
54 this.suggestions = config.suggestions !== undefined ? config.suggestions : true;
55 this.showRedirectTargets = config.showRedirectTargets !== false;
56 this.showImages = !!config.showImages;
57 this.showDescriptions = !!config.showDescriptions;
58 this.showDisambigsLast = !!config.showDisambigsLast;
59 this.showMissing = config.showMissing !== undefined ? !!config.showMissing : this.namespace === null;
60 this.showInterwikis = !!config.showInterwikis;
61 this.searchFragments = !!config.searchFragments;
62 this.addQueryInput = config.addQueryInput !== false;
63 this.excludeCurrentPage = !!config.excludeCurrentPage;
64 this.excludeDynamicNamespaces = !!config.excludeDynamicNamespaces;
65 this.validateTitle = config.validateTitle !== undefined ? config.validateTitle : true;
66 this.highlightSearchQuery = config.highlightSearchQuery === undefined ? true : !!config.highlightSearchQuery;
67 this.cache = config.cache;
68 this.api = config.api || new mw.Api();
69 this.compare = new Intl.Collator(
70 mw.language.bcp47( mw.config.get( 'wgContentLanguage' ) ),
71 { sensitivity: 'base' }
72 ).compare;
73 this.sectionsCache = {};
74
75 // Initialization
76 this.$element.addClass( 'mw-widget-titleWidget' );
77 };
78
79 /* Setup */
80
81 OO.initClass( mw.widgets.TitleWidget );
82
83 /* Static properties */
84
85 mw.widgets.TitleWidget.static.interwikiPrefixesPromiseCache = {};
86
87 /* Methods */
88
89 /**
90 * Get the current value of the search query.
91 *
92 * @abstract
93 * @method
94 * @return {string} Search query
95 */
96 mw.widgets.TitleWidget.prototype.getQueryValue = null;
97
98 /**
99 * Get the namespace to prepend to titles in suggestions, if any.
100 *
101 * @return {number|null} Namespace number
102 */
103 mw.widgets.TitleWidget.prototype.getNamespace = function () {
104 return this.namespace;
105 };
106
107 /**
108 * Set the namespace to prepend to titles in suggestions, if any.
109 *
110 * @param {number|null} namespace Namespace number
111 */
112 mw.widgets.TitleWidget.prototype.setNamespace = function ( namespace ) {
113 this.namespace = namespace;
114 };
115
116 mw.widgets.TitleWidget.prototype.getInterwikiPrefixesPromise = function () {
117 if ( !this.showInterwikis ) {
118 return $.Deferred().resolve( [] ).promise();
119 }
120
121 const api = this.getApi();
122 const cache = this.constructor.static.interwikiPrefixesPromiseCache;
123 const key = api.defaults.ajax.url;
124
125 if ( !Object.prototype.hasOwnProperty.call( cache, key ) ) {
126 cache[ key ] = api.get( {
127 action: 'query',
128 meta: 'siteinfo',
129 siprop: 'interwikimap',
130 // Cache client-side for a day since this info is mostly static
131 maxage: 60 * 60 * 24,
132 smaxage: 60 * 60 * 24,
133 // Workaround T97096 by setting uselang=content
134 uselang: 'content'
135 } ).then( ( data ) => data.query.interwikimap.map( ( interwiki ) => interwiki.prefix ) );
136 }
137 return cache[ key ];
138 };
139
140 /**
141 * Suggest link fragments from the sections API.
142 *
143 * @param {string} title Title, extracted form the user input
144 * @param {string} fragmentQuery Partial link fragment, from the user input
145 * @return {jQuery.Promise} Suggestions promise
146 */
147 mw.widgets.TitleWidget.prototype.getSectionSuggestions = function ( title, fragmentQuery ) {
148 const normalizedTitle = mw.Title.newFromText( title || mw.config.get( 'wgRelevantPageName' ) );
149 if ( !normalizedTitle ) {
150 return $.Deferred().resolve( [] ).promise();
151 }
152 const normalizedTitleText = normalizedTitle.getPrefixedText();
153 this.sectionsCache[ normalizedTitleText ] = this.sectionsCache[ normalizedTitleText ] || this.getApi().get( {
154 action: 'parse',
155 page: normalizedTitleText,
156 prop: 'sections'
157 } );
158
159 function normalizeFragment( fragment ) {
160 return fragment.toLowerCase().replace( /_/g, ' ' );
161 }
162
163 return this.sectionsCache[ normalizedTitleText ].then( ( response ) => {
164 const sections = OO.getProp( response, 'parse', 'sections' ) || [];
165 const normalizedFragmentQuery = normalizeFragment( fragmentQuery );
166 const results = sections.filter( ( section ) => normalizeFragment( section.line ).indexOf( normalizedFragmentQuery ) !== -1 ).map( ( section ) => {
167 const fragment = section.linkAnchor.replace( /_/g, ' ' );
168 // TODO: Make promise abortable
169 return {
170 title: title + '#' + fragment,
171 // `title`` could be empty for a relative fragment, so store the normalized
172 // title if that is needed later.
173 normalizedTitle: normalizedTitle + '#' + fragment,
174 ns: normalizedTitle.getNamespaceId(),
175 // Sort prefix matches to the top
176 index: normalizeFragment( section.line ).indexOf( normalizedFragmentQuery ) === 0 ? 0 : 1
177 };
178 } );
179 // Sorting also happens later, but we need to do it now before we truncate
180 results.sort( ( a, b ) => a.index - b.index );
181 // Fake query result
182 return {
183 query: {
184 pages: results.slice( 0, this.limit )
185 }
186 };
187 } ).promise( { abort: function () {} } );
188 };
189
190 /**
191 * Get a promise which resolves with an API response for suggested
192 * links for the current query.
193 *
194 * @return {jQuery.Promise} Suggestions promise
195 */
196 mw.widgets.TitleWidget.prototype.getSuggestionsPromise = function () {
197 const api = this.getApi(),
198 query = this.getQueryValue(),
199 promiseAbortObject = { abort: function () {
200 // Do nothing. This is just so OOUI doesn't break due to abort being undefined.
201 } };
202
203 if ( this.searchFragments ) {
204 const hashIndex = query.indexOf( '#' );
205 if ( hashIndex !== -1 ) {
206 return this.getSectionSuggestions( query.slice( 0, hashIndex ), query.slice( hashIndex + 1 ) );
207 }
208 }
209
210 if ( !mw.Title.newFromText( query ) ) {
211 // Don't send invalid titles to the API.
212 // Just pretend it returned nothing so we can show the 'invalid title' section
213 return $.Deferred().resolve( {} ).promise( promiseAbortObject );
214 }
215
216 return this.getInterwikiPrefixesPromise().then( ( interwikiPrefixes ) => {
217 // Optimization: check we have any prefixes.
218 if ( interwikiPrefixes.length ) {
219 const interwiki = query.slice( 0, Math.max( 0, query.indexOf( ':' ) ) );
220 if (
221 interwiki !== '' &&
222 interwikiPrefixes.indexOf( interwiki ) !== -1
223 ) {
224 // Interwiki prefix is valid: return the original query as a valid title
225 // NB: This doesn't check if the title actually exists on the other wiki
226 return $.Deferred().resolve( { query: {
227 pages: [ {
228 title: query
229 } ]
230 } } ).promise( promiseAbortObject );
231 }
232 }
233 // Not a interwiki: do a prefix-search API lookup of the query.
234 const prefixSearchRequest = api.get( this.getApiParams( query ) );
235 promiseAbortObject.abort = prefixSearchRequest.abort.bind( prefixSearchRequest ); // TODO ew
236 return prefixSearchRequest.then( ( prefixSearchResponse ) => {
237 if ( !this.showMissing ) {
238 return prefixSearchResponse;
239 }
240 const title = this.namespace && this.getMWTitle( query );
241 // Add the query title as the first result, after looking up its details.
242 const queryTitleRequest = api.get( {
243 action: 'query',
244 titles: title ? title.getPrefixedDb() : query
245 } );
246 promiseAbortObject.abort = queryTitleRequest.abort.bind( queryTitleRequest );
247 return queryTitleRequest.then( ( queryTitleResponse ) => {
248 // By default, return the prefix-search result.
249 const result = prefixSearchResponse;
250 if ( prefixSearchResponse.query === undefined ) {
251 // There are no prefix-search results, so make the only result the query title.
252 // The API response structures are identical because both API calls are action=query.
253 result.query = queryTitleResponse.query;
254 } else if ( queryTitleResponse.query.pages && queryTitleResponse.query.pages[ -1 ] !== undefined &&
255 !this.responseContainsNonExistingTitle( prefixSearchResponse, queryTitleResponse.query.pages[ -1 ].title )
256 ) {
257 // There are prefix-search results, but the query title isn't in them,
258 // so add it as a new result. It's under the new key 'queryTitle', because
259 // all other results will be under their page ID or a negative integer ID,
260 // and the keys aren't actually used for anything.
261 result.query.pages.queryTitle = queryTitleResponse.query.pages[ -1 ];
262 // Give it the lowest possible sort-index (the API only returns index > 0)
263 // to make this result be sorted at the top.
264 result.query.pages.queryTitle.index = 0;
265 }
266 return result;
267 } );
268 } );
269 } ).promise( promiseAbortObject );
270 };
271
272 /**
273 * Check for the existence of a given title in an API result set.
274 *
275 * As the title is known not to exist, this doesn't check in apiResponse.query.pages,
276 * but only in the redirect targets in apiResponse.query.redirects.
277 *
278 * @private
279 * @param {Object} apiResponse The API result set to search in.
280 * @param {string} title The page title to search for.
281 * @return {boolean}
282 */
283 mw.widgets.TitleWidget.prototype.responseContainsNonExistingTitle = function ( apiResponse, title ) {
284 // Make sure there are redirects in the data.
285 if ( apiResponse.query.redirects === undefined ) {
286 return false;
287 }
288 // Check the targets against the given title.
289 for ( const redirect in apiResponse.query.redirects ) {
290 if ( apiResponse.query.redirects[ redirect ].to === title ) {
291 return true;
292 }
293 }
294 // The title wasn't found.
295 return false;
296 };
297
298 /**
299 * Get API params for a given query.
300 *
301 * @param {string} query User query
302 * @return {Object} API params
303 */
304 mw.widgets.TitleWidget.prototype.getApiParams = function ( query ) {
305 const params = {
306 action: 'query',
307 prop: [ 'info', 'pageprops' ],
308 generator: 'prefixsearch',
309 gpssearch: query,
310 gpsnamespace: this.namespace !== null ? this.namespace : undefined,
311 gpslimit: this.limit,
312 ppprop: 'disambiguation'
313 };
314 if ( this.showRedirectTargets ) {
315 params.redirects = true;
316 }
317 if ( this.showImages ) {
318 params.prop.push( 'pageimages' );
319 params.pithumbsize = 80;
320 params.pilimit = this.limit;
321 }
322 if ( this.showDescriptions ) {
323 params.prop.push( 'description' );
324 }
325 return params;
326 };
327
328 /**
329 * Get the API object for title requests.
330 *
331 * @return {mw.Api} MediaWiki API
332 */
333 mw.widgets.TitleWidget.prototype.getApi = function () {
334 return this.api;
335 };
336
337 /**
338 * Get option widgets from the server response.
339 *
340 * @param {Object} data Query result
341 * @return {OO.ui.OptionWidget[]} Menu items
342 */
343 mw.widgets.TitleWidget.prototype.getOptionsFromData = function ( data ) {
344 const currentPageName = new mw.Title( mw.config.get( 'wgRelevantPageName' ) ).getPrefixedText(),
345 items = [],
346 titles = [],
347 disambigs = [],
348 titleObj = mw.Title.newFromText( this.getQueryValue() ),
349 redirectsTo = {},
350 redirectIndices = {},
351 pageData = {};
352
353 if ( data.redirects ) {
354 for ( let r = 0, rLen = data.redirects.length; r < rLen; r++ ) {
355 const redirect = data.redirects[ r ];
356 redirectsTo[ redirect.to ] = redirectsTo[ redirect.to ] || [];
357 redirectsTo[ redirect.to ].push( redirect.from );
358 // Save the lowest index for this redirect target.
359 redirectIndices[ redirect.to ] = Math.min( redirectIndices[ redirect.to ] || redirect.index, redirect.index );
360 }
361 }
362
363 for ( const index in data.pages ) {
364 const suggestionPage = data.pages[ index ];
365
366 // When excludeCurrentPage is set, don't list the current page unless the user has type the full title
367 if ( this.excludeCurrentPage && suggestionPage.title === currentPageName && suggestionPage.title !== titleObj.getPrefixedText() ) {
368 continue;
369 }
370
371 // When excludeDynamicNamespaces is set, ignore all pages with negative namespace
372 if ( this.excludeDynamicNamespaces && suggestionPage.ns < 0 ) {
373 continue;
374 }
375 pageData[ suggestionPage.title ] = {
376 known: suggestionPage.known !== undefined,
377 missing: suggestionPage.missing !== undefined,
378 redirect: suggestionPage.redirect !== undefined,
379 disambiguation: OO.getProp( suggestionPage, 'pageprops', 'disambiguation' ) !== undefined,
380 imageUrl: OO.getProp( suggestionPage, 'thumbnail', 'source' ),
381 description: suggestionPage.description,
382 // Sort index
383 index: suggestionPage.index !== undefined ? suggestionPage.index : redirectIndices[ suggestionPage.title ],
384 originalData: suggestionPage
385 };
386
387 // Throw away pages from wrong namespaces. This can happen when 'showRedirectTargets' is true
388 // and we encounter a cross-namespace redirect.
389 if ( this.namespace === null || this.namespace === suggestionPage.ns ) {
390 titles.push( suggestionPage.title );
391 }
392
393 const redirects = hasOwn.call( redirectsTo, suggestionPage.title ) ? redirectsTo[ suggestionPage.title ] : [];
394 for ( let i = 0, iLen = redirects.length; i < iLen; i++ ) {
395 pageData[ redirects[ i ] ] = {
396 missing: false,
397 known: true,
398 redirect: true,
399 disambiguation: false,
400 description: mw.msg( 'mw-widgets-titleinput-description-redirect', suggestionPage.title ),
401 // Sort index, just below its target
402 index: pageData[ suggestionPage.title ].index + 0.5,
403 originalData: suggestionPage
404 };
405 titles.push( redirects[ i ] );
406 }
407 }
408
409 titles.sort( ( a, b ) => pageData[ a ].index - pageData[ b ].index );
410
411 // If not found, run value through mw.Title to avoid treating a match as a
412 // mismatch where normalisation would make them matching (T50476)
413
414 const pageExistsExact = (
415 hasOwn.call( pageData, this.getQueryValue() ) &&
416 (
417 !pageData[ this.getQueryValue() ].missing ||
418 pageData[ this.getQueryValue() ].known
419 )
420 );
421 const pageExists = pageExistsExact || (
422 titleObj &&
423 hasOwn.call( pageData, titleObj.getPrefixedText() ) &&
424 (
425 !pageData[ titleObj.getPrefixedText() ].missing ||
426 pageData[ titleObj.getPrefixedText() ].known
427 )
428 );
429
430 // Offer the exact text as a suggestion if the page exists
431 if ( this.addQueryInput && pageExists && !pageExistsExact ) {
432 titles.unshift( this.getQueryValue() );
433 // Ensure correct page metadata gets used
434 pageData[ this.getQueryValue() ] = pageData[ titleObj.getPrefixedText() ];
435 }
436
437 if ( this.cache ) {
438 this.cache.set( pageData );
439 }
440
441 for ( let t = 0, tLen = titles.length; t < tLen; t++ ) {
442 const page = hasOwn.call( pageData, titles[ t ] ) ? pageData[ titles[ t ] ] : {};
443 const option = this.createOptionWidget( this.getOptionWidgetData( titles[ t ], page ) );
444
445 if ( this.showDisambigsLast && page.disambiguation ) {
446 disambigs.push( option );
447 } else {
448 items.push( option );
449 }
450 }
451
452 return items.concat( disambigs );
453 };
454
455 /**
456 * Create a menu option widget with specified data.
457 *
458 * @param {Object} data Data for option widget
459 * @return {OO.ui.MenuOptionWidget} Data for option widget
460 */
461 mw.widgets.TitleWidget.prototype.createOptionWidget = function ( data ) {
462 return new mw.widgets.TitleOptionWidget( data );
463 };
464
465 /**
466 * Get menu option widget data from the title and page data.
467 *
468 * @param {string} title Title object
469 * @param {Object} data Page data
470 * @return {Object} Data for option widget
471 */
472 mw.widgets.TitleWidget.prototype.getOptionWidgetData = function ( title, data ) {
473 let description = data.description;
474 if ( !description && ( data.missing && !data.known ) ) {
475 description = mw.msg( 'mw-widgets-titleinput-description-new-page' );
476 }
477 const mwTitle = new mw.Title( OO.getProp( data, 'originalData', 'normalizedTitle' ) || title );
478 return {
479 data: this.namespace !== null && this.relative ?
480 mwTitle.getRelativeText( this.namespace ) :
481 title,
482 url: mwTitle.getUrl(),
483 showImages: this.showImages,
484 imageUrl: this.showImages ? data.imageUrl : null,
485 description: this.showDescriptions ? description : null,
486 missing: data.missing && !data.known,
487 redirect: data.redirect,
488 disambiguation: data.disambiguation,
489 query: this.highlightSearchQuery ? this.getQueryValue() : null,
490 compare: this.compare
491 };
492 };
493
494 /**
495 * Get title object corresponding to given value, or #getQueryValue if not given.
496 *
497 * @param {string} [value] Value to get a title for
498 * @return {mw.Title|null} Title object, or null if value is invalid
499 */
500 mw.widgets.TitleWidget.prototype.getMWTitle = function ( value ) {
501 const title = value !== undefined ? value : this.getQueryValue(),
502 // mw.Title doesn't handle null well
503 titleObj = mw.Title.newFromText( title, this.namespace !== null ? this.namespace : undefined );
504
505 return titleObj;
506 };
507
508 /**
509 * Check if the query is valid.
510 *
511 * @return {boolean} The query is valid
512 */
513 mw.widgets.TitleWidget.prototype.isQueryValid = function () {
514 if ( !this.validateTitle ) {
515 return true;
516 }
517 if ( !this.required && this.getQueryValue() === '' ) {
518 return true;
519 }
520 return !!this.getMWTitle();
521 };
522
523 }() );