Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor MediaWiki Initialization DesktopArticleTarget 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 * MediaWiki desktop article target.
12 *
13 * @class
14 * @extends ve.init.mw.ArticleTarget
15 *
16 * @constructor
17 * @param {Object} [config]
18 */
19 ve.init.mw.DesktopArticleTarget = function VeInitMwDesktopArticleTarget( config ) {
20 // Parent constructor
21 ve.init.mw.DesktopArticleTarget.super.call( this, config );
22
23 // Parent constructor bound key event handlers, but we don't want them bound until
24 // we activate; so unbind them again
25 this.unbindHandlers();
26
27 this.onWatchToggleHandler = this.onWatchToggle.bind( this );
28
29 // Properties
30 this.onBeforeUnloadFallback = null;
31 this.onBeforeUnload = this.onBeforeUnload.bind( this );
32 this.onUnloadHandler = this.onUnload.bind( this );
33 this.activating = false;
34 this.deactivating = false;
35 this.deactivatingDeferred = null;
36 this.recreating = false;
37 this.activatingDeferred = null;
38 this.toolbarSetupDeferred = null;
39 this.suppressNormalStartupDialogs = false;
40 this.editingTabDialog = null;
41 this.welcomeDialog = null;
42 this.welcomeDialogPromise = null;
43
44 // If this is true then #transformPage / #restorePage will not call pushState
45 // This is to avoid adding a new history entry for the url we just got from onpopstate
46 // (which would mess up with the expected order of Back/Forwards browsing)
47 this.actFromPopState = false;
48 this.popState = {
49 tag: 'visualeditor'
50 };
51 this.scrollTop = null;
52 this.section = null;
53 if ( $( '#wpSummary' ).length ) {
54 this.initialEditSummary = $( '#wpSummary' ).val();
55 } else {
56 this.initialEditSummary = this.currentUrl.searchParams.get( 'summary' );
57 }
58 this.initialCheckboxes = $( '.editCheckboxes input' ).toArray()
59 .reduce( ( initialCheckboxes, node ) => {
60 initialCheckboxes[ node.name ] = node.checked;
61 return initialCheckboxes;
62 }, {} );
63
64 this.tabLayout = mw.config.get( 'wgVisualEditorConfig' ).tabLayout;
65 this.events = new ve.init.mw.ArticleTargetEvents( this );
66 this.$originalContent = $( '<div>' ).addClass( 've-init-mw-desktopArticleTarget-originalContent' );
67 this.$editableContent.addClass( 've-init-mw-desktopArticleTarget-editableContent' );
68
69 // Initialization
70 this.$element
71 .addClass( 've-init-mw-desktopArticleTarget' )
72 .append( this.$originalContent );
73
74 // We replace the current state with one that's marked with our tag. This way, when users
75 // use the Back button to exit the editor we can restore Read mode. This is because we want
76 // to ignore foreign states in onWindowPopState. Without this, the Read state is foreign.
77 // FIXME: There should be a much better solution than this.
78 history.replaceState( this.popState, '', this.currentUrl );
79
80 this.setupSkinTabs();
81
82 window.addEventListener( 'popstate', this.onWindowPopState.bind( this ) );
83 };
84
85 /* Inheritance */
86
87 OO.inheritClass( ve.init.mw.DesktopArticleTarget, ve.init.mw.ArticleTarget );
88
89 /* Static Properties */
90
91 ve.init.mw.DesktopArticleTarget.static.toolbarGroups = ve.copy( ve.init.mw.DesktopArticleTarget.static.toolbarGroups );
92 ve.init.mw.DesktopArticleTarget.static.toolbarGroups.push(
93 {
94 name: 'help',
95 align: 'after',
96 type: 'mwHelpList',
97 icon: 'help',
98 indicator: null,
99 title: ve.msg( 'visualeditor-help-tool' ),
100 include: [ { group: 'help' } ],
101 promote: [ 'mwUserGuide' ]
102 },
103 {
104 name: 'notices',
105 align: 'after',
106 include: [ { group: 'notices' } ]
107 },
108 {
109 name: 'pageMenu',
110 align: 'after',
111 type: 'list',
112 icon: 'menu',
113 indicator: null,
114 title: ve.msg( 'visualeditor-pagemenu-tooltip' ),
115 label: ve.msg( 'visualeditor-pagemenu-tooltip' ),
116 invisibleLabel: true,
117 include: [ { group: 'utility' } ],
118 demote: [ 'changeDirectionality', 'findAndReplace' ]
119 },
120 {
121 name: 'editMode',
122 align: 'after',
123 type: 'list',
124 icon: 'edit',
125 title: ve.msg( 'visualeditor-mweditmode-tooltip' ),
126 label: ve.msg( 'visualeditor-mweditmode-tooltip' ),
127 invisibleLabel: true,
128 include: [ { group: 'editMode' } ]
129 },
130 {
131 name: 'save',
132 align: 'after',
133 type: 'bar',
134 include: [ { group: 'save' } ]
135 }
136 );
137
138 ve.init.mw.DesktopArticleTarget.static.platformType = 'desktop';
139
140 /* Events */
141
142 /**
143 * @event ve.init.mw.DesktopArticleTarget#deactivate
144 */
145
146 /**
147 * @event ve.init.mw.DesktopArticleTarget#transformPage
148 */
149
150 /**
151 * @event ve.init.mw.DesktopArticleTarget#restorePage
152 */
153
154 /**
155 * Fired when user clicks the button to open the save dialog.
156 *
157 * @event ve.init.mw.DesktopArticleTarget#saveWorkflowBegin
158 */
159
160 /**
161 * Fired when user exits the save workflow
162 *
163 * @event ve.init.mw.DesktopArticleTarget#saveWorkflowEnd
164 */
165
166 /**
167 * Fired when user initiates review changes in save workflow
168 *
169 * @event ve.init.mw.DesktopArticleTarget#saveReview
170 */
171
172 /**
173 * Fired when user initiates saving of the document
174 *
175 * @event ve.init.mw.DesktopArticleTarget#saveInitiated
176 */
177
178 /* Methods */
179
180 /**
181 * @inheritdoc
182 */
183 ve.init.mw.DesktopArticleTarget.prototype.addSurface = function ( dmDoc, config ) {
184 config = ve.extendObject( {
185 $overlayContainer: $(
186 document.querySelector( '[data-mw-ve-target-container]' ) ||
187 document.getElementById( 'content' )
188 ),
189 // Vector-2022 content area has no padding itself, so popups render too close
190 // to the edge of the text (T258501). Use a negative value to allow popups to
191 // position slightly outside the content. Padding elsewhere means we are
192 // guaranteed 30px of space between the content and the edge of the viewport.
193 // Other skins pass 'undefined' to use the default padding of +10px.
194 overlayPadding: mw.config.get( 'skin' ) === 'vector-2022' ? -10 : undefined
195 }, config );
196 return ve.init.mw.DesktopArticleTarget.super.prototype.addSurface.call( this, dmDoc, config );
197 };
198
199 /**
200 * Set the container for the target, appending the target to it
201 *
202 * @param {jQuery} $container
203 */
204 ve.init.mw.DesktopArticleTarget.prototype.setContainer = function ( $container ) {
205 $container.append( this.$element );
206 this.$container = $container;
207 };
208
209 /**
210 * Verify that a PopStateEvent correlates to a state we created.
211 *
212 * @param {any} popState From PopStateEvent#state
213 * @return {boolean}
214 */
215 ve.init.mw.DesktopArticleTarget.prototype.verifyPopState = function ( popState ) {
216 return popState && popState.tag === 'visualeditor';
217 };
218
219 /**
220 * @inheritdoc
221 */
222 ve.init.mw.DesktopArticleTarget.prototype.setupToolbar = function ( surface ) {
223 const mode = surface.getMode(),
224 wasSetup = !!this.toolbar;
225
226 ve.track( 'trace.setupToolbar.enter', { mode: mode } );
227
228 // Parent method
229 ve.init.mw.DesktopArticleTarget.super.prototype.setupToolbar.call( this, surface );
230
231 const toolbar = this.getToolbar();
232
233 // Allow the toolbar to start floating now if necessary
234 this.onContainerScroll();
235
236 ve.track( 'trace.setupToolbar.exit', { mode: mode } );
237 if ( !wasSetup ) {
238 toolbar.$element
239 .addClass( 've-init-mw-desktopArticleTarget-toolbar-open' );
240 if ( !toolbar.isFloating() ) {
241 toolbar.$element.css( 'height', '' );
242 }
243 this.toolbarSetupDeferred.resolve();
244
245 this.toolbarSetupDeferred.done( () => {
246 const newSurface = this.getSurface();
247 // Check the surface wasn't torn down while the toolbar was animating
248 if ( newSurface ) {
249 ve.track( 'trace.initializeToolbar.enter', { mode: mode } );
250 this.getToolbar().initialize();
251 newSurface.getView().emit( 'position' );
252 newSurface.getContext().updateDimensions();
253 ve.track( 'trace.initializeToolbar.exit', { mode: mode } );
254 ve.track( 'trace.activate.exit', { mode: mode } );
255 }
256 } );
257 }
258 };
259
260 /**
261 * @inheritdoc
262 */
263 ve.init.mw.DesktopArticleTarget.prototype.attachToolbar = function () {
264 // Set edit notices, will be shown after welcome dialog.
265 // Make sure notices actually exists, because this might be a mode-switch and
266 // we've already removed it.
267 const editNotices = this.getEditNotices(),
268 actionTools = this.toolbar.tools;
269 if ( editNotices && editNotices.length && actionTools.notices ) {
270 actionTools.notices.setNotices( editNotices );
271 } else if ( actionTools.notices ) {
272 actionTools.notices.destroy();
273 actionTools.notices = null;
274 }
275
276 // Move the toolbar to top of target, before heading etc.
277 // Avoid re-attaching as it breaks CSS animations
278 if ( !this.toolbar.$element.parent().is( this.$element ) ) {
279 this.toolbar.$element
280 // Set 0 before attach (expanded in #setupToolbar)
281 .css( 'height', '0' )
282 .addClass( 've-init-mw-desktopArticleTarget-toolbar' );
283 this.$element.prepend( this.toolbar.$element );
284
285 // Calculate if the 'oo-ui-toolbar-narrow' class is needed (OOUI does it too late for our
286 // toolbar because the methods are called in the wrong order, see T92282).
287 this.toolbar.onWindowResize();
288 }
289 };
290
291 /**
292 * @inheritdoc
293 */
294 ve.init.mw.DesktopArticleTarget.prototype.setupToolbarSaveButton = function () {
295 this.toolbarSaveButton = this.toolbar.getToolGroupByName( 'save' ).items[ 0 ];
296 };
297
298 /**
299 * @inheritdoc
300 */
301 ve.init.mw.DesktopArticleTarget.prototype.updateTabs = function () {
302 mw.libs.ve.updateTabs( true, this.getDefaultMode(), this.section === 'new' );
303 };
304
305 /**
306 * @inheritdoc
307 */
308 ve.init.mw.DesktopArticleTarget.prototype.loadSuccess = function () {
309 // Parent method
310 ve.init.mw.DesktopArticleTarget.super.prototype.loadSuccess.apply( this, arguments );
311
312 this.wikitextFallbackLoading = false;
313 // Duplicate of this code in ve.init.mw.DesktopArticleTarget.init.js
314 // eslint-disable-next-line no-jquery/no-class-state
315 if ( $( '#ca-edit' ).hasClass( 'visualeditor-showtabdialog' ) ) {
316 $( '#ca-edit' ).removeClass( 'visualeditor-showtabdialog' );
317 // Set up a temporary window manager
318 const windowManager = new OO.ui.WindowManager();
319 $( OO.ui.getTeleportTarget() ).append( windowManager.$element );
320 this.editingTabDialog = new mw.libs.ve.EditingTabDialog();
321 windowManager.addWindows( [ this.editingTabDialog ] );
322 windowManager.openWindow( this.editingTabDialog )
323 .closed.then( ( data ) => {
324 // Detach the temporary window manager
325 windowManager.destroy();
326
327 if ( data && data.action === 'prefer-wt' ) {
328 this.switchToWikitextEditor( false );
329 } else if ( data && data.action === 'multi-tab' ) {
330 location.reload();
331 }
332 } );
333
334 // Pretend the user saw the welcome dialog before suppressing it.
335 mw.libs.ve.stopShowingWelcomeDialog();
336 this.suppressNormalStartupDialogs = true;
337 }
338 };
339
340 /**
341 * Handle the watch button being toggled on/off.
342 *
343 * @param {boolean} isWatched
344 * @param {string} expiry
345 * @param {string} expirySelected
346 */
347 ve.init.mw.DesktopArticleTarget.prototype.onWatchToggle = function ( isWatched ) {
348 if ( !this.active && !this.activating ) {
349 return;
350 }
351 if ( this.checkboxesByName && this.checkboxesByName.wpWatchthis ) {
352 this.checkboxesByName.wpWatchthis.setSelected(
353 !!mw.user.options.get( 'watchdefault' ) ||
354 ( !!mw.user.options.get( 'watchcreations' ) && !this.pageExists ) ||
355 isWatched
356 );
357 }
358 };
359
360 /**
361 * @inheritdoc
362 */
363 ve.init.mw.DesktopArticleTarget.prototype.bindHandlers = function () {
364 ve.init.mw.DesktopArticleTarget.super.prototype.bindHandlers.call( this );
365 if ( this.onWatchToggleHandler ) {
366 mw.hook( 'wikipage.watchlistChange' ).add( this.onWatchToggleHandler );
367 }
368 };
369
370 /**
371 * @inheritdoc
372 */
373 ve.init.mw.DesktopArticleTarget.prototype.unbindHandlers = function () {
374 ve.init.mw.DesktopArticleTarget.super.prototype.unbindHandlers.call( this );
375 if ( this.onWatchToggleHandler ) {
376 mw.hook( 'wikipage.watchlistChange' ).remove( this.onWatchToggleHandler );
377 }
378 };
379
380 /**
381 * Switch to edit mode.
382 *
383 * @param {jQuery.Promise} [dataPromise] Promise for pending request from
384 * mw.libs.ve.targetLoader#requestPageData, if any
385 * @return {jQuery.Promise}
386 */
387 ve.init.mw.DesktopArticleTarget.prototype.activate = function ( dataPromise ) {
388 // We may be re-activating an old target, during which time ve.init.target
389 // has been overridden.
390 ve.init.target = ve.init.articleTarget;
391
392 if ( !this.active && !this.activating ) {
393 this.activating = true;
394 this.activatingDeferred = ve.createDeferred();
395 this.toolbarSetupDeferred = ve.createDeferred();
396
397 $( 'html' ).addClass( 've-activating' );
398 ve.promiseAll( [ this.activatingDeferred, this.toolbarSetupDeferred ] ).done( () => {
399 if ( !this.suppressNormalStartupDialogs ) {
400 this.maybeShowWelcomeDialog();
401 this.maybeShowMetaDialog();
402 }
403 this.afterActivate();
404 } ).fail( () => {
405 $( 'html' ).removeClass( 've-activating' );
406 } );
407
408 // Handlers were unbound in constructor. Will be unbound again in teardown.
409 this.bindHandlers();
410
411 this.originalEditondbclick = mw.user.options.get( 'editondblclick' );
412 mw.user.options.set( 'editondblclick', 0 );
413
414 // User interface changes
415 this.changeDocumentTitle();
416 this.transformPage();
417
418 this.load( dataPromise );
419 }
420 return this.activatingDeferred.promise();
421 };
422
423 /**
424 * Edit mode has finished activating
425 */
426 ve.init.mw.DesktopArticleTarget.prototype.afterActivate = function () {
427 $( 'html' ).removeClass( 've-activating' ).addClass( 've-active' );
428
429 // Disable TemplateStyles in the original content
430 // (We do this here because toggling 've-active' class above hides it)
431 this.$editableContent.find( 'style[data-mw-deduplicate^="TemplateStyles:"]' ).prop( 'disabled', true );
432
433 this.afterSurfaceReady();
434
435 if ( !this.editingTabDialog ) {
436 if ( this.sectionTitle ) {
437 this.sectionTitle.focus();
438 } else {
439 // We have to focus the page after hiding the original content, otherwise
440 // in firefox the contentEditable container was below the view page, and
441 // 'focus' scrolled the screen down.
442 // Support: Firefox
443 this.getSurface().getView().focus();
444 }
445 // Transfer and initial source range to the surface (e.g. from tempWikitextEditor)
446 if ( this.initialSourceRange && this.getSurface().getMode() === 'source' ) {
447 const surfaceModel = this.getSurface().getModel();
448 const range = surfaceModel.getRangeFromSourceOffsets( this.initialSourceRange.from, this.initialSourceRange.to );
449 surfaceModel.setLinearSelection( range );
450 }
451 }
452 };
453
454 /**
455 * @inheritdoc
456 */
457 ve.init.mw.DesktopArticleTarget.prototype.setSurface = function ( surface ) {
458 const resetSurface = surface !== this.surface;
459
460 if ( resetSurface ) {
461 this.$editableContent.after( surface.$element );
462 }
463
464 // Parent method
465 ve.init.mw.DesktopArticleTarget.super.prototype.setSurface.apply( this, arguments );
466
467 if ( resetSurface ) {
468 this.setupNewSection( surface );
469 }
470 };
471
472 /**
473 * Setup new section input for a surface, if required
474 *
475 * @param {ve.ui.Surface} surface
476 */
477 ve.init.mw.DesktopArticleTarget.prototype.setupNewSection = function ( surface ) {
478 if ( surface.getMode() === 'source' && this.section === 'new' ) {
479 if ( !this.sectionTitle ) {
480 this.sectionTitle = new OO.ui.TextInputWidget( {
481 $element: $( '<h2>' ),
482 classes: [ 've-init-mw-desktopArticleTarget-sectionTitle' ],
483 placeholder: ve.msg( 'visualeditor-section-title-placeholder' ),
484 spellcheck: true
485 } );
486 if ( this.recovered ) {
487 this.sectionTitle.setValue(
488 ve.init.platform.sessionStorage.get( 've-docsectiontitle' ) || ''
489 );
490 }
491 this.sectionTitle.connect( this, { change: 'onSectionTitleChange' } );
492 }
493 surface.setPlaceholder( ve.msg( 'visualeditor-section-body-placeholder' ) );
494 this.$editableContent.before( this.sectionTitle.$element );
495
496 if ( this.currentUrl.searchParams.has( 'preloadtitle' ) ) {
497 this.sectionTitle.setValue( this.currentUrl.searchParams.get( 'preloadtitle' ) );
498 }
499 surface.once( 'destroy', this.teardownNewSection.bind( this, surface ) );
500 } else {
501 ve.init.platform.sessionStorage.remove( 've-docsectiontitle' );
502 }
503 };
504
505 /**
506 * Handle section title changes
507 */
508 ve.init.mw.DesktopArticleTarget.prototype.onSectionTitleChange = function () {
509 ve.init.platform.sessionStorage.set( 've-docsectiontitle', this.sectionTitle.getValue() );
510 this.updateToolbarSaveButtonState();
511 };
512
513 /**
514 * Teardown new section inputs
515 *
516 * @param {ve.ui.Surface} surface
517 */
518 ve.init.mw.DesktopArticleTarget.prototype.teardownNewSection = function ( surface ) {
519 surface.setPlaceholder( '' );
520 if ( this.sectionTitle ) {
521 this.sectionTitle.$element.remove();
522 this.sectionTitle = null;
523 }
524 };
525
526 /**
527 * @inheritdoc
528 *
529 * A prompt will not be shown if tryTeardown() is called while activation is still in progress.
530 * If tryTeardown() is called while the target is deactivating, or while it's not active and
531 * not activating, nothing happens.
532 */
533 ve.init.mw.DesktopArticleTarget.prototype.tryTeardown = function ( noPrompt, trackMechanism ) {
534 if ( this.deactivating || ( !this.active && !this.activating ) ) {
535 return this.teardownPromise || ve.createDeferred().resolve().promise();
536 }
537
538 // Just in case these weren't closed before
539 if ( this.welcomeDialog ) {
540 this.welcomeDialog.close();
541 }
542 if ( this.editingTabDialog ) {
543 this.editingTabDialog.close();
544 }
545 this.editingTabDialog = null;
546
547 // Parent method
548 return ve.init.mw.DesktopArticleTarget.super.prototype.tryTeardown.call( this, noPrompt || this.activating, trackMechanism );
549 };
550
551 /**
552 * @inheritdoc
553 *
554 * @param {string} [trackMechanism]
555 * @fires ve.init.mw.DesktopArticleTarget#deactivate
556 */
557 ve.init.mw.DesktopArticleTarget.prototype.teardown = function ( trackMechanism ) {
558 // Event tracking
559 let abortType, abortedMode;
560 if ( trackMechanism ) {
561 if ( this.activating ) {
562 abortType = 'preinit';
563 } else if ( !this.edited ) {
564 abortType = 'nochange';
565 } else if ( this.saving ) {
566 abortType = 'abandonMidsave';
567 } else {
568 // switchwith and switchwithout do not go through this code path,
569 // they go through switchToWikitextEditor() instead
570 abortType = 'abandon';
571 }
572 abortedMode = this.surface ? this.surface.getMode() : this.getDefaultMode();
573 }
574
575 // Cancel activating, start deactivating
576 this.deactivating = true;
577 this.deactivatingDeferred = ve.createDeferred();
578 this.activating = false;
579 this.activatingDeferred.reject();
580 $( 'html' ).addClass( 've-deactivating' ).removeClass( 've-activated ve-active' );
581
582 this.emit( 'deactivate' );
583
584 // Restore TemplateStyles of the original content
585 // (We do this here because toggling 've-active' class above displays it)
586 this.$editableContent.find( 'style[data-mw-deduplicate^="TemplateStyles:"]' ).prop( 'disabled', false );
587
588 // User interface changes
589 this.restorePage();
590 this.restoreDocumentTitle();
591
592 mw.user.options.set( 'editondblclick', this.originalEditondbclick );
593 this.originalEditondbclick = undefined;
594
595 // TODO: Use better checks to see if these restorations are required.
596 if ( this.getSurface() ) {
597 if ( this.active ) {
598 this.teardownUnloadHandlers();
599 }
600 }
601
602 // Parent method
603 return ve.init.mw.DesktopArticleTarget.super.prototype.teardown.call( this ).then( () => {
604 // After teardown
605 this.active = false;
606
607 // If there is a load in progress, try to abort it
608 if ( this.loading && this.loading.abort ) {
609 this.loading.abort();
610 }
611
612 this.clearState();
613 this.initialEditSummary = new URL( location.href ).searchParams.get( 'summary' );
614 this.editSummaryValue = null;
615
616 // Move original content back out of the target
617 this.$element.parent().append( this.$originalContent.children() );
618
619 $( '.ve-init-mw-desktopArticleTarget-uneditableContent' )
620 .removeClass( 've-init-mw-desktopArticleTarget-uneditableContent' );
621
622 this.deactivating = false;
623 this.deactivatingDeferred.resolve();
624 $( 'html' ).removeClass( 've-deactivating' );
625
626 // Event tracking
627 if ( trackMechanism ) {
628 ve.track( 'editAttemptStep', {
629 action: 'abort',
630 type: abortType,
631 mechanism: trackMechanism,
632 mode: abortedMode
633 } );
634 }
635
636 if ( !this.isViewPage ) {
637 const newUrl = new URL( this.viewUrl );
638 if ( mw.config.get( 'wgIsRedirect' ) ) {
639 newUrl.searchParams.set( 'redirect', 'no' );
640 }
641 location.href = newUrl;
642 }
643 } );
644 };
645
646 /**
647 * @inheritdoc
648 */
649 ve.init.mw.DesktopArticleTarget.prototype.loadFail = function ( code, errorDetails ) {
650 // Parent method
651 ve.init.mw.DesktopArticleTarget.super.prototype.loadFail.apply( this, arguments );
652
653 if ( this.wikitextFallbackLoading ) {
654 // Failed twice now
655 mw.log.warn( 'Failed to fall back to wikitext', code, errorDetails );
656 const newUrl = new URL( this.viewUrl );
657 newUrl.searchParams.set( 'action', 'edit' );
658 newUrl.searchParams.set( 'veswitched', '1' );
659 location.href = newUrl;
660 return;
661 }
662
663 if ( !this.activating ) {
664 // Load failed after activation abandoned (e.g. user pressed escape).
665 // Nothing more to do.
666 return;
667 }
668
669 const $confirmPromptMessage = this.extractErrorMessages( errorDetails );
670
671 OO.ui.confirm( $confirmPromptMessage, {
672 actions: [
673 { action: 'accept', label: OO.ui.msg( 'ooui-dialog-process-retry' ), flags: 'primary' },
674 { action: 'reject', label: OO.ui.msg( 'ooui-dialog-message-reject' ), flags: 'safe' }
675 ]
676 } ).done( ( confirmed ) => {
677 if ( confirmed ) {
678 // Retry load
679 this.load();
680 } else {
681 // User pressed "cancel"
682 if ( this.getSurface() ) {
683 // Restore the mode of the current surface
684 this.setDefaultMode( this.getSurface().getMode() );
685 this.activatingDeferred.reject();
686 } else {
687 // We're switching from read mode or the 2010 wikitext editor:
688 // just give up and stay where you are
689 this.tryTeardown( true );
690 }
691 }
692 } );
693 };
694
695 /**
696 * @inheritdoc
697 */
698 ve.init.mw.DesktopArticleTarget.prototype.surfaceReady = function () {
699 if ( !this.activating ) {
700 // Activation was aborted before we got here. Do nothing
701 // TODO are there things we need to clean up?
702 return;
703 }
704
705 const surface = this.getSurface();
706
707 this.activating = false;
708
709 // TODO: mwTocWidget should probably live in a ve.ui.MWSurface subclass
710 if ( mw.config.get( 'wgVisualEditorConfig' ).enableTocWidget ) {
711 surface.mwTocWidget = new ve.ui.MWTocWidget( this.getSurface() );
712 surface.once( 'destroy', () => {
713 surface.mwTocWidget.$element.remove();
714 } );
715 }
716
717 const metaList = this.getSurface().getModel().getDocument().getMetaList();
718
719 metaList.connect( this, {
720 insert: 'onMetaItemInserted',
721 remove: 'onMetaItemRemoved'
722 } );
723 // Rebuild the category list from the page we got from the API. This makes
724 // it work regardless of whether we came here from activating on an
725 // existing page, or loading via an edit URL.
726 this.rebuildCategories( metaList.getItemsInGroup( 'mwCategory' ), true );
727
728 // Parent method
729 ve.init.mw.DesktopArticleTarget.super.prototype.surfaceReady.apply( this, arguments );
730
731 const redirectMetaItems = metaList.getItemsInGroup( 'mwRedirect' );
732 if ( redirectMetaItems.length ) {
733 this.setFakeRedirectInterface( redirectMetaItems[ 0 ].getAttribute( 'title' ) );
734 } else {
735 this.setFakeRedirectInterface( null );
736 }
737
738 this.setupUnloadHandlers();
739
740 this.activatingDeferred.resolve();
741 this.events.trackActivationComplete();
742 };
743
744 /**
745 * Update the redirect and category interfaces when a meta item is inserted into the page.
746 *
747 * @param {ve.dm.MetaItem} metaItem Item that was inserted
748 */
749 ve.init.mw.DesktopArticleTarget.prototype.onMetaItemInserted = function ( metaItem ) {
750 switch ( metaItem.getType() ) {
751 case 'mwRedirect':
752 this.setFakeRedirectInterface( metaItem.getAttribute( 'title' ) );
753 break;
754 case 'mwCategory': {
755 const metaList = this.getSurface().getModel().getDocument().getMetaList();
756 this.rebuildCategories( metaList.getItemsInGroup( 'mwCategory' ) );
757 break;
758 }
759 }
760 };
761
762 /**
763 * Update the redirect and category interfaces when a meta item is removed from the page.
764 *
765 * @param {ve.dm.MetaItem} metaItem Item that was removed
766 * @param {number} offset Linear model offset that the item was at
767 * @param {number} index Index within that offset the item was at
768 */
769 ve.init.mw.DesktopArticleTarget.prototype.onMetaItemRemoved = function ( metaItem ) {
770 switch ( metaItem.getType() ) {
771 case 'mwRedirect':
772 this.setFakeRedirectInterface( null );
773 break;
774 case 'mwCategory': {
775 const metaList = this.getSurface().getModel().getDocument().getMetaList();
776 this.rebuildCategories( metaList.getItemsInGroup( 'mwCategory' ) );
777 break;
778 }
779 }
780 };
781
782 /**
783 * Redisplay the category list on the page
784 *
785 * This is used for the preview while editing. Leaving the editor either restores the initial
786 * categories, or uses the ones generated by the save API.
787 *
788 * @param {ve.dm.MetaItem[]} categoryItems Array of category metaitems to display
789 */
790 ve.init.mw.DesktopArticleTarget.prototype.rebuildCategories = function ( categoryItems ) {
791 this.renderCategories( categoryItems ).done( ( $categories ) => {
792 // Clone the existing catlinks for any specific properties which might
793 // be needed by the rest of the page. Also gives us a not-attached
794 // version, which we can pass to wikipage.categories as it requests.
795 const $catlinks = $( '#catlinks' ).clone().empty().removeClass( 'categories-allhidden' )
796 .append( $categories.children() );
797 // If all categories are hidden, we need to hide the box.
798 $catlinks.toggleClass( 'catlinks-allhidden',
799 $catlinks.find( '.mw-normal-catlinks' ).length === 0 &&
800 // Some situations make the hidden-categories visible (a user
801 // preference, and being on a category page) so rather than
802 // encoding that logic here just check whether they're visible:
803 // eslint-disable-next-line no-jquery/no-sizzle
804 $catlinks.find( '.mw-hidden-catlinks:visible' ).length === 0
805 );
806 this.transformCategoryLinks( $catlinks );
807 mw.hook( 'wikipage.categories' ).fire( $catlinks );
808 $( '#catlinks' ).replaceWith( $catlinks );
809 } );
810 };
811
812 /**
813 * Handle clicks on the view tab.
814 *
815 * @param {jQuery.Event} e Mouse click event
816 */
817 ve.init.mw.DesktopArticleTarget.prototype.onViewTabClick = function ( e ) {
818 if ( ( !this.active && !this.activating ) || !ve.isUnmodifiedLeftClick( e ) ) {
819 return;
820 }
821 this.tryTeardown( false, 'navigate-read' );
822 e.preventDefault();
823 };
824
825 /**
826 * @inheritdoc
827 */
828 ve.init.mw.DesktopArticleTarget.prototype.saveComplete = function ( data ) {
829 // Parent method
830 ve.init.mw.DesktopArticleTarget.super.prototype.saveComplete.apply( this, arguments );
831
832 // If there is no content, then parent method will reload the whole page
833 if ( !data.nocontent ) {
834 // Fix permalinks
835 if ( data.newrevid !== undefined ) {
836 $( '#t-permalink' ).add( '#coll-download-as-rl' ).find( 'a' ).each( ( i, el ) => {
837 const permalinkUrl = new URL( el.href );
838 permalinkUrl.searchParams.set( 'oldid', data.newrevid );
839 $( el ).attr( 'href', permalinkUrl.toString() );
840 } );
841 }
842
843 if ( data.newrevid !== undefined ) {
844 // (T370771) Update wgCurRevisionId and wgRevisionId (!)
845 // Mirror of DiscussionTools's cb5d585b93d83f9a7b4df10a71a0d574295f861c
846 mw.config.set( {
847 wgCurRevisionId: data.newrevid,
848 wgRevisionId: data.newrevid
849 } );
850
851 // Actually fire the postEdit hook, now that the save is complete
852 require( 'mediawiki.action.view.postEdit' ).fireHook( 'saved' );
853 }
854 }
855 };
856
857 /**
858 * @inheritdoc
859 */
860 ve.init.mw.DesktopArticleTarget.prototype.serialize = function () {
861 // Parent method
862 const promise = ve.init.mw.DesktopArticleTarget.super.prototype.serialize.apply( this, arguments );
863
864 return promise.fail( ( error, response ) => {
865 const $errorMessages = this.extractErrorMessages( response );
866 OO.ui.alert( $errorMessages );
867
868 // It's possible to get here while the save dialog has never been opened (if the user uses
869 // the switch to source mode option)
870 if ( this.saveDialog ) {
871 this.saveDialog.popPending();
872 }
873 } );
874 };
875
876 /**
877 * Handle clicks on the MwMeta button in the toolbar.
878 *
879 * @param {jQuery.Event} e Mouse click event
880 */
881 ve.init.mw.DesktopArticleTarget.prototype.onToolbarMetaButtonClick = function () {
882 this.getSurface().getDialogs().openWindow( 'meta' );
883 };
884
885 /**
886 * Modify tabs in the skin to support in-place editing.
887 *
888 * 'Read' and 'Edit source' (when not using single edit tab) bound here,
889 * 'Edit' and single edit tab are bound in mw.DesktopArticleTarget.init.
890 */
891 ve.init.mw.DesktopArticleTarget.prototype.setupSkinTabs = function () {
892 if ( this.isViewPage ) {
893 const namespaceNumber = mw.config.get( 'wgNamespaceNumber' );
894 const namespaceName = mw.config.get( 'wgCanonicalNamespace' );
895 const isTalkNamespace = mw.Title.isTalkNamespace( namespaceNumber );
896 // Title::getNamespaceKey()
897 let namespaceKey = namespaceName.toLowerCase() || 'main';
898 if ( namespaceKey === 'file' ) {
899 namespaceKey = 'image';
900 }
901 let namespaceTabId;
902 // SkinTemplate::buildContentNavigationUrls()
903 if ( isTalkNamespace ) {
904 namespaceTabId = 'ca-talk';
905 } else {
906 namespaceTabId = 'ca-nstab-' + namespaceKey;
907 }
908 // Allow instant switching back to view mode, without refresh
909 $( '#ca-view' ).add( '#' + namespaceTabId ).find( 'a' )
910 .on( 'click.ve-target', this.onViewTabClick.bind( this ) );
911 }
912
913 // Used by Extension:GuidedTour
914 mw.hook( 've.skinTabSetupComplete' ).fire();
915 };
916
917 /**
918 * @inheritdoc
919 */
920 ve.init.mw.DesktopArticleTarget.prototype.getSaveDialogOpeningData = function () {
921 const data = ve.init.mw.DesktopArticleTarget.super.prototype.getSaveDialogOpeningData.apply( this, arguments );
922 data.editSummary = this.editSummaryValue || this.initialEditSummary;
923 return data;
924 };
925
926 /**
927 * @inheritdoc
928 */
929 ve.init.mw.DesktopArticleTarget.prototype.teardownToolbar = function () {
930 const deferred = ve.createDeferred();
931
932 if ( !this.toolbar ) {
933 return deferred.resolve().promise();
934 }
935
936 this.toolbar.$element
937 .addClass( 've-init-mw-desktopArticleTarget-toolbar-preclose' )
938 .css( 'height', this.toolbar.$bar[ 0 ].offsetHeight );
939 requestAnimationFrame( () => {
940 this.toolbar.$element
941 .css( 'height', '0' )
942 .addClass( 've-init-mw-desktopArticleTarget-toolbar-close' );
943 this.toolbar.$element.one( 'transitionend', () => {
944 // Parent method
945 ve.init.mw.DesktopArticleTarget.super.prototype.teardownToolbar.call( this );
946 deferred.resolve();
947 } );
948 } );
949 return deferred.promise();
950 };
951
952 /**
953 * Change the document title to state that we are now editing.
954 */
955 ve.init.mw.DesktopArticleTarget.prototype.changeDocumentTitle = function () {
956 const title = mw.Title.newFromText( this.getPageName() );
957 const pageTitleMsg = mw.message( 'pagetitle',
958 ve.msg(
959 this.pageExists ? 'editing' : 'creating',
960 title.getPrefixedText()
961 )
962 );
963
964 // T317600
965 if ( pageTitleMsg.isParseable() ) {
966 // Use the real title if we loaded a view page, otherwise reconstruct it
967 this.originalDocumentTitle = this.isViewPage ? document.title : ve.msg( 'pagetitle', title.getPrefixedText() );
968 // Reconstruct an edit title
969 document.title = pageTitleMsg.text();
970 } else {
971 mw.log.warn( 'VisualEditor: MediaWiki:Pagetitle contains unsupported syntax. ' +
972 'https://www.mediawiki.org/wiki/Manual:Messages_API#Feature_support_in_JavaScript' );
973 }
974 };
975
976 /**
977 * Restore the original document title.
978 */
979 ve.init.mw.DesktopArticleTarget.prototype.restoreDocumentTitle = function () {
980 if ( this.originalDocumentTitle ) {
981 document.title = this.originalDocumentTitle;
982 }
983 };
984
985 /**
986 * Page modifications for switching to edit mode.
987 *
988 * @fires ve.init.mw.DesktopArticleTarget#transformPage
989 */
990 ve.init.mw.DesktopArticleTarget.prototype.transformPage = function () {
991 this.updateTabs();
992 this.emit( 'transformPage' );
993
994 // TODO: Deprecate in favour of ve.activationComplete
995 // Only used by one gadget
996 mw.hook( 've.activate' ).fire();
997
998 // Move all native content inside the target
999 // Exclude notification area to work around T143837
1000 this.$originalContent.append(
1001 this.$element.siblings()
1002 .not( '.mw-notification-area' )
1003 .not( '.ve-init-mw-desktopArticleTarget-toolbarPlaceholder' )
1004 );
1005
1006 // To preserve event handlers (e.g. HotCat) if editing is cancelled, detach the original container
1007 // and replace it with a clone during editing
1008 this.$originalCategories = $( '#catlinks' );
1009 this.$originalCategories.after( this.$originalCategories.clone() );
1010 this.$originalCategories.detach();
1011
1012 // Mark every non-direct ancestor between editableContent and the container as uneditable
1013 let $content = this.$editableContent;
1014 while ( $content && $content.length && !$content.parent().is( this.$container ) ) {
1015 $content.prevAll( ':not( .ve-init-mw-tempWikitextEditorWidget )' ).addClass( 've-init-mw-desktopArticleTarget-uneditableContent' );
1016 $content.nextAll( ':not( .ve-init-mw-tempWikitextEditorWidget )' ).addClass( 've-init-mw-desktopArticleTarget-uneditableContent' );
1017 $content = $content.parent();
1018 }
1019
1020 this.restoreEditTabsIfNeeded( $content );
1021 this.updateHistoryState();
1022 };
1023
1024 /**
1025 * Checks the edit/view tabs have not been marked as disabled. The view tab provides a way
1026 * to exit the VisualEditor so its important it is not marked as uneditable.
1027 *
1028 * @param {jQuery} $content area
1029 */
1030 ve.init.mw.DesktopArticleTarget.prototype.restoreEditTabsIfNeeded = function ( $content ) {
1031 const $viewTab = $content.find( '.ve-init-mw-desktopArticleTarget-uneditableContent #ca-view' );
1032 if ( $viewTab.length ) {
1033 $viewTab.parents( '.ve-init-mw-desktopArticleTarget-uneditableContent' ).removeClass( 've-init-mw-desktopArticleTarget-uneditableContent' );
1034 }
1035 };
1036
1037 /**
1038 * Category link section transformations for switching to edit mode. Broken out
1039 * so it can be re-applied when displaying changes to the categories.
1040 *
1041 * @param {jQuery} $catlinks Category links container element
1042 */
1043 ve.init.mw.DesktopArticleTarget.prototype.transformCategoryLinks = function ( $catlinks ) {
1044 // Un-disable the catlinks wrapper, but not the links
1045 if ( this.getSurface() && this.getSurface().getMode() === 'visual' ) {
1046 $catlinks.removeClass( 've-init-mw-desktopArticleTarget-uneditableContent' )
1047 .on( 'click.ve-target', () => {
1048 const windowAction = ve.ui.actionFactory.create( 'window', this.getSurface() );
1049 windowAction.open( 'meta', { page: 'categories' } );
1050 return false;
1051 } )
1052 .find( 'a' ).addClass( 've-init-mw-desktopArticleTarget-uneditableContent' );
1053 } else {
1054 $catlinks.addClass( 've-init-mw-desktopArticleTarget-uneditableContent' ).off( 'click.ve-target' );
1055 }
1056 };
1057
1058 /**
1059 * Update the history state based on the editor mode
1060 */
1061 ve.init.mw.DesktopArticleTarget.prototype.updateHistoryState = function () {
1062 const veaction = this.getDefaultMode() === 'visual' ? 'edit' : 'editsource',
1063 section = this.section;
1064
1065 // Push veaction=edit(source) url in history (if not already present).
1066 // If we got here from DesktopArticleTarget.init, then it will be already present.
1067 if (
1068 !this.actFromPopState &&
1069 (
1070 this.currentUrl.searchParams.get( 'veaction' ) !== veaction ||
1071 this.currentUrl.searchParams.get( 'section' ) !== section
1072 ) &&
1073 this.currentUrl.searchParams.get( 'action' ) !== 'edit'
1074 ) {
1075 // Set the current URL
1076 const url = this.currentUrl;
1077
1078 if ( mw.libs.ve.isSingleEditTab ) {
1079 url.searchParams.set( 'action', 'edit' );
1080 mw.config.set( 'wgAction', 'edit' );
1081 } else {
1082 url.searchParams.set( 'veaction', veaction );
1083 url.searchParams.delete( 'action' );
1084 mw.config.set( 'wgAction', 'view' );
1085 }
1086 if ( this.section !== null ) {
1087 url.searchParams.set( 'section', this.section );
1088 } else {
1089 url.searchParams.delete( 'section' );
1090 }
1091
1092 history.pushState( this.popState, '', url );
1093 }
1094 this.actFromPopState = false;
1095 };
1096
1097 /**
1098 * Page modifications for switching back to view mode.
1099 *
1100 * @fires ve.init.mw.DesktopArticleTarget#restorePage
1101 */
1102 ve.init.mw.DesktopArticleTarget.prototype.restorePage = function () {
1103 // Restore any previous redirectMsg/redirectsub
1104 this.setRealRedirectInterface();
1105 if ( this.$originalCategories ) {
1106 $( '#catlinks' ).replaceWith( this.$originalCategories );
1107 }
1108
1109 // TODO: Deprecate in favour of ve.deactivationComplete
1110 mw.hook( 've.deactivate' ).fire();
1111 this.emit( 'restorePage' );
1112
1113 // Push article url into history
1114 if ( !this.actFromPopState ) {
1115 // Remove the VisualEditor query parameters
1116 const url = this.currentUrl;
1117 if ( url.searchParams.has( 'veaction' ) ) {
1118 url.searchParams.delete( 'veaction' );
1119 }
1120 if ( this.section !== null ) {
1121 // Translate into a hash for the new URL:
1122 // This should be after replacePageContent if this is post-save, so we can just look
1123 // at the headers on the page.
1124 const hash = this.getSectionHashFromPage();
1125 if ( hash ) {
1126 url.hash = hash;
1127 this.viewUrl.hash = hash;
1128 const target = document.getElementById( hash.slice( 1 ) );
1129
1130 if ( target ) {
1131 // Scroll the page to the edited section
1132 setTimeout( () => {
1133 target.scrollIntoView( true );
1134 } );
1135 }
1136 }
1137 url.searchParams.delete( 'section' );
1138 }
1139 if ( url.searchParams.has( 'action' ) && $( '#wpTextbox1:not(.ve-dummyTextbox)' ).length === 0 ) {
1140 // If we're not overlaid on an edit page, remove action=edit
1141 url.searchParams.delete( 'action' );
1142 mw.config.set( 'wgAction', 'view' );
1143 }
1144 if ( url.searchParams.has( 'oldid' ) && !this.restoring ) {
1145 // We have an oldid in the query string but it's the most recent one, so remove it
1146 url.searchParams.delete( 'oldid' );
1147 }
1148
1149 // Remove parameters which are only intended for the editor, not for read mode
1150 url.searchParams.delete( 'editintro' );
1151 url.searchParams.delete( 'preload' );
1152 url.searchParams.delete( 'preloadparams[]' );
1153 url.searchParams.delete( 'preloadtitle' );
1154 url.searchParams.delete( 'summary' );
1155
1156 // If there are any other query parameters left, re-use that URL object.
1157 // Otherwise use the canonical style view URL (T44553, T102363).
1158 const keys = [];
1159 url.searchParams.forEach( ( val, key ) => {
1160 keys.push( key );
1161 } );
1162 if ( !keys.length || ( keys.length === 1 && keys[ 0 ] === 'title' ) ) {
1163 history.pushState( this.popState, '', this.viewUrl );
1164 } else {
1165 history.pushState( this.popState, '', url );
1166 }
1167 }
1168 };
1169
1170 /**
1171 * @param {Event} e Native event object
1172 */
1173 ve.init.mw.DesktopArticleTarget.prototype.onWindowPopState = function ( e ) {
1174 if ( !this.verifyPopState( e.state ) ) {
1175 // Ignore popstate events fired for states not created by us
1176 // This also filters out the initial fire in Chrome (T59901).
1177 return;
1178 }
1179
1180 const oldUrl = this.currentUrl;
1181
1182 this.currentUrl = new URL( location.href );
1183 let veaction = this.currentUrl.searchParams.get( 'veaction' );
1184 const action = this.currentUrl.searchParams.get( 'action' );
1185
1186 if ( !veaction && action === 'edit' ) {
1187 veaction = this.getDefaultMode() === 'source' ? 'editsource' : 'edit';
1188 }
1189
1190 if ( this.isModeAvailable( 'source' ) && this.active ) {
1191 if ( veaction === 'editsource' && this.getDefaultMode() === 'visual' ) {
1192 this.actFromPopState = true;
1193 this.switchToWikitextEditor();
1194 } else if ( veaction === 'edit' && this.getDefaultMode() === 'source' ) {
1195 this.actFromPopState = true;
1196 this.switchToVisualEditor();
1197 }
1198 }
1199 if ( !this.active && ( veaction === 'edit' || veaction === 'editsource' ) ) {
1200 this.actFromPopState = true;
1201 this.emit( 'reactivate' );
1202 }
1203 if ( this.active && veaction !== 'edit' && veaction !== 'editsource' ) {
1204 this.actFromPopState = true;
1205 // "Undo" the pop-state, as the event is not cancellable
1206 history.pushState( this.popState, '', oldUrl );
1207 this.currentUrl = oldUrl;
1208 this.tryTeardown( false, 'navigate-back' ).then( () => {
1209 // Teardown was successful, re-apply the undone state
1210 history.back();
1211 } ).always( () => {
1212 this.actFromPopState = false;
1213 } );
1214 }
1215 };
1216
1217 /**
1218 * @inheritdoc
1219 */
1220 ve.init.mw.DesktopArticleTarget.prototype.replacePageContent = function (
1221 html, categoriesHtml, displayTitle, lastModified /* , contentSub, sections */
1222 ) {
1223 // Parent method
1224 ve.init.mw.DesktopArticleTarget.super.prototype.replacePageContent.apply( this, arguments );
1225
1226 if ( lastModified ) {
1227 // If we were not viewing the most recent revision before (a requirement
1228 // for lastmod to have been added by MediaWiki), we will be now.
1229 if ( !$( '#footer-info-lastmod' ).length ) {
1230 $( '#footer-info' ).prepend(
1231 $( '<li>' ).attr( 'id', 'footer-info-lastmod' )
1232 );
1233 }
1234
1235 // Intentionally treated as HTML (message is parsed)
1236 // eslint-disable-next-line no-jquery/no-html
1237 $( '#footer-info-lastmod' ).html( ' ' + lastModified.message );
1238 }
1239
1240 this.$originalCategories = null;
1241
1242 // Re-set any edit section handlers now that the page content has been replaced
1243 mw.libs.ve.setupEditLinks();
1244 };
1245
1246 /**
1247 * Add onunload and onbeforeunload handlers.
1248 */
1249 ve.init.mw.DesktopArticleTarget.prototype.setupUnloadHandlers = function () {
1250 if ( window.onbeforeunload !== this.onBeforeUnload ) {
1251 // Remember any already set beforeunload handler
1252 this.onBeforeUnloadFallback = window.onbeforeunload;
1253 // Attach our handlers
1254 window.onbeforeunload = this.onBeforeUnload;
1255 window.addEventListener( 'unload', this.onUnloadHandler );
1256 }
1257 };
1258 /**
1259 * Remove onunload and onbeforunload handlers.
1260 */
1261 ve.init.mw.DesktopArticleTarget.prototype.teardownUnloadHandlers = function () {
1262 // Restore whatever previous onbeforeunload hook existed
1263 window.onbeforeunload = this.onBeforeUnloadFallback;
1264 this.onBeforeUnloadFallback = null;
1265 window.removeEventListener( 'unload', this.onUnloadHandler );
1266 };
1267
1268 /**
1269 * Show the beta dialog as needed
1270 */
1271 ve.init.mw.DesktopArticleTarget.prototype.maybeShowWelcomeDialog = function () {
1272 const editorMode = this.getDefaultMode(),
1273 windowManager = this.getSurface().dialogs;
1274
1275 this.welcomeDialogPromise = ve.createDeferred();
1276
1277 if ( mw.libs.ve.shouldShowWelcomeDialog() ) {
1278 this.welcomeDialog = new mw.libs.ve.WelcomeDialog();
1279 windowManager.addWindows( [ this.welcomeDialog ] );
1280 windowManager.openWindow(
1281 this.welcomeDialog,
1282 {
1283 switchable: editorMode === 'source' ? this.isModeAvailable( 'visual' ) : true,
1284 editor: editorMode
1285 }
1286 )
1287 .closed.then( ( data ) => {
1288 this.welcomeDialogPromise.resolve();
1289 this.welcomeDialog = null;
1290 if ( data && data.action === 'switch-wte' ) {
1291 this.switchToWikitextEditor( false );
1292 } else if ( data && data.action === 'switch-ve' ) {
1293 this.switchToVisualEditor();
1294 }
1295 } );
1296 mw.libs.ve.stopShowingWelcomeDialog();
1297 } else {
1298 this.welcomeDialogPromise.reject();
1299 }
1300 };
1301
1302 /**
1303 * Show the meta dialog as needed on load.
1304 */
1305 ve.init.mw.DesktopArticleTarget.prototype.maybeShowMetaDialog = function () {
1306 if ( this.welcomeDialogPromise ) {
1307 // Pop out the notices when the welcome dialog is closed
1308 this.welcomeDialogPromise
1309 .always( () => {
1310 if (
1311 this.switched &&
1312 !mw.user.options.get( 'visualeditor-hidevisualswitchpopup' )
1313 ) {
1314 // Show "switched" popup
1315 const popup = new mw.libs.ve.SwitchPopupWidget( 'visual' );
1316 this.toolbar.tools.editModeSource.toolGroup.$element.append( popup.$element );
1317 popup.toggle( true );
1318 } else if ( this.toolbar.tools.notices ) {
1319 // Show notices
1320 this.toolbar.tools.notices.getPopup().toggle( true );
1321 }
1322 } );
1323 }
1324
1325 const redirectMetaItems = this.getSurface().getModel().getDocument().getMetaList().getItemsInGroup( 'mwRedirect' );
1326 if ( redirectMetaItems.length ) {
1327 const windowAction = ve.ui.actionFactory.create( 'window', this.getSurface() );
1328 windowAction.open( 'meta', { page: 'settings' } );
1329 }
1330 };
1331
1332 /**
1333 * Handle before unload event.
1334 *
1335 * @return {string|undefined} Message
1336 */
1337 ve.init.mw.DesktopArticleTarget.prototype.onBeforeUnload = function () {
1338 // Check if someone already set on onbeforeunload hook
1339 if ( this.onBeforeUnloadFallback ) {
1340 // Get the result of their onbeforeunload hook
1341 const fallbackResult = this.onBeforeUnloadFallback();
1342 // If it returned something, exit here and return their message
1343 if ( fallbackResult !== undefined ) {
1344 return fallbackResult;
1345 }
1346 }
1347 // Check if there's been an edit
1348 if (
1349 this.getSurface() &&
1350 $.contains( document, this.getSurface().$element.get( 0 ) ) &&
1351 this.edited &&
1352 !this.submitting &&
1353 mw.user.options.get( 'useeditwarning' )
1354 ) {
1355 // Return our message
1356 return ve.msg( 'mw-widgets-abandonedit' );
1357 }
1358 };
1359
1360 /**
1361 * Handle unload event.
1362 */
1363 ve.init.mw.DesktopArticleTarget.prototype.onUnload = function () {
1364 if ( !this.submitting ) {
1365 ve.track( 'editAttemptStep', {
1366 action: 'abort',
1367 type: this.edited ? 'unknown-edited' : 'unknown',
1368 mechanism: 'navigate',
1369 mode: this.surface ? this.surface.getMode() : this.getDefaultMode()
1370 } );
1371 }
1372 };
1373
1374 /**
1375 * @inheritdoc
1376 */
1377 ve.init.mw.DesktopArticleTarget.prototype.switchToVisualEditor = function () {
1378 // Parent method
1379 ve.init.mw.DesktopArticleTarget.super.prototype.switchToVisualEditor.apply( this, arguments );
1380
1381 if ( this.isModeAvailable( 'visual' ) ) {
1382 ve.track( 'activity.editor-switch', { action: 'visual-desktop' } );
1383 }
1384 };
1385
1386 /**
1387 * @inheritdoc
1388 */
1389 ve.init.mw.DesktopArticleTarget.prototype.switchToWikitextEditor = function () {
1390 // Parent method
1391 ve.init.mw.DesktopArticleTarget.super.prototype.switchToWikitextEditor.apply( this, arguments );
1392
1393 if ( this.isModeAvailable( 'source' ) ) {
1394 ve.track( 'activity.editor-switch', { action: 'source-nwe-desktop' } );
1395 }
1396 };
1397
1398 /**
1399 * @inheritdoc
1400 */
1401 ve.init.mw.DesktopArticleTarget.prototype.switchToWikitextSection = function () {
1402 // Parent method
1403 ve.init.mw.DesktopArticleTarget.super.prototype.switchToWikitextSection.apply( this, arguments );
1404
1405 ve.track( 'activity.editor-switch', { action: 'source-nwe-desktop' } );
1406 };
1407
1408 /**
1409 * @inheritdoc
1410 */
1411 ve.init.mw.DesktopArticleTarget.prototype.switchToFallbackWikitextEditor = function ( modified ) {
1412 const oldId = mw.config.get( 'wgRevisionId' ) || $( 'input[name=parentRevId]' ).val();
1413 const prefPromise = mw.libs.ve.setEditorPreference( 'wikitext' );
1414
1415 if ( !modified ) {
1416 ve.track( 'activity.editor-switch', { action: 'source-desktop' } );
1417 ve.track( 'editAttemptStep', {
1418 action: 'abort',
1419 type: 'switchnochange',
1420 mechanism: 'navigate',
1421 mode: 'visual'
1422 } );
1423 this.submitting = true;
1424 return prefPromise.then( () => {
1425 const url = new URL( this.viewUrl );
1426 url.searchParams.set( 'action', 'edit' );
1427 // No changes, safe to stay in section mode
1428 if ( this.section !== null ) {
1429 url.searchParams.set( 'section', this.section );
1430 } else {
1431 url.searchParams.delete( 'section' );
1432 }
1433 url.searchParams.set( 'veswitched', '1' );
1434 if ( oldId && oldId !== mw.config.get( 'wgCurRevisionId' ) ) {
1435 url.searchParams.set( 'oldid', oldId );
1436 }
1437 if ( mw.libs.ve.isWelcomeDialogSuppressed() ) {
1438 url.searchParams.set( 'vehidebetadialog', '1' );
1439 }
1440 location.href = url.toString();
1441 } );
1442 } else {
1443 return this.serialize( this.getDocToSave() ).then( ( data ) => {
1444 ve.track( 'activity.editor-switch', { action: 'source-desktop' } );
1445 ve.track( 'editAttemptStep', {
1446 action: 'abort',
1447 type: 'switchwith',
1448 mechanism: 'navigate',
1449 mode: 'visual'
1450 } );
1451 this.submitWithSaveFields( { wpDiff: true, wpAutoSummary: '' }, data.content );
1452 } );
1453 }
1454 };
1455
1456 /**
1457 * @inheritdoc
1458 */
1459 ve.init.mw.DesktopArticleTarget.prototype.reloadSurface = function () {
1460 this.activating = true;
1461 this.activatingDeferred = ve.createDeferred();
1462
1463 // Parent method
1464 ve.init.mw.DesktopArticleTarget.super.prototype.reloadSurface.apply( this, arguments );
1465
1466 this.activatingDeferred.done( () => {
1467 this.updateHistoryState();
1468 this.afterActivate();
1469 this.setupTriggerListeners();
1470 } );
1471 this.toolbarSetupDeferred.resolve();
1472 };
1473
1474 /* Registration */
1475
1476 ve.init.mw.targetFactory.register( ve.init.mw.DesktopArticleTarget );