Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/ui/widgets/ve.ui.MWTemplateTitleInputWidget.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface MWTemplateTitleInputWidget class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Input field for entering a template title, for example when adding a template
10 * in the template dialog. Autocomplete fetches TemplateData and performs
11 * searching in the background, to display information about matching templates
12 * on the wiki.
13 *
14 * @class
15 * @extends mw.widgets.TitleInputWidget
16 *
17 * @constructor
18 * @param {Object} [config] Configuration options
19 * @param {number} [config.namespace] Namespace to prepend to queries. Defaults to template namespace.
20 * @param {boolean} [config.showDescriptions] Show template descriptions from the TemplateData API
21 * @param {mw.Api} [config.api]
22 */
23 ve.ui.MWTemplateTitleInputWidget = function VeUiMWTemplateTitleInputWidget( config ) {
24 config = ve.extendObject( {}, {
25 namespace: mw.config.get( 'wgNamespaceIds' ).template,
26 showMissing: false,
27 // We don't need results to show up twice normalized and unnormalized
28 addQueryInput: false,
29 icon: 'search',
30 placeholder: ve.msg( 'visualeditor-dialog-transclusion-placeholder-input-placeholder' )
31 }, config );
32
33 // Parent constructor
34 ve.ui.MWTemplateTitleInputWidget.super.call( this, config );
35 // All code below expects this, but ContentTranslation doesn't necessarily set it to 2
36 this.api.defaults.parameters.formatversion = 2;
37
38 this.showTemplateDescriptions = this.showDescriptions;
39 // Clear the showDescriptions flag for subsequent requests as we implement
40 // description fetch ourselves
41 this.showDescriptions = false;
42
43 // Properties
44 this.descriptions = {};
45
46 // Initialization
47 this.$element.addClass( 've-ui-mwTemplateTitleInputWidget' );
48 };
49
50 /* Inheritance */
51
52 // FIXME: This should extend mw.widgets.TitleSearchWidget instead
53 OO.inheritClass( ve.ui.MWTemplateTitleInputWidget, mw.widgets.TitleInputWidget );
54
55 /* Methods */
56
57 // @inheritdoc mw.widgets.TitleWidget
58 ve.ui.MWTemplateTitleInputWidget.prototype.getApiParams = function ( query ) {
59 const params = ve.ui.MWTemplateTitleInputWidget.super.prototype.getApiParams.call( this, query );
60
61 // TODO: This should stay as a feature flag for 3rd-parties to fallback to prefixsearch
62 if ( mw.config.get( 'wgVisualEditorConfig' ).cirrusSearchLookup ) {
63 ve.extendObject( params, {
64 generator: 'search',
65 gsrsearch: params.gpssearch,
66 gsrnamespace: params.gpsnamespace,
67 gsrlimit: params.gpslimit
68 } );
69 // Adding the asterisk to emulate a prefix search behavior. It does not make sense in all
70 // cases though. We're limiting it to be add only of the term ends with a letter or numeric
71 // character.
72 // eslint-disable-next-line es-x/no-regexp-unicode-property-escapes, prefer-regex-literals
73 const endsWithAlpha = new RegExp( '[\\p{L}\\p{N}]$', 'u' );
74 if ( endsWithAlpha.test( params.gsrsearch ) ) {
75 params.gsrsearch += '*';
76 }
77 if ( this.showRedirectTargets ) {
78 params.gsrprop = 'redirecttitle';
79 }
80 delete params.gpssearch;
81 delete params.gpsnamespace;
82 delete params.gpslimit;
83 }
84 return params;
85 };
86
87 // @inheritdoc mw.widgets.TitleInputWidget
88 ve.ui.MWTemplateTitleInputWidget.prototype.getLookupRequest = function () {
89 let promise = ve.ui.MWTemplateTitleInputWidget.super.prototype.getLookupRequest.call( this );
90 if ( mw.config.get( 'wgVisualEditorConfig' ).cirrusSearchLookup ) {
91 promise = promise
92 .then( this.addExactMatch.bind( this ) )
93 .promise( { abort: () => {} } );
94 }
95
96 if ( !this.showTemplateDescriptions ) {
97 return promise;
98 }
99
100 const templateDataMessage = mw.message( 'templatedata-doc-subpage' ),
101 templateDataInstalled = templateDataMessage.exists(),
102 templateDocPageFragment = '/' + templateDataMessage.text();
103
104 let originalResponse;
105 return promise
106 .then( ( response ) => {
107 const redirects = ( response.query && response.query.redirects ) || [];
108 let newPages = ( response.query && response.query.pages ) || [];
109
110 newPages.forEach( ( page ) => {
111 if ( !( 'index' in page ) ) {
112 // Watch out for cases where the index is specified on the redirect object
113 // rather than the page object.
114 for ( const j in redirects ) {
115 if ( redirects[ j ].to === page.title ) {
116 page.index = redirects[ j ].index;
117 break;
118 }
119 }
120 }
121 } );
122
123 // T54448: Filter out matches which end in /doc or as configured on-wiki
124 if ( templateDataInstalled ) {
125 newPages = newPages.filter(
126 // Can't use String.endsWith() as that's ES6.
127 // page.title.endsWith( templateDocPageFragment )
128 ( page ) => page.title.slice( -templateDocPageFragment.length ) !== templateDocPageFragment
129 );
130 }
131
132 // Ensure everything goes into the order defined by the page's index key
133 newPages.sort( ( a, b ) => {
134 // T366299: Avoid unstable sort.
135 if ( a.index === undefined || b.index === undefined ) {
136 return 0;
137 }
138 return a.index - b.index;
139 } );
140
141 const titles = newPages.map( ( page ) => page.title );
142
143 ve.setProp( response, 'query', 'pages', newPages );
144 originalResponse = response; // lie!
145
146 // Also get descriptions
147 // FIXME: This should go through MWTransclusionModel rather than duplicate.
148 if ( titles.length > 0 ) {
149 const xhr = this.getApi().get( {
150 action: 'templatedata',
151 titles: titles,
152 redirects: !!this.showRedirects,
153 includeMissingTitles: '1',
154 lang: mw.config.get( 'wgUserLanguage' )
155 } );
156 return xhr.promise( { abort: xhr.abort } );
157 }
158 } )
159 .then( ( templateDataResponse ) => {
160 const pages = ( templateDataResponse && templateDataResponse.pages ) || {};
161 // Look for descriptions and cache them
162 for ( const i in pages ) {
163 const page = pages[ i ];
164
165 if ( page.missing ) {
166 // Remember templates that don't exist in the link cache
167 // { title: { missing: true|false }
168 const missingTitle = {};
169 missingTitle[ page.title ] = { missing: true };
170 ve.init.platform.linkCache.setMissing( missingTitle );
171 } else if ( !page.notemplatedata ) {
172 // Cache descriptions
173 this.descriptions[ page.title ] = page.description;
174 }
175 }
176 // Return the original response
177 return originalResponse;
178 // API request failed; most likely, we're on a wiki which doesn't have TemplateData.
179 }, () => originalResponse || ve.createDeferred().reject() )
180 .promise( { abort: () => {} } );
181 };
182
183 /**
184 * @private
185 * @method
186 * @param {Object} response Action API response from server
187 * @return {Object} Modified response
188 */
189 ve.ui.MWTemplateTitleInputWidget.prototype.addExactMatch = function ( response ) {
190 const query = this.getQueryValue(),
191 title = mw.Title.newFromText( query, this.namespace );
192 // No point in trying anything when the title is invalid
193 if ( !title ) {
194 return response;
195 }
196
197 if ( !response.query ) {
198 response.query = { pages: [] };
199 }
200
201 const lowerTitle = title.getPrefixedText().toLowerCase(),
202 metadata = response.query.redirects || [],
203 foundMatchingMetadata = metadata.some( ( redirect ) => redirect.from.toLowerCase() === lowerTitle );
204 if ( foundMatchingMetadata ) {
205 // Redirects will be carefully positioned later in TitleWidget.getOptionsFromData()
206 return response;
207 }
208
209 /**
210 * @typedef {Object} PageResponse
211 * @memberof ve.ui.MWTemplateTitleInputWidget
212 * @param {number} pageId Page ID
213 * @param {number} index Page ID
214 */
215
216 /**
217 * @param {ve.ui.MWTemplateTitleInputWidget.PageResponse[]} pages
218 * @param {number} pageId
219 * @return {boolean}
220 */
221 const containsPageId = ( pages, pageId ) => pageId && pages.some( ( page ) => page.pageid === pageId );
222
223 /**
224 * @param {ve.ui.MWTemplateTitleInputWidget.PageResponse[]} pages
225 * @param {Object} [newPage]
226 */
227 const unshiftPages = ( pages, newPage ) => {
228 pages.forEach( ( page ) => {
229 page.index++;
230 } );
231 if ( newPage && newPage.title ) {
232 newPage.index = 1;
233 pages.unshift( newPage );
234 if ( pages.length > this.limit ) {
235 pages.sort( ( a, b ) => a.index - b.index ).splice( this.limit );
236 }
237 }
238 };
239
240 const matchingRedirects = response.query.pages.filter( ( page ) => page.redirecttitle && page.redirecttitle.toLowerCase() === lowerTitle );
241 if ( matchingRedirects.length ) {
242 for ( let i = matchingRedirects.length; i--; ) {
243 const matchingRedirect = matchingRedirects[ i ];
244 // Offer redirects as separate options when the user's input is an exact match
245 unshiftPages( response.query.pages, {
246 pageid: matchingRedirect.pageid,
247 ns: matchingRedirect.ns,
248 title: matchingRedirect.redirecttitle
249 } );
250 }
251 return response;
252 }
253
254 const matchingTitles = response.query.pages.filter( ( page ) => page.title.toLowerCase() === lowerTitle );
255 if ( matchingTitles.length ) {
256 for ( let i = matchingTitles.length; i--; ) {
257 // Make sure exact matches are at the very top
258 unshiftPages( response.query.pages );
259 matchingTitles[ i ].index = 1;
260 }
261 return response;
262 }
263
264 return this.getApi().get( {
265 action: 'query',
266 // Can't use a direct lookup by title because we need this to be case-insensitive
267 generator: 'prefixsearch',
268 gpssearch: query,
269 gpsnamespace: this.namespace,
270 // Try to fill with prefix matches, otherwise just the top-1 prefix match
271 gpslimit: this.limit
272 } ).then( ( prefixMatches ) => {
273 // action=query returns page objects in `{ query: { pages: [] } }`, not keyed by page id
274 const pages = prefixMatches.query && prefixMatches.query.pages || [];
275 pages.sort( ( a, b ) => a.index - b.index );
276 for ( const i in pages ) {
277 const prefixMatch = pages[ i ];
278 if ( !containsPageId( response.query.pages, prefixMatch.pageid ) ) {
279 // Move prefix matches to the top, indexed from -9 to 0, relevant for e.g. {{!!}}
280 // Note: Sorting happens later in mw.widgets.TitleWidget.getOptionsFromData()
281 prefixMatch.index -= this.limit;
282 response.query.pages.push( prefixMatch );
283 }
284 // Check only after the top-1 prefix match is guaranteed to be present
285 if ( response.query.pages.length >= this.limit ) {
286 break;
287 }
288 }
289 return response;
290 // Proceed with the unmodified response in case the additional API request failed
291 }, () => response )
292 .promise( { abort: () => {} } );
293 };
294
295 // @inheritdoc mw.widgets.TitleWidget
296 ve.ui.MWTemplateTitleInputWidget.prototype.getOptionWidgetData = function ( title, data ) {
297 return ve.extendObject(
298 ve.ui.MWTemplateTitleInputWidget.super.prototype.getOptionWidgetData.apply( this, arguments ),
299 {
300 description: this.descriptions[ title ],
301 redirecttitle: data.originalData.redirecttitle
302 }
303 );
304 };
305
306 // @inheritdoc mw.widgets.TitleWidget
307 ve.ui.MWTemplateTitleInputWidget.prototype.createOptionWidget = function ( data ) {
308 const widget = ve.ui.MWTemplateTitleInputWidget.super.prototype.createOptionWidget.call( this, data );
309
310 if ( data.redirecttitle ) {
311 // Same conditions as in mw.widgets.TitleWidget.getOptionWidgetData()
312 const title = new mw.Title( data.redirecttitle ),
313 text = this.namespace !== null && this.relative ?
314 title.getRelativeText( this.namespace ) :
315 data.redirecttitle;
316
317 let $desc = widget.$element.find( '.mw-widget-titleOptionWidget-description' );
318 if ( !$desc.length ) {
319 $desc = $( '<span>' )
320 .addClass( 'mw-widget-titleOptionWidget-description' )
321 .appendTo( widget.$element );
322 }
323 $desc.prepend( $( '<div>' )
324 .addClass( 've-ui-mwTemplateTitleInputWidget-redirectedfrom' )
325 .text( mw.msg( 'redirectedfrom', text ) ) );
326 }
327
328 return widget;
329 };