Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor MediaWiki DesktopArticleTarget init.
3 *
4 * This file must remain as widely compatible as the base compatibility
5 * for MediaWiki itself (see mediawiki/core:/resources/startup.js).
6 * Avoid use of: SVG, HTML5 DOM, ContentEditable etc.
7 *
8 * @copyright See AUTHORS.txt
9 * @license The MIT License (MIT); see LICENSE.txt
10 */
11
12 /* eslint-disable no-jquery/no-global-selector */
13 // TODO: ve.now and ve.track should be moved to mw.libs.ve
14 /* global ve */
15
16 /**
17 * Platform preparation for the MediaWiki view page. This loads (when user needs it) the
18 * actual MediaWiki integration and VisualEditor library.
19 */
20 ( function () {
21 const configData = require( './data.json' ),
22 veactionToMode = {
23 edit: 'visual',
24 editsource: 'source'
25 },
26 availableModes = [];
27 let init = null,
28 conf = null,
29 tabMessages = null,
30 pageExists = null,
31 viewUrl = null,
32 veEditUrl = null,
33 tabPreference = null;
34 let veEditSourceUrl, targetPromise, url,
35 initialWikitext, oldId,
36 isLoading, tempWikitextEditor, tempWikitextEditorData,
37 $toolbarPlaceholder, $toolbarPlaceholderBar,
38 contentTop, wasFloating,
39 active = false,
40 targetLoaded = false,
41 plugins = [],
42 welcomeDialogDisabled = false,
43 educationPopupsDisabled = false,
44 // Defined after document-ready below
45 $targetContainer = null;
46
47 if ( mw.config.get( 'wgMFMode' ) ) {
48 mw.log.warn( 'Attempted to load desktop target on mobile.' );
49 return;
50 }
51
52 /**
53 * Show the loading progress bar
54 */
55 function showLoading() {
56 if ( isLoading ) {
57 return;
58 }
59
60 isLoading = true;
61
62 $( 'html' ).addClass( 've-activated ve-loading' );
63 if ( !init.$loading ) {
64 init.progressBar = new mw.libs.ve.ProgressBarWidget();
65 init.$loading = $( '<div>' )
66 .addClass( 've-init-mw-desktopArticleTarget-loading-overlay' )
67 .append( init.progressBar.$element );
68 }
69 $( document ).on( 'keydown', onDocumentKeyDown );
70
71 $toolbarPlaceholderBar.append( init.$loading );
72 }
73
74 /**
75 * Increment loading progress by one step
76 *
77 * See mw.libs.ve.ProgressBarWidget for steps.
78 */
79 function incrementLoadingProgress() {
80 init.progressBar.incrementLoadingProgress();
81 }
82
83 /**
84 * Clear and hide the loading progress bar
85 */
86 function clearLoading() {
87 init.progressBar.clearLoading();
88 isLoading = false;
89 $( document ).off( 'keydown', onDocumentKeyDown );
90 $( 'html' ).removeClass( 've-loading' );
91 if ( init.$loading ) {
92 init.$loading.detach();
93 }
94
95 if ( tempWikitextEditor ) {
96 teardownTempWikitextEditor();
97 }
98 hideToolbarPlaceholder();
99 }
100
101 /**
102 * Handle window scroll events
103 *
104 * @param {Event} e
105 */
106 function onWindowScroll() {
107 const scrollTop = $( document.documentElement ).scrollTop();
108 const floating = scrollTop > contentTop;
109 if ( floating !== wasFloating ) {
110 const width = $targetContainer.outerWidth();
111 $toolbarPlaceholder.toggleClass( 've-init-mw-desktopArticleTarget-toolbarPlaceholder-floating', floating );
112 $toolbarPlaceholderBar.css( 'width', width );
113 wasFloating = floating;
114 }
115 }
116
117 const onWindowScrollListener = mw.util.throttle( onWindowScroll, 250 );
118
119 /**
120 * Show a placeholder for the VE toolbar
121 */
122 function showToolbarPlaceholder() {
123 if ( !$toolbarPlaceholder ) {
124 // Create an equal-height placeholder for the toolbar to avoid vertical jump
125 // when the real toolbar is ready.
126 $toolbarPlaceholder = $( '<div>' ).addClass( 've-init-mw-desktopArticleTarget-toolbarPlaceholder' );
127 $toolbarPlaceholderBar = $( '<div>' ).addClass( 've-init-mw-desktopArticleTarget-toolbarPlaceholder-bar' );
128 $toolbarPlaceholder.append( $toolbarPlaceholderBar );
129 }
130 // Toggle -floating class before append (if required) to avoid content moving later
131 contentTop = $targetContainer.offset().top;
132 wasFloating = null;
133 onWindowScroll();
134
135 const scrollTopBefore = $( document.documentElement ).scrollTop();
136
137 $targetContainer.prepend( $toolbarPlaceholder );
138
139 window.addEventListener( 'scroll', onWindowScrollListener, { passive: true } );
140
141 if ( wasFloating ) {
142 // Browser might not support scroll anchoring:
143 // https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor/Guide_to_scroll_anchoring
144 // ...so compute the new scroll offset ourselves.
145 window.scrollTo( 0, scrollTopBefore + $toolbarPlaceholder.outerHeight() );
146 }
147
148 // Add class for transition after first render
149 setTimeout( () => {
150 $toolbarPlaceholder.addClass( 've-init-mw-desktopArticleTarget-toolbarPlaceholder-open' );
151 } );
152 }
153
154 /**
155 * Hide the placeholder for the VE toolbar
156 */
157 function hideToolbarPlaceholder() {
158 if ( $toolbarPlaceholder ) {
159 window.removeEventListener( 'scroll', onWindowScrollListener );
160 $toolbarPlaceholder.detach();
161 $toolbarPlaceholder.removeClass( 've-init-mw-desktopArticleTarget-toolbarPlaceholder-open' );
162 }
163 }
164
165 /**
166 * Create a temporary `<textarea>` wikitext editor while source mode loads
167 *
168 * @param {Object} data Initialisation data for VE
169 */
170 function setupTempWikitextEditor( data ) {
171 let wikitext = data.content;
172 // Add trailing linebreak to non-empty wikitext documents for consistency
173 // with old editor and usability. Will be stripped on save. T156609
174 if ( wikitext ) {
175 wikitext += '\n';
176 }
177 tempWikitextEditor = new mw.libs.ve.MWTempWikitextEditorWidget( { value: wikitext } );
178 tempWikitextEditorData = data;
179
180 // Bring forward some transformations that show the editor is now ready
181 // Grey out the page title if it is below the editing toolbar (depending on skin), to show it is uneditable.
182 $( '.ve-init-mw-desktopArticleTarget-targetContainer #firstHeading' ).addClass( 've-init-mw-desktopArticleTarget-uneditableContent' );
183 $( '#mw-content-text' )
184 .before( tempWikitextEditor.$element )
185 .addClass( 'oo-ui-element-hidden' );
186 $( 'html' ).addClass( 've-tempSourceEditing' ).removeClass( 've-loading' );
187
188 // Resize the textarea to fit content. We could do this more often (e.g. on change)
189 // but hopefully this temporary textarea won't be visible for too long.
190 tempWikitextEditor.adjustSize().moveCursorToStart();
191 ve.track( 'editAttemptStep', { action: 'ready', mode: 'source', platform: 'desktop' } );
192 mw.libs.ve.tempWikitextEditor = tempWikitextEditor;
193 mw.hook( 've.wikitextInteractive' ).fire();
194 }
195
196 /**
197 * Synchronise state of temporary wikitexteditor back to the VE initialisation data object
198 */
199 function syncTempWikitextEditor() {
200 let wikitext = tempWikitextEditor.getValue();
201
202 // Strip trailing linebreak. Will get re-added in ArticleTarget#parseDocument.
203 if ( wikitext.slice( -1 ) === '\n' ) {
204 wikitext = wikitext.slice( 0, -1 );
205 }
206
207 if ( wikitext !== tempWikitextEditorData.content ) {
208 // Write changes back to response data object,
209 // which will be used to construct the surface.
210 tempWikitextEditorData.content = wikitext;
211 // TODO: Consider writing changes using a
212 // transaction so they can be undone.
213 // For now, just mark surface as pre-modified
214 tempWikitextEditorData.fromEditedState = true;
215 }
216
217 // Store the last-seen selection and pass to the target
218 tempWikitextEditorData.initialSourceRange = tempWikitextEditor.getRange();
219
220 tempWikitextEditor.$element.prop( 'readonly', true );
221 }
222
223 /**
224 * Teardown the temporary wikitext editor
225 */
226 function teardownTempWikitextEditor() {
227 // Destroy widget and placeholder
228 tempWikitextEditor.$element.remove();
229 mw.libs.ve.tempWikitextEditor = tempWikitextEditor = null;
230 tempWikitextEditorData = null;
231
232 $( '#mw-content-text' ).removeClass( 'oo-ui-element-hidden' );
233 $( 'html' ).removeClass( 've-tempSourceEditing' );
234 }
235
236 /**
237 * Abort loading the editor
238 */
239 function abortLoading() {
240 $( 'html' ).removeClass( 've-activated' );
241 active = false;
242 updateTabs( false );
243 // Push read tab URL to history
244 if ( $( '#ca-view a' ).length ) {
245 history.pushState( { tag: 'visualeditor' }, '', $( '#ca-view a' ).attr( 'href' ) );
246 }
247 clearLoading();
248 }
249
250 /**
251 * Handle keydown events on the document
252 *
253 * @param {jQuery.Event} e Keydown event
254 */
255 function onDocumentKeyDown( e ) {
256 if ( e.which === 27 /* OO.ui.Keys.ESCAPE */ ) {
257 abortLoading();
258 e.preventDefault();
259 }
260 }
261
262 /**
263 * Parse a section value from a query string object
264 *
265 * @example
266 * parseSection( new URL( location.href ).searchParams.get( 'section' ) )
267 *
268 * @param {string|undefined} section Section value from query object
269 * @return {string|null} Section if valid, null otherwise
270 */
271 function parseSection( section ) {
272 // Section must be a number, 'new' or 'T-' prefixed
273 if ( section && /^(new|\d+|T-\d+)$/.test( section ) ) {
274 return section;
275 }
276 return null;
277 }
278
279 /**
280 * Use deferreds to avoid loading and instantiating Target multiple times.
281 *
282 * @private
283 * @param {string} mode Target mode: 'visual' or 'source'
284 * @param {string} section Section to edit
285 * @return {jQuery.Promise}
286 */
287 function getTarget( mode, section ) {
288 if ( !targetPromise ) {
289 // The TargetLoader module is loaded in the bottom queue, so it should have been
290 // requested already but it might not have finished loading yet
291 targetPromise = mw.loader.using( 'ext.visualEditor.targetLoader' )
292 .then( () => {
293 mw.libs.ve.targetLoader.addPlugin(
294 // Run VisualEditorPreloadModules, but if they fail, we still want to continue
295 // loading, so convert failure to success
296 () => mw.loader.using( conf.preloadModules ).catch(
297 () => $.Deferred().resolve()
298 )
299 );
300 // Add modules specific to desktop (modules shared between desktop
301 // and mobile are already added by TargetLoader)
302 [
303 'ext.visualEditor.desktopArticleTarget',
304 // Add requested plugins
305 ...plugins
306 ].forEach( mw.libs.ve.targetLoader.addPlugin );
307 plugins = [];
308 return mw.libs.ve.targetLoader.loadModules( mode );
309 } )
310 .then( () => {
311 if ( !active ) {
312 // Loading was aborted
313 // TODO: Make loaders abortable instead of waiting
314 targetPromise = null;
315 return $.Deferred().reject().promise();
316 }
317
318 const target = ve.init.mw.targetFactory.create(
319 conf.contentModels[ mw.config.get( 'wgPageContentModel' ) ], {
320 modes: availableModes,
321 defaultMode: mode
322 }
323 );
324 target.on( 'deactivate', () => {
325 active = false;
326 updateTabs( false );
327 } );
328 target.on( 'reactivate', () => {
329 url = new URL( location.href );
330 activateTarget(
331 getEditModeFromUrl( url ),
332 parseSection( url.searchParams.get( 'section' ) )
333 );
334 } );
335 target.setContainer( $targetContainer );
336 targetLoaded = true;
337 return target;
338 }, ( e ) => {
339 mw.log.warn( 'VisualEditor failed to load: ' + e );
340 return $.Deferred().reject( e ).promise();
341 } );
342 }
343
344 targetPromise.then( ( target ) => {
345 target.section = section;
346 } );
347
348 return targetPromise;
349 }
350
351 /**
352 * @private
353 * @param {Object} initData
354 * @param {URL} [linkUrl]
355 */
356 function trackActivateStart( initData, linkUrl ) {
357 if ( !linkUrl ) {
358 linkUrl = url;
359 }
360 if ( linkUrl.searchParams.get( 'wvprov' ) === 'sticky-header' ) {
361 initData.mechanism += '-sticky-header';
362 }
363 ve.track( 'trace.activate.enter', { mode: initData.mode } );
364 initData.action = 'init';
365 initData.integration = 'page';
366 ve.track( 'editAttemptStep', initData );
367 mw.libs.ve.activationStart = ve.now();
368 }
369
370 /**
371 * Get the skin-specific message for an edit tab
372 *
373 * @param {string} tabMsg Base tab message key
374 * @return {string} Message text
375 */
376 function getTabMessage( tabMsg ) {
377 let tabMsgKey = tabMessages[ tabMsg ];
378 const skinMsgKeys = {
379 edit: 'edit',
380 create: 'create',
381 editlocaldescription: 'edit-local',
382 createlocaldescription: 'create-local'
383 };
384 const key = skinMsgKeys[ tabMsg ];
385 if ( !tabMsgKey && key ) {
386 // Some skins don't use the default skin message keys.
387 // The following messages can be used here:
388 // * vector-view-edit
389 // * vector-view-create
390 // * vector-view-edit-local
391 // * vector-view-create-local
392 // * messages for other skins
393 tabMsgKey = mw.config.get( 'skin' ) + '-view-' + key;
394 if ( !mw.message( tabMsgKey ).exists() ) {
395 // The following messages can be used here:
396 // * skin-view-edit
397 // * skin-view-create
398 // * skin-view-edit-local
399 // * skin-view-create-local
400 tabMsgKey = 'skin-view-' + key;
401 }
402 }
403 // eslint-disable-next-line mediawiki/msg-doc
404 const msg = mw.message( tabMsgKey );
405 if ( !msg.isParseable() ) {
406 mw.log.warn( 'VisualEditor: MediaWiki:' + tabMsgKey + ' contains unsupported syntax. ' +
407 'https://www.mediawiki.org/wiki/Manual:Messages_API#Feature_support_in_JavaScript' );
408 return undefined;
409 }
410 return msg.text();
411 }
412
413 /**
414 * Set the user's new preferred editor
415 *
416 * @param {string} editor Preferred editor, 'visualeditor' or 'wikitext'
417 * @return {jQuery.Promise} Promise which resolves when the preference has been set
418 */
419 function setEditorPreference( editor ) {
420 // If visual mode isn't available, don't set the editor preference as the
421 // user has expressed no choice by opening this editor. (T246259)
422 // Strictly speaking the same thing should happen if visual mode is
423 // available but source mode isn't, but that is never the case.
424 if ( !init.isVisualAvailable ) {
425 return $.Deferred().resolve().promise();
426 }
427
428 if ( editor !== 'visualeditor' && editor !== 'wikitext' ) {
429 throw new Error( 'setEditorPreference called with invalid option: ', editor );
430 }
431
432 let key = pageExists ? 'edit' : 'create',
433 sectionKey = 'editsection';
434
435 if (
436 mw.config.get( 'wgVisualEditorConfig' ).singleEditTab &&
437 tabPreference === 'remember-last'
438 ) {
439 if ( $( '#ca-view-foreign' ).length ) {
440 key += 'localdescription';
441 }
442 if ( editor === 'wikitext' ) {
443 key += 'source';
444 sectionKey += 'source';
445 }
446
447 $( '#ca-edit a' ).text( getTabMessage( key ) );
448 $( '.mw-editsection a' ).text( getTabMessage( sectionKey ) );
449 }
450
451 mw.cookie.set( 'VEE', editor, { path: '/', expires: 30 * 86400, prefix: '' } );
452
453 // Save user preference if logged in
454 if (
455 mw.user.isNamed() &&
456 mw.user.options.get( 'visualeditor-editor' ) !== editor
457 ) {
458 // Same as ve.init.target.getLocalApi()
459 return new mw.Api().saveOption( 'visualeditor-editor', editor ).then( () => {
460 mw.user.options.set( 'visualeditor-editor', editor );
461 } );
462 }
463 return $.Deferred().resolve().promise();
464 }
465
466 /**
467 * Update state of editing tabs
468 *
469 * @param {boolean} editing Whether the editor is loaded
470 * @param {string} [mode='visual'] Edit mode ('visual' or 'source')
471 * @param {boolean} [isNewSection] Adding a new section
472 */
473 function updateTabs( editing, mode, isNewSection ) {
474 let $tab;
475
476 if ( editing ) {
477 if ( isNewSection ) {
478 $tab = $( '#ca-addsection' );
479 } else if ( $( '#ca-ve-edit' ).length ) {
480 if ( !mode || mode === 'visual' ) {
481 $tab = $( '#ca-ve-edit' );
482 } else {
483 $tab = $( '#ca-edit' );
484 }
485 } else {
486 // Single edit tab
487 $tab = $( '#ca-edit' );
488 }
489 } else {
490 $tab = $( '#ca-view' );
491 }
492
493 // Deselect current mode (e.g. "view" or "history") in skins that have
494 // separate tab sections for content actions and namespaces, like Vector.
495 $( '#p-views' ).find( 'li.selected' ).removeClass( 'selected' );
496 // In skins like MonoBook that don't have the separate tab sections,
497 // deselect the known tabs for editing modes (when switching or exiting editor).
498 $( '#ca-edit, #ca-ve-edit, #ca-addsection' ).not( $tab ).removeClass( 'selected' );
499
500 $tab.addClass( 'selected' );
501 }
502
503 /**
504 * Scroll to a specific heading before VE loads
505 *
506 * Similar to ve.init.mw.ArticleTarget.prototype.scrollToHeading
507 *
508 * @param {string} section Parsed section (string)
509 */
510 function scrollToSection( section ) {
511 if ( section === '0' || section === 'new' ) {
512 return;
513 }
514
515 let $heading;
516 $( '#mw-content-text .mw-editsection a:not( .mw-editsection-visualeditor )' ).each( ( i, el ) => {
517 const linkUrl = new URL( el.href );
518 if ( section === parseSection( linkUrl.searchParams.get( 'section' ) ) ) {
519 $heading = $( el ).closest( '.mw-heading, h1, h2, h3, h4, h5, h6' );
520 return false;
521 }
522 } );
523 // When loading on action=edit URLs, there is no page content
524 if ( !$heading || !$heading.length ) {
525 return;
526 }
527
528 let offset = 0;
529 const enableVisualSectionEditing = mw.config.get( 'wgVisualEditorConfig' ).enableVisualSectionEditing;
530 if ( enableVisualSectionEditing === true || enableVisualSectionEditing === 'desktop' ) {
531 // Heading will jump to the top of the page in visual section editing.
532 // This measurement already includes the height of $toolbarPlaceholder.
533 offset = $( '#mw-content-text' ).offset().top;
534 } else {
535 // Align with top of heading margin. Doesn't apply in visual section editing as the margin collapses.
536 offset = parseInt( $heading.css( 'margin-top' ) ) + $toolbarPlaceholder.outerHeight();
537 }
538
539 // Support for CSS `scroll-behavior: smooth;` and JS `window.scroll( { behavior: 'smooth' } )`
540 // is correlated:
541 // * https://caniuse.com/css-scroll-behavior
542 // * https://caniuse.com/mdn-api_window_scroll_options_behavior_parameter
543 const supportsSmoothScroll = 'scrollBehavior' in document.documentElement.style;
544 const newScrollTop = $heading.offset().top - offset;
545 if ( supportsSmoothScroll ) {
546 window.scroll( {
547 top: newScrollTop,
548 behavior: 'smooth'
549 } );
550 } else {
551 // Ideally we would use OO.ui.Element.static.getRootScrollableElement here
552 // as it has slightly better browser support (Chrome < 60)
553 const scrollContainer = document.documentElement;
554
555 $( scrollContainer ).animate( {
556 scrollTop: newScrollTop
557 } );
558 }
559 }
560
561 /**
562 * Load and activate the target.
563 *
564 * If you need to call methods on the target before activate is called, call getTarget()
565 * yourself, chain your work onto that promise, and pass that chained promise in as targetPromise.
566 * E.g. `activateTarget( getTarget().then( function( target ) { target.doAThing(); } ) );`
567 *
568 * @private
569 * @param {string} mode Target mode: 'visual' or 'source'
570 * @param {string} [section] Section to edit.
571 * If visual section editing is not enabled, we will jump to the start of this section, and still
572 * the heading to prefix the edit summary.
573 * @param {jQuery.Promise} [tPromise] Promise that will be resolved with a ve.init.mw.DesktopArticleTarget
574 * @param {boolean} [modified=false] The page has been modified before loading (e.g. in source mode)
575 */
576 function activateTarget( mode, section, tPromise, modified ) {
577 let dataPromise;
578
579 updateTabs( true, mode, section === 'new' );
580
581 // Only call requestPageData early if the target object isn't there yet.
582 // If the target object is there, this is a second or subsequent load, and the
583 // internal state of the target object can influence the load request.
584 if ( !targetLoaded ) {
585 // The TargetLoader module is loaded in the bottom queue, so it should have been
586 // requested already but it might not have finished loading yet
587 dataPromise = mw.loader.using( 'ext.visualEditor.targetLoader' )
588 .then( () => mw.libs.ve.targetLoader.requestPageData( mode, mw.config.get( 'wgRelevantPageName' ), {
589 sessionStore: true,
590 section: section,
591 oldId: oldId,
592 // Should be ve.init.mw.DesktopArticleTarget.static.trackingName, but the
593 // class hasn't loaded yet.
594 // This is used for stats tracking, so do not change!
595 targetName: 'mwTarget',
596 modified: modified,
597 editintro: url.searchParams.get( 'editintro' ),
598 preload: url.searchParams.get( 'preload' ),
599 preloadparams: mw.util.getArrayParam( 'preloadparams', url.searchParams ),
600 // If switching to visual with modifications, check if we have wikitext to convert
601 wikitext: mode === 'visual' && modified ? $( '#wpTextbox1' ).textSelection( 'getContents' ) : undefined
602 } ) );
603
604 dataPromise
605 .then( ( response ) => {
606 if (
607 // Check target promise hasn't already failed (isLoading=false)
608 isLoading &&
609 // TODO: Support tempWikitextEditor when section=new (T185633)
610 mode === 'source' && section !== 'new' &&
611 // Can't use temp editor when recovering an autosave
612 !( response.visualeditor && response.visualeditor.recovered )
613 ) {
614 setupTempWikitextEditor( response.visualeditor );
615 }
616 } )
617 .then( incrementLoadingProgress );
618 }
619
620 // Do this before section scrolling
621 showToolbarPlaceholder();
622 mw.hook( 've.activationStart' ).fire();
623
624 let visibleSection = null;
625 let visibleSectionOffset = null;
626 if ( section === null ) {
627 let firstVisibleEditSection = null;
628 $( '#firstHeading, #mw-content-text .mw-editsection' ).each( ( i, el ) => {
629 const top = el.getBoundingClientRect().top;
630 if ( top > 0 ) {
631 firstVisibleEditSection = el;
632 // break
633 return false;
634 }
635 } );
636
637 if ( firstVisibleEditSection && firstVisibleEditSection.id !== 'firstHeading' ) {
638 const firstVisibleSectionLink = firstVisibleEditSection.querySelector( 'a' );
639 const linkUrl = new URL( firstVisibleSectionLink.href );
640 visibleSection = parseSection( linkUrl.searchParams.get( 'section' ) );
641
642 const firstVisibleHeading = $( firstVisibleEditSection ).closest( '.mw-heading, h1, h2, h3, h4, h5, h6' )[ 0 ];
643 visibleSectionOffset = firstVisibleHeading.getBoundingClientRect().top;
644 }
645 } else if ( mode === 'visual' ) {
646 scrollToSection( section );
647 }
648
649 showLoading( mode );
650 incrementLoadingProgress();
651 active = true;
652
653 tPromise = tPromise || getTarget( mode, section );
654 tPromise
655 .then( ( target ) => {
656 target.visibleSection = visibleSection;
657 target.visibleSectionOffset = visibleSectionOffset;
658
659 incrementLoadingProgress();
660 // If target was already loaded, ensure the mode is correct
661 target.setDefaultMode( mode );
662 // syncTempWikitextEditor modified the result object in the dataPromise
663 if ( tempWikitextEditor ) {
664 syncTempWikitextEditor();
665 }
666
667 const deactivating = target.deactivatingDeferred || $.Deferred().resolve();
668 return deactivating.then( () => {
669 target.currentUrl = new URL( location.href );
670 const activatePromise = target.activate( dataPromise );
671
672 // toolbarSetupDeferred resolves slightly before activatePromise, use done
673 // to run in the same paint cycle as the VE toolbar being drawn
674 target.toolbarSetupDeferred.done( () => {
675 hideToolbarPlaceholder();
676 } );
677
678 return activatePromise;
679 } );
680 } )
681 .then( () => {
682 if ( mode === 'visual' ) {
683 // `action: 'ready'` has already been fired for source mode in setupTempWikitextEditor
684 ve.track( 'editAttemptStep', { action: 'ready', mode: mode } );
685 } else if ( !tempWikitextEditor ) {
686 // We're in source mode, but skipped the
687 // tempWikitextEditor, so make sure we do relevant
688 // tracking / hooks:
689 ve.track( 'editAttemptStep', { action: 'ready', mode: mode } );
690 mw.hook( 've.wikitextInteractive' ).fire();
691 }
692 ve.track( 'editAttemptStep', { action: 'loaded', mode: mode } );
693 } )
694 .always( clearLoading );
695 }
696
697 /**
698 * @private
699 * @param {string} mode Target mode: 'visual' or 'source'
700 * @param {string} [section]
701 * @param {boolean} [modified=false] The page has been modified before loading (e.g. in source mode)
702 * @param {URL} [linkUrl] URL to navigate to, potentially with extra parameters
703 */
704 function activatePageTarget( mode, section, modified, linkUrl ) {
705 trackActivateStart( { type: 'page', mechanism: mw.config.get( 'wgArticleId' ) ? 'click' : 'new', mode: mode }, linkUrl );
706
707 if ( !active ) {
708 // Replace the current state with one that is tagged as ours, to prevent the
709 // back button from breaking when used to exit VE. FIXME: there should be a better
710 // way to do this. See also similar code in the DesktopArticleTarget constructor.
711 history.replaceState( { tag: 'visualeditor' }, '', url );
712 // Set action=edit or veaction=edit/editsource
713 // Use linkUrl to preserve parameters like 'editintro' (T56029)
714 history.pushState( { tag: 'visualeditor' }, '', linkUrl || ( mode === 'source' ? veEditSourceUrl : veEditUrl ) );
715 // Update URL instance
716 url = linkUrl || veEditUrl;
717
718 activateTarget( mode, section, undefined, modified );
719 }
720 }
721
722 /**
723 * Get the last mode a user used
724 *
725 * @return {string|null} 'visualeditor', 'wikitext' or null
726 */
727 function getLastEditor() {
728 // This logic matches VisualEditorHooks::getLastEditor
729 let editor = mw.cookie.get( 'VEE', '' );
730 // Set editor to user's preference or site's default (ignore the cookie) if …
731 if (
732 // … user is logged in,
733 mw.user.isNamed() ||
734 // … no cookie is set, or
735 !editor ||
736 // value is invalid.
737 !( editor === 'visualeditor' || editor === 'wikitext' )
738 ) {
739 editor = mw.user.options.get( 'visualeditor-editor' );
740 }
741 return editor;
742 }
743
744 /**
745 * Get the preferred editor for this edit page
746 *
747 * For the preferred *available* editor, use getAvailableEditPageEditor.
748 *
749 * @return {string|null} 'visualeditor', 'wikitext' or null
750 */
751 function getEditPageEditor() {
752 // This logic matches VisualEditorHooks::getEditPageEditor
753 // !!+ casts '0' to false
754 const isRedLink = !!+url.searchParams.get( 'redlink' );
755 // On dual-edit-tab wikis, the edit page must mean the user wants wikitext,
756 // unless following a redlink
757 if ( !mw.config.get( 'wgVisualEditorConfig' ).singleEditTab && !isRedLink ) {
758 return 'wikitext';
759 }
760
761 switch ( tabPreference ) {
762 case 'prefer-ve':
763 return 'visualeditor';
764 case 'prefer-wt':
765 return 'wikitext';
766 case 'multi-tab':
767 // 'multi-tab'
768 // TODO: See VisualEditor.hooks.php
769 return isRedLink ?
770 getLastEditor() :
771 'wikitext';
772 case 'remember-last':
773 default:
774 return getLastEditor();
775 }
776 }
777
778 /**
779 * Get the preferred editor which is also available on this edit page
780 *
781 * @return {string} 'visual' or 'source'
782 */
783 function getAvailableEditPageEditor() {
784 switch ( getEditPageEditor() ) {
785 case 'visualeditor':
786 if ( init.isVisualAvailable ) {
787 return 'visual';
788 }
789 if ( init.isWikitextAvailable ) {
790 return 'source';
791 }
792 return null;
793
794 case 'wikitext':
795 default:
796 return init.isWikitextAvailable ? 'source' : null;
797 }
798 }
799
800 /**
801 * Check if a boolean preference is set in user options, mw.storage or a cookie
802 *
803 * @param {string} prefName Preference name
804 * @param {string} storageKey mw.storage key
805 * @param {string} cookieName Cookie name
806 * @return {boolean} Preference is set
807 */
808 function checkPreferenceOrStorage( prefName, storageKey, cookieName ) {
809 storageKey = storageKey || prefName;
810 cookieName = cookieName || storageKey;
811 return !!( mw.user.options.get( prefName ) ||
812 (
813 !mw.user.isNamed() && (
814 mw.storage.get( storageKey ) ||
815 mw.cookie.get( cookieName, '' )
816 )
817 )
818 );
819 }
820
821 /**
822 * Set a boolean preference to true in user options, mw.storage or a cookie
823 *
824 * @param {string} prefName Preference name
825 * @param {string} storageKey mw.storage key
826 * @param {string} cookieName Cookie name
827 */
828 function setPreferenceOrStorage( prefName, storageKey, cookieName ) {
829 storageKey = storageKey || prefName;
830 cookieName = cookieName || storageKey;
831 if ( !mw.user.isNamed() ) {
832 // Try local storage first; if that fails, set a cookie
833 if ( !mw.storage.set( storageKey, 1 ) ) {
834 mw.cookie.set( cookieName, 1, { path: '/', expires: 30 * 86400, prefix: '' } );
835 }
836 } else {
837 new mw.Api().saveOption( prefName, '1' );
838 mw.user.options.set( prefName, '1' );
839 }
840 }
841
842 conf = mw.config.get( 'wgVisualEditorConfig' );
843 tabMessages = conf.tabMessages;
844 viewUrl = new URL( mw.util.getUrl( mw.config.get( 'wgRelevantPageName' ) ), location.href );
845 url = new URL( location.href );
846 // T156998: Don't trust 'oldid' query parameter, it'll be wrong if 'diff' or 'direction'
847 // is set to 'next' or 'prev'.
848 oldId = mw.config.get( 'wgRevisionId' ) || $( 'input[name=parentRevId]' ).val();
849 if ( oldId === mw.config.get( 'wgCurRevisionId' ) || mw.config.get( 'wgEditLatestRevision' ) ) {
850 // The page may have been edited by someone else after we loaded it, setting this to "undefined"
851 // indicates that we should load the actual latest revision.
852 oldId = undefined;
853 }
854 pageExists = !!mw.config.get( 'wgRelevantArticleId' );
855 const isViewPage = mw.config.get( 'wgIsArticle' ) && !url.searchParams.has( 'diff' );
856 const wgAction = mw.config.get( 'wgAction' );
857 const isEditPage = wgAction === 'edit' || wgAction === 'submit';
858 const pageCanLoadEditor = isViewPage || isEditPage;
859 const pageIsProbablyEditable = mw.config.get( 'wgIsProbablyEditable' ) ||
860 mw.config.get( 'wgRelevantPageIsProbablyEditable' );
861
862 // Cast "0" (T89513)
863 const enable = !!+mw.user.options.get( 'visualeditor-enable' );
864 const tempdisable = !!+mw.user.options.get( 'visualeditor-betatempdisable' );
865 const autodisable = !!+mw.user.options.get( 'visualeditor-autodisable' );
866 tabPreference = mw.user.options.get( 'visualeditor-tabs' );
867
868 /**
869 * The only edit tab shown to the user is for visual mode
870 *
871 * @return {boolean}
872 */
873 function isOnlyTabVE() {
874 return conf.singleEditTab && getAvailableEditPageEditor() === 'visual';
875 }
876
877 /**
878 * The only edit tab shown to the user is for source mode
879 *
880 * @return {boolean}
881 */
882 function isOnlyTabWikitext() {
883 return conf.singleEditTab && getAvailableEditPageEditor() === 'source';
884 }
885
886 init = {
887 /**
888 * Add a plugin module or function.
889 *
890 * Plugins are run after VisualEditor is loaded, but before it is initialized. This allows
891 * plugins to add classes and register them with the factories and registries.
892 *
893 * The parameter to this function can be a ResourceLoader module name or a function.
894 *
895 * If it's a module name, it will be loaded together with the VisualEditor core modules when
896 * VE is loaded. No special care is taken to ensure that the module runs after the VE
897 * classes are loaded, so if this is desired, the module should depend on
898 * ext.visualEditor.core .
899 *
900 * If it's a function, it will be invoked once the VisualEditor core modules and any
901 * plugin modules registered through this function have been loaded, but before the editor
902 * is intialized. The function can optionally return a jQuery.Promise . VisualEditor will
903 * only be initialized once all promises returned by plugin functions have been resolved.
904 *
905 * // Register ResourceLoader module
906 * mw.libs.ve.addPlugin( 'ext.gadget.foobar' );
907 *
908 * // Register a callback
909 * mw.libs.ve.addPlugin( ( target ) => {
910 * ve.dm.Foobar = .....
911 * } );
912 *
913 * // Register a callback that loads another script
914 * mw.libs.ve.addPlugin( () => $.getScript( 'http://example.com/foobar.js' ) );
915 *
916 * @param {string|Function} plugin Module name or callback that optionally returns a promise
917 */
918 addPlugin: function ( plugin ) {
919 plugins.push( plugin );
920 },
921
922 /**
923 * Adjust edit page links in the current document
924 *
925 * This will run multiple times in a page lifecycle, notably when the
926 * page first loads and after post-save content replacement occurs. It
927 * needs to avoid doing anything which will cause problems if it's run
928 * twice or more.
929 */
930 setupEditLinks: function () {
931 // NWE
932 if ( init.isWikitextAvailable && !isOnlyTabVE() ) {
933 $(
934 // Edit section links, except VE ones when both editors visible
935 '.mw-editsection a:not( .mw-editsection-visualeditor ),' +
936 // Edit tab
937 '#ca-edit a,' +
938 // Add section is currently a wikitext-only feature
939 '#ca-addsection a'
940 ).each( ( i, el ) => {
941 if ( !el.href ) {
942 // Not a real link, probably added by a gadget or another extension (T328094)
943 return;
944 }
945
946 const linkUrl = new URL( el.href );
947 if ( linkUrl.searchParams.has( 'action' ) ) {
948 linkUrl.searchParams.delete( 'action' );
949 linkUrl.searchParams.set( 'veaction', 'editsource' );
950 $( el ).attr( 'href', linkUrl.toString() );
951 }
952 } );
953 }
954
955 // Set up the tabs appropriately if the user has VE on
956 if ( init.isAvailable ) {
957 // … on two-edit-tab wikis, or single-edit-tab wikis, where the user wants both …
958 if (
959 !init.isSingleEditTab && init.isVisualAvailable &&
960 // T253941: This option does not actually disable the editor, only leaves the tabs/links unchanged
961 !( conf.disableForAnons && mw.user.isAnon() )
962 ) {
963 // … set the skin up with both tabs and both section edit links.
964 init.setupMultiTabSkin();
965 } else if (
966 pageCanLoadEditor && (
967 ( init.isVisualAvailable && isOnlyTabVE() ) ||
968 ( init.isWikitextAvailable && isOnlyTabWikitext() )
969 )
970 ) {
971 // … on single-edit-tab wikis, where VE or NWE is the user's preferred editor
972 // Handle section edit link clicks
973 $( '.mw-editsection a' ).off( '.ve-target' ).on( 'click.ve-target', ( e ) => {
974 // isOnlyTabVE is computed on click as it may have changed since load
975 init.onEditSectionLinkClick( isOnlyTabVE() ? 'visual' : 'source', e );
976 } );
977 // Allow instant switching to edit mode, without refresh
978 $( '#ca-edit' ).off( '.ve-target' ).on( 'click.ve-target', ( e ) => {
979 init.onEditTabClick( isOnlyTabVE() ? 'visual' : 'source', e );
980 } );
981 }
982 }
983 },
984
985 /**
986 * Setup multiple edit tabs and section links (edit + edit source)
987 */
988 setupMultiTabSkin: function () {
989 init.setupMultiTabs();
990 init.setupMultiSectionLinks();
991 },
992
993 /**
994 * Setup multiple edit tabs (edit + edit source)
995 */
996 setupMultiTabs: function () {
997 // Minerva puts the '#ca-...' ids on <a> nodes, other skins put them on <li>
998 const $caEdit = $( '#ca-edit' );
999 const $caVeEdit = $( '#ca-ve-edit' );
1000
1001 if ( pageCanLoadEditor ) {
1002 // Allow instant switching to edit mode, without refresh
1003 $caVeEdit.off( '.ve-target' ).on( 'click.ve-target', init.onEditTabClick.bind( init, 'visual' ) );
1004 }
1005 if ( pageCanLoadEditor ) {
1006 // Always bind "Edit source" tab, because we want to handle switching with changes
1007 $caEdit.off( '.ve-target' ).on( 'click.ve-target', init.onEditTabClick.bind( init, 'source' ) );
1008 }
1009 if ( pageCanLoadEditor && init.isWikitextAvailable ) {
1010 // Only bind "Add topic" tab if NWE is available, because VE doesn't support section
1011 // so we never have to switch from it when editing a section
1012 $( '#ca-addsection' ).off( '.ve-target' ).on( 'click.ve-target', init.onEditTabClick.bind( init, 'source' ) );
1013 }
1014
1015 if ( init.isVisualAvailable ) {
1016 if ( conf.tabPosition === 'before' ) {
1017 $caEdit.addClass( 'collapsible' );
1018 } else {
1019 $caVeEdit.addClass( 'collapsible' );
1020 }
1021 }
1022 },
1023
1024 /**
1025 * Setup multiple section links (edit + edit source)
1026 */
1027 setupMultiSectionLinks: function () {
1028 if ( pageCanLoadEditor ) {
1029 const $editsections = $( '#mw-content-text .mw-editsection' );
1030
1031 // Only init without refresh if we're on a view page. Though section edit links
1032 // are rarely shown on non-view pages, they appear in one other case, namely
1033 // when on a diff against the latest version of a page. In that case we mustn't
1034 // init without refresh as that'd initialise for the wrong rev id (T52925)
1035 // and would preserve the wrong DOM with a diff on top.
1036 $editsections.find( '.mw-editsection-visualeditor' )
1037 .off( '.ve-target' ).on( 'click.ve-target', init.onEditSectionLinkClick.bind( init, 'visual' ) );
1038 if ( init.isWikitextAvailable ) {
1039 // TOOD: Make this less fragile
1040 $editsections.find( 'a:not( .mw-editsection-visualeditor )' )
1041 .off( '.ve-target' ).on( 'click.ve-target', init.onEditSectionLinkClick.bind( init, 'source' ) );
1042 }
1043 }
1044 },
1045
1046 /**
1047 * Check whether a jQuery event represents a plain left click, without
1048 * any modifiers or a programmatically triggered click.
1049 *
1050 * This is a duplicate of a function in ve.utils, because this file runs
1051 * before any of VE core or OOui has been loaded.
1052 *
1053 * @param {jQuery.Event} e
1054 * @return {boolean} Whether it was an unmodified left click
1055 */
1056 isUnmodifiedLeftClick: function ( e ) {
1057 return e && ( (
1058 e.which && e.which === 1 && !( e.shiftKey || e.altKey || e.ctrlKey || e.metaKey )
1059 ) || e.isTrigger );
1060 },
1061
1062 /**
1063 * Handle click events on an edit tab
1064 *
1065 * @param {string} mode Edit mode, 'visual' or 'source'
1066 * @param {Event} e Event
1067 */
1068 onEditTabClick: function ( mode, e ) {
1069 if ( !init.isUnmodifiedLeftClick( e ) ) {
1070 return;
1071 }
1072 if ( !active && mode === 'source' && !init.isWikitextAvailable ) {
1073 // We're not active so we don't need to manage a switch, and
1074 // we don't have source mode available so we don't need to
1075 // activate VE. Just follow the link.
1076 return;
1077 }
1078 e.preventDefault();
1079 if ( isLoading ) {
1080 return;
1081 }
1082
1083 const section = $( e.target ).closest( '#ca-addsection' ).length ? 'new' : null;
1084
1085 if ( active ) {
1086 targetPromise.done( ( target ) => {
1087 if ( target.getDefaultMode() === 'source' ) {
1088 if ( mode === 'visual' ) {
1089 target.switchToVisualEditor();
1090 } else if ( mode === 'source' ) {
1091 // Requested section may have changed --
1092 // switchToWikitextSection will do nothing if the
1093 // section is unchanged.
1094 target.switchToWikitextSection( section );
1095 }
1096 } else if ( target.getDefaultMode() === 'visual' ) {
1097 if ( mode === 'source' ) {
1098 if ( section ) {
1099 // switching from visual via the "add section" tab
1100 target.switchToWikitextSection( section );
1101 } else {
1102 target.editSource();
1103 }
1104 }
1105 // Visual-to-visual doesn't need to do anything,
1106 // because we don't have any section concerns. Just
1107 // no-op it.
1108 }
1109 } );
1110 } else {
1111 const link = $( e.target ).closest( 'a' )[ 0 ];
1112 const linkUrl = link && link.href ? new URL( link.href ) : null;
1113 if ( section !== null ) {
1114 init.activateVe( mode, linkUrl, section );
1115 } else {
1116 // Do not pass `section` to handle switching from section editing in WikiEditor if needed
1117 init.activateVe( mode, linkUrl );
1118 }
1119 }
1120 },
1121
1122 /**
1123 * Activate VE
1124 *
1125 * @param {string} mode Target mode: 'visual' or 'source'
1126 * @param {URL} [linkUrl] URL to navigate to, potentially with extra parameters
1127 * @param {string} [section]
1128 */
1129 activateVe: function ( mode, linkUrl, section ) {
1130 const wikitext = $( '#wpTextbox1' ).textSelection( 'getContents' ),
1131 modified = mw.config.get( 'wgAction' ) === 'submit' ||
1132 (
1133 mw.config.get( 'wgAction' ) === 'edit' &&
1134 wikitext !== initialWikitext
1135 );
1136
1137 if ( section === undefined ) {
1138 const sectionVal = $( 'input[name=wpSection]' ).val();
1139 section = sectionVal !== '' && sectionVal !== undefined ? sectionVal : null;
1140 }
1141
1142 // Close any open jQuery.UI dialogs (e.g. WikiEditor's find and replace)
1143 if ( $.fn.dialog ) {
1144 $( '.ui-dialog-content' ).dialog( 'close' );
1145 }
1146
1147 // Release the edit warning on #wpTextbox1 which was setup in mediawiki.action.edit.editWarning.js
1148 $( window ).off( 'beforeunload.editwarning' );
1149 activatePageTarget( mode, section, modified, linkUrl );
1150 },
1151
1152 /**
1153 * Handle section edit links being clicked
1154 *
1155 * @param {string} mode Edit mode
1156 * @param {jQuery.Event} e Click event
1157 * @param {string} [section] Override edit section, taken from link URL if not specified
1158 */
1159 onEditSectionLinkClick: function ( mode, e, section ) {
1160 const link = $( e.target ).closest( 'a' )[ 0 ];
1161 if ( !link || !link.href ) {
1162 // Not a real link, probably added by a gadget or another extension (T328094)
1163 return;
1164 }
1165
1166 const linkUrl = new URL( link.href );
1167 const title = mw.Title.newFromText( linkUrl.searchParams.get( 'title' ) || '' );
1168
1169 if (
1170 // Modified click (e.g. ctrl+click)
1171 !init.isUnmodifiedLeftClick( e ) ||
1172 // Not an edit action
1173 !( linkUrl.searchParams.has( 'action' ) || linkUrl.searchParams.has( 'veaction' ) ) ||
1174 // Edit target is on another host (e.g. commons file)
1175 linkUrl.host !== location.host ||
1176 // Title param doesn't match current page
1177 title && title.getPrefixedText() !== new mw.Title( mw.config.get( 'wgRelevantPageName' ) ).getPrefixedText()
1178 ) {
1179 return;
1180 }
1181 e.preventDefault();
1182 if ( isLoading ) {
1183 return;
1184 }
1185
1186 trackActivateStart( { type: 'section', mechanism: section === 'new' ? 'new' : 'click', mode: mode }, linkUrl );
1187
1188 if ( !active ) {
1189 // Replace the current state with one that is tagged as ours, to prevent the
1190 // back button from breaking when used to exit VE. FIXME: there should be a better
1191 // way to do this. See also similar code in the DesktopArticleTarget constructor.
1192 history.replaceState( { tag: 'visualeditor' }, '', url );
1193 // Use linkUrl to preserve the 'section' parameter and others like 'editintro' (T56029)
1194 history.pushState( { tag: 'visualeditor' }, '', linkUrl );
1195 // Update URL instance
1196 url = linkUrl;
1197
1198 // Use section from URL
1199 if ( section === undefined ) {
1200 section = parseSection( linkUrl.searchParams.get( 'section' ) );
1201 }
1202 const tPromise = getTarget( mode, section );
1203 activateTarget( mode, section, tPromise );
1204 }
1205 },
1206
1207 /**
1208 * Check whether the welcome dialog should be shown.
1209 *
1210 * The welcome dialog can be disabled in configuration; or by calling disableWelcomeDialog();
1211 * or using a query string parameter; or if we've recorded that we've already shown it before
1212 * in a user preference, local storage or a cookie.
1213 *
1214 * @return {boolean}
1215 */
1216 shouldShowWelcomeDialog: function () {
1217 return !(
1218 // Disabled in config?
1219 !mw.config.get( 'wgVisualEditorConfig' ).showBetaWelcome ||
1220 // Disabled for the current request?
1221 this.isWelcomeDialogSuppressed() ||
1222 // Joining a collab session
1223 url.searchParams.has( 'collabSession' ) ||
1224 // Hidden using preferences, local storage or cookie?
1225 checkPreferenceOrStorage( 'visualeditor-hidebetawelcome', 've-beta-welcome-dialog' )
1226 );
1227 },
1228
1229 /**
1230 * Check whether the welcome dialog is temporarily disabled.
1231 *
1232 * @return {boolean}
1233 */
1234 isWelcomeDialogSuppressed: function () {
1235 return !!(
1236 // Disabled by calling disableWelcomeDialog()?
1237 welcomeDialogDisabled ||
1238 // Hidden using URL parameter?
1239 new URL( location.href ).searchParams.has( 'vehidebetadialog' ) ||
1240 // Check for deprecated hidewelcomedialog parameter (T249954)
1241 new URL( location.href ).searchParams.has( 'hidewelcomedialog' )
1242 );
1243 },
1244
1245 /**
1246 * Record that we've already shown the welcome dialog to this user, so that it won't be shown
1247 * to them again.
1248 *
1249 * Uses a preference for logged-in users; uses local storage or a cookie for anonymous users.
1250 */
1251 stopShowingWelcomeDialog: function () {
1252 setPreferenceOrStorage( 'visualeditor-hidebetawelcome', 've-beta-welcome-dialog' );
1253 },
1254
1255 /**
1256 * Prevent the welcome dialog from being shown on this page view only.
1257 *
1258 * Causes shouldShowWelcomeDialog() to return false, but doesn't save anything to preferences
1259 * or local storage, so future page views are not affected.
1260 */
1261 disableWelcomeDialog: function () {
1262 welcomeDialogDisabled = true;
1263 },
1264
1265 /**
1266 * Check whether the user education popups (ve.ui.MWEducationPopupWidget) should be shown.
1267 *
1268 * The education popups can be disabled by calling disableWelcomeDialog(), or if we've
1269 * recorded that we've already shown it before in a user preference, local storage or a cookie.
1270 *
1271 * @return {boolean}
1272 */
1273 shouldShowEducationPopups: function () {
1274 return !(
1275 // Disabled by calling disableEducationPopups()?
1276 educationPopupsDisabled ||
1277 // Hidden using preferences, local storage, or cookie?
1278 checkPreferenceOrStorage( 'visualeditor-hideusered', 've-hideusered' )
1279 );
1280 },
1281
1282 /**
1283 * Record that we've already shown the education popups to this user, so that it won't be
1284 * shown to them again.
1285 *
1286 * Uses a preference for logged-in users; uses local storage or a cookie for anonymous users.
1287 */
1288 stopShowingEducationPopups: function () {
1289 setPreferenceOrStorage( 'visualeditor-hideusered', 've-hideusered' );
1290 },
1291
1292 /**
1293 * Prevent the education popups from being shown on this page view only.
1294 *
1295 * Causes shouldShowEducationPopups() to return false, but doesn't save anything to
1296 * preferences or local storage, so future page views are not affected.
1297 */
1298 disableEducationPopups: function () {
1299 educationPopupsDisabled = true;
1300 }
1301 };
1302
1303 init.isSingleEditTab = conf.singleEditTab && tabPreference !== 'multi-tab';
1304
1305 // On a view page, extend the current URL so extra parameters are carried over
1306 // On a non-view page, use viewUrl
1307 veEditUrl = new URL( pageCanLoadEditor ? url : viewUrl );
1308 if ( oldId ) {
1309 veEditUrl.searchParams.set( 'oldid', oldId );
1310 }
1311 veEditUrl.searchParams.delete( 'veaction' );
1312 veEditUrl.searchParams.delete( 'action' );
1313 if ( init.isSingleEditTab ) {
1314 veEditUrl.searchParams.set( 'action', 'edit' );
1315 veEditSourceUrl = veEditUrl;
1316 } else {
1317 veEditSourceUrl = new URL( veEditUrl );
1318 veEditUrl.searchParams.set( 'veaction', 'edit' );
1319 veEditSourceUrl.searchParams.set( 'veaction', 'editsource' );
1320 }
1321
1322 // Whether VisualEditor should be available for the current user, page, wiki, mediawiki skin,
1323 // browser etc.
1324 init.isAvailable = VisualEditorSupportCheck();
1325 // Extensions can disable VE in certain circumstances using the VisualEditorBeforeEditor hook (T174180)
1326
1327 const enabledForUser = (
1328 // User has 'visualeditor-enable' preference enabled (for alpha opt-in)
1329 // User has 'visualeditor-betatempdisable' preference disabled
1330 // User has 'visualeditor-autodisable' preference disabled
1331 ( conf.isBeta ? enable : !tempdisable ) && !autodisable
1332 );
1333
1334 // Duplicated in VisualEditor.hooks.php#isVisualAvailable()
1335 init.isVisualAvailable = (
1336 init.isAvailable &&
1337
1338 // If forced by the URL parameter, skip the namespace check (T221892) and preference check
1339 ( url.searchParams.get( 'veaction' ) === 'edit' || (
1340 // Only in enabled namespaces
1341 conf.namespaces.indexOf( new mw.Title( mw.config.get( 'wgRelevantPageName' ) ).getNamespaceId() ) !== -1 &&
1342
1343 // Enabled per user preferences
1344 enabledForUser
1345 ) ) &&
1346
1347 // Only for pages with a supported content model
1348 Object.prototype.hasOwnProperty.call( conf.contentModels, mw.config.get( 'wgPageContentModel' ) )
1349 );
1350
1351 // Duplicated in VisualEditor.hooks.php#isWikitextAvailable()
1352 init.isWikitextAvailable = (
1353 init.isAvailable &&
1354
1355 // If forced by the URL parameter, skip the checks (T239796)
1356 ( url.searchParams.get( 'veaction' ) === 'editsource' || (
1357 // Enabled on site
1358 conf.enableWikitext &&
1359
1360 // User preference
1361 mw.user.options.get( 'visualeditor-newwikitext' )
1362 ) ) &&
1363
1364 // Only on wikitext pages
1365 mw.config.get( 'wgPageContentModel' ) === 'wikitext'
1366 );
1367
1368 if ( init.isVisualAvailable ) {
1369 availableModes.push( 'visual' );
1370 }
1371
1372 if ( init.isWikitextAvailable ) {
1373 availableModes.push( 'source' );
1374 }
1375
1376 // FIXME: We should do this more elegantly
1377 init.setEditorPreference = setEditorPreference;
1378
1379 init.updateTabs = updateTabs;
1380
1381 // Note: Though VisualEditor itself only needed this exposure for a very small reason
1382 // (namely to access the old init.unsupportedList from the unit tests...) this has become one
1383 // of the nicest ways to easily detect whether the VisualEditor initialisation code is present.
1384 //
1385 // The VE global was once available always, but now that platform integration initialisation
1386 // is properly separated, it doesn't exist until the platform loads VisualEditor core.
1387 //
1388 // Most of mw.libs.ve is considered subject to change and private. An exception is that
1389 // mw.libs.ve.isVisualAvailable is public, and indicates whether the VE editor itself can be loaded
1390 // on this page. See above for why it may be false.
1391 mw.libs.ve = $.extend( mw.libs.ve || {}, init );
1392
1393 if ( init.isVisualAvailable ) {
1394 $( 'html' ).addClass( 've-available' );
1395 } else {
1396 $( 'html' ).addClass( 've-not-available' );
1397 // Don't return here because we do want the skin setup to consistently happen
1398 // for e.g. "Edit" > "Edit source" even when VE is not available.
1399 }
1400
1401 /**
1402 * Check if a URL doesn't contain any params which would prevent VE from loading, e.g. 'undo'
1403 *
1404 * @param {URL} editUrl
1405 * @return {boolean} URL contains no unsupported params
1406 */
1407 function isSupportedEditPage( editUrl ) {
1408 return configData.unsupportedEditParams.every( ( param ) => !editUrl.searchParams.has( param ) );
1409 }
1410
1411 /**
1412 * Get the edit mode for the given URL
1413 *
1414 * @param {URL} editUrl Edit URL
1415 * @return {string|null} 'visual' or 'source', null if the editor is not being loaded
1416 */
1417 function getEditModeFromUrl( editUrl ) {
1418 if ( mw.config.get( 'wgDiscussionToolsStartNewTopicTool' ) ) {
1419 // Avoid conflicts with DiscussionTools
1420 return null;
1421 }
1422 if ( isViewPage && init.isAvailable ) {
1423 // On view pages if veaction is correctly set
1424 const mode = veactionToMode[ editUrl.searchParams.get( 'veaction' ) ] ||
1425 // Always load VE visual mode if collabSession is set
1426 ( editUrl.searchParams.has( 'collabSession' ) ? 'visual' : null );
1427 if ( mode && availableModes.indexOf( mode ) !== -1 ) {
1428 return mode;
1429 }
1430 }
1431 // Edit pages
1432 if ( isEditPage && isSupportedEditPage( editUrl ) ) {
1433 // User has disabled VE, or we are in view source only mode, or we have landed here with posted data
1434 if ( !enabledForUser || $( '#ca-viewsource' ).length || mw.config.get( 'wgAction' ) === 'submit' ) {
1435 return null;
1436 }
1437 return getAvailableEditPageEditor();
1438 }
1439 return null;
1440 }
1441
1442 $( () => {
1443 $targetContainer = $(
1444 document.querySelector( '[data-mw-ve-target-container]' ) ||
1445 document.getElementById( 'content' )
1446 );
1447 if ( pageCanLoadEditor ) {
1448 $targetContainer.addClass( 've-init-mw-desktopArticleTarget-targetContainer' );
1449 }
1450
1451 let showWikitextWelcome = true;
1452 const numEditButtons = $( '#ca-edit, #ca-ve-edit' ).length,
1453 section = parseSection( url.searchParams.get( 'section' ) );
1454
1455 const requiredSkinElements =
1456 $targetContainer.length &&
1457 $( '#mw-content-text' ).length &&
1458 // A link to open the editor is technically not necessary if it's going to open itself
1459 ( isEditPage || numEditButtons );
1460
1461 if ( url.searchParams.get( 'action' ) === 'edit' && $( '#wpTextbox1' ).length ) {
1462 initialWikitext = $( '#wpTextbox1' ).textSelection( 'getContents' );
1463 }
1464
1465 if ( ( init.isVisualAvailable || init.isWikitextAvailable ) &&
1466 pageCanLoadEditor &&
1467 pageIsProbablyEditable &&
1468 !requiredSkinElements
1469 ) {
1470 mw.log.warn(
1471 'Your skin is incompatible with VisualEditor. ' +
1472 'See https://www.mediawiki.org/wiki/Extension:VisualEditor/Skin_requirements for the requirements.'
1473 );
1474 // If the edit buttons are not there it's likely a browser extension or gadget for anonymous user
1475 // has removed them. We're not interested in errors from this scenario so don't log.
1476 // If they exist log the error so we can address the problem.
1477 if ( numEditButtons > 0 ) {
1478 const err = new Error( 'Incompatible with VisualEditor' );
1479 err.name = 'VeIncompatibleSkinWarning';
1480 mw.errorLogger.logError( err, 'error.visualeditor' );
1481 }
1482 } else if ( init.isAvailable ) {
1483 const mode = getEditModeFromUrl( url );
1484 if ( mode ) {
1485 showWikitextWelcome = false;
1486 trackActivateStart( {
1487 type: section === null ? 'page' : 'section',
1488 mechanism: ( section === 'new' || !mw.config.get( 'wgArticleId' ) ) ? 'url-new' : 'url',
1489 mode: mode
1490 } );
1491 activateTarget( mode, section );
1492 } else if (
1493 init.isVisualAvailable &&
1494 pageCanLoadEditor &&
1495 init.isSingleEditTab
1496 ) {
1497 // In single edit tab mode we never have an edit tab
1498 // with accesskey 'v' so create one
1499 $( document.body ).append(
1500 $( '<a>' )
1501 .attr( { accesskey: mw.msg( 'accesskey-ca-ve-edit' ), href: veEditUrl } )
1502 // Accesskey fires a click event
1503 .on( 'click.ve-target', init.onEditTabClick.bind( init, 'visual' ) )
1504 .addClass( 'oo-ui-element-hidden' )
1505 );
1506 }
1507
1508 // Add the switch button to WikiEditor on edit pages
1509 if (
1510 init.isVisualAvailable &&
1511 isEditPage &&
1512 $( '#wpTextbox1' ).length
1513 ) {
1514 mw.loader.load( 'ext.visualEditor.switching' );
1515 mw.hook( 'wikiEditor.toolbarReady' ).add( ( $textarea ) => {
1516 mw.loader.using( 'ext.visualEditor.switching' ).done( () => {
1517 const showPopup = url.searchParams.has( 'veswitched' ) && !mw.user.options.get( 'visualeditor-hidesourceswitchpopup' ),
1518 toolFactory = new OO.ui.ToolFactory(),
1519 toolGroupFactory = new OO.ui.ToolGroupFactory();
1520
1521 toolFactory.register( mw.libs.ve.MWEditModeVisualTool );
1522 toolFactory.register( mw.libs.ve.MWEditModeSourceTool );
1523 const switchToolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory, {
1524 classes: [ 've-init-mw-editSwitch' ]
1525 } );
1526
1527 switchToolbar.on( 'switchEditor', ( m ) => {
1528 if ( m === 'visual' ) {
1529 $( '#wpTextbox1' ).trigger( 'wikiEditor-switching-visualeditor' );
1530 init.activateVe( 'visual' );
1531 }
1532 } );
1533
1534 switchToolbar.setup( [ {
1535 name: 'editMode',
1536 type: 'list',
1537 icon: 'edit',
1538 title: mw.msg( 'visualeditor-mweditmode-tooltip' ),
1539 label: mw.msg( 'visualeditor-mweditmode-tooltip' ),
1540 invisibleLabel: true,
1541 include: [ 'editModeVisual', 'editModeSource' ]
1542 } ] );
1543
1544 const popup = new mw.libs.ve.SwitchPopupWidget( 'source' );
1545
1546 switchToolbar.tools.editModeVisual.toolGroup.$element.append( popup.$element );
1547 switchToolbar.emit( 'updateState' );
1548
1549 $textarea.wikiEditor( 'addToToolbar', {
1550 section: 'secondary',
1551 group: 'default',
1552 tools: {
1553 veEditSwitch: {
1554 type: 'element',
1555 element: switchToolbar.$element
1556 }
1557 }
1558 } );
1559
1560 popup.toggle( showPopup );
1561
1562 // Duplicate of this code in ve.init.mw.DesktopArticleTarget.js
1563 // eslint-disable-next-line no-jquery/no-class-state
1564 if ( $( '#ca-edit' ).hasClass( 'visualeditor-showtabdialog' ) ) {
1565 $( '#ca-edit' ).removeClass( 'visualeditor-showtabdialog' );
1566 // Set up a temporary window manager
1567 const windowManager = new OO.ui.WindowManager();
1568 $( OO.ui.getTeleportTarget() ).append( windowManager.$element );
1569 const editingTabDialog = new mw.libs.ve.EditingTabDialog();
1570 windowManager.addWindows( [ editingTabDialog ] );
1571 windowManager.openWindow( editingTabDialog )
1572 .closed.then( ( data ) => {
1573 // Detach the temporary window manager
1574 windowManager.destroy();
1575
1576 if ( data && data.action === 'prefer-ve' ) {
1577 location.href = veEditUrl;
1578 } else if ( data && data.action === 'multi-tab' ) {
1579 location.reload();
1580 }
1581 } );
1582 }
1583 } );
1584 } );
1585
1586 // Remember that the user wanted wikitext, at least this time
1587 mw.libs.ve.setEditorPreference( 'wikitext' );
1588
1589 // If the user has loaded WikiEditor, clear any auto-save state they
1590 // may have from a previous VE session
1591 // We don't have access to the VE session storage methods, but invalidating
1592 // the docstate is sufficient to prevent the data from being used.
1593 mw.storage.session.remove( 've-docstate' );
1594 }
1595
1596 init.setupEditLinks();
1597 }
1598
1599 if (
1600 pageCanLoadEditor &&
1601 showWikitextWelcome &&
1602 // At least one editor is available (T201928)
1603 ( init.isVisualAvailable || init.isWikitextAvailable || $( '#wpTextbox1' ).length ) &&
1604 isEditPage &&
1605 init.shouldShowWelcomeDialog() &&
1606 // Not on protected pages
1607 pageIsProbablyEditable
1608 ) {
1609 mw.loader.using( 'ext.visualEditor.welcome' ).done( () => {
1610 // Check shouldShowWelcomeDialog() again: any code that might have called
1611 // stopShowingWelcomeDialog() wouldn't have had an opportunity to do that
1612 // yet by the first time we checked
1613 if ( !init.shouldShowWelcomeDialog() ) {
1614 return;
1615 }
1616 const windowManager = new OO.ui.WindowManager();
1617 const welcomeDialog = new mw.libs.ve.WelcomeDialog();
1618 $( OO.ui.getTeleportTarget() ).append( windowManager.$element );
1619 windowManager.addWindows( [ welcomeDialog ] );
1620 windowManager.openWindow(
1621 welcomeDialog,
1622 {
1623 switchable: init.isVisualAvailable,
1624 editor: 'source'
1625 }
1626 )
1627 .closed.then( ( data ) => {
1628 windowManager.destroy();
1629 if ( data && data.action === 'switch-ve' ) {
1630 init.activateVe( 'visual' );
1631 }
1632 } );
1633
1634 init.stopShowingWelcomeDialog();
1635 } );
1636 }
1637
1638 if ( url.searchParams.has( 'venotify' ) ) {
1639 url.searchParams.delete( 'venotify' );
1640 // Get rid of the ?venotify= from the URL
1641 history.replaceState( null, '', url );
1642 }
1643 } );
1644 }() );