Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor MediaWiki Initialization Target class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Initialization MediaWiki target.
10 *
11 * @class
12 * @extends ve.init.Target
13 *
14 * @constructor
15 * @param {Object} config
16 * @param {string[]} [config.surfaceClasses=[]] Surface classes to apply
17 */
18 ve.init.mw.Target = function VeInitMwTarget( config ) {
19 this.surfaceClasses = config.surfaceClasses || [];
20
21 // Parent constructor
22 ve.init.mw.Target.super.call( this, config );
23
24 this.active = false;
25 this.pageName = mw.config.get( 'wgRelevantPageName' );
26 this.recovered = false;
27 this.fromEditedState = false;
28 this.originalHtml = null;
29
30 // Initialization
31 this.$element.addClass( 've-init-mw-target' );
32 };
33
34 /* Inheritance */
35
36 OO.inheritClass( ve.init.mw.Target, ve.init.Target );
37
38 /* Static Properties */
39
40 /**
41 * Symbolic name for this target class.
42 *
43 * @static
44 * @property {string}
45 * @inheritable
46 */
47 ve.init.mw.Target.static.name = null;
48
49 ve.init.mw.Target.static.toolbarGroups = [
50 {
51 name: 'history',
52 include: [ { group: 'history' } ]
53 },
54 {
55 name: 'format',
56 type: 'menu',
57 title: OO.ui.deferMsg( 'visualeditor-toolbar-format-tooltip' ),
58 include: [ { group: 'format' } ],
59 promote: [ 'paragraph' ],
60 demote: [ 'preformatted', 'blockquote', 'heading1' ]
61 },
62 {
63 name: 'style',
64 type: 'list',
65 icon: 'textStyle',
66 title: OO.ui.deferMsg( 'visualeditor-toolbar-style-tooltip' ),
67 label: OO.ui.deferMsg( 'visualeditor-toolbar-style-tooltip' ),
68 invisibleLabel: true,
69 include: [ { group: 'textStyle' } ],
70 forceExpand: [ 'bold', 'italic', 'clear' ],
71 promote: [ 'bold', 'italic', 'superscript', 'subscript' ],
72 demote: [ 'clear' ]
73 },
74 {
75 name: 'link',
76 include: [ 'link' ]
77 },
78 // Placeholder for reference tools (e.g. Cite and/or Citoid)
79 {
80 name: 'reference'
81 },
82 {
83 name: 'structure',
84 type: 'list',
85 icon: 'listBullet',
86 title: OO.ui.deferMsg( 'visualeditor-toolbar-structure' ),
87 label: OO.ui.deferMsg( 'visualeditor-toolbar-structure' ),
88 invisibleLabel: true,
89 include: [ { group: 'structure' } ],
90 demote: [ 'outdent', 'indent' ]
91 },
92 {
93 name: 'insert',
94 label: OO.ui.deferMsg( 'visualeditor-toolbar-insert' ),
95 title: OO.ui.deferMsg( 'visualeditor-toolbar-insert' ),
96 narrowConfig: {
97 invisibleLabel: true,
98 icon: 'add'
99 },
100 include: '*',
101 forceExpand: [ 'media', 'transclusion', 'insertTable' ],
102 promote: [ 'media', 'transclusion', 'insertTable' ]
103 },
104 {
105 name: 'specialCharacter',
106 include: [ 'specialCharacter' ]
107 }
108 ];
109
110 ve.init.mw.Target.static.importRules = ve.copy( ve.init.mw.Target.static.importRules );
111
112 ve.init.mw.Target.static.importRules.external.removeOriginalDomElements = true;
113
114 ve.init.mw.Target.static.importRules.external.blacklist = ve.extendObject( {
115 // Annotations
116 'textStyle/underline': true,
117 'meta/language': true,
118 'textStyle/datetime': true,
119 'link/mwExternal': !mw.config.get( 'wgVisualEditorConfig' ).allowExternalLinkPaste,
120 // Node
121 article: true,
122 section: true
123 }, ve.init.mw.Target.static.importRules.external.blacklist );
124
125 ve.init.mw.Target.static.importRules.external.htmlBlacklist.remove = ve.extendObject( {
126 // TODO: Create a plugin system for extending the blacklist, so this code
127 // can be moved to the Cite extension.
128 // Remove reference numbers copied from MW read mode (T150418)
129 'sup.reference:not( [typeof] )': true,
130 // ...sometimes we need a looser match if the HTML has been mangled
131 // in a third-party editor e.g. LibreOffice (T232461)
132 'a[ href *= "#cite_note" ]': true
133 }, ve.init.mw.Target.static.importRules.external.htmlBlacklist.remove );
134
135 // This is required to prevent an invalid insertion (as mwHeading can only be at the root) (T339155)
136 // TODO: This should be handled by the DM based on ve.dm.MWHeadingNode.static.suggestedParentNodeTypes,
137 // rather than just throwing an exception.
138 // This would also not prevent pasting from a VE standalone editor as that is considered
139 // an internal paste.
140 ve.init.mw.Target.static.importRules.external.htmlBlacklist.unwrap = ve.extendObject( {
141 'li h1, li h2, li h3, li h4, li h5, li h6': true,
142 'blockquote h1, blockquote h2, blockquote h3, blockquote h4, blockquote h5, blockquote h6': true
143 }, ve.init.mw.Target.static.importRules.external.htmlBlacklist.unwrap );
144
145 /**
146 * Type of integration. Used for event tracking.
147 *
148 * @static
149 * @property {string}
150 * @inheritable
151 */
152 ve.init.mw.Target.static.integrationType = null;
153
154 /**
155 * Type of platform. Used for event tracking.
156 *
157 * @static
158 * @property {string}
159 * @inheritable
160 */
161 ve.init.mw.Target.static.platformType = null;
162
163 /* Static Methods */
164
165 /**
166 * Fix the base URL from Parsoid if necessary.
167 *
168 * Absolutizes the base URL if it's relative, and sets a base URL based on wgArticlePath
169 * if there was no base URL at all.
170 *
171 * @param {HTMLDocument} doc Parsoid document
172 */
173 ve.init.mw.Target.static.fixBase = function ( doc ) {
174 ve.fixBase( doc, document, ve.resolveUrl(
175 // Don't replace $1 with the page name, because that'll break if
176 // the page name contains a slash
177 mw.config.get( 'wgArticlePath' ).replace( '$1', '' ),
178 document
179 ) );
180 };
181
182 /**
183 * @inheritdoc
184 */
185 ve.init.mw.Target.static.createModelFromDom = function ( doc, mode, options ) {
186 const conf = mw.config.get( 'wgVisualEditor' );
187
188 options = ve.extendObject( {
189 lang: conf.pageLanguageCode,
190 dir: conf.pageLanguageDir
191 }, options );
192
193 // Parent method
194 return ve.init.mw.Target.super.static.createModelFromDom.call( this, doc, mode, options );
195 };
196
197 // Deprecated alias
198 ve.init.mw.Target.prototype.createModelFromDom = function () {
199 return this.constructor.static.createModelFromDom.apply( this.constructor.static, arguments );
200 };
201
202 /**
203 * @inheritdoc
204 * @param {string} documentString
205 * @param {string} mode
206 * @param {string|null} [section] Section. Use null to unwrap all sections.
207 * @param {boolean} [onlySection=false] Only return the requested section, otherwise returns the
208 * whole document with just the requested section still wrapped (visual mode only).
209 * @return {HTMLDocument|string} HTML document, or document string (source mode)
210 */
211 ve.init.mw.Target.static.parseDocument = function ( documentString, mode, section, onlySection ) {
212 let doc;
213 if ( mode === 'source' ) {
214 // Parent method
215 doc = ve.init.mw.Target.super.static.parseDocument.call( this, documentString, mode );
216 } else {
217 doc = ve.createDocumentFromHtml( documentString );
218 if ( section !== undefined ) {
219 if ( onlySection ) {
220 const sectionNode = doc.body.querySelector( '[data-mw-section-id="' + section + '"]' );
221 doc.body.innerHTML = '';
222 if ( sectionNode ) {
223 doc.body.appendChild( sectionNode );
224 }
225 } else {
226 // Strip Parsoid sections
227 mw.libs.ve.unwrapParsoidSections( doc.body, section );
228 }
229 }
230 // Strip legacy IDs, for example in section headings
231 mw.libs.ve.stripParsoidFallbackIds( doc.body );
232 // Re-duplicate deduplicated TemplateStyles, for correct rendering when editing a section or
233 // when templates are removed during the edit
234 mw.libs.ve.reduplicateStyles( doc.body );
235 // Fix relative or missing base URL if needed
236 this.fixBase( doc );
237 // Test: Remove tags injected by plugins during parse (T298147)
238 Array.prototype.forEach.call( doc.querySelectorAll( 'script' ), ( element ) => {
239 function truncate( text, l ) {
240 return text.length > l ? text.slice( 0, l ) + '…' : text;
241 }
242 const errorMessage = 'DOM content matching deny list found during parse:\n' + truncate( element.outerHTML, 100 ) +
243 '\nContext:\n' + truncate( element.parentNode.outerHTML, 200 );
244 mw.log.error( errorMessage );
245 const err = new Error( errorMessage );
246 err.name = 'VeDomDenyListWarning';
247 mw.errorLogger.logError( err, 'error.visualeditor' );
248 element.parentNode.removeChild( element );
249 } );
250 }
251
252 return doc;
253 };
254
255 /* Methods */
256
257 /**
258 * Handle both DOM and modules being loaded and ready.
259 *
260 * @param {HTMLDocument|string} doc HTML document or source text
261 */
262 ve.init.mw.Target.prototype.documentReady = function ( doc ) {
263 this.setupSurface( doc );
264 };
265
266 /**
267 * Once surface is ready, initialize the UI
268 *
269 * @fires ve.init.Target#surfaceReady
270 */
271 ve.init.mw.Target.prototype.surfaceReady = function () {
272 this.emit( 'surfaceReady' );
273 };
274
275 /**
276 * @deprecated Moved to mw.libs.ve.targetSaver.getHtml
277 * @param {HTMLDocument} newDoc
278 * @param {HTMLDocument} [oldDoc]
279 * @return {string}
280 */
281 ve.init.mw.Target.prototype.getHtml = function ( newDoc, oldDoc ) {
282 OO.ui.warnDeprecation( 've.init.mw.Target#getHtml is deprecated. Use mw.libs.ve.targetSaver.getHtml.' );
283 return mw.libs.ve.targetSaver.getHtml( newDoc, oldDoc );
284 };
285
286 /**
287 * Track an event
288 *
289 * @param {string} name Event name
290 */
291 ve.init.mw.Target.prototype.track = function () {};
292
293 /**
294 * Get a list of CSS classes to be added to surfaces, and target widget surfaces
295 *
296 * @return {string[]} CSS classes
297 */
298 ve.init.mw.Target.prototype.getSurfaceClasses = function () {
299 return this.surfaceClasses;
300 };
301
302 /**
303 * @inheritdoc
304 */
305 ve.init.mw.Target.prototype.createTargetWidget = function ( config ) {
306 return new ve.ui.MWTargetWidget( ve.extendObject( {
307 // Reset to visual mode for target widgets
308 modes: [ 'visual' ],
309 defaultMode: 'visual',
310 toolbarGroups: this.toolbarGroups.filter( ( group ) => group.align !== 'after' ),
311 surfaceClasses: this.getSurfaceClasses()
312 }, config ) );
313 };
314
315 /**
316 * @inheritdoc
317 */
318 ve.init.mw.Target.prototype.createSurface = function ( dmDoc, config ) {
319 if ( config && config.mode === 'source' ) {
320 const importRules = ve.copy( this.constructor.static.importRules );
321 importRules.all = importRules.all || {};
322 // Preserve empty linebreaks on paste in source editor
323 importRules.all.keepEmptyContentBranches = true;
324 config = this.getSurfaceConfig( ve.extendObject( {}, config, {
325 importRules: importRules
326 } ) );
327 return new ve.ui.MWWikitextSurface( this, dmDoc, config );
328 }
329
330 return new ve.ui.MWSurface( this, dmDoc, this.getSurfaceConfig( config ) );
331 };
332
333 /**
334 * @inheritdoc
335 */
336 ve.init.mw.Target.prototype.getSurfaceConfig = function ( config ) {
337 // If we're not asking for a specific mode's config, use the default mode.
338 config = ve.extendObject( { mode: this.defaultMode }, config );
339 // eslint-disable-next-line mediawiki/class-doc
340 return ve.init.mw.Target.super.prototype.getSurfaceConfig.call( this, ve.extendObject( {
341 // Provide the wikitext versions of the registries, if we're using source mode
342 commandRegistry: config.mode === 'source' ? ve.ui.wikitextCommandRegistry : ve.ui.commandRegistry,
343 sequenceRegistry: config.mode === 'source' ? ve.ui.wikitextSequenceRegistry : ve.ui.sequenceRegistry,
344 dataTransferHandlerFactory: config.mode === 'source' ? ve.ui.wikitextDataTransferHandlerFactory : ve.ui.dataTransferHandlerFactory,
345 classes: this.getSurfaceClasses()
346 }, config ) );
347 };
348
349 /**
350 * Switch to editing mode.
351 *
352 * @param {HTMLDocument|string} doc HTML document or source text
353 */
354 ve.init.mw.Target.prototype.setupSurface = function ( doc ) {
355 setTimeout( () => {
356 // Build model
357 this.track( 'trace.convertModelFromDom.enter' );
358 const dmDoc = this.constructor.static.createModelFromDom( doc, this.getDefaultMode() );
359 this.track( 'trace.convertModelFromDom.exit' );
360
361 // Build DM tree now (otherwise it gets lazily built when building the CE tree)
362 this.track( 'trace.buildModelTree.enter' );
363 dmDoc.buildNodeTree();
364 this.track( 'trace.buildModelTree.exit' );
365
366 setTimeout( () => {
367 this.addSurface( dmDoc );
368 } );
369 } );
370 };
371
372 /**
373 * @inheritdoc
374 */
375 ve.init.mw.Target.prototype.addSurface = function () {
376 // Clear dummy surfaces
377 // TODO: Move to DesktopArticleTarget
378 this.clearSurfaces();
379
380 // Create ui.Surface (also creates ce.Surface and dm.Surface and builds CE tree)
381 this.track( 'trace.createSurface.enter' );
382 // Parent method
383 const surface = ve.init.mw.Target.super.prototype.addSurface.apply( this, arguments );
384 // Add classes specific to surfaces attached directly to the target,
385 // as opposed to TargetWidget surfaces
386 if ( !surface.inTargetWidget ) {
387 surface.$element.addClass( 've-init-mw-target-surface' );
388 }
389 this.track( 'trace.createSurface.exit' );
390
391 this.setSurface( surface );
392
393 setTimeout( () => {
394 // Initialize surface
395 this.track( 'trace.initializeSurface.enter' );
396
397 this.active = true;
398 // Now that the surface is attached to the document and ready,
399 // let it initialize itself
400 surface.initialize();
401
402 this.track( 'trace.initializeSurface.exit' );
403 this.surfaceReady();
404 } );
405
406 return surface;
407 };
408
409 /**
410 * @inheritdoc
411 */
412 ve.init.mw.Target.prototype.setSurface = function ( surface ) {
413 if ( !surface.$element.parent().length ) {
414 this.$element.append( surface.$element );
415 }
416
417 // Parent method
418 ve.init.mw.Target.super.prototype.setSurface.apply( this, arguments );
419 };
420
421 /**
422 * Intialise autosave, recovering changes if applicable
423 *
424 * @param {Object} [config] Configuration options
425 * @param {boolean} [config.suppressNotification=false] Don't notify the user if changes are recovered
426 * @param {string} [config.docId] Document ID for storage grouping
427 * @param {ve.init.SafeStorage} [config.storage] Storage interface
428 * @param {number} [config.storageExpiry] Storage expiry time in seconds (optional)
429 */
430 ve.init.mw.Target.prototype.initAutosave = function ( config ) {
431 // Old function signature
432 // TODO: Remove after fixed downstream
433 if ( typeof config === 'boolean' ) {
434 config = { suppressNotification: config };
435 } else {
436 config = config || {};
437 }
438
439 const surfaceModel = this.getSurface().getModel();
440
441 if ( config.docId ) {
442 surfaceModel.setAutosaveDocId( config.docId );
443 }
444
445 if ( config.storage ) {
446 surfaceModel.setStorage( config.storage, config.storageExpiry );
447 }
448
449 if ( this.recovered ) {
450 // Restore auto-saved transactions if document state was recovered
451 try {
452 surfaceModel.restoreChanges();
453 if ( !config.suppressNotification ) {
454 ve.init.platform.notify(
455 ve.msg( 'visualeditor-autosave-recovered-text' ),
456 ve.msg( 'visualeditor-autosave-recovered-title' )
457 );
458 }
459 } catch ( e ) {
460 mw.log.warn( e );
461 ve.init.platform.notify(
462 ve.msg( 'visualeditor-autosave-not-recovered-text' ),
463 ve.msg( 'visualeditor-autosave-not-recovered-title' ),
464 { type: 'error' }
465 );
466 }
467 } else {
468 // ...otherwise store this document state for later recovery
469 if ( this.fromEditedState ) {
470 // Store immediately if the document was previously edited
471 // (e.g. in a different mode)
472 this.storeDocState( this.originalHtml );
473 } else {
474 // Only store after the first change if this is an unmodified document
475 surfaceModel.once( 'undoStackChange', () => {
476 // Check the surface hasn't been destroyed
477 if ( this.getSurface() ) {
478 this.storeDocState( this.originalHtml );
479 }
480 } );
481 }
482 }
483 // Start auto-saving transactions
484 surfaceModel.startStoringChanges();
485 // TODO: Listen to autosaveFailed event to notify user
486 };
487
488 /**
489 * Store a snapshot of the current document state.
490 *
491 * @param {string} [html] Document HTML, will generate from current state if not provided
492 */
493 ve.init.mw.Target.prototype.storeDocState = function ( html ) {
494 const mode = this.getSurface().getMode();
495 this.getSurface().getModel().storeDocState( { mode: mode }, html );
496 };
497
498 /**
499 * Clear any stored document state
500 */
501 ve.init.mw.Target.prototype.clearDocState = function () {
502 if ( this.getSurface() ) {
503 this.getSurface().getModel().removeDocStateAndChanges();
504 }
505 };
506
507 /**
508 * @inheritdoc
509 */
510 ve.init.mw.Target.prototype.teardown = function () {
511 // If target is closed cleanly (after save or deliberate close) then remove autosave state
512 this.clearDocState();
513
514 // Parent method
515 return ve.init.mw.Target.super.prototype.teardown.call( this );
516 };
517
518 /**
519 * Refresh our knowledge about the logged-in user.
520 *
521 * This should be called in response to a user assertion error, to look up
522 * the new user name, and update the current user variables in mw.config.
523 *
524 * @param {ve.dm.Document} [doc] Document to associate with the API request
525 * @return {jQuery.Promise} Promise resolved with new username, or null if anonymous
526 */
527 ve.init.mw.Target.prototype.refreshUser = function ( doc ) {
528 return this.getContentApi( doc ).get( {
529 action: 'query',
530 meta: 'userinfo'
531 } ).then( ( data ) => {
532 const userInfo = data.query && data.query.userinfo;
533
534 if ( userInfo.anon !== undefined ) {
535 // New session is an anonymous user
536 mw.config.set( {
537 // wgUserId is unset for anonymous users, not set to null
538 wgUserId: undefined,
539 // wgUserName is explicitly set to null for anonymous users,
540 // functions like mw.user.isAnon rely on this.
541 wgUserName: null
542 } );
543
544 // Call this only after clearing wgUserId, otherwise it does nothing
545 return mw.user.acquireTempUserName();
546 } else {
547 // New session is a logged in user (or a temporary user)
548 mw.config.set( {
549 wgUserId: userInfo.id,
550 wgUserName: userInfo.name
551 } );
552
553 return mw.user.getName();
554 }
555 } );
556 };
557
558 /**
559 * Get a wikitext fragment from a document
560 *
561 * @param {ve.dm.Document} doc
562 * @param {boolean} [useRevision=true] Whether to use the revision ID + ETag
563 * @return {jQuery.Promise} Abortable promise which resolves with a wikitext string
564 */
565 ve.init.mw.Target.prototype.getWikitextFragment = function ( doc, useRevision ) {
566 // Shortcut for empty document
567 if ( !doc.data.hasContent() ) {
568 return ve.createDeferred().resolve( '' );
569 }
570
571 const params = {
572 action: 'visualeditoredit',
573 paction: 'serialize',
574 html: mw.libs.ve.targetSaver.getHtml(
575 ve.dm.converter.getDomFromModel( doc )
576 ),
577 page: this.getPageName()
578 };
579
580 if ( useRevision === undefined || useRevision ) {
581 params.oldid = this.revid;
582 params.etag = this.etag;
583 }
584
585 const xhr = this.getContentApi( doc ).postWithToken( 'csrf',
586 params,
587 { contentType: 'multipart/form-data' }
588 );
589
590 return xhr.then( ( response ) => {
591 if ( response.visualeditoredit ) {
592 return response.visualeditoredit.content;
593 }
594 return ve.createDeferred().reject();
595 } ).promise( { abort: xhr.abort } );
596 };
597
598 /**
599 * Parse a fragment of wikitext into HTML
600 *
601 * @param {string} wikitext
602 * @param {boolean} pst Perform pre-save transform
603 * @param {ve.dm.Document} [doc] Parse for a specific document, defaults to current surface's
604 * @return {jQuery.Promise} Abortable promise
605 */
606 ve.init.mw.Target.prototype.parseWikitextFragment = function ( wikitext, pst, doc ) {
607 let abortable, aborted;
608 const abortedPromise = ve.createDeferred().reject( 'http',
609 { textStatus: 'abort', exception: 'abort' } ).promise();
610
611 function abort() {
612 aborted = true;
613 if ( abortable && abortable.abort ) {
614 abortable.abort();
615 }
616 }
617
618 // Acquire a temporary user username before previewing or diffing, so that signatures and
619 // user-related magic words display the temp user instead of IP user in the preview. (T331397)
620 let tempUserNamePromise;
621 if ( pst ) {
622 tempUserNamePromise = mw.user.acquireTempUserName();
623 } else {
624 tempUserNamePromise = ve.createDeferred().resolve( null );
625 }
626
627 return tempUserNamePromise
628 .then( () => {
629 if ( aborted ) {
630 return abortedPromise;
631 }
632 return ( abortable = this.getContentApi( doc ).post( {
633 action: 'visualeditor',
634 paction: 'parsefragment',
635 page: this.getPageName( doc ),
636 wikitext: wikitext,
637 pst: pst
638 } ) );
639 } )
640 .promise( { abort: abort } );
641 };
642
643 /**
644 * Get the page name associated with a specific document
645 *
646 * @param {ve.dm.Document} [doc] Document, defaults to current surface's
647 * @return {string} Page name
648 */
649 ve.init.mw.Target.prototype.getPageName = function () {
650 return this.pageName;
651 };
652
653 /**
654 * Get an API object associated with the wiki where the document
655 * content is hosted.
656 *
657 * This would be overridden if editing content on another wiki.
658 *
659 * @param {ve.dm.Document} [doc] API for a specific document, should default to document of current surface.
660 * @param {Object} [options] API options
661 * @param {Object} [options.parameters] Default query parameters for all API requests. Defaults
662 * include action=query, format=json, and formatversion=2 if not specified otherwise.
663 * @return {mw.Api}
664 */
665 ve.init.mw.Target.prototype.getContentApi = function ( doc, options ) {
666 options = options || {};
667 options.parameters = ve.extendObject( { formatversion: 2 }, options.parameters );
668 return new mw.Api( options );
669 };
670
671 /**
672 * Get an API object associated with the local wiki.
673 *
674 * For example you would always use getLocalApi for actions
675 * associated with the current user.
676 *
677 * @param {Object} [options] API options
678 * @return {mw.Api}
679 */
680 ve.init.mw.Target.prototype.getLocalApi = function ( options ) {
681 options = options || {};
682 options.parameters = ve.extendObject( { formatversion: 2 }, options.parameters );
683 return new mw.Api( options );
684 };