Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/preinit/ve.init.mw.ArticleTargetLoader.js

raw symbols SCIP
1 /*!
2 * VisualEditor MediaWiki ArticleTargetLoader.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 // TODO: ve.now and ve.track should be moved to mw.libs.ve
9 /* global ve */
10
11 /**
12 * Target loader.
13 *
14 * Light-weight loader that loads ResourceLoader modules for VisualEditor
15 * and HTML and page data from the API. Also handles plugin registration.
16 *
17 * @class mw.libs.ve.targetLoader
18 * @singleton
19 * @hideconstructor
20 */
21 ( function () {
22 const conf = mw.config.get( 'wgVisualEditorConfig' ),
23 pluginCallbacks = [],
24 modules = [
25 'ext.visualEditor.articleTarget',
26 // Add modules from $wgVisualEditorPluginModules
27 ...conf.pluginModules.filter( mw.loader.getState )
28 ];
29
30 const url = new URL( location.href );
31 // Provide the new wikitext editor
32 if (
33 mw.user.options.get( 'visualeditor-newwikitext' ) ||
34 url.searchParams.get( 'veaction' ) === 'editsource'
35 ) {
36 modules.push( 'ext.visualEditor.mwwikitext' );
37 }
38
39 // A/B test enrollment for edit check (T342930)
40 if ( conf.editCheckABTest ) {
41 let inABTest;
42 if ( mw.user.isAnon() ) {
43 // can't just use mw.user.sessionId() because we need this to last across sessions
44 const token = mw.cookie.get( 'VEECid', '', mw.user.generateRandomSessionId() );
45 // Store the token so our state is consistent across pages
46 mw.cookie.set( 'VEECid', token, { path: '/', expires: 90 * 86400, prefix: '' } );
47 inABTest = parseInt( token.slice( 0, 8 ), 16 ) % 2 === 1;
48 } else {
49 inABTest = mw.user.getId() % 2 === 1;
50 }
51 conf.editCheck = inABTest;
52 // Communicate the bucket to instrumentation:
53 mw.config.set( 'wgVisualEditorEditCheckABTestBucket', '2024-02-editcheck-reference-' + ( inABTest ? 'test' : 'control' ) );
54 }
55
56 const editCheck = conf.editCheck || !!url.searchParams.get( 'ecenable' ) || !!window.MWVE_FORCE_EDIT_CHECK_ENABLED;
57 if ( conf.editCheckTagging || editCheck ) {
58 modules.push( 'ext.visualEditor.editCheck' );
59 }
60
61 const namespaces = mw.config.get( 'wgNamespaceIds' );
62 // Load signature tool if *any* namespace supports it.
63 // It will be shown disabled on namespaces that don't support it.
64 if (
65 Object.keys( namespaces ).some( ( name ) => mw.Title.wantSignaturesNamespace( namespaces[ name ] ) )
66 ) {
67 modules.push( 'ext.visualEditor.mwsignature' );
68 }
69
70 mw.libs.ve = mw.libs.ve || {};
71
72 mw.libs.ve.targetLoader = {
73 /**
74 * Add a plugin module or callback.
75 *
76 * If a module name is passed, that module will be loaded alongside the other modules.
77 *
78 * If a callback is passed, it will be executed after the modules have loaded. The callback
79 * may optionally return a jQuery.Promise; if it does, loading won't be complete until
80 * that promise is resolved.
81 *
82 * @param {string|Function} plugin Plugin module name or callback
83 */
84 addPlugin: function ( plugin ) {
85 if ( typeof plugin === 'string' ) {
86 modules.push( plugin );
87 } else {
88 pluginCallbacks.push( plugin );
89 }
90 },
91
92 /**
93 * Load modules needed for VisualEditor, as well as plugins.
94 *
95 * This loads the base VE modules as well as any registered plugin modules.
96 * Once those are loaded, any registered plugin callbacks are executed,
97 * and we wait for all promises returned by those callbacks to resolve.
98 *
99 * @param {string} mode Initial editor mode, for tracking
100 * @return {jQuery.Promise} Promise resolved when the loading process is complete
101 */
102 loadModules: function ( mode ) {
103 mw.hook( 've.loadModules' ).fire( this.addPlugin.bind( this ) );
104 ve.track( 'trace.moduleLoad.enter', { mode: mode } );
105 return mw.loader.using( modules )
106 .then( () => {
107 ve.track( 'trace.moduleLoad.exit', { mode: mode } );
108 pluginCallbacks.push( ve.init.platform.getInitializedPromise.bind( ve.init.platform ) );
109 // Execute plugin callbacks and collect promises
110 return $.when.apply( $, pluginCallbacks.map( ( callback ) => {
111 try {
112 return callback();
113 } catch ( e ) {
114 mw.log.warn( 'Failed to load VE plugin:', e );
115 return null;
116 }
117 } ) );
118 } );
119 },
120
121 /**
122 * Creates an OOUI checkbox inside an inline field layout
123 *
124 * @param {Object[]} checkboxesDef Checkbox definitions from the API
125 * @param {Object} [widgetConfig] Additional widget config
126 * @return {Object} Result object with checkboxFields (OO.ui.FieldLayout[]) and
127 * checkboxesByName (keyed object of OO.ui.CheckboxInputWidget).
128 */
129 createCheckboxFields: function ( checkboxesDef, widgetConfig ) {
130 const checkboxFields = [],
131 checkboxesByName = {};
132
133 if ( checkboxesDef ) {
134 Object.keys( checkboxesDef ).forEach( ( name ) => {
135 const options = checkboxesDef[ name ];
136 let accesskey = null,
137 title = null;
138
139 // The messages documented below are just the ones defined in core.
140 // Extensions may add other checkboxes.
141 if ( options.tooltip ) {
142 // The following messages are used here:
143 // * accesskey-minoredit
144 // * accesskey-watch
145 accesskey = mw.message( 'accesskey-' + options.tooltip ).text();
146 // The following messages are used here:
147 // * tooltip-minoredit
148 // * tooltip-watch
149 title = mw.message( 'tooltip-' + options.tooltip ).text();
150 }
151 if ( options[ 'title-message' ] ) {
152 // Not used in core
153 // eslint-disable-next-line mediawiki/msg-doc
154 title = mw.message( options[ 'title-message' ] ).text();
155 }
156 // The following messages are used here:
157 // * minoredit
158 // * watchthis
159 const $label = mw.message( options[ 'label-message' ] ).parseDom();
160
161 const config = $.extend( {
162 accessKey: accesskey,
163 // The following classes are used here:
164 // * ve-ui-mwSaveDialog-checkbox-wpMinoredit
165 // * ve-ui-mwSaveDialog-checkbox-wpWatchthis
166 // * ve-ui-mwSaveDialog-checkbox-wpWatchlistExpiry
167 classes: [ 've-ui-mwSaveDialog-checkbox-' + name ]
168 }, widgetConfig );
169
170 let checkbox;
171 switch ( options.class ) {
172 case 'OOUI\\DropdownInputWidget':
173 checkbox = new OO.ui.DropdownInputWidget( $.extend( config, {
174 value: options.default,
175 options: options.options
176 } ) );
177 break;
178
179 default:
180 checkbox = new OO.ui.CheckboxInputWidget( $.extend( config, {
181 selected: options.default
182 } ) );
183 break;
184 }
185
186 checkboxFields.push(
187 new OO.ui.FieldLayout( checkbox, {
188 align: 'inline',
189 label: $label,
190 title: title,
191 invisibleLabel: !!options.invisibleLabel,
192 // * ve-ui-mwSaveDialog-field-wpMinoredit
193 // * ve-ui-mwSaveDialog-field-wpWatchthis
194 // * ve-ui-mwSaveDialog-field-wpWatchlistExpiry
195 classes: [ 've-ui-mwSaveDialog-field-' + name ]
196 } )
197 );
198 checkboxesByName[ name ] = checkbox;
199 } );
200 }
201 return {
202 checkboxFields: checkboxFields,
203 checkboxesByName: checkboxesByName
204 };
205 },
206
207 /**
208 * Request the page data and various metadata from the MediaWiki API (which will use
209 * Parsoid or RESTBase).
210 *
211 * @param {string} mode Target mode: 'visual' or 'source'
212 * @param {string} pageName Page name to request, in prefixed DB key form (underscores instead of spaces)
213 * @param {Object} [options]
214 * @param {boolean} [options.sessionStore] Store result in session storage (by page+mode+section) for auto-save
215 * @param {null|string} [options.section] Section to edit; number, 'T-'-prefixed, null or 'new' (currently just source mode)
216 * @param {number} [options.oldId] Old revision ID. Current if omitted.
217 * @param {string} [options.targetName] Optional target name for tracking
218 * @param {boolean} [options.modified] The page has been modified before loading (e.g. in source mode)
219 * @param {string} [options.wikitext] Wikitext to convert to HTML. The original document is fetched if undefined.
220 * @param {string} [options.editintro] Name of a page to use as edit intro message
221 * @param {string} [options.preload] Name of a page to use as preloaded content if pageName is empty
222 * @param {string[]} [options.preloadparams] Parameters to substitute into preload if it's used
223 * @return {jQuery.Promise} Abortable promise resolved with a JSON object
224 */
225 requestPageData: function ( mode, pageName, options ) {
226 options = options || {};
227 const apiRequest = mode === 'source' ?
228 this.requestWikitext.bind( this, pageName, options ) :
229 this.requestParsoidData.bind( this, pageName, options );
230
231 if ( options.sessionStore ) {
232 let sessionState;
233 try {
234 // ve.init.platform.getSessionObject is not available yet
235 sessionState = JSON.parse( mw.storage.session.get( 've-docstate' ) );
236 } catch ( e ) {}
237
238 if ( sessionState ) {
239 const request = sessionState.request || {};
240 // Check true section editing is in use
241 const enableVisualSectionEditing = conf.enableVisualSectionEditing;
242 const section = request.mode === 'source' || enableVisualSectionEditing === true || enableVisualSectionEditing === options.targetName ?
243 options.section : null;
244 // Check the requested page, mode and section match the stored one
245 if (
246 request.pageName === pageName &&
247 request.mode === mode &&
248 request.section === section
249 // NB we don't cache by oldid so that cached results can be recovered
250 // even if the page has been since edited
251 ) {
252 const dataPromise = $.Deferred().resolve( {
253 visualeditor: $.extend(
254 { content: mw.storage.session.get( 've-dochtml' ) },
255 sessionState.response,
256 { recovered: true }
257 )
258 } ).promise();
259 // If the document hasn't been edited since the user first loaded it, recover
260 // their changes automatically.
261 if ( sessionState.response.oldid === mw.config.get( 'wgCurRevisionId' ) ) {
262 return dataPromise;
263 } else {
264 // Otherwise, prompt them if they want to recover, or reload the document
265 // to see the latest version
266 // This prompt will throw off all of our timing data, so just disable tracking
267 // for this session
268 ve.track = function () {};
269 return mw.loader.using( 'oojs-ui-windows' ).then( () => OO.ui.confirm( mw.msg( 'visualeditor-autosave-modified-prompt-message' ), {
270 title: mw.msg( 'visualeditor-autosave-modified-prompt-title' ),
271 actions: [
272 { action: 'accept', label: mw.msg( 'visualeditor-autosave-modified-prompt-accept' ), flags: [ 'primary', 'progressive' ] },
273 { action: 'reject', label: mw.msg( 'visualeditor-autosave-modified-prompt-reject' ), flags: 'destructive' }
274 ] }
275 ).then( ( confirmed ) => {
276 if ( confirmed ) {
277 return dataPromise;
278 } else {
279 // If they requested the latest version, invalidate the autosave state
280 mw.storage.session.remove( 've-docstate' );
281 return apiRequest();
282 }
283 } ) );
284 }
285 }
286 }
287 }
288
289 return apiRequest();
290 },
291
292 /**
293 * Request the page HTML and various metadata from the MediaWiki API (which will use
294 * Parsoid or RESTBase).
295 *
296 * @param {string} pageName See #requestPageData
297 * @param {Object} [options] See #requestPageData
298 * @param {boolean} [noRestbase=false] Don't query RESTBase directly
299 * @param {boolean} [noMetadata=false] Don't fetch document metadata when querying RESTBase. Metadata
300 * is not required for some use cases, e.g. diffing.
301 * @return {jQuery.Promise} Abortable promise resolved with a JSON object
302 */
303 requestParsoidData: function ( pageName, options, noRestbase, noMetadata ) {
304 const section = options.section !== undefined ? options.section : null,
305 useRestbase = !noRestbase && ( conf.fullRestbaseUrl || conf.restbaseUrl ) && section === null;
306
307 options = options || {};
308 const data = {
309 action: 'visualeditor',
310 paction: useRestbase ? 'metadata' : 'parse',
311 page: pageName,
312 badetag: options.badetag,
313 uselang: mw.config.get( 'wgUserLanguage' ),
314 editintro: options.editintro,
315 preload: options.preload,
316 preloadparams: options.preloadparams,
317 formatversion: 2
318 };
319
320 // Only request the API to explicitly load the currently visible revision if we're restoring
321 // from oldid. Otherwise we should load the latest version. This prevents us from editing an
322 // old version if an edit was made while the user was viewing the page and/or the user is
323 // seeing (slightly) stale cache.
324 if ( options.oldId !== undefined ) {
325 data.oldid = options.oldId;
326 }
327 // Load DOM
328 const start = ve.now();
329 ve.track( 'trace.apiLoad.enter', { mode: 'visual' } );
330
331 let apiXhr, apiPromise;
332 let switched = false,
333 fromEditedState = false;
334 if ( !useRestbase && options.wikitext !== undefined ) {
335 // Non-RESTBase custom wikitext parse
336 data.paction = 'parse';
337 data.stash = true;
338 switched = true;
339 fromEditedState = options.modified;
340 data.wikitext = options.wikitext;
341 data.section = options.section;
342 data.oldid = options.oldId;
343 apiXhr = new mw.Api().post( data );
344 } else {
345 if ( useRestbase && noMetadata ) {
346 apiPromise = $.Deferred().resolve( { visualeditor: {} } ).promise();
347 } else {
348 apiXhr = new mw.Api().get( data );
349 }
350 }
351 if ( !apiPromise ) {
352 apiPromise = apiXhr.then( ( response ) => {
353 ve.track( 'trace.apiLoad.exit', { mode: 'visual' } );
354 mw.track( 'timing.ve.' + options.targetName + '.performance.system.apiLoad',
355 ve.now() - start );
356 if ( response.visualeditor ) {
357 response.visualeditor.switched = switched;
358 response.visualeditor.fromEditedState = fromEditedState;
359 }
360 return response;
361 } );
362 }
363
364 let dataPromise, abort;
365 if ( useRestbase ) {
366 ve.track( 'trace.restbaseLoad.enter', { mode: 'visual' } );
367
368 const headers = {
369 // Should be synchronised with DirectParsoidClient.php
370 Accept: 'text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/2.8.0"',
371 'Accept-Language': mw.config.get( 'wgVisualEditor' ).pageLanguageCode,
372 'Api-User-Agent': 'VisualEditor-MediaWiki/' + mw.config.get( 'wgVersion' )
373 };
374
375 let restbaseXhr, pageHtmlUrl;
376 // Convert specified Wikitext to HTML
377 if (
378 // wikitext can be an empty string
379 options.wikitext !== undefined &&
380 // eslint-disable-next-line no-jquery/no-global-selector
381 !$( '[name=wpSection]' ).val()
382 ) {
383 if ( conf.fullRestbaseUrl ) {
384 pageHtmlUrl = conf.fullRestbaseUrl + 'v1/transform/wikitext/to/html/';
385 } else {
386 pageHtmlUrl = conf.restbaseUrl.replace( 'v1/page/html/', 'v1/transform/wikitext/to/html/' );
387 }
388 switched = true;
389 fromEditedState = options.modified;
390 window.onbeforeunload = null;
391 $( window ).off( 'beforeunload' );
392 restbaseXhr = $.ajax( {
393 url: pageHtmlUrl + encodeURIComponent( pageName ) +
394 ( data.oldid === undefined ? '' : '/' + data.oldid ),
395 type: 'POST',
396 data: {
397 title: pageName,
398 wikitext: options.wikitext,
399 stash: 'true'
400 },
401 headers: headers,
402 dataType: 'text'
403 } );
404 } else {
405 // Fetch revision
406 if ( conf.fullRestbaseUrl ) {
407 pageHtmlUrl = conf.fullRestbaseUrl + 'v1/page/html/';
408 } else {
409 pageHtmlUrl = conf.restbaseUrl;
410 }
411 restbaseXhr = $.ajax( {
412 url: pageHtmlUrl + encodeURIComponent( pageName ) +
413 ( data.oldid === undefined ? '' : '/' + data.oldid ) +
414 '?redirect=false&stash=true',
415 type: 'GET',
416 headers: headers,
417 dataType: 'text'
418 } );
419 }
420 const restbasePromise = restbaseXhr.then(
421 ( response, status, jqxhr ) => {
422 ve.track( 'trace.restbaseLoad.exit', { mode: 'visual' } );
423 mw.track( 'timing.ve.' + options.targetName + '.performance.system.restbaseLoad',
424 ve.now() - start );
425 return [ response, jqxhr.getResponseHeader( 'etag' ) ];
426 },
427 ( xhr, code, _ ) => {
428 if ( xhr.status === 404 ) {
429 // Page does not exist, so let the user start with a blank document.
430 return $.Deferred().resolve( [ '', undefined ] ).promise();
431 } else {
432 mw.log.warn( 'RESTBase load failed: ' + xhr.statusText );
433 return $.Deferred().reject( code, xhr, _ ).promise();
434 }
435 }
436 );
437
438 dataPromise = $.when( apiPromise, restbasePromise )
439 .then( ( apiData, restbaseData ) => {
440 if ( apiData.visualeditor ) {
441 if ( restbaseData[ 0 ] || !apiData.visualeditor.content ) {
442 // If we have actual content loaded, use it.
443 // Otherwise, allow fallback content if present.
444 // If no fallback content, this will give us an empty string for
445 // content, which is desirable.
446 apiData.visualeditor.content = restbaseData[ 0 ];
447 apiData.visualeditor.etag = restbaseData[ 1 ];
448 }
449 apiData.visualeditor.switched = switched;
450 apiData.visualeditor.fromEditedState = fromEditedState;
451 }
452 return apiData;
453 } );
454 abort = function () {
455 if ( apiXhr ) {
456 apiXhr.abort();
457 }
458 restbaseXhr.abort();
459 };
460 } else {
461 dataPromise = apiPromise;
462 if ( apiXhr ) {
463 abort = apiXhr.abort;
464 }
465 }
466
467 return dataPromise.then( ( resp ) => {
468 // Adapted from RESTBase mwUtil.parseETag()
469 const etagRegexp = /^(?:W\/)?"?([^"/]+)(?:\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))(?:\/([^"]+))?"?$/;
470
471 // `etag` is expected to be undefined when creating a new page.
472 // We can detect that case by `content` being empty, and not retry.
473 if ( useRestbase && resp.visualeditor.content && (
474 !resp.visualeditor.etag ||
475 !etagRegexp.test( resp.visualeditor.etag )
476 ) ) {
477 // Direct request to RESTBase returned a mangled or missing etag.
478 // Retry via the MediaWiki API.
479 return mw.libs.ve.targetLoader.requestParsoidData(
480 pageName,
481 $.extend( {}, options, { badetag: resp.visualeditor.etag || '' } ),
482 true
483 );
484 }
485
486 resp.veMode = 'visual';
487 return resp;
488 } ).promise( { abort: abort } );
489 },
490
491 /**
492 * Request the page wikitext and various metadata from the MediaWiki API.
493 *
494 * @param {string} pageName See #requestPageData
495 * @param {Object} [options] See #requestPageData
496 * @return {jQuery.Promise} Abortable promise resolved with a JSON object
497 */
498 requestWikitext: function ( pageName, options ) {
499 options = options || {};
500 const data = {
501 action: 'visualeditor',
502 paction: 'wikitext',
503 page: pageName,
504 uselang: mw.config.get( 'wgUserLanguage' ),
505 editintro: options.editintro,
506 preload: options.preload,
507 preloadparams: options.preloadparams,
508 formatversion: 2
509 };
510
511 // section should never really be undefined, but check just in case
512 if ( options.section !== null && options.section !== undefined ) {
513 data.section = options.section;
514 }
515
516 if ( options.oldId !== undefined ) {
517 data.oldid = options.oldId;
518 }
519
520 const dataPromise = new mw.Api().get( data );
521 return dataPromise.then( ( resp ) => {
522 resp.veMode = 'source';
523 return resp;
524 } ).promise( { abort: dataPromise.abort } );
525 }
526 };
527 }() );