Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/init/targets/ve.init.mw.ArticleTarget.js

raw symbols SCIP
1 /*!
2 * VisualEditor MediaWiki Initialization ArticleTarget class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /* eslint-disable no-jquery/no-global-selector */
9
10 /**
11 * Initialization MediaWiki article target.
12 *
13 * @class
14 * @extends ve.init.mw.Target
15 *
16 * @constructor
17 * @param {Object} [config] Configuration options
18 * @param {Object} [config.toolbarConfig]
19 * @param {boolean} [config.register=true]
20 */
21 ve.init.mw.ArticleTarget = function VeInitMwArticleTarget( config ) {
22 config = config || {};
23 config.toolbarConfig = ve.extendObject( {
24 shadow: true,
25 actions: true,
26 floatable: true
27 }, config.toolbarConfig );
28
29 // Parent constructor
30 ve.init.mw.ArticleTarget.super.call( this, config );
31
32 // Register
33 if ( config.register !== false ) {
34 // ArticleTargets are never destroyed, but we can't trust ve.init.target to
35 // not get overridden by other targets that may get created on the page.
36 ve.init.articleTarget = this;
37 }
38
39 // Properties
40 this.saveDialog = null;
41 this.saveDeferred = null;
42 this.saveFields = {};
43 this.docToSave = null;
44 this.originalDmDocPromise = null;
45 this.originalHtml = null;
46 this.toolbarSaveButton = null;
47 this.pageExists = mw.config.get( 'wgRelevantArticleId', 0 ) !== 0;
48 const enableVisualSectionEditing = mw.config.get( 'wgVisualEditorConfig' ).enableVisualSectionEditing;
49 this.enableVisualSectionEditing = enableVisualSectionEditing === true || enableVisualSectionEditing === this.constructor.static.trackingName;
50 this.toolbarScrollOffset = mw.config.get( 'wgVisualEditorToolbarScrollOffset', 0 );
51 this.currentUrl = new URL( location.href );
52 this.section = null;
53 this.visibleSection = null;
54 this.visibleSectionOffset = null;
55 this.sectionTitle = null;
56 this.editSummaryValue = null;
57 this.initialEditSummary = null;
58 this.initialCheckboxes = {};
59
60 this.viewUrl = new URL( mw.util.getUrl( this.getPageName() ), location.href );
61 this.isViewPage = (
62 mw.config.get( 'wgAction' ) === 'view' &&
63 !this.currentUrl.searchParams.has( 'diff' )
64 );
65
66 this.copyrightWarning = null;
67 this.checkboxFields = null;
68 this.checkboxesByName = null;
69 this.$saveAccessKeyElements = null;
70
71 this.$editableContent = this.getEditableContent();
72
73 // Sometimes we actually don't want to send a useful oldid
74 // if we do, PostEdit will give us a 'page restored' message
75 // Use undefined instead of 0 for new documents (T262838)
76 this.requestedRevId = mw.config.get( 'wgEditLatestRevision' ) ? mw.config.get( 'wgCurRevisionId' ) : mw.config.get( 'wgRevisionId' ) || undefined;
77 this.currentRevisionId = mw.config.get( 'wgCurRevisionId' ) || undefined;
78 this.revid = this.requestedRevId || this.currentRevisionId;
79
80 this.edited = false;
81 this.restoring = !!this.requestedRevId && this.requestedRevId !== this.currentRevisionId;
82 this.pageDeletedWarning = false;
83 this.events = {
84 track: () => {},
85 trackActivationStart: () => {},
86 trackActivationComplete: () => {}
87 };
88
89 this.preparedCacheKeyPromise = null;
90 this.clearState();
91
92 // Initialization
93 this.$element.addClass( 've-init-mw-articleTarget' );
94 };
95
96 /* Inheritance */
97
98 OO.inheritClass( ve.init.mw.ArticleTarget, ve.init.mw.Target );
99
100 /* Events */
101
102 /**
103 * @event ve.init.mw.ArticleTarget#save
104 * @param {Object} data Save data from the API, see ve.init.mw.ArticleTarget#saveComplete
105 * Fired immediately after a save is successfully completed
106 */
107
108 /**
109 * @event ve.init.mw.ArticleTarget#savePreview
110 */
111
112 /**
113 * @event ve.init.mw.ArticleTarget#saveReview
114 */
115
116 /**
117 * @event ve.init.mw.ArticleTarget#saveInitiated
118 */
119
120 /**
121 * @event ve.init.mw.ArticleTarget#saveWorkflowBegin
122 */
123
124 /**
125 * @event ve.init.mw.ArticleTarget#showChanges
126 */
127
128 /**
129 * @event ve.init.mw.ArticleTarget#noChanges
130 */
131
132 /**
133 * @event ve.init.mw.ArticleTarget#saveError
134 * @param {string} code Error code
135 */
136
137 /**
138 * @event ve.init.mw.ArticleTarget#loadError
139 */
140
141 /**
142 * @event ve.init.mw.ArticleTarget#showChangesError
143 */
144
145 /**
146 * @event ve.init.mw.ArticleTarget#serializeError
147 */
148
149 /**
150 * Fired when serialization is complete
151 *
152 * @event ve.init.mw.ArticleTarget#serializeComplete
153 */
154
155 /* Static Properties */
156
157 /**
158 * @inheritdoc
159 */
160 ve.init.mw.ArticleTarget.static.name = 'article';
161
162 /**
163 * Tracking name of target class. Used by ArticleTargetEvents to identify which target we are tracking.
164 *
165 * @static
166 * @property {string}
167 * @inheritable
168 */
169 ve.init.mw.ArticleTarget.static.trackingName = 'mwTarget';
170
171 /**
172 * @inheritdoc
173 */
174 ve.init.mw.ArticleTarget.static.integrationType = 'page';
175
176 /**
177 * @inheritdoc
178 */
179 ve.init.mw.ArticleTarget.static.platformType = 'other';
180
181 /**
182 * @inheritdoc
183 */
184 ve.init.mw.ArticleTarget.static.documentCommands = [
185 ...ve.init.mw.ArticleTarget.super.static.documentCommands,
186 // Make help dialog triggerable from anywhere
187 'commandHelp',
188 // Make save commands triggerable from anywhere
189 'showSave',
190 'showChanges',
191 'showPreview',
192 'showMinoredit',
193 'showWatchthis'
194 ];
195
196 /* Static methods */
197
198 /**
199 * @inheritdoc
200 */
201 ve.init.mw.ArticleTarget.static.parseDocument = function ( documentString, mode, section, onlySection ) {
202 // Add trailing linebreak to non-empty wikitext documents for consistency
203 // with old editor and usability. Will be stripped on save. T156609
204 if ( mode === 'source' && documentString ) {
205 documentString += '\n';
206 }
207
208 // Parent method
209 return ve.init.mw.ArticleTarget.super.static.parseDocument.call( this, documentString, mode, section, onlySection );
210 };
211
212 /**
213 * Get the editable part of the page
214 *
215 * @return {jQuery} Editable DOM selection
216 */
217 ve.init.mw.ArticleTarget.prototype.getEditableContent = function () {
218 return $( '#mw-content-text' );
219 };
220
221 /**
222 * Build DOM for the redirect page subtitle (#redirectsub).
223 *
224 * @return {jQuery}
225 */
226 ve.init.mw.ArticleTarget.static.buildRedirectSub = function () {
227 const $subMsg = mw.message( 'redirectpagesub' ).parseDom();
228 // Page subtitle
229 // Compare: Article::view()
230 return $( '<span>' )
231 .attr( 'id', 'redirectsub' )
232 .append( $subMsg );
233 };
234
235 /**
236 * Build DOM for the redirect page content header (.redirectMsg).
237 *
238 * @param {string} title Redirect target
239 * @return {jQuery}
240 */
241 ve.init.mw.ArticleTarget.static.buildRedirectMsg = function ( title ) {
242 const $link = $( '<a>' )
243 .attr( {
244 href: mw.Title.newFromText( title ).getUrl(),
245 title: mw.msg( 'visualeditor-redirect-description', title )
246 } )
247 .text( title );
248 ve.init.platform.linkCache.styleElement( title, $link );
249
250 // Page content header
251 // Compare: LinkRenderer::makeRedirectHeader()
252 return $( '<div>' )
253 .addClass( 'redirectMsg' )
254 // Hack: This is normally inside #mw-content-text, but we may insert it before, so we need this.
255 // The following classes are used here:
256 // * mw-content-ltr
257 // * mw-content-rtl
258 .addClass( 'mw-content-' + mw.config.get( 'wgVisualEditor' ).pageLanguageDir )
259 .append(
260 $( '<p>' ).text( mw.msg( 'redirectto' ) ),
261 $( '<ul>' )
262 .addClass( 'redirectText' )
263 .append( $( '<li>' ).append( $link ) )
264 );
265 };
266
267 /* Methods */
268
269 /**
270 * @inheritdoc
271 */
272 ve.init.mw.ArticleTarget.prototype.setDefaultMode = function () {
273 const oldDefaultMode = this.defaultMode;
274 // Parent method
275 ve.init.mw.ArticleTarget.super.prototype.setDefaultMode.apply( this, arguments );
276
277 if ( this.defaultMode !== oldDefaultMode ) {
278 this.updateTabs();
279 if ( mw.libs.ve.setEditorPreference ) {
280 // only set up by DAT.init
281 mw.libs.ve.setEditorPreference( this.defaultMode === 'visual' ? 'visualeditor' : 'wikitext' );
282 }
283 }
284 };
285
286 /**
287 * Update state of editing tabs from this target
288 */
289 ve.init.mw.ArticleTarget.prototype.updateTabs = function () {};
290
291 /**
292 * Handle response to a successful load request.
293 *
294 * This method is called within the context of a target instance. If successful the DOM from the
295 * server will be parsed, stored in {this.doc} and then {this.documentReady} will be called.
296 *
297 * @param {Object} response API response data
298 * @param {string} status Text status message
299 */
300 ve.init.mw.ArticleTarget.prototype.loadSuccess = function ( response ) {
301 const data = response ? ( response.visualeditor || response.visualeditoredit ) : null;
302
303 if ( !data || typeof data.content !== 'string' ) {
304 this.loadFail( 've-api', { errors: [ {
305 code: 've-api',
306 html: mw.message( 'api-clientside-error-invalidresponse' ).parse()
307 } ] } );
308 } else if ( response.veMode && response.veMode !== this.getDefaultMode() ) {
309 this.loadFail( 've-mode', { errors: [ {
310 code: 've-mode',
311 html: mw.message( 'visualeditor-loaderror-wrongmode',
312 response.veMode, this.getDefaultMode() ).parse()
313 } ] } );
314 } else {
315 this.track( 'trace.parseResponse.enter' );
316 this.originalHtml = data.content;
317 this.etag = data.etag;
318 // We are reading from `preloaded` which comes from the VE API. If we want
319 // to make the VE API non-blocking in the future we will need to handle
320 // special-cases like this where the content doesn't come from RESTBase.
321 this.fromEditedState = !!data.fromEditedState || !!data.preloaded;
322 this.switched = data.switched;
323 const mode = this.getDefaultMode();
324 const section = ( mode === 'source' || this.enableVisualSectionEditing ) ? this.section : null;
325 this.doc = this.constructor.static.parseDocument( this.originalHtml, mode, section );
326 this.originalDmDocPromise = null;
327
328 // Properties that don't come from the API
329 this.initialSourceRange = data.initialSourceRange;
330 this.recovered = data.recovered;
331 this.isRedirect = false;
332
333 // Parse data this not available in RESTBase
334 if ( !this.parseMetadata( response ) ) {
335 // Invalid metadata, loadFail() or load() has been called
336 return;
337 }
338
339 this.track( 'trace.parseResponse.exit' );
340
341 // Everything worked, the page was loaded, continue initializing the editor
342 this.documentReady( this.doc );
343 }
344
345 if ( !this.isViewPage ) {
346 $( '#firstHeading' ).text(
347 mw.Title.newFromText( this.getPageName() ).getPrefixedText()
348 );
349 }
350 };
351
352 /**
353 * Parse document metadata from the API response
354 *
355 * @param {Object} response API response data
356 * @return {boolean} Whether metadata was loaded successfully. If true, you should call
357 * loadSuccess(). If false, either that loadFail() has been called or we're retrying via load().
358 */
359 ve.init.mw.ArticleTarget.prototype.parseMetadata = function ( response ) {
360 const data = response ? ( response.visualeditor || response.visualeditoredit ) : null;
361
362 if ( !data ) {
363 this.loadFail( 've-api', { errors: [ {
364 code: 've-api',
365 html: mw.message( 'api-clientside-error-invalidresponse' ).parse()
366 } ] } );
367 return false;
368 }
369
370 this.remoteNotices = ve.getObjectValues( data.notices );
371 this.protectedClasses = data.protectedClasses;
372
373 this.baseTimeStamp = data.basetimestamp;
374 this.startTimeStamp = data.starttimestamp;
375 this.revid = data.oldid || undefined;
376 this.preloaded = !!data.preloaded;
377
378 this.copyrightWarning = data.copyrightWarning;
379
380 this.checkboxesDef = data.checkboxesDef;
381 this.checkboxesMessages = data.checkboxesMessages;
382 mw.messages.set( data.checkboxesMessages );
383
384 this.canEdit = data.canEdit;
385 this.wouldautocreate = data.wouldautocreate;
386
387 // When docRevId is `undefined` it indicates that the page doesn't exist
388 let docRevId;
389 const aboutDoc = this.doc.documentElement && this.doc.documentElement.getAttribute( 'about' );
390 if ( aboutDoc ) {
391 const docRevIdMatches = aboutDoc.match( /revision\/([0-9]*)$/ );
392 if ( docRevIdMatches.length >= 2 ) {
393 docRevId = parseInt( docRevIdMatches[ 1 ] );
394 }
395 }
396 // There is no docRevId in source mode (doc is just a string), new visual documents, or when
397 // switching from source mode with changes.
398 if ( this.getDefaultMode() === 'visual' && !( this.switched && this.fromEditedState ) && docRevId !== this.revid ) {
399 if ( this.retriedRevIdConflict ) {
400 // Retried already, just error the second time.
401 this.loadFail( 've-api', { errors: [ {
402 code: 've-api',
403 html: mw.message( 'visualeditor-loaderror-revidconflict',
404 String( docRevId ), String( this.revid ) ).parse()
405 } ] } );
406 } else {
407 this.retriedRevIdConflict = true;
408 // TODO this retries both requests, in RESTbase mode we should only retry
409 // the request that gave us the lower revid
410 this.loading = null;
411 // HACK: Load with explicit revid to hopefully prevent this from happening again
412 this.requestedRevId = Math.max( docRevId || 0, this.revid );
413 this.load();
414 }
415 return false;
416 } else {
417 // Set this to false after a successful load, so we don't immediately give up
418 // if a subsequent load mismatches again
419 this.retriedRevIdConflict = false;
420 }
421
422 // Save dialog doesn't exist yet, so create an overlay for the widgets, and
423 // append it to the save dialog later.
424 this.$saveDialogOverlay = $( '<div>' ).addClass( 'oo-ui-window-overlay' );
425 const checkboxes = mw.libs.ve.targetLoader.createCheckboxFields( this.checkboxesDef, { $overlay: this.$saveDialogOverlay } );
426 this.checkboxFields = checkboxes.checkboxFields;
427 this.checkboxesByName = checkboxes.checkboxesByName;
428
429 this.checkboxFields.forEach( ( field ) => {
430 // TODO: This method should be upstreamed or moved so that targetLoader
431 // can use it safely.
432 ve.targetLinksToNewWindow( field.$label[ 0 ] );
433 } );
434
435 return true;
436 };
437
438 /**
439 * @inheritdoc
440 */
441 ve.init.mw.ArticleTarget.prototype.documentReady = function () {
442 // We need to wait until documentReady as local notices may require special messages
443 this.editNotices = this.remoteNotices.concat(
444 this.localNoticeMessages.map( ( msgKey ) => '<p>' + ve.init.platform.getParsedMessage( msgKey ) + '</p>' )
445 );
446
447 this.loading = null;
448 this.edited = this.fromEditedState;
449
450 // Parent method
451 ve.init.mw.ArticleTarget.super.prototype.documentReady.apply( this, arguments );
452 };
453
454 /**
455 * @inheritdoc
456 */
457 ve.init.mw.ArticleTarget.prototype.surfaceReady = function () {
458 const accessKeyPrefix = $.fn.updateTooltipAccessKeys.getAccessKeyPrefix().replace( /-/g, '+' ),
459 accessKeyModifiers = new ve.ui.Trigger( accessKeyPrefix + '-' ).modifiers,
460 surfaceModel = this.getSurface().getModel();
461
462 // loadSuccess() may have called setAssumeExistence( true );
463 ve.init.platform.linkCache.setAssumeExistence( false );
464 surfaceModel.connect( this, {
465 history: 'updateToolbarSaveButtonState'
466 } );
467
468 // Handle cancel events, i.e. pressing <escape>
469 this.getSurface().connect( this, {
470 cancel: 'onSurfaceCancel'
471 } );
472
473 // Iterate over the trigger registry and resolve any access key conflicts
474 for ( const name in ve.ui.triggerRegistry.registry ) {
475 const triggers = ve.ui.triggerRegistry.registry[ name ];
476 for ( let i = 0; i < triggers.length; i++ ) {
477 if ( ve.compare( triggers[ i ].modifiers, accessKeyModifiers ) ) {
478 this.disableAccessKey( triggers[ i ].primary );
479 }
480 }
481 }
482
483 if ( !mw.config.get( 'wgVisualEditorConfig' ).enableHelpCompletion ) {
484 this.getSurface().commandRegistry.unregister( 'openHelpCompletions' );
485 this.getSurface().commandRegistry.unregister( 'openHelpCompletionsTrigger' );
486 }
487
488 if ( !this.canEdit ) {
489 this.getSurface().setReadOnly( true );
490 } else {
491 // TODO: If the user rejects joining the collab session, start auto-save
492 if ( !this.currentUrl.searchParams.has( 'collabSession' ) ) {
493 // Auto-save
494 this.initAutosave();
495 }
496
497 setTimeout( () => {
498 mw.libs.ve.targetSaver.preloadDeflate();
499 }, 500 );
500 }
501
502 // Parent method
503 ve.init.mw.ArticleTarget.super.prototype.surfaceReady.apply( this, arguments );
504
505 mw.hook( 've.activationComplete' ).fire();
506 };
507
508 /**
509 * Handle surface cancel events
510 */
511 ve.init.mw.ArticleTarget.prototype.onSurfaceCancel = function () {
512 this.tryTeardown( false, 'navigate-read' );
513 };
514
515 /**
516 * Runs after the surface has been made ready and visible
517 *
518 * Implementing sub-classes must call this method.
519 */
520 ve.init.mw.ArticleTarget.prototype.afterSurfaceReady = function () {
521 this.restoreEditSection();
522 };
523
524 /**
525 * @inheritdoc
526 */
527 ve.init.mw.ArticleTarget.prototype.storeDocState = function ( html ) {
528 const mode = this.getSurface().getMode();
529 this.getSurface().getModel().storeDocState( {
530 request: {
531 pageName: this.getPageName(),
532 mode: mode,
533 // Check true section editing is in use
534 section: ( mode === 'source' || this.enableVisualSectionEditing ) ? this.section : null
535 },
536 response: {
537 etag: this.etag,
538 fromEditedState: this.fromEditedState,
539 switched: this.switched,
540 preloaded: this.preloaded,
541 notices: this.remoteNotices,
542 protectedClasses: this.protectedClasses,
543 basetimestamp: this.baseTimeStamp,
544 starttimestamp: this.startTimeStamp,
545 oldid: this.revid,
546 canEdit: this.canEdit,
547 wouldautocreate: this.wouldautocreate,
548 copyrightWarning: this.copyrightWarning,
549 checkboxesDef: this.checkboxesDef,
550 checkboxesMessages: this.checkboxesMessages
551 }
552 }, html );
553 };
554
555 /**
556 * Disable an access key by removing the attribute from any element containing it
557 *
558 * @param {string} key Access key
559 */
560 ve.init.mw.ArticleTarget.prototype.disableAccessKey = function ( key ) {
561 $( '[accesskey=' + key + ']' ).each( ( i, el ) => {
562 const $el = $( el );
563
564 $el
565 .attr( 'data-old-accesskey', $el.attr( 'accesskey' ) )
566 .removeAttr( 'accesskey' );
567 } );
568 };
569
570 /**
571 * Re-enable all access keys
572 */
573 ve.init.mw.ArticleTarget.prototype.restoreAccessKeys = function () {
574 $( '[data-old-accesskey]' ).each( ( i, el ) => {
575 const $el = $( el );
576
577 $el
578 .attr( 'accesskey', $el.attr( 'data-old-accesskey' ) )
579 .removeAttr( 'data-old-accesskey' );
580 } );
581 };
582
583 /**
584 * Handle an unsuccessful load request.
585 *
586 * This method is called within the context of a target instance.
587 *
588 * @param {string} code Error code from mw.Api
589 * @param {Object} errorDetails API response
590 * @fires ve.init.mw.ArticleTarget#loadError
591 */
592 ve.init.mw.ArticleTarget.prototype.loadFail = function () {
593 this.loading = null;
594 this.emit( 'loadError' );
595 };
596
597 /**
598 * Replace the page content with new HTML.
599 *
600 * @method
601 * @param {string} html Rendered HTML from server
602 * @param {string} categoriesHtml Rendered categories HTML from server
603 * @param {string} displayTitle HTML to show as the page title
604 * @param {Object} lastModified Object containing user-formatted date
605 * and time strings, or undefined if we made no change.
606 * @param {string} contentSub HTML to show as the content subtitle
607 * @param {Array} sections Section data to display in the TOC
608 */
609 ve.init.mw.ArticleTarget.prototype.replacePageContent = function (
610 html, categoriesHtml, displayTitle, lastModified, contentSub, sections
611 ) {
612 // eslint-disable-next-line no-jquery/no-append-html
613 this.$editableContent.find( '.mw-parser-output' ).first().replaceWith( html );
614 mw.hook( 'wikipage.content' ).fire( this.$editableContent );
615
616 if ( displayTitle ) {
617 // eslint-disable-next-line no-jquery/no-html
618 $( '#firstHeading' ).html( displayTitle );
619 }
620
621 // Categories are only shown in AMC on mobile
622 if ( $( '#catlinks' ).length ) {
623 const $categories = $( $.parseHTML( categoriesHtml ) );
624 mw.hook( 'wikipage.categories' ).fire( $categories );
625 $( '#catlinks' ).replaceWith( $categories );
626 }
627
628 mw.util.clearSubtitle();
629 mw.util.addSubtitle( contentSub );
630
631 this.setRealRedirectInterface();
632
633 mw.hook( 'wikipage.tableOfContents' ).fire( sections );
634 };
635
636 /**
637 * Handle successful DOM save event.
638 *
639 * @param {Object} data Save data from the API
640 * @param {boolean} data.nocontent Indicates that page HTML and related properties were omitted
641 * @param {string} data.content Rendered page HTML from server
642 * @param {string} data.categorieshtml Rendered categories HTML from server
643 * @param {number} data.newrevid New revision id, undefined if unchanged
644 * @param {boolean} data.isRedirect Whether this page is a redirect or not
645 * @param {string} data.displayTitleHtml What HTML to show as the page title
646 * @param {Object} data.lastModified Object containing user-formatted date
647 * and time strings, or undefined if we made no change.
648 * @param {string} data.contentSub HTML to show as the content subtitle
649 * @param {Array} data.modules The modules to be loaded on the page
650 * @param {Object} data.jsconfigvars The mw.config values needed on the page
651 * @param {Array} data.sections Section data to display in the TOC
652 * @param {boolean} data.tempusercreated True if we just became logged in as a temporary user
653 * @param {string} data.tempusercreatedredirect URL to visit to finish creating temp account
654 * @fires ve.init.mw.ArticleTarget#save
655 */
656 ve.init.mw.ArticleTarget.prototype.saveComplete = function ( data ) {
657 this.editSummaryValue = null;
658 this.initialEditSummary = null;
659
660 this.saveDeferred.resolve();
661 this.emit( 'save', data );
662
663 // This is a page creation, a restoration, or we loaded the editor from a non-view page,
664 // or we just became logged in as a temporary user: refresh the page.
665 if ( data.nocontent || data.tempusercreated ) {
666 // Teardown the target, ensuring auto-save data is cleared
667 this.teardown().then( () => {
668 if ( data.newrevid !== undefined ) {
669 let action;
670 if ( this.restoring ) {
671 action = 'restored';
672 } else if ( !this.pageExists ) {
673 action = 'created';
674 } else {
675 action = 'saved';
676 }
677 require( 'mediawiki.action.view.postEdit' ).fireHookOnPageReload( action, data.tempusercreated );
678 }
679
680 if ( data.tempusercreatedredirect ) {
681 location.href = data.tempusercreatedredirect;
682 } else {
683 const newUrl = new URL( this.viewUrl );
684 if ( data.newrevid !== undefined ) {
685 // For GrowthExperiments
686 newUrl.searchParams.set( 'venotify', 'saved' );
687 }
688 if ( data.isRedirect ) {
689 newUrl.searchParams.set( 'redirect', 'no' );
690 }
691 location.href = newUrl;
692 }
693 } );
694 } else {
695 // Update watch link to match 'watch checkbox' in save dialog.
696 // User logged in if module loaded.
697 if ( mw.loader.getState( 'mediawiki.page.watch.ajax' ) === 'ready' ) {
698 const watch = require( 'mediawiki.page.watch.ajax' );
699
700 watch.updatePageWatchStatus(
701 data.watched,
702 data.watchlistexpiry
703 );
704 }
705
706 // If we were explicitly editing an older version, make sure we won't
707 // load the same old version again, now that we've saved the next edit
708 // will be against the latest version.
709 // If there is an ?oldid= parameter in the URL, this will cause restorePage() to remove it.
710 this.restoring = false;
711
712 // Clear requestedRevId in case it was set by a retry or something; after saving
713 // we don't want to go back into oldid mode anyway
714 this.requestedRevId = undefined;
715
716 if ( data.newrevid !== undefined ) {
717 mw.config.set( {
718 wgCurRevisionId: data.newrevid,
719 wgRevisionId: data.newrevid
720 } );
721 this.revid = data.newrevid;
722 this.currentRevisionId = data.newrevid;
723 }
724
725 // Update module JS config values and notify ResourceLoader of any new
726 // modules needed to be added to the page
727 mw.config.set( data.jsconfigvars );
728 mw.loader.load( data.modules );
729
730 mw.config.set( {
731 wgIsRedirect: !!data.isRedirect
732 } );
733
734 if ( this.saveDialog ) {
735 this.saveDialog.reset();
736 }
737
738 this.replacePageContent(
739 data.content,
740 data.categorieshtml,
741 data.displayTitleHtml,
742 data.lastModified,
743 data.contentSub,
744 data.sections
745 );
746
747 // Tear down the target now that we're done saving
748 // Not passing trackMechanism because this isn't an abort action
749 this.tryTeardown( true );
750 }
751 };
752
753 /**
754 * Handle an unsuccessful save request.
755 *
756 * @param {HTMLDocument} doc HTML document we tried to save
757 * @param {Object} saveData Options that were used
758 * @param {string} code Error code
759 * @param {Object|null} data Full API response data, or XHR error details
760 * @fires ve.init.mw.ArticleTarget#saveError
761 */
762 ve.init.mw.ArticleTarget.prototype.saveFail = function ( doc, saveData, code, data ) {
763 this.pageDeletedWarning = false;
764
765 let handled = false;
766 // Handle empty response
767 if ( !data ) {
768 this.saveErrorEmpty();
769 handled = true;
770 }
771
772 if ( !handled && data.errors ) {
773 for ( let i = 0; i < data.errors.length; i++ ) {
774 const error = data.errors[ i ];
775
776 if ( error.code === 'assertanonfailed' || error.code === 'assertuserfailed' || error.code === 'assertnameduserfailed' ) {
777 this.refreshUser().then( ( username ) => {
778 // Reattempt the save after successfully refreshing the
779 // user, but only if it's a temporary account (T345975)
780 if ( error.code === 'assertanonfailed' && mw.util.isTemporaryUser( username ) ) {
781 this.startSave( this.getSaveOptions() );
782 } else {
783 this.saveErrorNewUser( username );
784 }
785 }, () => {
786 this.saveErrorUnknown( data );
787 } );
788 handled = true;
789 } else if ( error.code === 'editconflict' ) {
790 this.editConflict();
791 handled = true;
792 } else if ( error.code === 'pagedeleted' ) {
793 this.saveErrorPageDeleted();
794 handled = true;
795 } else if ( error.code === 'hookaborted' ) {
796 this.saveErrorHookAborted( data );
797 handled = true;
798 } else if ( error.code === 'readonly' ) {
799 this.saveErrorReadOnly( data );
800 handled = true;
801 }
802 }
803 }
804
805 if ( !handled ) {
806 const saveErrorHandlerFactory = ve.init.mw.saveErrorHandlerFactory;
807 for ( const name in saveErrorHandlerFactory.registry ) {
808 const handler = saveErrorHandlerFactory.lookup( name );
809 if ( handler.static.matchFunction( data ) ) {
810 handler.static.process( data, this );
811 handled = true;
812 }
813 }
814 }
815
816 // Handle (other) unknown and/or unrecoverable errors
817 if ( !handled ) {
818 this.saveErrorUnknown( data );
819 handled = true;
820 }
821
822 let errorCodes;
823 if ( data.errors ) {
824 errorCodes = OO.unique( data.errors.map( ( err ) => err.code ) ).join( ',' );
825 } else if ( ve.getProp( data, 'visualeditoredit', 'edit', 'captcha' ) ) {
826 // Eww
827 errorCodes = 'captcha';
828 } else {
829 errorCodes = 'http-' + ( ( data.xhr && data.xhr.status ) || 0 );
830 }
831 this.emit( 'saveError', errorCodes );
832 };
833
834 /**
835 * Show an save process error message
836 *
837 * @param {string|jQuery|Node[]} msg Message content (string of HTML, jQuery object or array of
838 * Node objects)
839 * @param {boolean} [warning=false] Whether or not this is a warning.
840 */
841 ve.init.mw.ArticleTarget.prototype.showSaveError = function ( msg, warning ) {
842 this.saveDeferred.reject( [ new OO.ui.Error( msg, { warning: warning } ) ] );
843 };
844
845 /**
846 * Extract the error messages from an erroneous API response
847 *
848 * @param {Object} data API response data
849 * @return {jQuery}
850 */
851 ve.init.mw.ArticleTarget.prototype.extractErrorMessages = function ( data ) {
852 const $errorMsgs = ( new mw.Api() ).getErrorMessage( data );
853 // Warning, this assumes there are only Element nodes in the jQuery set
854 $errorMsgs.toArray().forEach( ve.targetLinksToNewWindow );
855 return $errorMsgs;
856 };
857
858 /**
859 * Handle general save error
860 */
861 ve.init.mw.ArticleTarget.prototype.saveErrorEmpty = function () {
862 this.showSaveError( this.extractErrorMessages( null ) );
863 };
864
865 /**
866 * Handle hook abort save error
867 *
868 * @param {Object} data API response data
869 */
870 ve.init.mw.ArticleTarget.prototype.saveErrorHookAborted = function ( data ) {
871 this.showSaveError( this.extractErrorMessages( data ) );
872 };
873
874 /**
875 * Handle assert error indicating another user is logged in.
876 *
877 * @param {string|null} username Name of newly logged-in user, or a temporary account name,
878 * or null if logged-out and temporary accounts are disabled
879 */
880 ve.init.mw.ArticleTarget.prototype.saveErrorNewUser = function ( username ) {
881 const $msg = mw.message(
882 username === null ?
883 'visualeditor-savedialog-identify-anon' :
884 mw.util.isTemporaryUser( username ) ?
885 'visualeditor-savedialog-identify-temp' :
886 'visualeditor-savedialog-identify-user',
887 username
888 ).parseDom();
889
890 this.showSaveError( $msg, true );
891 };
892
893 /**
894 * Handle unknown save error
895 *
896 * @param {Object|null} data API response data
897 */
898 ve.init.mw.ArticleTarget.prototype.saveErrorUnknown = function ( data ) {
899 this.showSaveError( this.extractErrorMessages( data ) );
900 };
901
902 /**
903 * Handle page deleted error
904 */
905 ve.init.mw.ArticleTarget.prototype.saveErrorPageDeleted = function () {
906 this.pageDeletedWarning = true;
907 // The API error message 'apierror-pagedeleted' is poor, make our own
908 this.showSaveError( mw.msg( 'visualeditor-recreate', mw.msg( 'ooui-dialog-process-continue' ) ), true );
909 };
910
911 /**
912 * Handle read only error
913 *
914 * @param {Object} data API response data
915 */
916 ve.init.mw.ArticleTarget.prototype.saveErrorReadOnly = function ( data ) {
917 this.showSaveError( this.extractErrorMessages( data ), true );
918 };
919
920 /**
921 * Handle an edit conflict
922 */
923 ve.init.mw.ArticleTarget.prototype.editConflict = function () {
924 this.saveDialog.popPending();
925 this.saveDialog.swapPanel( 'conflict' );
926 };
927
928 /**
929 * Handle clicks on the review button in the save dialog.
930 *
931 * @fires ve.init.mw.ArticleTarget#saveReview
932 */
933 ve.init.mw.ArticleTarget.prototype.onSaveDialogReview = function () {
934 if ( !this.saveDialog.hasDiff ) {
935 this.emit( 'saveReview' );
936 this.saveDialog.pushPending();
937 // Acquire a temporary user username before diffing, so that signatures and
938 // user-related magic words display the temp user instead of IP user in the diff. (T331397)
939 mw.user.acquireTempUserName().then( () => {
940 if ( this.pageExists ) {
941 // Has no callback, handled via this.showChangesDiff
942 this.showChanges( this.getDocToSave() );
943 } else {
944 this.serialize( this.getDocToSave() ).then( ( data ) => {
945 this.onSaveDialogReviewComplete( data.content );
946 } );
947 }
948 } );
949 } else {
950 this.saveDialog.swapPanel( 'review' );
951 }
952 };
953
954 /**
955 * Handle clicks on the show preview button in the save dialog.
956 *
957 * @fires ve.init.mw.ArticleTarget#savePreview
958 */
959 ve.init.mw.ArticleTarget.prototype.onSaveDialogPreview = function () {
960 const api = this.getContentApi();
961
962 if ( !this.saveDialog.$previewViewer.children().length ) {
963 this.emit( 'savePreview' );
964 this.saveDialog.pushPending();
965
966 const params = {};
967
968 const sectionTitle = this.sectionTitle && this.sectionTitle.getValue();
969 if ( sectionTitle ) {
970 params.section = 'new';
971 params.sectiontitle = sectionTitle;
972 }
973 if ( mw.config.get( 'wgUserVariant' ) ) {
974 params.variant = mw.config.get( 'wgUserVariant' );
975 }
976
977 // Acquire a temporary user username before previewing, so that signatures and
978 // user-related magic words display the temp user instead of IP user in the preview. (T331397)
979 mw.user.acquireTempUserName().then( () => api.post( ve.extendObject( params, {
980 action: 'parse',
981 title: this.getPageName(),
982 text: this.getDocToSave(),
983 pst: true,
984 preview: true,
985 sectionpreview: this.section !== null,
986 disableeditsection: true,
987 uselang: mw.config.get( 'wgUserLanguage' ),
988 useskin: mw.config.get( 'skin' ),
989 mobileformat: OO.ui.isMobile(),
990 prop: [ 'text', 'categorieshtml', 'displaytitle', 'subtitle', 'modules', 'jsconfigvars' ]
991 } ) ) ).then( ( response ) => {
992 this.saveDialog.showPreview( response );
993 }, ( errorCode, details ) => {
994 this.saveDialog.showPreview( this.extractErrorMessages( details ) );
995 } ).always( () => {
996 this.bindSaveDialogClearDiff();
997 } );
998 } else {
999 this.saveDialog.swapPanel( 'preview' );
1000 }
1001 };
1002
1003 /**
1004 * Clear the save dialog's diff cache when the document changes
1005 */
1006 ve.init.mw.ArticleTarget.prototype.bindSaveDialogClearDiff = function () {
1007 // Invalidate the viewer wikitext on next change
1008 this.getSurface().getModel().getDocument().once( 'transact',
1009 this.saveDialog.clearDiff.bind( this.saveDialog )
1010 );
1011 if ( this.sectionTitle ) {
1012 this.sectionTitle.once( 'change', this.saveDialog.clearDiff.bind( this.saveDialog ) );
1013 }
1014 };
1015
1016 /**
1017 * Handle completed serialize request for diff views for new page creations.
1018 *
1019 * @param {string} wikitext
1020 */
1021 ve.init.mw.ArticleTarget.prototype.onSaveDialogReviewComplete = function ( wikitext ) {
1022 this.bindSaveDialogClearDiff();
1023 this.saveDialog.setDiffAndReview(
1024 ve.createDeferred().resolve( $( '<pre>' ).text( wikitext ) ).promise(),
1025 this.getVisualDiffGeneratorPromise(),
1026 this.getSurface().getModel().getDocument().getHtmlDocument()
1027 );
1028 };
1029
1030 /**
1031 * Get a visual diff object for the current document state
1032 *
1033 * @return {jQuery.Promise} Promise resolving with a generator for a ve.dm.VisualDiff visual diff
1034 */
1035 ve.init.mw.ArticleTarget.prototype.getVisualDiffGeneratorPromise = function () {
1036 return mw.loader.using( 'ext.visualEditor.diffLoader' ).then( () => {
1037 const mode = this.getSurface().getMode();
1038
1039 if ( !this.originalDmDocPromise ) {
1040 if ( mode === 'source' ) {
1041 // Always load full doc in source mode for correct reference diffing (T260008)
1042 this.originalDmDocPromise = mw.libs.ve.diffLoader.fetchRevision( this.revid, this.getPageName() );
1043 } else {
1044 if ( !this.fromEditedState ) {
1045 const dmDoc = this.constructor.static.createModelFromDom( this.doc, 'visual' );
1046 let dmDocOrNode;
1047 if ( this.section !== null && this.enableVisualSectionEditing ) {
1048 dmDocOrNode = dmDoc.getNodesByType( 'section' )[ 0 ];
1049 } else {
1050 dmDocOrNode = dmDoc;
1051 }
1052 this.originalDmDocPromise = ve.createDeferred().resolve( dmDocOrNode ).promise();
1053 } else {
1054 this.originalDmDocPromise = mw.libs.ve.diffLoader.fetchRevision( this.revid, this.getPageName(), this.section );
1055 }
1056 }
1057 }
1058
1059 if ( mode === 'source' ) {
1060 // Acquire a temporary user username before diffing, so that signatures and
1061 // user-related magic words display the temp user instead of IP user in the diff. (T331397)
1062 const newRevPromise = mw.user.acquireTempUserName().then( () => this.getContentApi().post( {
1063 action: 'visualeditor',
1064 paction: 'parse',
1065 page: this.getPageName(),
1066 wikitext: this.getSurface().getDom(),
1067 section: this.section,
1068 stash: 0,
1069 pst: true
1070 } ) ).then(
1071 // Source mode always fetches the whole document, so set section=null to unwrap sections
1072 ( response ) => mw.libs.ve.diffLoader.getModelFromResponse( response, null )
1073 );
1074
1075 return mw.libs.ve.diffLoader.getVisualDiffGeneratorPromise( this.originalDmDocPromise, newRevPromise );
1076 } else {
1077 return this.originalDmDocPromise.then(
1078 ( originalDmDoc ) => () => new ve.dm.VisualDiff( originalDmDoc, this.getSurface().getModel().getDocument().getAttachedRoot() )
1079 );
1080 }
1081 } );
1082 };
1083
1084 /**
1085 * Handle clicks on the resolve conflict button in the conflict dialog.
1086 */
1087 ve.init.mw.ArticleTarget.prototype.onSaveDialogResolveConflict = function () {
1088 const fields = { wpSave: 1 };
1089
1090 if ( this.getSurface().getMode() === 'source' && this.section !== null ) {
1091 // TODO: This should happen in #getSaveFields, check if moving it there breaks anything
1092 fields.section = this.section;
1093 }
1094 // Get Wikitext from the DOM, and set up a submit call when it's done
1095 this.serialize( this.getDocToSave() ).then( ( data ) => {
1096 this.submitWithSaveFields( fields, data.content );
1097 } );
1098 };
1099
1100 /**
1101 * Handle dialog retry events
1102 * So we can handle trying to save again after page deletion warnings
1103 */
1104 ve.init.mw.ArticleTarget.prototype.onSaveDialogRetry = function () {
1105 if ( this.pageDeletedWarning ) {
1106 this.recreating = true;
1107 this.pageExists = false;
1108 }
1109 };
1110
1111 /**
1112 * Load the editor.
1113 *
1114 * This method initiates an API request for the page data unless dataPromise is passed in,
1115 * in which case it waits for that promise instead.
1116 *
1117 * @param {jQuery.Promise} [dataPromise] Promise for pending request, if any
1118 * @return {jQuery.Promise} Data promise
1119 */
1120 ve.init.mw.ArticleTarget.prototype.load = function ( dataPromise ) {
1121 // Prevent duplicate requests
1122 if ( this.loading ) {
1123 return this.loading;
1124 }
1125 this.events.trackActivationStart( mw.libs.ve.activationStart );
1126 mw.libs.ve.activationStart = null;
1127
1128 const url = new URL( location.href );
1129 dataPromise = dataPromise || mw.libs.ve.targetLoader.requestPageData( this.getDefaultMode(), this.getPageName(), {
1130 sessionStore: true,
1131 section: this.section,
1132 oldId: this.requestedRevId,
1133 targetName: this.constructor.static.trackingName,
1134 editintro: url.searchParams.get( 'editintro' ),
1135 preload: url.searchParams.get( 'preload' ),
1136 preloadparams: mw.util.getArrayParam( 'preloadparams', url.searchParams )
1137 } );
1138
1139 this.loading = dataPromise;
1140 dataPromise
1141 .done( this.loadSuccess.bind( this ) )
1142 .fail( this.loadFail.bind( this ) );
1143
1144 return dataPromise;
1145 };
1146
1147 /**
1148 * Clear the state of this target, preparing it to be reactivated later.
1149 */
1150 ve.init.mw.ArticleTarget.prototype.clearState = function () {
1151 this.restoreAccessKeys();
1152 this.clearPreparedCacheKey();
1153 this.loading = null;
1154 this.saving = null;
1155 this.clearDiff();
1156 this.serializing = false;
1157 this.submitting = false;
1158 this.baseTimeStamp = null;
1159 this.startTimeStamp = null;
1160 this.checkboxes = null;
1161 this.initialSourceRange = null;
1162 this.doc = null;
1163 this.originalDmDocPromise = null;
1164 this.originalHtml = null;
1165 this.toolbarSaveButton = null;
1166 this.section = null;
1167 this.visibleSection = null;
1168 this.visibleSectionOffset = null;
1169 this.editNotices = [];
1170 this.remoteNotices = [];
1171 this.localNoticeMessages = [];
1172 this.recovered = false;
1173 this.teardownPromise = null;
1174 };
1175
1176 /**
1177 * Switch to edit source mode
1178 *
1179 * Opens a confirmation dialog if the document is modified or VE wikitext mode
1180 * is not available.
1181 */
1182 ve.init.mw.ArticleTarget.prototype.editSource = function () {
1183 const modified = this.fromEditedState || this.getSurface().getModel().hasBeenModified();
1184
1185 this.switchToWikitextEditor( modified );
1186 };
1187
1188 /**
1189 * Get a document to save, cached until the surface is modified
1190 *
1191 * The default implementation returns an HTMLDocument, but other targets
1192 * may use a different document model (e.g. plain text for source mode).
1193 *
1194 * @return {Object} Document to save
1195 */
1196 ve.init.mw.ArticleTarget.prototype.getDocToSave = function () {
1197 if ( !this.docToSave ) {
1198 this.docToSave = this.createDocToSave();
1199 // Cache clearing events
1200 const surface = this.getSurface();
1201 surface.getModel().getDocument().once( 'transact', this.clearDocToSave.bind( this ) );
1202 surface.once( 'destroy', this.clearDocToSave.bind( this ) );
1203 }
1204 return this.docToSave;
1205 };
1206
1207 /**
1208 * Create a document to save
1209 *
1210 * @return {Object} Document to save
1211 */
1212 ve.init.mw.ArticleTarget.prototype.createDocToSave = function () {
1213 return this.getSurface().getDom();
1214 };
1215
1216 /**
1217 * Clear the document to save from the cache
1218 */
1219 ve.init.mw.ArticleTarget.prototype.clearDocToSave = function () {
1220 this.docToSave = null;
1221 this.clearPreparedCacheKey();
1222 };
1223
1224 /**
1225 * Serialize the current document and store the result in the serialization cache on the server.
1226 *
1227 * This function returns a promise that is resolved once serialization is complete, with the
1228 * cache key passed as the first parameter.
1229 *
1230 * If there's already a request pending for the same (reference-identical) HTMLDocument, this
1231 * function will not initiate a new request but will return the promise for the pending request.
1232 * If a request for the same document has already been completed, this function will keep returning
1233 * the same promise (which will already have been resolved) until clearPreparedCacheKey() is called.
1234 *
1235 * @param {HTMLDocument} doc Document to serialize
1236 */
1237 ve.init.mw.ArticleTarget.prototype.prepareCacheKey = function ( doc ) {
1238 const start = ve.now();
1239
1240 if ( this.getSurface().getMode() === 'source' ) {
1241 return;
1242 }
1243
1244 if ( this.preparedCacheKeyPromise && this.preparedCacheKeyPromise.doc === doc ) {
1245 return;
1246 }
1247 this.clearPreparedCacheKey();
1248
1249 let xhr;
1250 let aborted = false;
1251 this.preparedCacheKeyPromise = mw.libs.ve.targetSaver.deflateDoc( doc, this.doc )
1252 .then( ( deflatedHtml ) => {
1253 if ( aborted ) {
1254 return ve.createDeferred().reject();
1255 }
1256 xhr = this.getContentApi().postWithToken( 'csrf',
1257 {
1258 action: 'visualeditoredit',
1259 paction: 'serializeforcache',
1260 html: deflatedHtml,
1261 page: this.getPageName(),
1262 oldid: this.revid,
1263 etag: this.etag
1264 },
1265 { contentType: 'multipart/form-data' }
1266 );
1267 return xhr.then(
1268 ( response ) => {
1269 const trackData = { duration: ve.now() - start };
1270 if ( response.visualeditoredit && typeof response.visualeditoredit.cachekey === 'string' ) {
1271 this.events.track( 'performance.system.serializeforcache', trackData );
1272 return {
1273 cacheKey: response.visualeditoredit.cachekey,
1274 // Pass the HTML for retries.
1275 html: deflatedHtml
1276 };
1277 } else {
1278 this.events.track( 'performance.system.serializeforcache.nocachekey', trackData );
1279 return ve.createDeferred().reject();
1280 }
1281 },
1282 () => {
1283 this.events.track( 'performance.system.serializeforcache.fail', { duration: ve.now() - start } );
1284 return ve.createDeferred().reject();
1285 }
1286 );
1287 } )
1288 .promise( {
1289 abort: () => {
1290 if ( xhr ) {
1291 xhr.abort();
1292 }
1293 aborted = true;
1294 },
1295 doc: doc
1296 } );
1297 };
1298
1299 /**
1300 * Get the prepared wikitext, if any. Same as prepareWikitext() but does not initiate a request
1301 * if one isn't already pending or finished. Instead, it returns a rejected promise in that case.
1302 *
1303 * @param {HTMLDocument} doc Document to serialize
1304 * @return {jQuery.Promise} Abortable promise, resolved with a plain object containing `cacheKey`,
1305 * and `html` for retries.
1306 */
1307 ve.init.mw.ArticleTarget.prototype.getPreparedCacheKey = function ( doc ) {
1308 if ( this.preparedCacheKeyPromise && this.preparedCacheKeyPromise.doc === doc ) {
1309 return this.preparedCacheKeyPromise;
1310 }
1311 return ve.createDeferred().reject().promise();
1312 };
1313
1314 /**
1315 * Clear the promise for the prepared wikitext cache key, and abort it if it's still in progress.
1316 */
1317 ve.init.mw.ArticleTarget.prototype.clearPreparedCacheKey = function () {
1318 if ( this.preparedCacheKeyPromise ) {
1319 this.preparedCacheKeyPromise.abort();
1320 this.preparedCacheKeyPromise = null;
1321 }
1322 };
1323
1324 /**
1325 * Try submitting an API request with a cache key for prepared wikitext, falling back to submitting
1326 * HTML directly if there is no cache key present or pending, or if the request for the cache key
1327 * fails, or if using the cache key fails with a badcachekey error.
1328 *
1329 * This function will use mw.Api#postWithToken to retry automatically when encountering a 'badtoken'
1330 * error.
1331 *
1332 * @param {HTMLDocument|string} doc Document to submit or string in source mode
1333 * @param {Object} extraData POST parameters to send. Do not include 'html', 'cachekey' or 'format'.
1334 * @param {string} [eventName] If set, log an event when the request completes successfully. The
1335 * full event name used will be 'performance.system.{eventName}.withCacheKey' or .withoutCacheKey
1336 * depending on whether or not a cache key was used.
1337 * @return {jQuery.Promise} Promise which resolves/rejects when saving is complete/fails
1338 */
1339 ve.init.mw.ArticleTarget.prototype.tryWithPreparedCacheKey = function ( doc, extraData, eventName ) {
1340 if ( this.getSurface().getMode() === 'source' ) {
1341 const data = ve.copy( extraData );
1342
1343 // TODO: This should happen in #getSaveOptions, check if moving it there breaks anything
1344 if ( this.section !== null ) {
1345 data.section = this.section;
1346 }
1347 if ( this.sectionTitle ) {
1348 data.sectiontitle = this.sectionTitle.getValue();
1349 data.summary = undefined;
1350 }
1351
1352 return mw.libs.ve.targetSaver.postWikitext(
1353 doc,
1354 data,
1355 { api: this.getContentApi() }
1356 );
1357 }
1358
1359 // getPreparedCacheKey resolves with { cacheKey: ..., html: ... } or rejects.
1360 // After modification it never rejects, just resolves with { html: ... } instead
1361 const htmlOrCacheKeyPromise = this.getPreparedCacheKey( doc ).then(
1362 // Success, use promise as-is.
1363 null,
1364 // Fail, get deflatedHtml promise
1365 () => mw.libs.ve.targetSaver.deflateDoc( doc, this.doc ).then( ( html ) => ( { html: html } ) ) );
1366
1367 return htmlOrCacheKeyPromise.then( ( htmlOrCacheKey ) => mw.libs.ve.targetSaver.postHtml(
1368 htmlOrCacheKey.html,
1369 htmlOrCacheKey.cacheKey,
1370 extraData,
1371 {
1372 onCacheKeyFail: this.clearPreparedCacheKey.bind( this ),
1373 api: this.getContentApi(),
1374 track: this.events.track.bind( this.events ),
1375 eventName: eventName,
1376 now: ve.now
1377 }
1378 ) );
1379 };
1380
1381 /**
1382 * Handle the save dialog's save event
1383 *
1384 * Validates the inputs then starts the save process
1385 *
1386 * @param {jQuery.Deferred} saveDeferred Deferred object to resolve/reject when the save
1387 * succeeds/fails.
1388 * @fires ve.init.mw.ArticleTarget#saveInitiated
1389 */
1390 ve.init.mw.ArticleTarget.prototype.onSaveDialogSave = function ( saveDeferred ) {
1391 if ( this.deactivating ) {
1392 return;
1393 }
1394
1395 const saveOptions = this.getSaveOptions();
1396
1397 if (
1398 +mw.user.options.get( 'forceeditsummary' ) &&
1399 ( saveOptions.summary === '' || saveOptions.summary === this.initialEditSummary ) &&
1400 !this.saveDialog.messages.missingsummary
1401 ) {
1402 this.saveDialog.showMessage(
1403 'missingsummary',
1404 new OO.ui.HtmlSnippet( ve.init.platform.getParsedMessage( 'missingsummary' ) )
1405 );
1406 this.saveDialog.popPending();
1407 } else {
1408 this.emit( 'saveInitiated' );
1409 this.startSave( saveOptions );
1410 this.saveDeferred = saveDeferred;
1411 }
1412 };
1413
1414 /**
1415 * Start the save process
1416 *
1417 * @param {Object} saveOptions Save options
1418 */
1419 ve.init.mw.ArticleTarget.prototype.startSave = function ( saveOptions ) {
1420 this.save( this.getDocToSave(), saveOptions );
1421 };
1422
1423 /**
1424 * Get save form fields from the save dialog form.
1425 *
1426 * @return {Object} Form data for submission to the MediaWiki action=edit UI
1427 */
1428 ve.init.mw.ArticleTarget.prototype.getSaveFields = function () {
1429 const fields = {};
1430
1431 if ( this.section === 'new' ) {
1432 // MediaWiki action=edit UI doesn't have separate parameters for edit summary and new section
1433 // title. The edit summary parameter is supposed to contain the section title, and the real
1434 // summary is autogenerated.
1435 fields.wpSummary = this.sectionTitle ? this.sectionTitle.getValue() : '';
1436 } else {
1437 fields.wpSummary = this.saveDialog ?
1438 this.saveDialog.editSummaryInput.getValue() :
1439 ( this.editSummaryValue || this.initialEditSummary );
1440 }
1441
1442 let name;
1443 // Extra save fields added by extensions
1444 for ( name in this.saveFields ) {
1445 fields[ name ] = this.saveFields[ name ]();
1446 }
1447
1448 if ( this.recreating ) {
1449 fields.wpRecreate = true;
1450 }
1451
1452 for ( name in this.checkboxesByName ) {
1453 // DropdownInputWidget or CheckboxInputWidget
1454 if ( !this.checkboxesByName[ name ].isSelected || this.checkboxesByName[ name ].isSelected() ) {
1455 fields[ name ] = this.checkboxesByName[ name ].getValue();
1456 }
1457 }
1458
1459 return fields;
1460 };
1461
1462 /**
1463 * Invoke #submit with the data from #getSaveFields
1464 *
1465 * @param {Object} fields Fields to add in addition to those from #getSaveFields
1466 * @param {string} wikitext Wikitext to submit
1467 * @return {boolean} Whether submission was started
1468 */
1469 ve.init.mw.ArticleTarget.prototype.submitWithSaveFields = function ( fields, wikitext ) {
1470 return this.submit( wikitext, ve.extendObject( this.getSaveFields(), fields ) );
1471 };
1472
1473 /**
1474 * Get edit API options from the save dialog form.
1475 *
1476 * @return {Object} Save options for submission to the MediaWiki API
1477 */
1478 ve.init.mw.ArticleTarget.prototype.getSaveOptions = function () {
1479 const options = this.getSaveFields(),
1480 fieldMap = {
1481 wpSummary: 'summary',
1482 wpMinoredit: 'minor',
1483 wpWatchthis: 'watchlist',
1484 wpCaptchaId: 'captchaid',
1485 wpCaptchaWord: 'captchaword'
1486 };
1487
1488 for ( const key in fieldMap ) {
1489 if ( options[ key ] !== undefined ) {
1490 options[ fieldMap[ key ] ] = options[ key ];
1491 delete options[ key ];
1492 }
1493 }
1494
1495 options.watchlist = 'watchlist' in options ? 'watch' : 'unwatch';
1496
1497 return options;
1498 };
1499
1500 /**
1501 * Post DOM data to the Parsoid API.
1502 *
1503 * This method performs an asynchronous action and uses a callback function to handle the result.
1504 *
1505 * this.save( dom, { summary: 'test', minor: true, watch: false } );
1506 *
1507 * @param {HTMLDocument} doc Document to save
1508 * @param {Object} options Saving options. All keys are passed through, including unrecognized ones.
1509 * - {string} summary Edit summary
1510 * - {boolean} minor Edit is a minor edit
1511 * - {boolean} watch Watch the page
1512 * @return {jQuery.Promise} Save promise, see mw.libs.ve.targetSaver.postHtml
1513 */
1514 ve.init.mw.ArticleTarget.prototype.save = function ( doc, options ) {
1515 // Prevent duplicate requests
1516 if ( this.saving ) {
1517 return this.saving;
1518 }
1519
1520 const data = ve.extendObject( {}, options, {
1521 page: this.getPageName(),
1522 oldid: this.revid,
1523 basetimestamp: this.baseTimeStamp,
1524 starttimestamp: this.startTimeStamp,
1525 etag: this.etag,
1526 assert: mw.user.isAnon() ? 'anon' : 'user',
1527 assertuser: mw.user.getName() || undefined
1528 } );
1529
1530 if ( !this.pageExists || this.restoring || !this.isViewPage ) {
1531 // This is a page creation, a restoration, or we loaded the editor from a non-view page.
1532 // We can't update the interface to reflect this new state, so we're going to reload the whole page.
1533 // Therefore we don't need the new revision's HTML content in the API response.
1534 data.nocontent = true;
1535 }
1536
1537 if ( this.wouldautocreate ) {
1538 // This means that we might need to redirect to an opaque URL,
1539 // so we must set up query parameters we want ahead of time.
1540 // TODO: `this.isRedirect` is only set in visual mode, not in source mode
1541 data.returntoquery = this.isRedirect ? 'redirect=no' : '';
1542 data.returntoanchor = this.getSectionHashFromPage();
1543 }
1544
1545 const config = mw.config.get( 'wgVisualEditorConfig' );
1546
1547 const taglist = data.vetags ? data.vetags.split( ',' ) : [];
1548
1549 if ( config.useChangeTagging ) {
1550 taglist.push(
1551 this.getSurface().getMode() === 'source' ? 'visualeditor-wikitext' : 'visualeditor'
1552 );
1553 }
1554
1555 if (
1556 this.getSurface().getMode() === 'visual' &&
1557 mw.config.get( 'wgVisualEditorConfig' ).editCheckTagging
1558 ) {
1559 const documentModel = this.getSurface().getModel().getDocument();
1560 // New content needing a reference
1561 if ( mw.editcheck.hasAddedContentNeedingReference( documentModel ) ) {
1562 taglist.push( 'editcheck-references' );
1563 }
1564 // New content, regardless of if it needs a reference
1565 if ( mw.editcheck.hasAddedContentNeedingReference( documentModel, true ) ) {
1566 taglist.push( 'editcheck-newcontent' );
1567 }
1568 // Rejection reasons for references
1569 const rejections = mw.editcheck.getRejectionReasons();
1570 if ( rejections.length > 0 ) {
1571 rejections.forEach( ( reason ) => {
1572 taglist.push( 'editcheck-reference-decline-' + reason );
1573 } );
1574 }
1575 }
1576
1577 data.vetags = taglist.join( ',' );
1578
1579 const promise = this.saving = this.tryWithPreparedCacheKey( doc, data, 'save' )
1580 .done( this.saveComplete.bind( this ) )
1581 .fail( this.saveFail.bind( this, doc, data ) )
1582 .always( () => {
1583 this.saving = null;
1584 } );
1585
1586 return promise;
1587 };
1588
1589 /**
1590 * Show changes in the save dialog
1591 *
1592 * @param {Object} doc Document
1593 */
1594 ve.init.mw.ArticleTarget.prototype.showChanges = function ( doc ) {
1595 // Invalidate the viewer diff on next change
1596 this.getSurface().getModel().getDocument().once( 'transact', () => {
1597 this.clearDiff();
1598 } );
1599 this.saveDialog.setDiffAndReview(
1600 this.getWikitextDiffPromise( doc ),
1601 this.getVisualDiffGeneratorPromise(),
1602 this.getSurface().getModel().getDocument().getHtmlDocument()
1603 );
1604 };
1605
1606 /**
1607 * Clear all state associated with the diff
1608 */
1609 ve.init.mw.ArticleTarget.prototype.clearDiff = function () {
1610 if ( this.saveDialog ) {
1611 this.saveDialog.clearDiff();
1612 }
1613 this.wikitextDiffPromise = null;
1614 };
1615
1616 /**
1617 * Post DOM data to the Parsoid API to retrieve wikitext diff.
1618 *
1619 * @param {HTMLDocument} doc Document to compare against (via wikitext)
1620 * @return {jQuery.Promise} Promise which resolves with the wikitext diff, or rejects with an error
1621 * @fires ve.init.mw.ArticleTarget#showChanges
1622 * @fires ve.init.mw.ArticleTarget#showChangesError
1623 */
1624 ve.init.mw.ArticleTarget.prototype.getWikitextDiffPromise = function ( doc ) {
1625 if ( !this.wikitextDiffPromise ) {
1626 this.wikitextDiffPromise = this.tryWithPreparedCacheKey( doc, {
1627 paction: 'diff',
1628 page: this.getPageName(),
1629 oldid: this.revid,
1630 etag: this.etag
1631 }, 'diff' ).then( ( data ) => {
1632 if ( !data.diff ) {
1633 this.emit( 'noChanges' );
1634 }
1635 return data.diff;
1636 } );
1637 this.wikitextDiffPromise
1638 .done( this.emit.bind( this, 'showChanges' ) )
1639 .fail( this.emit.bind( this, 'showChangesError' ) );
1640 }
1641 return this.wikitextDiffPromise;
1642 };
1643
1644 /**
1645 * Post wikitext to MediaWiki.
1646 *
1647 * This method performs a synchronous action and will take the user to a new page when complete.
1648 *
1649 * this.submit( wikitext, { wpSummary: 'test', wpMinorEdit: 1, wpSave: 1 } );
1650 *
1651 * @param {string} wikitext Wikitext to submit
1652 * @param {Object} fields Other form fields to add (e.g. wpSummary, wpWatchthis, etc.). To actually
1653 * save the wikitext, add { wpSave: 1 }. To go to the diff view, add { wpDiff: 1 }.
1654 * @return {boolean} Submitting has been started
1655 */
1656 ve.init.mw.ArticleTarget.prototype.submit = function ( wikitext, fields ) {
1657 // Prevent duplicate requests
1658 if ( this.submitting ) {
1659 return false;
1660 }
1661 // Clear autosave now that we don't expect to need it again.
1662 // FIXME: This isn't transactional, so if the save fails we're left with no recourse.
1663 this.clearDocState();
1664 // Save DOM
1665 this.submitting = true;
1666 const $form = $( '<form>' ).attr( { method: 'post', enctype: 'multipart/form-data' } ).addClass( 'oo-ui-element-hidden' );
1667 const params = ve.extendObject( {
1668 format: 'text/x-wiki',
1669 model: 'wikitext',
1670 oldid: this.requestedRevId,
1671 wpStarttime: this.startTimeStamp,
1672 wpEdittime: this.baseTimeStamp,
1673 wpTextbox1: wikitext,
1674 wpEditToken: mw.user.tokens.get( 'csrfToken' ),
1675 // MediaWiki function-verification parameters, mostly relevant to the
1676 // classic editpage, but still required here:
1677 wpUnicodeCheck: 'ℳ𝒲♥𝓊𝓃𝒾𝒸ℴ𝒹ℯ',
1678 wpUltimateParam: true
1679 }, fields );
1680 // Add params as hidden fields
1681 for ( const key in params ) {
1682 $form.append( $( '<input>' ).attr( { type: 'hidden', name: key, value: params[ key ] } ) );
1683 }
1684 // Submit the form, mimicking a traditional edit
1685 // Firefox requires the form to be attached
1686 const submitUrl = mw.util.getUrl( this.getPageName(), {
1687 action: 'submit',
1688 veswitched: '1'
1689 } );
1690 $form.attr( 'action', submitUrl ).appendTo( 'body' ).trigger( 'submit' );
1691 return true;
1692 };
1693
1694 /**
1695 * Get Wikitext data from the Parsoid API.
1696 *
1697 * This method performs an asynchronous action and uses a callback function to handle the result.
1698 *
1699 * this.serialize( doc ).then( ( data ) => {
1700 * // Do something with data.content (wikitext)
1701 * } );
1702 *
1703 * @param {HTMLDocument} doc Document to serialize
1704 * @param {Function} [callback] Optional callback to run after.
1705 * Deprecated in favor of using the returned promise.
1706 * @return {jQuery.Promise} Serialize promise, see mw.libs.ve.targetSaver.postHtml
1707 */
1708 ve.init.mw.ArticleTarget.prototype.serialize = function ( doc, callback ) {
1709 // Prevent duplicate requests
1710 if ( this.serializing ) {
1711 return this.serializing;
1712 }
1713 const promise = this.serializing = this.tryWithPreparedCacheKey( doc, {
1714 paction: 'serialize',
1715 page: this.getPageName(),
1716 oldid: this.revid,
1717 etag: this.etag
1718 }, 'serialize' )
1719 .done( this.emit.bind( this, 'serializeComplete' ) )
1720 .fail( this.emit.bind( this, 'serializeError' ) )
1721 .always( () => {
1722 this.serializing = null;
1723 } );
1724
1725 if ( callback ) {
1726 OO.ui.warnDeprecation( 'Passing a callback to ve.init.mw.ArticleTarget#serialize is deprecated. Use the returned promise instead.' );
1727 promise.then( ( data ) => {
1728 callback.call( this, data.content );
1729 } );
1730 }
1731
1732 return promise;
1733 };
1734
1735 /**
1736 * Get list of edit notices.
1737 *
1738 * @return {Array} List of edit notices
1739 */
1740 ve.init.mw.ArticleTarget.prototype.getEditNotices = function () {
1741 return this.editNotices;
1742 };
1743
1744 // FIXME: split out view specific functionality, emit to subclass
1745
1746 /**
1747 * @inheritdoc
1748 */
1749 ve.init.mw.ArticleTarget.prototype.track = function ( name ) {
1750 const mode = this.surface ? this.surface.getMode() : this.getDefaultMode();
1751 ve.track( name, { mode: mode } );
1752 };
1753
1754 /**
1755 * @inheritdoc
1756 */
1757 ve.init.mw.ArticleTarget.prototype.createSurface = function ( dmDoc, config ) {
1758 const sections = dmDoc.getNodesByType( 'section' );
1759 let attachedRoot;
1760 if ( sections.length && sections.length === 1 ) {
1761 attachedRoot = sections[ 0 ];
1762 if ( !attachedRoot.isSurfaceable() ) {
1763 throw new Error( 'Not a surfaceable node' );
1764 }
1765 }
1766
1767 // Parent method
1768 const surface = ve.init.mw.ArticleTarget.super.prototype.createSurface.call(
1769 this,
1770 dmDoc,
1771 ve.extendObject( { attachedRoot: attachedRoot }, config )
1772 );
1773
1774 return surface;
1775 };
1776
1777 /**
1778 * @inheritdoc
1779 */
1780 ve.init.mw.ArticleTarget.prototype.getSurfaceClasses = function () {
1781 const classes = ve.init.mw.ArticleTarget.super.prototype.getSurfaceClasses.call( this );
1782 return [ ...classes, 'mw-body-content' ];
1783 };
1784
1785 /**
1786 * @inheritdoc
1787 */
1788 ve.init.mw.ArticleTarget.prototype.getSurfaceConfig = function ( config ) {
1789 return ve.init.mw.ArticleTarget.super.prototype.getSurfaceConfig.call( this, ve.extendObject( {
1790 // Don't null selection on blur when editing a document.
1791 // Do use it in new section mode as there are multiple inputs
1792 // on the surface (header+content).
1793 nullSelectionOnBlur: this.section === 'new',
1794 classes: this.getSurfaceClasses()
1795 // The following classes are used here:
1796 // * mw-textarea-proteced
1797 // * mw-textarea-cproteced
1798 // * mw-textarea-sproteced
1799 .concat( this.protectedClasses )
1800 // addClass doesn't like empty strings
1801 .filter( ( c ) => c )
1802 }, config ) );
1803 };
1804
1805 /**
1806 * @inheritdoc
1807 */
1808 ve.init.mw.ArticleTarget.prototype.teardown = function () {
1809 if ( !this.teardownPromise ) {
1810 const surface = this.getSurface();
1811
1812 // Restore access keys
1813 if ( this.$saveAccessKeyElements ) {
1814 this.$saveAccessKeyElements.attr( 'accesskey', ve.msg( 'accesskey-save' ) );
1815 this.$saveAccessKeyElements = null;
1816 }
1817 if ( surface ) {
1818 // Disconnect history listener
1819 surface.getModel().disconnect( this );
1820 }
1821
1822 let saveDialogPromise = ve.createDeferred().resolve().promise();
1823 if ( this.saveDialog ) {
1824 if ( this.saveDialog.isOpened() ) {
1825 // If the save dialog is still open (from saving) close it
1826 saveDialogPromise = this.saveDialog.close().closed;
1827 }
1828 // Release the reference
1829 this.saveDialog = null;
1830 }
1831
1832 // Parent method
1833 this.teardownPromise = ve.init.mw.ArticleTarget.super.prototype.teardown.call( this ).then( () => saveDialogPromise.then( () => {
1834 mw.hook( 've.deactivationComplete' ).fire( this.edited );
1835 } ) );
1836 }
1837 return this.teardownPromise;
1838 };
1839
1840 /**
1841 * Try to tear down the target, but leave ready for re-activation later
1842 *
1843 * Will first prompt the user if required, then call #teardown.
1844 *
1845 * @param {boolean} [noPrompt] Do not display a prompt to the user
1846 * @param {string} [trackMechanism] Abort mechanism; used for event tracking if present
1847 * @return {jQuery.Promise} Promise which resolves when the target has been torn down, rejects if the target won't be torn down
1848 */
1849 ve.init.mw.ArticleTarget.prototype.tryTeardown = function ( noPrompt, trackMechanism ) {
1850 if ( !noPrompt && this.edited && mw.user.options.get( 'useeditwarning' ) ) {
1851 return this.getSurface().dialogs.openWindow( 'abandonedit' )
1852 .closed.then( ( data ) => {
1853 if ( data && data.action === 'discard' ) {
1854 return this.teardown( trackMechanism );
1855 }
1856 return ve.createDeferred().reject().promise();
1857 } );
1858 } else {
1859 return this.teardown( trackMechanism );
1860 }
1861 };
1862
1863 /**
1864 * @inheritdoc
1865 */
1866 ve.init.mw.ArticleTarget.prototype.setupToolbar = function () {
1867 // Parent method
1868 ve.init.mw.ArticleTarget.super.prototype.setupToolbar.apply( this, arguments );
1869
1870 this.setupToolbarSaveButton();
1871 this.updateToolbarSaveButtonState();
1872
1873 if ( this.saveDialog ) {
1874 this.editSummaryValue = this.saveDialog.editSummaryInput.getValue();
1875 this.saveDialog.disconnect( this );
1876 this.saveDialog = null;
1877 }
1878 };
1879
1880 /**
1881 * Getting the message for the toolbar / save dialog save / publish button
1882 *
1883 * @param {boolean} [startProcess] Use version of the label for starting that process, i.e. with an ellipsis after it
1884 * @param {boolean} [forceShort] Force the short version of the label, always used on mobile
1885 * @return {Function|string} An i18n message or resolveable function
1886 */
1887 ve.init.mw.ArticleTarget.prototype.getSaveButtonLabel = function ( startProcess, forceShort ) {
1888 const suffix = startProcess ? '-start' : '';
1889
1890 if ( forceShort || OO.ui.isMobile() ) {
1891 // The following messages can be used here:
1892 // * visualeditor-savedialog-label-publish-short
1893 // * visualeditor-savedialog-label-publish-short-start
1894 // * visualeditor-savedialog-label-save-short
1895 // * visualeditor-savedialog-label-save-short-start
1896 if ( mw.config.get( 'wgEditSubmitButtonLabelPublish' ) ) {
1897 return OO.ui.deferMsg( 'visualeditor-savedialog-label-publish-short' + suffix );
1898 }
1899
1900 return OO.ui.deferMsg( 'visualeditor-savedialog-label-save-short' + suffix );
1901 }
1902
1903 // The following messages can be used here
1904 // * publishpage
1905 // * publishpage-start
1906 // * publishchanges
1907 // * publishchanges-start
1908 // * savearticle
1909 // * savearticle-start
1910 // * savechanges
1911 // * savechanges-start
1912 if ( mw.config.get( 'wgEditSubmitButtonLabelPublish' ) ) {
1913 return OO.ui.deferMsg( ( !this.pageExists ? 'publishpage' : 'publishchanges' ) + suffix );
1914 }
1915
1916 return OO.ui.deferMsg( ( !this.pageExists ? 'savearticle' : 'savechanges' ) + suffix );
1917 };
1918
1919 /**
1920 * Setup the toolbarSaveButton property to point to the save tool
1921 *
1922 * @method
1923 * @abstract
1924 */
1925 ve.init.mw.ArticleTarget.prototype.setupToolbarSaveButton = null;
1926
1927 /**
1928 * Re-evaluate whether the article can be saved
1929 *
1930 * @return {boolean} The article can be saved
1931 */
1932 ve.init.mw.ArticleTarget.prototype.isSaveable = function () {
1933 const surface = this.getSurface();
1934 if ( !surface ) {
1935 // Called before we're attached, so meaningless; abandon for now
1936 return false;
1937 }
1938
1939 this.edited =
1940 // Document was edited before loading
1941 this.fromEditedState ||
1942 // Document was edited
1943 surface.getModel().hasBeenModified() ||
1944 // Section title (if it exists) was edited
1945 ( !!this.sectionTitle && this.sectionTitle.getValue() !== '' );
1946
1947 return this.edited || this.restoring;
1948 };
1949
1950 /**
1951 * Update the toolbar save button to reflect if the article can be saved
1952 */
1953 ve.init.mw.ArticleTarget.prototype.updateToolbarSaveButtonState = function () {
1954 // This should really be an emit('updateState') but that would cause
1955 // every tool to be updated on every transaction.
1956 this.toolbarSaveButton.onUpdateState();
1957 };
1958
1959 /**
1960 * Show a save dialog
1961 *
1962 * @param {string} [action] Window action to trigger after opening
1963 * @param {string} [checkboxName] Checkbox to toggle after opening
1964 *
1965 * @fires ve.init.mw.ArticleTarget#saveWorkflowBegin
1966 */
1967 ve.init.mw.ArticleTarget.prototype.showSaveDialog = function ( action, checkboxName ) {
1968 let firstLoad = false;
1969
1970 if ( !this.isSaveable() || this.saveDialogIsOpening ) {
1971 return;
1972 }
1973
1974 const currentWindow = this.getSurface().getDialogs().getCurrentWindow();
1975 if ( currentWindow && currentWindow.constructor.static.name === 'mwSave' && ( action === 'save' || action === null ) ) {
1976 // The current window is the save dialog, and we've gotten here via
1977 // the save action. Trigger a save. We're doing this here instead of
1978 // relying on an accesskey on the save button, because that has some
1979 // cross-browser issues that makes it not work in Firefox.
1980 currentWindow.executeAction( 'save' );
1981 return;
1982 }
1983
1984 this.saveDialogIsOpening = true;
1985
1986 const saveProcess = new OO.ui.Process();
1987 mw.hook( 've.preSaveProcess' ).fire( saveProcess, this );
1988
1989 this.emit( 'saveWorkflowBegin' );
1990
1991 saveProcess.execute().done( () => {
1992 // Preload the serialization
1993 this.prepareCacheKey( this.getDocToSave() );
1994
1995 // Get the save dialog
1996 this.getSurface().getDialogs().getWindow( 'mwSave' ).done( ( win ) => {
1997 const windowAction = ve.ui.actionFactory.create( 'window', this.getSurface() );
1998
1999 if ( !this.saveDialog ) {
2000 this.saveDialog = win;
2001 firstLoad = true;
2002
2003 // Connect to save dialog
2004 this.saveDialog.connect( this, {
2005 save: 'onSaveDialogSave',
2006 review: 'onSaveDialogReview',
2007 preview: 'onSaveDialogPreview',
2008 resolve: 'onSaveDialogResolveConflict',
2009 retry: 'onSaveDialogRetry',
2010 // The array syntax is a way to call `this.emit( 'saveWorkflowEnd' )`.
2011 close: [ 'emit', 'saveWorkflowEnd' ]
2012 } );
2013
2014 // Attach custom overlay
2015 this.saveDialog.$element.append( this.$saveDialogOverlay );
2016 }
2017
2018 const data = this.getSaveDialogOpeningData();
2019
2020 if (
2021 ( action === 'review' && !data.canReview ) ||
2022 ( action === 'preview' && !data.canPreview )
2023 ) {
2024 this.saveDialogIsOpening = false;
2025 return;
2026 }
2027
2028 if ( firstLoad ) {
2029 for ( const name in this.checkboxesByName ) {
2030 if ( this.initialCheckboxes[ name ] !== undefined ) {
2031 this.checkboxesByName[ name ].setSelected( this.initialCheckboxes[ name ] );
2032 }
2033 }
2034 }
2035
2036 let checkbox;
2037 if ( checkboxName && ( checkbox = this.checkboxesByName[ checkboxName ] ) ) {
2038 const isSelected = !checkbox.isSelected();
2039 // Wait for native access key change to happen
2040 setTimeout( () => {
2041 checkbox.setSelected( isSelected );
2042 } );
2043 }
2044
2045 // When calling review/preview action, switch to those panels immediately
2046 if ( action === 'review' || action === 'preview' ) {
2047 data.initialPanel = action;
2048 }
2049
2050 // Open the dialog
2051 const openPromise = windowAction.open( 'mwSave', data, action );
2052 if ( openPromise ) {
2053 openPromise.always( () => {
2054 this.saveDialogIsOpening = false;
2055 } );
2056 }
2057 } );
2058 } ).fail( () => {
2059 this.saveDialogIsOpening = false;
2060 } );
2061 };
2062
2063 /**
2064 * Get opening data to pass to the save dialog
2065 *
2066 * @return {Object} Opening data
2067 */
2068 ve.init.mw.ArticleTarget.prototype.getSaveDialogOpeningData = function () {
2069 const mode = this.getSurface().getMode();
2070 return {
2071 canPreview: mode === 'source',
2072 canReview: !( mode === 'source' && this.section === 'new' ),
2073 sectionTitle: this.sectionTitle && this.sectionTitle.getValue(),
2074 saveButtonLabel: this.getSaveButtonLabel(),
2075 copyrightWarning: this.copyrightWarning,
2076 checkboxFields: this.checkboxFields,
2077 checkboxesByName: this.checkboxesByName
2078 };
2079 };
2080
2081 /**
2082 * Move the cursor in the editor to section specified by this.section.
2083 * Do nothing if this.section is undefined.
2084 */
2085 ve.init.mw.ArticleTarget.prototype.restoreEditSection = function () {
2086 const section = this.section !== null ? this.section : this.visibleSection;
2087 const surface = this.getSurface();
2088 const mode = surface.getMode();
2089
2090 if (
2091 mode === 'source' ||
2092 ( this.enableVisualSectionEditing && this.section !== null )
2093 ) {
2094 this.$scrollContainer.scrollTop( 0 );
2095 }
2096
2097 if ( section === null || section === 'new' || section === '0' || section === 'T-0' ) {
2098 return;
2099 }
2100
2101 const setExactScrollOffset = this.section === null && this.visibleSection !== null && this.visibleSectionOffset !== null,
2102 // User clicked section edit link with visual section editing not available:
2103 // Take them to the top of the section using goToHeading
2104 goToStartOfHeading = this.section !== null && !this.enableVisualSectionEditing,
2105 setEditSummary = this.section !== null;
2106
2107 let headingText;
2108 if ( mode === 'visual' ) {
2109 const dmDoc = surface.getModel().getDocument();
2110 // In mw.libs.ve.unwrapParsoidSections we copy the data-mw-section-id from the section element
2111 // to the heading. Iterate over headings to find the one with the correct attribute
2112 // in originalDomElements.
2113 let headingModel;
2114 dmDoc.getNodesByType( 'mwHeading' ).some( ( heading ) => {
2115 const domElements = heading.getOriginalDomElements( dmDoc.getStore() );
2116 if (
2117 domElements && domElements[ 0 ].nodeType === Node.ELEMENT_NODE &&
2118 domElements[ 0 ].getAttribute( 'data-mw-section-id' ) === section
2119 ) {
2120 headingModel = heading;
2121 return true;
2122 }
2123 return false;
2124 } );
2125 if ( headingModel ) {
2126 const headingView = surface.getView().getDocument().getDocumentNode().getNodeFromOffset( headingModel.getRange().start );
2127 if ( setEditSummary && !new URL( location.href ).searchParams.has( 'summary' ) ) {
2128 headingText = headingView.$element.text();
2129 }
2130 if ( setExactScrollOffset ) {
2131 this.scrollToHeading( headingView, this.visibleSectionOffset );
2132 } else if ( goToStartOfHeading ) {
2133 this.goToHeading( headingView );
2134 }
2135 }
2136 } else if ( mode === 'source' && setEditSummary ) {
2137 // With elements of extractSectionTitle + stripSectionName TODO:
2138 // Arguably, we should just throw this through the API and then do
2139 // the same extract-text pass we do in visual mode. Would save us
2140 // having to think about wikitext here.
2141 headingText = surface.getModel().getDocument().data.getText(
2142 false,
2143 surface.getModel().getDocument().getDocumentNode().children[ 0 ].getRange()
2144 )
2145 // Extract the title
2146 .replace( /^\s*=+\s*(.*?)\s*=+\s*$/, '$1' )
2147 // Remove links
2148 .replace( /\[\[:?([^[|]+)\|([^[]+)\]\]/g, '$2' )
2149 .replace( /\[\[:?([^[]+)\|?\]\]/g, '$1' )
2150 .replace( new RegExp( '\\[(?:' + ve.init.platform.getUnanchoredExternalLinkUrlProtocolsRegExp().source + ')([^ ]+?) ([^\\[]+)\\]', 'ig' ), '$3' )
2151 // Cheap HTML removal
2152 .replace( /<[^>]+?>/g, '' );
2153 }
2154 if ( headingText ) {
2155 this.initialEditSummary =
2156 '/* ' +
2157 ve.graphemeSafeSubstring( headingText, 0, 244 ) +
2158 ' */ ';
2159 }
2160 };
2161
2162 /**
2163 * Move the cursor to a given heading and scroll to it.
2164 *
2165 * @param {ve.ce.HeadingNode} headingNode Heading node to scroll to
2166 */
2167 ve.init.mw.ArticleTarget.prototype.goToHeading = function ( headingNode ) {
2168 const surface = this.getSurface(),
2169 surfaceView = surface.getView();
2170
2171 let offsetNode = headingNode,
2172 lastHeadingLevel = -1;
2173 let nextNode;
2174 // Find next sibling which isn't a heading
2175 while ( offsetNode instanceof ve.ce.HeadingNode && offsetNode.getModel().getAttribute( 'level' ) > lastHeadingLevel ) {
2176 lastHeadingLevel = offsetNode.getModel().getAttribute( 'level' );
2177 // Next sibling
2178 nextNode = offsetNode.parent.children[ offsetNode.parent.children.indexOf( offsetNode ) + 1 ];
2179 if ( !nextNode ) {
2180 break;
2181 }
2182 offsetNode = nextNode;
2183 }
2184 const startOffset = offsetNode.getModel().getOffset();
2185
2186 function setSelection() {
2187 surfaceView.selectRelativeSelectableContentOffset( startOffset, 1 );
2188 }
2189
2190 if ( surfaceView.isFocused() ) {
2191 setSelection();
2192 // Focussing the document triggers showSelection which calls scrollIntoView
2193 // which uses a jQuery animation, so make sure this is aborted.
2194 $( OO.ui.Element.static.getClosestScrollableContainer( surfaceView.$element[ 0 ] ) ).stop( true );
2195 } else {
2196 // onDocumentFocus is debounced, so wait for that to happen before setting
2197 // the model selection, otherwise it will get reset
2198 surfaceView.once( 'focus', setSelection );
2199 }
2200 this.scrollToHeading( headingNode );
2201 };
2202
2203 /**
2204 * Scroll to a given heading in the document.
2205 *
2206 * @param {ve.ce.HeadingNode} headingNode Heading node to scroll to
2207 * @param {number} [headingOffset=0] Set the top offset of the heading to a specific amount, relative
2208 * to the surface viewport.
2209 */
2210 ve.init.mw.ArticleTarget.prototype.scrollToHeading = function ( headingNode, headingOffset ) {
2211 this.$scrollContainer.scrollTop(
2212 headingNode.$element.offset().top - parseInt( headingNode.$element.css( 'margin-top' ) ) -
2213 ( this.getSurface().padding.top + ( headingOffset || 0 ) ) );
2214 };
2215
2216 /**
2217 * Get the URL hash for the current section's ID using the page's HTML.
2218 *
2219 * TODO: Do this in a less skin-dependent way
2220 *
2221 * @return {string} URL hash with leading '#', or empty string if not found
2222 */
2223 ve.init.mw.ArticleTarget.prototype.getSectionHashFromPage = function () {
2224 // Assume there are section edit links, as the user just did a section edit. This also means
2225 // that the section numbers line up correctly, as not every H_ tag is a numbered section.
2226 const $sections = this.$editableContent.find( '.mw-editsection' );
2227
2228 let section;
2229 if ( this.section === 'new' ) {
2230 // A new section is appended to the end, so take the last one.
2231 section = $sections.length;
2232 } else {
2233 section = this.section;
2234 }
2235 if ( section > 0 ) {
2236 // Compatibility with pre-T13555 markup
2237 const $section = $sections.eq( section - 1 )
2238 .closest( '.mw-heading, h1, h2, h3, h4, h5, h6' )
2239 .find( 'h1, h2, h3, h4, h5, h6, .mw-headline' );
2240
2241 if ( $section.length && $section.attr( 'id' ) ) {
2242 return '#' + $section.attr( 'id' );
2243 }
2244 }
2245 return '';
2246 };
2247
2248 /**
2249 * Switches to the wikitext editor, either keeping (default) or discarding changes.
2250 *
2251 * @param {boolean} [modified=false] Whether there were any changes at all.
2252 */
2253 ve.init.mw.ArticleTarget.prototype.switchToWikitextEditor = function ( modified ) {
2254 // When switching with changes we always pass the full page as changes in visual section mode
2255 // can still affect the whole document (e.g. removing a reference)
2256 if ( modified ) {
2257 this.section = null;
2258 }
2259
2260 if ( this.isModeAvailable( 'source' ) ) {
2261 if ( !modified ) {
2262 this.reloadSurface( 'source' );
2263 } else {
2264 const dataPromise = this.getWikitextDataPromiseForDoc( modified );
2265 this.reloadSurface( 'source', dataPromise );
2266 }
2267 } else {
2268 this.switchToFallbackWikitextEditor( modified );
2269 }
2270 };
2271
2272 /**
2273 * Get a data promise for wikitext editing based on the current doc state
2274 *
2275 * @param {boolean} modified Whether there were any changes
2276 * @return {jQuery.Promise} Data promise
2277 */
2278 ve.init.mw.ArticleTarget.prototype.getWikitextDataPromiseForDoc = function ( modified ) {
2279 return this.serialize( this.getDocToSave() ).then( ( data ) => {
2280 // HACK - add parameters the API doesn't provide for a VE->WT switch
2281 data.etag = this.etag;
2282 data.fromEditedState = modified;
2283 data.notices = this.remoteNotices;
2284 data.protectedClasses = this.protectedClasses;
2285 data.basetimestamp = this.baseTimeStamp;
2286 data.starttimestamp = this.startTimeStamp;
2287 data.oldid = this.revid;
2288 data.canEdit = this.canEdit;
2289 data.wouldautocreate = this.wouldautocreate;
2290 data.checkboxesDef = this.checkboxesDef;
2291 // Wrap up like a response object as that is what dataPromise is expected to be
2292 return { visualeditoredit: data };
2293 } );
2294 };
2295
2296 /**
2297 * Switches to the fallback wikitext editor, either keeping (default) or discarding changes.
2298 *
2299 * @param {boolean} [modified=false] Whether there were any changes at all.
2300 * @return {jQuery.Promise} Promise which rejects if the switch fails
2301 */
2302 ve.init.mw.ArticleTarget.prototype.switchToFallbackWikitextEditor = function () {
2303 return ve.createDeferred().resolve().promise();
2304 };
2305
2306 /**
2307 * Switch to the visual editor.
2308 */
2309 ve.init.mw.ArticleTarget.prototype.switchToVisualEditor = function () {
2310 if ( !this.edited ) {
2311 this.reloadSurface( 'visual' );
2312 return;
2313 }
2314
2315 const url = new URL( location.href );
2316 const dataPromise = mw.libs.ve.targetLoader.requestParsoidData( this.getPageName(), {
2317 oldId: this.revid,
2318 targetName: this.constructor.static.trackingName,
2319 modified: this.edited,
2320 wikitext: this.getDocToSave(),
2321 section: this.section,
2322 editintro: url.searchParams.get( 'editintro' ),
2323 preload: url.searchParams.get( 'preload' ),
2324 preloadparams: mw.util.getArrayParam( 'preloadparams', url.searchParams )
2325 } );
2326
2327 this.reloadSurface( 'visual', dataPromise );
2328 };
2329
2330 /**
2331 * Switch to a different wikitext section
2332 *
2333 * @param {string|null} section Section to switch to: a number, 'T-'-prefixed number, 'new'
2334 * or null (whole document)
2335 * @param {boolean} [noPrompt=false] Switch without prompting (changes will be lost either way)
2336 */
2337 ve.init.mw.ArticleTarget.prototype.switchToWikitextSection = function ( section, noPrompt ) {
2338 if ( section === this.section ) {
2339 return;
2340 }
2341 let promise;
2342 if ( !noPrompt && this.edited && mw.user.options.get( 'useeditwarning' ) ) {
2343 promise = this.getSurface().dialogs.openWindow( 'abandonedit' )
2344 .closed.then( ( data ) => data && data.action === 'discard' );
2345 } else {
2346 promise = ve.createDeferred().resolve( true ).promise();
2347 }
2348 promise.then( ( confirmed ) => {
2349 if ( confirmed ) {
2350 // Section has changed and edits have been discarded, so edit summary is no longer valid
2351 // TODO: Preserve summary if document changes can be preserved
2352 if ( this.saveDialog ) {
2353 this.saveDialog.reset();
2354 }
2355 // TODO: If switching to a non-null section, get the new section title
2356 this.initialEditSummary = null;
2357 this.section = section;
2358 this.reloadSurface( 'source' );
2359 this.updateTabs();
2360 }
2361 } );
2362 };
2363
2364 /**
2365 * Reload the target surface in the new editor mode
2366 *
2367 * @param {string} newMode New mode
2368 * @param {jQuery.Promise} [dataPromise] Data promise, if any
2369 */
2370 ve.init.mw.ArticleTarget.prototype.reloadSurface = function ( newMode, dataPromise ) {
2371 this.setDefaultMode( newMode );
2372 this.clearDiff();
2373 const promise = this.load( dataPromise );
2374 this.getSurface().createProgress(
2375 promise,
2376 ve.msg( newMode === 'source' ? 'visualeditor-mweditmodesource-progress' : 'visualeditor-mweditmodeve-progress' ),
2377 true /* non-cancellable */
2378 );
2379 };
2380
2381 /**
2382 * Display the given redirect subtitle and redirect page content header on the page.
2383 *
2384 * @param {jQuery} $sub Redirect subtitle, see #buildRedirectSub
2385 * @param {jQuery} $msg Redirect page content header, see #buildRedirectMsg
2386 */
2387 ve.init.mw.ArticleTarget.prototype.updateRedirectInterface = function ( $sub, $msg ) {
2388 // For the subtitle, replace the real one with ours.
2389 // This is more complicated than it should be because we have to fiddle with the <br>.
2390 const $currentSub = $( '#redirectsub' );
2391 if ( $currentSub.length ) {
2392 if ( $sub.length ) {
2393 $currentSub.replaceWith( $sub );
2394 } else {
2395 $currentSub.prev().filter( 'br' ).remove();
2396 $currentSub.remove();
2397 }
2398 } else {
2399 const $subtitle = $( '#contentSub' );
2400 if ( $sub.length ) {
2401 if ( $subtitle.children().length ) {
2402 $subtitle.append( $( '<br>' ) );
2403 }
2404 $subtitle.append( $sub );
2405 }
2406 }
2407
2408 if ( $msg.length ) {
2409 $msg
2410 // We need to be able to tell apart the real one and our fake one
2411 .addClass( 've-redirect-header' )
2412 .on( 'click', ( e ) => {
2413 const windowAction = ve.ui.actionFactory.create( 'window', this.getSurface() );
2414 windowAction.open( 'meta', { page: 'settings' } );
2415 e.preventDefault();
2416 } );
2417 }
2418 // For the content header, the real one is hidden, insert ours before it.
2419 const $currentMsg = $( '.ve-redirect-header' );
2420 if ( $currentMsg.length ) {
2421 $currentMsg.replaceWith( $msg );
2422 } else {
2423 // Hack: This is normally inside #mw-content-text, but that's hidden while editing.
2424 $( '#mw-content-text' ).before( $msg );
2425 }
2426 };
2427
2428 /**
2429 * Set temporary redirect interface to match the current state of redirection in the editor.
2430 *
2431 * @param {string|null} title Current redirect target, or null if none
2432 */
2433 ve.init.mw.ArticleTarget.prototype.setFakeRedirectInterface = function ( title ) {
2434 this.isRedirect = !!title;
2435 this.updateRedirectInterface(
2436 title ? this.constructor.static.buildRedirectSub() : $(),
2437 title ? this.constructor.static.buildRedirectMsg( title ) : $()
2438 );
2439 };
2440
2441 /**
2442 * Set the redirect interface to match the page's redirect state.
2443 */
2444 ve.init.mw.ArticleTarget.prototype.setRealRedirectInterface = function () {
2445 this.updateRedirectInterface(
2446 mw.config.get( 'wgIsRedirect' ) ? this.constructor.static.buildRedirectSub() : $(),
2447 // Remove our custom content header - the original one in #mw-content-text will be shown
2448 $()
2449 );
2450 };
2451
2452 /**
2453 * Render a list of categories
2454 *
2455 * Duplicate items are not shown.
2456 *
2457 * @param {ve.dm.MetaItem[]} categoryItems Array of category metaitems to display
2458 * @return {jQuery.Promise} A promise which will be resolved with the rendered categories
2459 */
2460 ve.init.mw.ArticleTarget.prototype.renderCategories = function ( categoryItems ) {
2461 const promises = [],
2462 categories = { hidden: {}, normal: {} };
2463 categoryItems.forEach( ( categoryItem, index ) => {
2464 const attributes = ve.copy( ve.getProp( categoryItem, 'element', 'attributes' ) );
2465 attributes.index = index;
2466 promises.push( ve.init.platform.linkCache.get( attributes.category ).done( ( result ) => {
2467 const group = result.hidden ? categories.hidden : categories.normal;
2468 // In case of duplicates, first entry wins (like in MediaWiki)
2469 if ( !group[ attributes.category ] || group[ attributes.category ].index > attributes.index ) {
2470 group[ attributes.category ] = attributes;
2471 }
2472 } ) );
2473 } );
2474 return ve.promiseAll( promises ).then( () => {
2475 const $output = $( '<div>' ).addClass( 'catlinks' );
2476 function renderPageLink( page ) {
2477 const title = mw.Title.newFromText( page ),
2478 $link = $( '<a>' ).attr( 'rel', 'mw:WikiLink' ).attr( 'href', title.getUrl() ).text( title.getMainText() );
2479 // Style missing links. The data should already have been fetched
2480 // as part of the earlier processing of categoryItems.
2481 ve.init.platform.linkCache.styleElement( title.getPrefixedText(), $link, false );
2482 return $link;
2483 }
2484 function renderPageLinks( pages ) {
2485 const $list = $( '<ul>' );
2486 for ( let i = 0; i < pages.length; i++ ) {
2487 const $link = renderPageLink( pages[ i ] );
2488 $list.append( $( '<li>' ).append( $link ) );
2489 }
2490 return $list;
2491 }
2492 function categorySort( group, a, b ) {
2493 return group[ a ].index - group[ b ].index;
2494 }
2495 const categoriesNormal = Object.keys( categories.normal );
2496 if ( categoriesNormal.length ) {
2497 categoriesNormal.sort( categorySort.bind( null, categories.normal ) );
2498 const $normal = $( '<div>' ).addClass( 'mw-normal-catlinks' );
2499 const $pageLink = renderPageLink( ve.msg( 'pagecategorieslink' ) ).text( ve.msg( 'pagecategories', categoriesNormal.length ) );
2500 const $pageLinks = renderPageLinks( categoriesNormal );
2501 $normal.append(
2502 $pageLink,
2503 $( document.createTextNode( ve.msg( 'colon-separator' ) ) ),
2504 $pageLinks
2505 );
2506 $output.append( $normal );
2507 }
2508 const categoriesHidden = Object.keys( categories.hidden );
2509 if ( categoriesHidden.length ) {
2510 categoriesHidden.sort( categorySort.bind( null, categories.hidden ) );
2511 const $hidden = $( '<div>' ).addClass( 'mw-hidden-catlinks' );
2512 if ( mw.user.options.get( 'showhiddencats' ) ) {
2513 $hidden.addClass( 'mw-hidden-cats-user-shown' );
2514 } else if ( mw.config.get( 'wgNamespaceIds' ).category === mw.config.get( 'wgNamespaceNumber' ) ) {
2515 $hidden.addClass( 'mw-hidden-cats-ns-shown' );
2516 } else {
2517 $hidden.addClass( 'mw-hidden-cats-hidden' );
2518 }
2519 const $hiddenPageLinks = renderPageLinks( categoriesHidden );
2520 $hidden.append(
2521 $( document.createTextNode( ve.msg( 'hidden-categories', categoriesHidden.length ) ) ),
2522 $( document.createTextNode( ve.msg( 'colon-separator' ) ) ),
2523 $hiddenPageLinks
2524 );
2525 $output.append( $hidden );
2526 }
2527 return $output;
2528 } );
2529 };
2530
2531 // Used in tryTeardown
2532 ve.ui.windowFactory.register( mw.widgets.AbandonEditDialog );