Debian Codegraph @

extensions/DiscussionTools/modules/CommentController.js

raw symbols SCIP
1 const
2 controller = require( './controller.js' ),
3 modifier = require( './modifier.js' ),
4 dtConf = require( './config.json' ),
5 CommentItem = require( './CommentItem.js' ),
6 scrollPadding = {
7 // eslint-disable-next-line no-jquery/no-class-state
8 top: 10 + ( $( document.documentElement ).hasClass( 'vector-feature-sticky-header-enabled' ) ? 50 : 0 ),
9 bottom: 10
10 },
11 defaultVisual = controller.defaultVisual,
12 enable2017Wikitext = controller.enable2017Wikitext;
13 /**
14 * Handles setup, save and teardown of commenting widgets
15 *
16 * @param {jQuery} $pageContainer Page container
17 * @param {ThreadItem} threadItem Thread item to attach new comment to
18 * @param {ThreadItemSet} threadItemSet
19 * @param {MemoryStorage} storage Storage object for autosave
20 */
21 function CommentController( $pageContainer, threadItem, threadItemSet, storage ) {
22 // Mixin constructors
23 OO.EventEmitter.call( this );
24
25 this.isTornDown = false;
26 this.$pageContainer = $pageContainer;
27 this.threadItem = threadItem;
28 this.threadItemSet = threadItemSet;
29 this.storage = storage;
30 this.newListItem = null;
31 this.replyWidgetPromise = null;
32 this.newComments = [];
33 this.parentRemoved = false;
34 this.oldId = mw.config.get( 'wgRevisionId' );
35 this.pollTimeout = null;
36 this.onVisibilityChangeHandler = this.onVisibilityChange.bind( this );
37 }
38
39 OO.initClass( CommentController );
40 OO.mixinClass( CommentController, OO.EventEmitter );
41
42 /* CommentController private utilities */
43
44 /**
45 * Get the latest revision ID of the page.
46 *
47 * @param {string} pageName
48 * @return {jQuery.Promise}
49 */
50 function getLatestRevId( pageName ) {
51 return controller.getApi().get( {
52 action: 'query',
53 prop: 'revisions',
54 rvprop: 'ids',
55 rvlimit: 1,
56 titles: pageName
57 } ).then( ( resp ) => resp.query.pages[ 0 ].revisions[ 0 ].revid );
58 }
59
60 /**
61 * Like #checkThreadItemOnPage, but assumes the comment was found on the current page,
62 * and then follows transclusions to determine the source page where it is written.
63 *
64 * @return {jQuery.Promise} Promise which resolves with a CommentDetails object, or rejects with an error
65 */
66 CommentController.prototype.getTranscludedFromSource = function () {
67 const pageName = mw.config.get( 'wgRelevantPageName' ),
68 oldId = mw.config.get( 'wgCurRevisionId' ),
69 threadItem = this.getThreadItem();
70
71 function followTransclusion( recursionLimit, code, data ) {
72 let errorData;
73 if ( recursionLimit > 0 && code === 'comment-is-transcluded' ) {
74 errorData = data.errors[ 0 ].data;
75 if ( errorData.follow && typeof errorData.transcludedFrom === 'string' ) {
76 return getLatestRevId( errorData.transcludedFrom ).then(
77 // Fetch the transcluded page, until we cross the recursion limit
78 ( latestRevId ) => controller.checkThreadItemOnPage( errorData.transcludedFrom, latestRevId, threadItem )
79 .catch( followTransclusion.bind( null, recursionLimit - 1 ) )
80 );
81 }
82 }
83 return $.Deferred().reject( code, data );
84 }
85
86 // Arbitrary limit of 10 steps, which should be more than anyone could ever need
87 // (there are reasonable use cases for at least 2)
88 const promise = controller.checkThreadItemOnPage( pageName, oldId, threadItem )
89 .catch( followTransclusion.bind( null, 10 ) );
90
91 return promise;
92 };
93
94 /* Static properties */
95
96 CommentController.static.initType = 'page';
97
98 /* Events */
99
100 /**
101 * The current widget has been torn down
102 *
103 * @event teardown
104 * @param string mode Teardown mode. See dt.ui.ReplyWidget#teardown.
105 */
106
107 /* Methods */
108
109 /**
110 * Create and setup the reply widget
111 *
112 * @param {Object} [options]
113 * @param {string} [options.mode] Optionally force a mode, 'visual' or 'source'
114 * @param {boolean} [options.hideErrors] Suppress errors, e.g. when restoring auto-save
115 * @param {boolean} [options.suppressNotifications] Don't notify the user if recovering auto-save
116 */
117 CommentController.prototype.setup = function ( options ) {
118 const threadItem = this.getThreadItem();
119
120 options = options || {};
121
122 if ( options.mode === undefined ) {
123 options.mode = mw.user.options.get( 'discussiontools-editmode' ) ||
124 ( defaultVisual ? 'visual' : 'source' );
125 }
126
127 mw.track( 'editAttemptStep', {
128 action: 'init',
129 type: this.constructor.static.initType || 'page',
130 mechanism: 'click',
131 integration: 'discussiontools',
132 // eslint-disable-next-line camelcase
133 editor_interface: options.mode === 'visual' ? 'visualeditor' :
134 ( enable2017Wikitext ? 'wikitext-2017' : 'wikitext' )
135 } );
136
137 if ( !this.replyWidgetPromise ) {
138 this.replyWidgetPromise = this.getTranscludedFromSource().then(
139 ( commentDetails ) => this.createReplyWidget( commentDetails, { mode: options.mode } ),
140 ( code, data ) => {
141 this.onReplyWidgetTeardown();
142
143 if ( !options.hideErrors ) {
144 OO.ui.alert(
145 code instanceof Error ? code.toString() : controller.getApi().getErrorMessage( data ),
146 { size: 'medium' }
147 );
148 mw.track( 'dt.commentSetupError', code );
149 }
150
151 mw.track( 'editAttemptStep', {
152 action: 'abort',
153 type: 'preinit'
154 } );
155
156 this.replyWidgetPromise = null;
157
158 return $.Deferred().reject();
159 }
160 );
161
162 // On first load, add a placeholder list item
163 this.newListItem = modifier.addListItem( threadItem, dtConf.replyIndentation );
164 if ( this.newListItem.tagName.toLowerCase() === 'li' ) {
165 // When using bullet syntax, hide the marker. (T259864#7634107)
166 $( this.newListItem ).addClass( 'ext-discussiontools-init-noMarker' );
167 }
168 $( this.newListItem ).append(
169 // Microsoft Edge's built-in translation feature replaces the entire element when it finishes
170 // translating it, which often happens after our interface has loaded, clobbering it, unless
171 // we wrap this loading message in another element.
172 $( '<span>' ).text( mw.msg( 'discussiontools-replywidget-loading' ) )
173 );
174 const scrollPaddingCollapsed = OO.copy( scrollPadding );
175 // We don't know exactly how tall the widge will be, but leave room for one line
176 // of preview in source mode (~270px). Visual mode is ~250px.
177 scrollPaddingCollapsed.bottom += 270;
178 OO.ui.Element.static.scrollIntoView( this.newListItem, {
179 padding: scrollPaddingCollapsed
180 } );
181
182 // Disable section collapsing on mobile. If the section were collapsed it would be hard to
183 // find your comment again. The "Return to reply" tool is broken by section collapsing as
184 // the reply widget is hidden and therefore not measureable. It's also possible the page is
185 // not long enough to trigger the "Return to reply" tool.
186 $( this.newListItem ).parents( '.collapsible-block' ).prev().addClass( 'collapsible-heading-disabled' );
187 }
188
189 if (
190 this.threadItem instanceof CommentItem &&
191 this.threadItem.getSubscribableHeading()
192 ) {
193 // Use the revision ID of the content on the page, not wgCurRevisionId
194 // This means you will more likely get a refresh warning when deliberately
195 // viewing old revisions, which is helpful.
196 this.startPoll();
197 $( document ).on( 'visibilitychange', this.onVisibilityChangeHandler );
198 }
199
200 this.replyWidgetPromise.then( ( replyWidget ) => {
201 if ( !this.newListItem ) {
202 // On subsequent loads, there's no list item yet, so create one now
203 this.newListItem = modifier.addListItem( threadItem, dtConf.replyIndentation );
204 if ( this.newListItem.tagName.toLowerCase() === 'li' ) {
205 // When using bullet syntax, hide the marker. (T259864#7634107)
206 $( this.newListItem ).addClass( 'ext-discussiontools-init-noMarker' );
207 }
208 }
209 $( this.newListItem ).empty().append( replyWidget.$element );
210
211 this.setupReplyWidget( replyWidget, {}, options.suppressNotifications );
212
213 this.showAndFocus();
214
215 mw.track( 'editAttemptStep', { action: 'ready' } );
216 mw.track( 'editAttemptStep', { action: 'loaded' } );
217 } );
218 };
219
220 /**
221 * Handle document visibilitychange events
222 *
223 * This allows us to pause polling when the user switches to another tab
224 */
225 CommentController.prototype.onVisibilityChange = function () {
226 if ( document.hidden ) {
227 this.stopPoll();
228 } else if ( !this.pollTimeout ) {
229 this.pollTimeout = setTimeout( this.startPoll.bind( this ), 5000 );
230 }
231 };
232
233 CommentController.prototype.startPoll = function ( nextDelay ) {
234 nextDelay = nextDelay || 5000;
235
236 if ( !(
237 this.threadItem instanceof CommentItem &&
238 this.threadItem.getSubscribableHeading()
239 ) ) {
240 return;
241 }
242
243 const threadItemId = this.threadItem.id;
244 const subscribableHeadingId = this.threadItem.getSubscribableHeading().id;
245 let aborted = false;
246
247 this.pollApiRequest = controller.getApi().get( {
248 action: 'discussiontoolscompare',
249 fromrev: this.oldId,
250 totitle: mw.config.get( 'wgRelevantPageName' )
251 } );
252 this.pollApiRequest.then( ( response ) => {
253 function relevantCommentFilter( cmt ) {
254 return cmt.subscribableHeadingId === subscribableHeadingId &&
255 // Ignore posts by yourself, if logged in
256 cmt.author !== mw.user.getName();
257 }
258
259 const result = OO.getProp( response, 'discussiontoolscompare' ) || {};
260 const addedComments = result.addedcomments.filter( relevantCommentFilter );
261 const removedComments = result.removedcomments.filter( relevantCommentFilter );
262
263 if ( addedComments.length || removedComments.length ) {
264 this.updateNewCommentsWarning( addedComments, removedComments );
265 }
266
267 // Parent comment was deleted
268 const isParentRemoved = result.removedcomments.some( ( cmt ) => cmt.id === threadItemId );
269 // Parent comment was deleted then added back (e.g. reverted vandalism)
270 const isParentAdded = result.addedcomments.some( ( cmt ) => cmt.id === threadItemId );
271
272 if ( isParentAdded ) {
273 this.setParentRemoved( false );
274 } else if ( isParentRemoved ) {
275 this.setParentRemoved( true );
276 }
277
278 this.oldId = result.torevid;
279 nextDelay = 5000;
280 }, ( code, data ) => {
281 if ( code === 'http' && data.textStatus === 'abort' ) {
282 aborted = true;
283 } else {
284 // Wait longer next time in case of error
285 nextDelay = nextDelay * 1.5;
286 }
287 } ).always( () => {
288 if ( this.isTornDown || aborted ) {
289 return;
290 }
291 // Stop polling after too many errors
292 if ( nextDelay < 1000 * 60 * 60 ) {
293 this.pollTimeout = setTimeout( this.startPoll.bind( this, nextDelay ), nextDelay );
294 }
295 } );
296 };
297
298 CommentController.prototype.stopPoll = function () {
299 if ( this.pollTimeout ) {
300 clearTimeout( this.pollTimeout );
301 this.pollTimeout = null;
302 }
303 if ( this.pollApiRequest ) {
304 this.pollApiRequest.abort();
305 this.pollApiRequest = null;
306 }
307 };
308
309 /**
310 * Get thread item this controller is attached to
311 *
312 * @return {ThreadItem} Thread item
313 */
314 CommentController.prototype.getThreadItem = function () {
315 return this.threadItem;
316 };
317
318 /**
319 * Get the reply widget class to use in this controller
320 *
321 * @param {boolean} visual Prefer the VE-based class
322 * @return {jQuery.Promise} Promise which resolves with a Function: the reply widget class
323 */
324 CommentController.prototype.getReplyWidgetClass = function ( visual ) {
325 // If 2017WTE mode is enabled, always use ReplyWidgetVisual.
326 visual = visual || enable2017Wikitext;
327
328 return mw.loader.using( controller.getReplyWidgetModules() )
329 .then( () => require( 'ext.discussionTools.ReplyWidget' )[ visual ? 'ReplyWidgetVisual' : 'ReplyWidgetPlain' ] );
330 };
331
332 /**
333 * Create a reply widget
334 *
335 * @param {CommentDetails} commentDetails
336 * @param {Object} config
337 * @return {jQuery.Promise} Promise resolved with a ReplyWidget
338 */
339 CommentController.prototype.createReplyWidget = function ( commentDetails, config ) {
340 return this.getReplyWidgetClass( config.mode === 'visual' )
341 .then( ( ReplyWidget ) => new ReplyWidget( this, commentDetails, config ) );
342 };
343
344 CommentController.prototype.setupReplyWidget = function ( replyWidget, data, suppressNotifications ) {
345 replyWidget.connect( this, {
346 teardown: 'onReplyWidgetTeardown',
347 reloadPage: this.emit.bind( this, 'reloadPage' )
348 } );
349
350 replyWidget.setup( data, suppressNotifications );
351 replyWidget.updateNewCommentsWarning( this.newComments );
352 replyWidget.updateParentRemovedError( this.parentRemoved );
353 replyWidget.connect( this, { submit: 'onReplySubmit' } );
354
355 this.replyWidget = replyWidget;
356 };
357
358 CommentController.prototype.storeEditSummary = function () {
359 if ( this.replyWidget ) {
360 this.replyWidget.storage.set( 'summary', this.replyWidget.getEditSummary() );
361 }
362 };
363
364 /**
365 * Focus the first input field inside the controller.
366 */
367 CommentController.prototype.focus = function () {
368 this.replyWidget.focus();
369 };
370
371 /**
372 * Scroll the widget into view and focus it
373 */
374 CommentController.prototype.showAndFocus = function () {
375 if ( this.replyWidgetPromise ) {
376 this.replyWidgetPromise.then( ( replyWidget ) => {
377 replyWidget.scrollElementIntoView( { padding: scrollPadding } )
378 .then( () => {
379 this.focus();
380 } );
381 } );
382 }
383 };
384
385 /**
386 * Try to tear down the reply widget, if it is setup
387 *
388 * @return {jQuery.Promise} Resolves when the widget is torn down, rejects if it fails.
389 */
390 CommentController.prototype.tryTeardown = function () {
391 if ( this.replyWidgetPromise ) {
392 return this.replyWidgetPromise.then( ( replyWidget ) => replyWidget.tryTeardown() );
393 }
394 return $.Deferred().resolve().promise();
395 };
396
397 /**
398 * Handle teardown events from the reply widget
399 *
400 * @param {string} mode Teardown mode. See dt.ui.ReplyWidget#teardown
401 */
402 CommentController.prototype.onReplyWidgetTeardown = function ( mode ) {
403 $( this.newListItem ).parents( '.collapsible-block' ).prev().removeClass( 'collapsible-heading-disabled' );
404
405 if ( mode === 'refresh' ) {
406 $( this.newListItem ).empty().append(
407 $( '<span>' ).text( mw.msg( 'discussiontools-replywidget-loading' ) )
408 );
409 } else {
410 modifier.removeAddedListItem( this.newListItem );
411 this.newListItem = null;
412 }
413
414 this.stopPoll();
415 $( document ).off( 'visibilitychange', this.onVisibilityChangeHandler );
416
417 this.isTornDown = true;
418 this.emit( 'teardown', mode );
419 };
420
421 /**
422 * Get the parameters of the API query that can be used to post this comment.
423 *
424 * @param {string} pageName Title of the page to post on
425 * @param {Object} checkboxes Value of the promise returned by controller#getCheckboxesPromise
426 * @param {Object} extraParams Extra params to pass to the API
427 * @return {Object.<string,string>} API query data
428 */
429 CommentController.prototype.getApiQuery = function ( pageName, checkboxes, extraParams ) {
430 const threadItem = this.getThreadItem();
431 const replyWidget = this.replyWidget;
432 const sameNameComments = this.threadItemSet.findCommentsByName( threadItem.name );
433
434 const mode = replyWidget.getMode();
435 const tags = [
436 'discussiontools',
437 'discussiontools-reply',
438 'discussiontools-' + mode
439 ];
440
441 if ( mode === 'source' && enable2017Wikitext ) {
442 tags.push( 'discussiontools-source-enhanced' );
443 }
444
445 const data = Object.assign( {
446 action: 'discussiontoolsedit',
447 paction: 'addcomment',
448 page: pageName,
449 commentname: threadItem.name,
450 // Only specify this if necessary to disambiguate, to avoid errors if the parent changes
451 commentid: sameNameComments.length > 1 ? threadItem.id : undefined,
452 summary: replyWidget.getEditSummary(),
453 formtoken: replyWidget.getFormToken(),
454 assert: mw.user.isAnon() ? 'anon' : 'user',
455 assertuser: mw.user.getName() || undefined,
456 uselang: mw.config.get( 'wgUserLanguage' ),
457 // Pass through dtenable query string param from original request
458 dtenable: new URLSearchParams( location.search ).get( 'dtenable' ) ? '1' : undefined,
459 dttags: tags.join( ',' )
460 }, extraParams );
461
462 if ( replyWidget.getMode() === 'source' ) {
463 data.wikitext = replyWidget.getValue();
464 } else {
465 data.html = replyWidget.getValue();
466 }
467
468 const captchaInput = replyWidget.captchaInput;
469 if ( captchaInput ) {
470 data.captchaid = captchaInput.getCaptchaId();
471 data.captchaword = captchaInput.getCaptchaWord();
472 }
473
474 if ( checkboxes.checkboxesByName.wpWatchthis ) {
475 data.watchlist = checkboxes.checkboxesByName.wpWatchthis.isSelected() ?
476 'watch' :
477 'unwatch';
478 }
479
480 return data;
481 };
482
483 /**
484 * Handle the reply widget being submitted
485 *
486 * @param {Object} extraParams Extra params to pass to the API
487 */
488 CommentController.prototype.onReplySubmit = function ( extraParams ) {
489 if ( !this.replyWidget ) {
490 return;
491 }
492
493 this.replyWidget.clearSaveErrorMessage();
494
495 this.saveInitiated = mw.now();
496 this.replyWidget.setPending( true );
497
498 mw.track( 'editAttemptStep', { action: 'saveIntent' } );
499 mw.track( 'editAttemptStep', { action: 'saveAttempt' } );
500
501 // TODO: When editing a transcluded page, VE API returning the page HTML is a waste, since we won't use it
502 this.save( this.replyWidget.pageName, extraParams )
503 .then( null, this.saveFail.bind( this ) )
504 .always( () => {
505 this.replyWidget.setPending( false );
506 } );
507 };
508
509 /**
510 * Handle save failures from the API
511 *
512 * @param {string} code Error code
513 * @param {Object} data Error data
514 */
515 CommentController.prototype.saveFail = function ( code, data ) {
516 this.startPoll();
517
518 const captchaData = OO.getProp( data, 'discussiontoolsedit', 'edit', 'captcha' );
519
520 if ( captchaData ) {
521 code = 'captcha';
522 this.replyWidget.clearCaptcha();
523 this.replyWidget.setCaptcha( captchaData );
524 } else {
525 this.replyWidget.setSaveErrorMessage( code, data );
526 }
527
528 if ( code instanceof Error ) {
529 code = 'exception';
530 }
531 // Log more precise error codes, mw.Api just gives us 'http' in all of these cases
532 if ( data ) {
533 if ( data.textStatus === 'timeout' || data.textStatus === 'abort' || data.textStatus === 'parsererror' ) {
534 code = data.textStatus;
535 } else if ( data.xhr ) {
536 code = 'http-' + ( data.xhr.status || 0 );
537 }
538 }
539
540 // Compare to ve.init.mw.ArticleTargetEvents.js in VisualEditor.
541 const typeMap = {
542 badtoken: 'userBadToken',
543 assertanonfailed: 'userNewUser',
544 assertuserfailed: 'userNewUser',
545 assertnameduserfailed: 'userNewUser',
546 'abusefilter-disallowed': 'extensionAbuseFilter',
547 'abusefilter-warning': 'extensionAbuseFilter',
548 captcha: 'extensionCaptcha',
549 spamblacklist: 'extensionSpamBlacklist',
550 'titleblacklist-forbidden': 'extensionTitleBlacklist',
551 pagedeleted: 'editPageDeleted',
552 editconflict: 'editConflict'
553 };
554 mw.track( 'editAttemptStep', {
555 action: 'saveFailure',
556 timing: mw.now() - this.saveInitiated,
557 message: code,
558 type: typeMap[ code ] || 'responseUnknown'
559 } );
560 };
561
562 /**
563 * Save the comment in the comment controller
564 *
565 * @param {string} pageName Page title
566 * @param {Object} extraParams Extra params to pass to the API
567 * @return {jQuery.Promise} Promise which resolves when the save is complete
568 */
569 CommentController.prototype.save = function ( pageName, extraParams ) {
570 this.stopPoll();
571
572 const replyWidget = this.replyWidget,
573 threadItem = this.getThreadItem();
574
575 return this.replyWidget.checkboxesPromise.then( ( checkboxes ) => {
576 const data = this.getApiQuery( pageName, checkboxes, extraParams );
577
578 if (
579 // We're saving the first comment on a page that previously didn't exist.
580 // Don't fetch the new revision's HTML content, because we will reload the whole page.
581 !mw.config.get( 'wgRelevantArticleId' ) ||
582 // We're saving a comment on a different page than the one being viewed.
583 // Don't fetch the new revision's HTML content, because we can't use it anyway.
584 pageName !== mw.config.get( 'wgRelevantPageName' )
585 ) {
586 data.nocontent = true;
587 }
588
589 if ( replyWidget.commentDetails.wouldAutoCreate ) {
590 // This means that we might need to redirect to an opaque URL,
591 // so we must set up query parameters we want ahead of time.
592 data.returnto = pageName;
593 const params = new URLSearchParams();
594 params.set( 'dtrepliedto', this.getThreadItem().id );
595 params.set( 'dttempusercreated', '1' );
596 data.returntoquery = params.toString();
597 }
598
599 // No timeout. Huge talk pages can take a long time to save, and falsely reporting an error
600 // could result in duplicate messages if the user retries. (T249071)
601 const defaults = OO.copy( controller.getApi().defaults );
602 defaults.ajax.timeout = 0;
603 const noTimeoutApi = new mw.Api( defaults );
604
605 return mw.libs.ve.targetSaver.postContent(
606 data, { api: noTimeoutApi }
607 ).catch( ( code, responseData ) => {
608 if ( code === 'assertanonfailed' ) {
609 // Reattempt the save when something already created a temporary account (T368263)
610 return controller.getApi().get( {
611 meta: 'userinfo'
612 } ).then( ( resp ) => {
613 if ( !resp.query.userinfo.temp ) {
614 // Return the original error response
615 return $.Deferred().reject( code, responseData ).promise();
616 }
617 // Set new parameters and retry
618 data.assert = 'user';
619 data.assertuser = resp.query.userinfo.name;
620 return mw.libs.ve.targetSaver.postContent(
621 data, { api: noTimeoutApi }
622 );
623 } );
624 }
625 return $.Deferred().reject( code, responseData ).promise();
626 } ).catch( ( code, responseData ) => {
627 // Better user-facing error messages
628 if ( code === 'editconflict' ) {
629 return $.Deferred().reject( code, { errors: [ {
630 code: code,
631 html: mw.message( 'discussiontools-error-comment-conflict' ).parse()
632 } ] } ).promise();
633 }
634 if (
635 code === 'discussiontools-commentid-notfound' ||
636 code === 'discussiontools-commentname-ambiguous' ||
637 code === 'discussiontools-commentname-notfound'
638 ) {
639 return $.Deferred().reject( code, { errors: [ {
640 code: code,
641 html: mw.message( 'discussiontools-error-comment-disappeared' ).parse()
642 } ] } ).promise();
643 }
644 return $.Deferred().reject( code, responseData ).promise();
645 } ).then( ( responseData ) => {
646 controller.update( responseData, threadItem, pageName, replyWidget );
647 } );
648 } );
649 };
650
651 /**
652 * Add a list of comment objects that are new on the page since it was last refreshed
653 *
654 * @param {Object[]} addedComments Array of JSON-serialized CommentItem's
655 * @param {Object[]} removedComments Array of JSON-serialized CommentItem's
656 */
657 CommentController.prototype.updateNewCommentsWarning = function ( addedComments, removedComments ) {
658 // Add new comments
659 this.newComments.push.apply( this.newComments, addedComments );
660
661 // Delete any comments which have since been deleted (e.g. posted then reverted)
662 const removedCommentIds = removedComments.filter( ( cmt ) => cmt.id );
663 this.newComments = this.newComments.filter(
664 // If comment ID is not in removedCommentIds, keep it
665 ( cmt ) => removedCommentIds.indexOf( cmt.id ) === -1
666 );
667
668 this.replyWidgetPromise.then( ( replyWidget ) => {
669 replyWidget.updateNewCommentsWarning( this.newComments );
670 } );
671 };
672
673 /**
674 * Record whether the parent thread item has been removed
675 *
676 * @param {boolean} parentRemoved
677 */
678 CommentController.prototype.setParentRemoved = function ( parentRemoved ) {
679 this.parentRemoved = parentRemoved;
680
681 this.replyWidgetPromise.then( ( replyWidget ) => {
682 replyWidget.updateParentRemovedError( this.parentRemoved );
683 } );
684 };
685
686 /**
687 * Switch reply widget to wikitext input
688 *
689 * @return {jQuery.Promise} Promise which resolves when switch is complete
690 */
691 CommentController.prototype.switchToWikitext = function () {
692 const oldWidget = this.replyWidget,
693 target = oldWidget.replyBodyWidget.target,
694 oldShowAdvanced = oldWidget.showAdvanced,
695 oldEditSummary = oldWidget.getEditSummary(),
696 previewDeferred = $.Deferred();
697
698 // TODO: We may need to pass oldid/etag when editing is supported
699 const wikitextPromise = target.getWikitextFragment( target.getSurface().getModel().getDocument() );
700 this.replyWidgetPromise = this.createReplyWidget(
701 oldWidget.commentDetails,
702 { mode: 'source' }
703 );
704
705 return $.when( wikitextPromise, this.replyWidgetPromise ).then( ( wikitext, replyWidget ) => {
706 // To prevent the "Reply" / "Cancel" buttons from shifting when the preview loads,
707 // wait for the preview (but no longer than 500 ms) before swithing the editors.
708 replyWidget.preparePreview( wikitext ).then( previewDeferred.resolve );
709 setTimeout( previewDeferred.resolve, 500 );
710
711 return previewDeferred.then( () => {
712 // Teardown the old widget
713 oldWidget.disconnect( this );
714 oldWidget.teardown();
715
716 // Swap out the DOM nodes
717 oldWidget.$element.replaceWith( replyWidget.$element );
718
719 this.setupReplyWidget( replyWidget, {
720 value: wikitext,
721 showAdvanced: oldShowAdvanced,
722 editSummary: oldEditSummary
723 } );
724
725 // Focus the editor
726 replyWidget.focus();
727 } );
728 } );
729 };
730
731 /**
732 * Remove empty lines and add indent characters to convert the paragraphs in given wikitext to
733 * definition list items, as customary in discussions.
734 *
735 * @param {string} wikitext
736 * @param {string} indent Indent character, ':' or '*'
737 * @return {string}
738 */
739 CommentController.prototype.doIndentReplacements = function ( wikitext, indent ) {
740 wikitext = modifier.sanitizeWikitextLinebreaks( wikitext );
741
742 wikitext = wikitext.split( '\n' ).map( ( line ) => indent + line ).join( '\n' );
743
744 return wikitext;
745 };
746
747 /**
748 * Turn definition list items, customary in discussions, back into normal paragraphs, suitable for
749 * the editing interface.
750 *
751 * @param {Node} rootNode Node potentially containing definition lists (modified in-place)
752 */
753 CommentController.prototype.undoIndentReplacements = function ( rootNode ) {
754 const children = Array.prototype.slice.call( rootNode.childNodes );
755 // There may be multiple lists when some lines are template generated
756 children.forEach( ( child ) => {
757 if ( child.nodeType === Node.ELEMENT_NODE ) {
758 // Unwrap list
759 modifier.unwrapList( child );
760 }
761 } );
762 };
763
764 /**
765 * Get the list of selectors that match nodes that can't be inserted in the comment. (We disallow
766 * things that generate wikitext syntax that may conflict with list item syntax.)
767 *
768 * @return {Object.<string,string>} Map of type used for error messages (string) to CSS selector (string)
769 */
770 CommentController.prototype.getUnsupportedNodeSelectors = function () {
771 return {
772 // Tables are almost always multi-line
773 table: 'table',
774 // Headings are converted to plain text before we can detect them:
775 // `:==h2==` -> `<p>==h2==</p>`
776 // heading: 'h1, h2, h3, h4, h5, h6',
777 // Templates can be multiline
778 template: '[typeof*="mw:Transclusion"]',
779 // Extensions (includes references) can be multiline, could be supported later (T251633)
780 extension: '[typeof*="mw:Extension"]'
781 // Images are probably fine unless a multi-line caption was used (rare)
782 // image: 'figure, figure-inline'
783 };
784 };
785
786 /**
787 * Switch reply widget to visual input
788 *
789 * @return {jQuery.Promise} Promise which resolves when switch is complete
790 */
791 CommentController.prototype.switchToVisual = function () {
792 const oldWidget = this.replyWidget,
793 oldShowAdvanced = oldWidget.showAdvanced,
794 oldEditSummary = oldWidget.getEditSummary();
795 let wikitext = oldWidget.getValue();
796
797 // Replace wikitext signatures with a special marker recognized by DtDmMWSignatureNode
798 // to render them as signature nodes in visual mode.
799 wikitext = wikitext.replace(
800 // Replace ~~~~ (four tildes), but not ~~~~~ (five tildes)
801 /([^~]|^)~~~~([^~]|$)/g,
802 '$1<span data-dtsignatureforswitching="1"></span>$2'
803 );
804
805 let parsePromise;
806 if ( wikitext ) {
807 wikitext = this.doIndentReplacements( wikitext, dtConf.replyIndentation === 'invisible' ? ':' : '*' );
808
809 // Based on ve.init.mw.Target#parseWikitextFragment
810 parsePromise = controller.getApi().post( {
811 action: 'visualeditor',
812 paction: 'parsefragment',
813 page: oldWidget.pageName,
814 wikitext: wikitext,
815 pst: true
816 } ).then( ( response ) => response && response.visualeditor.content );
817 } else {
818 parsePromise = $.Deferred().resolve( '' ).promise();
819 }
820 this.replyWidgetPromise = this.createReplyWidget(
821 oldWidget.commentDetails,
822 { mode: 'visual' }
823 );
824
825 return $.when( parsePromise, this.replyWidgetPromise ).then( ( html, replyWidget ) => {
826 const unsupportedSelectors = this.getUnsupportedNodeSelectors();
827
828 let doc;
829 if ( html ) {
830 doc = replyWidget.replyBodyWidget.target.parseDocument( html );
831 // Remove RESTBase IDs (T253584)
832 mw.libs.ve.stripRestbaseIds( doc );
833 // Check for tables, headings, images, templates
834 for ( const type in unsupportedSelectors ) {
835 if ( doc.querySelector( unsupportedSelectors[ type ] ) ) {
836 const $msg = $( '<div>' ).html(
837 mw.message(
838 'discussiontools-error-noswitchtove',
839 // The following messages are used here:
840 // * discussiontools-error-noswitchtove-extension
841 // * discussiontools-error-noswitchtove-table
842 // * discussiontools-error-noswitchtove-template
843 mw.msg( 'discussiontools-error-noswitchtove-' + type )
844 ).parse()
845 );
846 $msg.find( 'a' ).attr( {
847 target: '_blank',
848 rel: 'noopener'
849 } );
850 OO.ui.alert(
851 $msg.contents(),
852 {
853 title: mw.msg( 'discussiontools-error-noswitchtove-title' ),
854 size: 'medium'
855 }
856 );
857 mw.track( 'visualEditorFeatureUse', {
858 feature: 'editor-switch',
859 action: 'dialog-prevent-show'
860 } );
861
862 return $.Deferred().reject().promise();
863 }
864 }
865 this.undoIndentReplacements( doc.body );
866 }
867
868 // Teardown the old widget
869 oldWidget.disconnect( this );
870 oldWidget.teardown();
871
872 // Swap out the DOM nodes
873 oldWidget.$element.replaceWith( replyWidget.$element );
874
875 this.setupReplyWidget( replyWidget, {
876 value: doc,
877 showAdvanced: oldShowAdvanced,
878 editSummary: oldEditSummary
879 } );
880
881 // Focus the editor
882 replyWidget.focus();
883 } );
884 };
885
886 module.exports = CommentController;