Debian Codegraph @

extensions/DiscussionTools/modules/dt.ui.ReplyWidget.js

raw symbols SCIP
1 const controller = require( 'ext.discussionTools.init' ).controller,
2 utils = require( 'ext.discussionTools.init' ).utils,
3 ModeTabSelectWidget = require( './ModeTabSelectWidget.js' ),
4 ModeTabOptionWidget = require( './ModeTabOptionWidget.js' ),
5 contLangMessages = require( './contLangMessages.json' ),
6 licenseMessages = require( './licenseMessages.json' ),
7 featuresEnabled = mw.config.get( 'wgDiscussionToolsFeaturesEnabled' ) || {},
8 enable2017Wikitext = featuresEnabled.sourcemodetoolbar,
9 dtConf = require( 'ext.discussionTools.init' ).config;
10
11 require( './AbandonCommentDialog.js' );
12 require( './AbandonTopicDialog.js' );
13
14 /**
15 * DiscussionTools ReplyWidget class
16 *
17 * @class mw.dt.ReplyWidget
18 * @extends OO.ui.Widget
19 * @constructor
20 * @param {CommentController} commentController Comment controller
21 * @param {CommentDetails} commentDetails
22 * @param {Object} [config] Configuration options
23 * @param {Object} [config.input] Configuration options for the comment input widget
24 */
25 function ReplyWidget( commentController, commentDetails, config ) {
26 config = config || {};
27
28 // Parent constructor
29 ReplyWidget.super.call( this, config );
30
31 this.pending = false;
32 this.isTornDown = false;
33 this.commentController = commentController;
34 const threadItem = commentController.getThreadItem();
35 this.commentDetails = commentDetails;
36 this.isNewTopic = !!threadItem.isNewTopic;
37 this.pageName = commentDetails.pageName;
38 this.oldId = commentDetails.oldId;
39 // pageExists can only be false for the new comment tool, so we
40 // don't need to worry about transcluded replies.
41 this.pageExists = mw.config.get( 'wgRelevantArticleId', 0 ) !== 0;
42 const contextNode = utils.closestElement( threadItem.range.endContainer, [ 'dl', 'ul', 'ol' ] );
43 this.context = contextNode ? contextNode.tagName.toLowerCase() : 'dl';
44 this.storage = commentController.storage;
45 // eslint-disable-next-line no-jquery/no-global-selector
46 this.contentDir = $( '#mw-content-text' ).css( 'direction' );
47 this.hideNewCommentsWarning = false;
48 // Floating position for scroll back buttons: 'top', 'bottom', or null
49 this.floating = null;
50
51 this.$window = $( this.getElementWindow() );
52 this.onWindowScrollThrottled = OO.ui.throttle( this.onWindowScroll.bind( this ), 100 );
53
54 const inputConfig = Object.assign(
55 {
56 placeholder: this.isNewTopic ?
57 mw.msg( 'discussiontools-replywidget-placeholder-newtopic' ) :
58 mw.msg( 'discussiontools-replywidget-placeholder-reply', threadItem.author ),
59 authors: this.isNewTopic ?
60 // No suggestions in new topic tool yet (T277357)
61 [] :
62 // threadItem is a CommentItem when replying
63 threadItem.getHeading().getAuthorsBelow()
64 },
65 config.input
66 );
67 this.replyBodyWidget = this.createReplyBodyWidget( inputConfig );
68 this.replyButtonLabel = this.isNewTopic ?
69 mw.msg( 'discussiontools-replywidget-newtopic' ) :
70 mw.msg( 'discussiontools-replywidget-reply' );
71 this.replyButton = new OO.ui.ButtonWidget( {
72 flags: [ 'primary', 'progressive' ],
73 label: this.replyButtonLabel,
74 title: this.replyButtonLabel + ' [' +
75 new ve.ui.Trigger( ve.ui.commandHelpRegistry.lookup( 'dialogConfirm' ).shortcuts[ 0 ] ).getMessage() +
76 ']',
77 accessKey: mw.msg( 'discussiontools-replywidget-publish-accesskey' )
78 } );
79 this.cancelButton = new OO.ui.ButtonWidget( {
80 flags: [ 'destructive' ],
81 label: mw.msg( 'discussiontools-replywidget-cancel' ),
82 framed: false,
83 title: mw.msg( 'discussiontools-replywidget-cancel' ) + ' [' +
84 new ve.ui.Trigger( ve.ui.commandHelpRegistry.lookup( 'dialogCancel' ).shortcuts[ 0 ] ).getMessage() +
85 ']'
86 } );
87
88 this.$headerWrapper = $( '<div>' ).addClass( 'ext-discussiontools-ui-replyWidget-headerWrapper' );
89
90 if ( !OO.ui.isMobile() ) {
91 this.modeTabSelect = new ModeTabSelectWidget( {
92 classes: [ 'ext-discussiontools-ui-replyWidget-modeTabs' ],
93 items: [
94 new ModeTabOptionWidget( {
95 label: mw.msg( 'discussiontools-replywidget-mode-visual' ),
96 data: 'visual'
97 } ),
98 new ModeTabOptionWidget( {
99 label: mw.msg( 'discussiontools-replywidget-mode-source' ),
100 data: 'source'
101 } )
102 ],
103 framed: false
104 } );
105 this.modeTabSelect.$element.attr( 'aria-label', mw.msg( 'visualeditor-mweditmode-tooltip' ) );
106 // Make the option for the current mode disabled, to make it un-interactable
107 // (we override the styles to make it look as if it was selected)
108 this.modeTabSelect.findItemFromData( this.getMode() ).setDisabled( true );
109 this.modeTabSelect.connect( this, {
110 choose: 'onModeTabSelectChoose'
111 } );
112 this.$headerWrapper.append(
113 // Visual mode toolbar attached here by CommentTarget#attachToolbar
114 this.modeTabSelect.$element
115 );
116 }
117
118 this.$bodyWrapper = $( '<div>' ).addClass( 'ext-discussiontools-ui-replyWidget-bodyWrapper' ).append(
119 this.replyBodyWidget.$element
120 );
121
122 this.$preview = $( '<div>' )
123 .addClass( 'ext-discussiontools-ui-replyWidget-preview' )
124 .attr( 'data-label', mw.msg( 'discussiontools-replywidget-preview' ) )
125 // Set preview direction to content direction
126 .attr( 'dir', this.contentDir );
127 this.$actionsWrapper = $( '<div>' ).addClass( 'ext-discussiontools-ui-replyWidget-actionsWrapper' );
128 this.$actions = $( '<div>' ).addClass( 'ext-discussiontools-ui-replyWidget-actions' ).append(
129 this.cancelButton.$element,
130 this.replyButton.$element
131 );
132
133 this.editSummaryInput = new OO.ui.TextInputWidget( {
134 classes: [ 'ext-discussiontools-ui-replyWidget-editSummary' ]
135 } );
136 mw.widgets.visibleCodePointLimit( this.editSummaryInput, mw.config.get( 'wgCommentCodePointLimit' ) );
137
138 this.editSummaryField = new OO.ui.FieldLayout(
139 this.editSummaryInput,
140 {
141 align: 'top',
142 classes: [ 'ext-discussiontools-ui-replyWidget-editSummaryField' ],
143 label: mw.msg( 'discussiontools-replywidget-summary' )
144 }
145 );
146
147 this.advancedToggle = new OO.ui.ButtonWidget( {
148 label: mw.msg( 'discussiontools-replywidget-advanced' ),
149 indicator: 'down',
150 framed: false,
151 flags: [ 'progressive' ],
152 classes: [ 'ext-discussiontools-ui-replyWidget-advancedToggle' ]
153 } );
154 this.advanced = new OO.ui.MessageWidget( {
155 type: 'message',
156 $content: this.editSummaryField.$element,
157 classes: [ 'ext-discussiontools-ui-replyWidget-advanced' ]
158 } ).toggle( false ).setIcon( '' );
159
160 this.enterWarning = new OO.ui.MessageWidget( {
161 classes: [ 'ext-discussiontools-ui-replyWidget-enterWarning' ],
162 type: 'warning',
163 label: mw.msg(
164 'discussiontools-replywidget-keyboard-shortcut-submit',
165 new ve.ui.Trigger( ve.ui.commandHelpRegistry.lookup( 'dialogConfirm' ).shortcuts[ 0 ] ).getMessage()
166 )
167 } ).toggle( false );
168
169 this.$footer = $( '<div>' ).addClass( 'ext-discussiontools-ui-replyWidget-footer' );
170 if ( this.pageName !== mw.config.get( 'wgRelevantPageName' ) ) {
171 this.$footer.append( $( '<p>' ).append(
172 mw.message( 'discussiontools-replywidget-transcluded', this.pageName ).parseDom()
173 ) );
174 }
175 const $footerLinks = $( '<ul>' ).addClass( 'ext-discussiontools-ui-replyWidget-footer-links' );
176 if ( mw.user.isNamed() ) {
177 $footerLinks.append(
178 $( '<li>' ).append(
179 $( '<a>' )
180 .attr( {
181 href: mw.util.getUrl( 'Special:Preferences#mw-prefsection-editing-discussion' ),
182 target: '_blank',
183 rel: 'noopener'
184 } )
185 .text( mw.msg( 'discussiontools-replywidget-preferences' ) )
186 )
187 );
188 }
189 if ( dtConf.showFeedbackLinks ) {
190 $footerLinks.append(
191 $( '<li>' ).append(
192 $( '<a>' )
193 .attr( {
194 href: this.isNewTopic ?
195 mw.msg( 'discussiontools-replywidget-feedback-link-newtopic' ) :
196 mw.msg( 'discussiontools-replywidget-feedback-link' ),
197 target: '_blank',
198 rel: 'noopener'
199 } )
200 .text( mw.msg( 'discussiontools-replywidget-feedback' ) )
201 )
202 );
203 }
204 this.$footer.append(
205 $( '<p>' ).addClass( 'plainlinks' ).html(
206 this.isNewTopic ? licenseMessages.newtopic : licenseMessages.reply
207 )
208 );
209 if ( $footerLinks.children().length ) {
210 this.$footer.append( $footerLinks );
211 }
212 this.$actionsWrapper.append( this.$footer, this.$actions );
213
214 this.viewportScrollContainer = OO.ui.Element.static.getClosestScrollableContainer( document.body );
215 this.scrollBackTopButton = new OO.ui.ButtonWidget( {
216 classes: [ 'ext-discussiontools-ui-replyWidget-scrollback-top mw-sticky-header-element' ],
217 icon: 'collapse',
218 label: mw.msg(
219 this.isNewTopic ?
220 'discussiontools-replywidget-return-to-newtopic' :
221 'discussiontools-replywidget-return-to-reply'
222 ),
223 flags: [ 'progressive' ]
224 } );
225 this.scrollBackBottomButton = new OO.ui.ButtonWidget( {
226 classes: [ 'ext-discussiontools-ui-replyWidget-scrollback-bottom' ],
227 icon: 'expand',
228 label: mw.msg(
229 this.isNewTopic ?
230 'discussiontools-replywidget-return-to-newtopic' :
231 'discussiontools-replywidget-return-to-reply'
232 ),
233 flags: [ 'progressive' ]
234 } );
235
236 // Events
237 this.replyButton.connect( this, { click: 'onReplyClick' } );
238 this.cancelButton.connect( this, { click: 'tryTeardown' } );
239 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
240 this.beforeUnloadHandler = this.onBeforeUnload.bind( this );
241 this.unloadHandler = this.onUnload.bind( this );
242 this.onWatchToggleHandler = this.onWatchToggle.bind( this );
243 this.advancedToggle.connect( this, { click: 'onAdvancedToggleClick' } );
244 this.editSummaryInput.connect( this, { change: 'onEditSummaryChange' } );
245 this.editSummaryInput.$input.on( 'keydown', this.onKeyDown.bind( this ) );
246 if ( this.isNewTopic ) {
247 this.commentController.sectionTitle.$input.on( 'keydown', this.onKeyDown.bind( this ) );
248 }
249 this.scrollBackTopButton.connect( this, { click: 'onScrollBackButtonClick' } );
250 this.scrollBackBottomButton.connect( this, { click: 'onScrollBackButtonClick' } );
251
252 this.onInputChangeThrottled = OO.ui.throttle( this.onInputChange.bind( this ), 1000 );
253
254 // Initialization
255 this.$element.addClass( 'ext-discussiontools-ui-replyWidget' ).append(
256 this.$headerWrapper,
257 this.$bodyWrapper,
258 this.$preview,
259 this.advancedToggle.$element,
260 this.advanced.$element,
261 this.enterWarning.$element,
262 this.$actionsWrapper,
263 this.scrollBackTopButton.$element,
264 this.scrollBackBottomButton.$element
265 );
266 // Set direction to interface direction
267 this.$element.attr( 'dir', $( document.body ).css( 'direction' ) );
268 if ( this.isNewTopic ) {
269 this.$element.addClass( 'ext-discussiontools-ui-replyWidget-newTopic' );
270 }
271
272 if ( mw.user.isAnon() ) {
273 const msg = this.commentDetails.wouldAutoCreate ?
274 'discussiontools-replywidget-autocreate-warning' :
275 'discussiontools-replywidget-anon-warning';
276 const returnTo = {
277 returntoquery: window.location.search.slice( 1 ),
278 returnto: mw.config.get( 'wgPageName' )
279 };
280 this.anonWarning = new OO.ui.MessageWidget( {
281 classes: [ 'ext-discussiontools-ui-replyWidget-anonWarning' ],
282 type: 'warning',
283 // eslint-disable-next-line mediawiki/msg-doc
284 label: mw.message( msg )
285 .params( [
286 mw.util.getUrl( 'Special:Userlogin', returnTo ),
287 mw.util.getUrl( 'Special:Userlogin/signup', returnTo ),
288 contLangMessages[ 'tempuser-helppage' ]
289 ] )
290 .parseDom()
291 } );
292 this.anonWarning.$element.append( this.$actions );
293 this.anonWarning.$label.addClass( 'plainlinks' );
294 this.$element.append( this.anonWarning.$element, this.$footer );
295 this.$actionsWrapper.detach();
296 }
297
298 function trackCheckbox( n ) {
299 mw.track( 'visualEditorFeatureUse', {
300 feature: 'dtReply',
301 action: 'checkbox-' + n
302 } );
303 }
304
305 this.checkboxesPromise = controller.getCheckboxesPromise( this.pageName, this.oldId );
306 this.checkboxesPromise.then( ( checkboxes ) => {
307 if ( checkboxes.checkboxFields ) {
308 this.$checkboxes = $( '<div>' ).addClass( 'ext-discussiontools-ui-replyWidget-checkboxes' );
309 checkboxes.checkboxFields.forEach( ( field ) => {
310 this.$checkboxes.append( field.$element );
311 } );
312 this.editSummaryField.$body.append( this.$checkboxes );
313
314 // bind logging:
315 for ( const name in checkboxes.checkboxesByName ) {
316 checkboxes.checkboxesByName[ name ].$element.off( '.dtReply' ).on( 'click.dtReply', trackCheckbox.bind( this, name ) );
317 }
318 }
319 } );
320 }
321
322 /* Inheritance */
323
324 OO.inheritClass( ReplyWidget, OO.ui.Widget );
325
326 /* Events */
327
328 /**
329 * The widget has been torn down
330 *
331 * @event teardown
332 * @param string mode Teardown mode. See #teardown.
333 */
334
335 /**
336 * The widget has had contents cleared
337 *
338 * @event clear
339 */
340
341 /**
342 * Auto save storage has been cleared for the widget
343 *
344 * @event clearStorage
345 */
346
347 /**
348 * The 'Reload page' button in the widget was clicked
349 *
350 * @event reloadPage
351 */
352
353 /**
354 * The reply widget is submitted
355 *
356 * @event submit
357 */
358
359 /* Methods */
360
361 /**
362 * Create the widget for the reply body
363 *
364 * The body widget should implement #setReadOnly, #pushPending and #popPending
365 *
366 * @method
367 * @return {OO.ui.Widget}
368 */
369 ReplyWidget.prototype.createReplyBodyWidget = null;
370
371 /**
372 * Focus the widget
373 *
374 * @method
375 * @chainable
376 * @return {ReplyWidget}
377 */
378 ReplyWidget.prototype.focus = null;
379
380 /**
381 * Get value of reply body, HTML or wikitext
382 *
383 * @method
384 * @return {string}
385 */
386 ReplyWidget.prototype.getValue = null;
387
388 /**
389 * Check if the reply widget is empty
390 *
391 * @method
392 * @return {boolean}
393 */
394 ReplyWidget.prototype.isEmpty = null;
395
396 /**
397 * Get the current input mode of the reply widget, 'source' or 'visual'
398 *
399 * @method
400 * @return {string}
401 */
402 ReplyWidget.prototype.getMode = null;
403
404 /**
405 * Clear the save error message
406 */
407 ReplyWidget.prototype.clearSaveErrorMessage = function () {
408 if ( this.saveErrorMessage ) {
409 this.saveErrorMessage.$element.remove();
410 this.saveErrorMessage = null;
411 }
412 };
413
414 /**
415 * Restore the widget to its original state
416 *
417 * Clear any widget values, reset UI states, and clear
418 * any (optional) auto-save values.
419 *
420 * @param {boolean} [preserveStorage] Preserve auto-save storage
421 */
422 ReplyWidget.prototype.clear = function ( preserveStorage ) {
423 this.clearSaveErrorMessage();
424
425 if ( this.previewRequest ) {
426 this.previewRequest.abort();
427 this.previewRequest = null;
428 }
429 this.$preview.empty();
430 this.previewWikitext = null;
431 this.previewTitle = null;
432 this.toggleAdvanced( false );
433
434 if ( !preserveStorage ) {
435 this.clearStorage();
436 } else {
437 this.storage.set( 'saveable', '1' );
438 }
439
440 this.emit( 'clear' );
441 };
442
443 /**
444 * Remove any storage that the widget is using
445 */
446 ReplyWidget.prototype.clearStorage = function () {
447 this.storage.clear();
448 this.emit( 'clearStorage' );
449 };
450
451 /**
452 * Handle window scroll events
453 */
454 ReplyWidget.prototype.onWindowScroll = function () {
455 const rect = this.$element[ 0 ].getBoundingClientRect();
456 const viewportHeight = window.visualViewport ? visualViewport.height : this.viewportScrollContainer.clientHeight;
457 const floating = rect.bottom < 0 ? 'top' :
458 ( rect.top > viewportHeight ? 'bottom' : null );
459
460 if ( floating !== this.floating ) {
461 this.floating = floating;
462 // Always remove classes as we have switched directly from top to bottom with a fast scroll
463 this.$element
464 .removeClass( 'ext-discussiontools-ui-replyWidget-floating-top ext-discussiontools-ui-replyWidget-floating-bottom' );
465
466 if ( this.floating ) {
467 // The following classes are used here:
468 // * ext-discussiontools-ui-replyWidget-floating-top
469 // * ext-discussiontools-ui-replyWidget-floating-bottom
470 this.$element.addClass( 'ext-discussiontools-ui-replyWidget-floating-' + this.floating );
471 }
472 }
473 };
474
475 ReplyWidget.prototype.setPending = function ( pending ) {
476 this.pending = pending;
477 if ( pending ) {
478 this.replyButton.setDisabled( true );
479 this.cancelButton.setDisabled( true );
480 this.replyBodyWidget.setReadOnly( true );
481 this.replyBodyWidget.pushPending();
482 } else {
483 this.replyButton.setDisabled( false );
484 this.cancelButton.setDisabled( false );
485 this.replyBodyWidget.setReadOnly( false );
486 this.replyBodyWidget.popPending();
487 this.updateButtons();
488 }
489 };
490
491 ReplyWidget.prototype.saveEditMode = function ( mode ) {
492 controller.getApi().saveOption( 'discussiontools-editmode', mode ).then( () => {
493 mw.user.options.set( 'discussiontools-editmode', mode );
494 } );
495 };
496
497 ReplyWidget.prototype.onAdvancedToggleClick = function () {
498 const showAdvanced = !this.showAdvanced;
499 mw.track( 'visualEditorFeatureUse', {
500 feature: 'dtReply',
501 action: 'advanced-' + ( showAdvanced ? 'show' : 'hide' )
502 } );
503 controller.getApi().saveOption( 'discussiontools-showadvanced', +showAdvanced ).then( () => {
504 mw.user.options.set( 'discussiontools-showadvanced', +showAdvanced );
505 } );
506 this.toggleAdvanced( showAdvanced );
507
508 if ( showAdvanced ) {
509 const summary = this.editSummaryInput.getValue();
510
511 // If the current summary has not been edited yet, select the text following the autocomment to
512 // make it easier to change. Otherwise, move cursor to end.
513 let selectFromIndex = summary.length;
514 if ( this.isNewTopic ) {
515 const titleText = this.commentController.sectionTitle.getValue();
516 if ( summary === this.commentController.generateSummary( titleText ) ) {
517 selectFromIndex = titleText.length + '/* '.length + ' */ '.length;
518 }
519 } else {
520 // Same as summary.endsWith( defaultReplyTrail )
521 const defaultReplyTrail = '*/ ' + mw.msg( 'discussiontools-defaultsummary-reply' );
522 const endCommentIndex = summary.indexOf( defaultReplyTrail );
523 if ( endCommentIndex + defaultReplyTrail.length === summary.length ) {
524 selectFromIndex = endCommentIndex + 3;
525 }
526 }
527
528 this.editSummaryInput.selectRange( selectFromIndex, summary.length );
529 this.editSummaryInput.focus();
530 } else {
531 this.focus();
532 }
533 };
534
535 ReplyWidget.prototype.toggleAdvanced = function ( showAdvanced ) {
536 this.showAdvanced = showAdvanced === undefined ? !this.showAdvanced : showAdvanced;
537 this.advanced.toggle( !!this.showAdvanced );
538 this.advancedToggle.setIndicator( this.showAdvanced ? 'up' : 'down' );
539
540 this.storage.set( 'showAdvanced', this.showAdvanced ? '1' : '' );
541 };
542
543 ReplyWidget.prototype.showEnterWarning = function () {
544 this.enterWarning.toggle( true );
545 };
546
547 ReplyWidget.prototype.onEditSummaryChange = function () {
548 this.commentController.storeEditSummary();
549 };
550
551 ReplyWidget.prototype.getEditSummary = function () {
552 return this.editSummaryInput.getValue();
553 };
554
555 ReplyWidget.prototype.onModeTabSelectChoose = function ( option ) {
556 const mode = option.getData();
557
558 if ( mode === this.getMode() ) {
559 return;
560 }
561
562 this.modeTabSelect.setDisabled( true );
563 this.switch( mode ).then(
564 null,
565 () => {
566 // Switch failed, clear the tab selection
567 this.modeTabSelect.selectItem( null );
568 }
569 ).always( () => {
570 this.modeTabSelect.setDisabled( false );
571 } );
572 };
573
574 ReplyWidget.prototype.switch = function ( mode ) {
575 if ( mode === this.getMode() ) {
576 return $.Deferred().reject().promise();
577 }
578
579 let promise;
580 this.setPending( true );
581 switch ( mode ) {
582 case 'source':
583 promise = this.commentController.switchToWikitext();
584 break;
585 case 'visual':
586 promise = this.commentController.switchToVisual();
587 break;
588 }
589 // TODO: We rely on #setup to call #saveEditMode, so when we have 2017WTE
590 // we will need to save the new preference here as switching will not
591 // reload the editor.
592 return promise.then( () => {
593 // Switch succeeded
594 mw.track( 'visualEditorFeatureUse', {
595 feature: 'editor-switch',
596 action: (
597 mode === 'visual' ?
598 'visual' :
599 ( enable2017Wikitext ? 'source-nwe' : 'source' )
600 ) + '-desktop'
601 } );
602 } ).always( () => {
603 this.setPending( false );
604 } );
605 };
606
607 /**
608 * Setup the widget
609 *
610 * @param {Object} [data] Initial data
611 * @param {any} [data.value] Initial value
612 * @param {string} [data.showAdvanced] Whether the "Advanced" menu is initially visible
613 * @param {string} [data.editSummary] Initial edit summary
614 * @chainable
615 * @return {ReplyWidget}
616 */
617 ReplyWidget.prototype.setup = function ( data ) {
618 data = data || {};
619
620 this.bindBeforeUnloadHandler();
621 if ( this.modeTabSelect ) {
622 // Make the option for the current mode disabled, to make it un-interactable
623 // (we override the styles to make it look as if it was selected)
624 this.modeTabSelect.findItemFromData( this.getMode() ).setDisabled( true );
625 }
626 this.saveEditMode( this.getMode() );
627
628 let summary = this.storage.get( 'summary' ) || data.editSummary;
629
630 if ( !summary ) {
631 if ( this.isNewTopic ) {
632 // Edit summary is filled in when the user inputs the topic title,
633 // in NewTopicController#onSectionTitleChange
634 summary = '';
635 } else {
636 const title = this.commentController.getThreadItem().getHeading().getLinkableTitle();
637 summary = ( title ? '/* ' + title + ' */ ' : '' ) +
638 mw.msg( 'discussiontools-defaultsummary-reply' );
639 }
640 }
641
642 this.toggleAdvanced(
643 !!this.storage.get( 'showAdvanced' ) ||
644 !!+mw.user.options.get( 'discussiontools-showadvanced' ) ||
645 !!data.showAdvanced
646 );
647
648 this.editSummaryInput.setValue( summary );
649
650 if ( this.isNewTopic ) {
651 this.commentController.sectionTitle.connect( this, { change: 'onInputChangeThrottled' } );
652 } else {
653 // De-indent replies on mobile
654 if ( OO.ui.isMobile() ) {
655 this.$element.css( 'margin-left', -this.$element.position().left );
656 }
657 }
658
659 mw.hook( 'wikipage.watchlistChange' ).add( this.onWatchToggleHandler );
660
661 this.$window[ 0 ].addEventListener( 'scroll', this.onWindowScrollThrottled, { passive: true } );
662
663 return this;
664 };
665
666 /**
667 * Perform additional actions once the widget has been setup and is ready for input
668 */
669 ReplyWidget.prototype.afterSetup = function () {
670 // Init preview and button state
671 this.onInputChange();
672 // Autosave
673 this.storage.set( 'mode', this.getMode() );
674 };
675
676 /**
677 * Get a random token that is unique to this reply instance
678 *
679 * @return {string} Form token
680 */
681 ReplyWidget.prototype.getFormToken = function () {
682 let formToken = this.storage.get( 'formToken' );
683 if ( !formToken ) {
684 // See ApiBase::PARAM_MAX_CHARS in ApiDiscussionToolsEdit.php
685 const maxLength = 16;
686 formToken = Math.random().toString( 36 ).slice( 2, maxLength + 2 );
687 this.storage.set( 'formToken', formToken );
688 }
689 return formToken;
690 };
691
692 /**
693 * Try to teardown the widget, prompting the user if unsaved changes will be lost.
694 *
695 * @chainable
696 * @return {jQuery.Promise} Resolves if widget was torn down, rejects if it wasn't
697 */
698 ReplyWidget.prototype.tryTeardown = function () {
699 let promise;
700
701 if ( !this.isEmpty() || ( this.isNewTopic && this.commentController.sectionTitle.getValue() ) ) {
702 promise = OO.ui.getWindowManager().openWindow( this.isNewTopic ? 'abandontopic' : 'abandoncomment' )
703 .closed.then( ( data ) => {
704 if ( !( data && data.action === 'discard' ) ) {
705 return $.Deferred().reject().promise();
706 }
707 mw.track( 'editAttemptStep', {
708 action: 'abort',
709 mechanism: 'cancel',
710 type: 'abandon'
711 } );
712 } );
713 } else {
714 promise = $.Deferred().resolve().promise();
715 mw.track( 'editAttemptStep', {
716 action: 'abort',
717 mechanism: 'cancel',
718 type: 'nochange'
719 } );
720 }
721 promise = promise.then( () => {
722 this.teardown( 'abandoned' );
723 } );
724 return promise;
725 };
726
727 /**
728 * Teardown the widget
729 *
730 * @param {string} [mode] Teardown mode:
731 * - 'default': The reply was saved and can be discarded
732 * - 'abandoned': The reply was abandoned and discarded
733 * - 'refresh': The page is being refreshed, preserve auto-save
734 * @chainable
735 * @return {ReplyWidget}
736 */
737 ReplyWidget.prototype.teardown = function ( mode ) {
738 // Call the change handler to save the current value in auto-save
739 this.onInputChange();
740
741 if ( this.isNewTopic ) {
742 this.commentController.sectionTitle.disconnect( this );
743 }
744 // Make sure that the selector is blurred before it gets removed from the document, otherwise
745 // event handlers for arrow keys are not removed, and it keeps trying to switch modes (T274423)
746 if ( this.modeTabSelect ) {
747 this.modeTabSelect.blur();
748 }
749 this.unbindBeforeUnloadHandler();
750 this.$window[ 0 ].removeEventListener( 'scroll', this.onWindowScrollThrottled );
751 mw.hook( 'wikipage.watchlistChange' ).remove( this.onWatchToggleHandler );
752
753 this.isTornDown = true;
754 this.clear( mode === 'refresh' );
755 this.emit( 'teardown', mode );
756 return this;
757 };
758
759 /**
760 * Handle changes to the watch state of the page
761 *
762 * @param {boolean} isWatched
763 * @param {string} expiry
764 * @param {string} expirySelected
765 */
766 ReplyWidget.prototype.onWatchToggle = function ( isWatched ) {
767 if ( this.pageName === mw.config.get( 'wgRelevantPageName' ) ) {
768 this.checkboxesPromise.then( ( checkboxes ) => {
769 if ( checkboxes.checkboxesByName.wpWatchthis ) {
770 checkboxes.checkboxesByName.wpWatchthis.setSelected(
771 !!mw.user.options.get( 'watchdefault' ) ||
772 ( !!mw.user.options.get( 'watchcreations' ) && !this.pageExists ) ||
773 isWatched
774 );
775 }
776 } );
777 }
778 };
779
780 /**
781 * Handle key down events anywhere in the reply widget
782 *
783 * @param {jQuery.Event} e Key down event
784 * @return {boolean|undefined} Return false to prevent default event
785 */
786 ReplyWidget.prototype.onKeyDown = function ( e ) {
787 if ( e.which === OO.ui.Keys.ESCAPE ) {
788 this.tryTeardown();
789 return false;
790 }
791
792 // VE surfaces already handle CTRL+Enter, but this will catch
793 // the plain surface, and the edit summary input.
794 // Require CTRL+Enter even on single line inputs per T326500.
795 if ( e.which === OO.ui.Keys.ENTER ) {
796 if ( e.ctrlKey || e.metaKey ) {
797 this.onReplyClick();
798 return false;
799 } else if ( e.target.tagName === 'INPUT' && !this.$bodyWrapper[ 0 ].contains( e.target ) && !this.replyButton.isDisabled() ) {
800 // The body wrapper can contain VE UI widgets that you may need to press enter within
801 this.showEnterWarning();
802 return false;
803 }
804 }
805 };
806
807 /**
808 * Handle input change events anywhere in the reply widget
809 */
810 ReplyWidget.prototype.onInputChange = function () {
811 if ( this.isTornDown ) {
812 // Ignore calls after teardown, which would clear the auto-save or crash
813 return;
814 }
815
816 this.updateButtons();
817 this.storage.set( 'saveable', this.isEmpty() ? '' : '1' );
818 this.preparePreview();
819 };
820
821 /**
822 * Update the interface with the preview of the given wikitext.
823 *
824 * @param {string} [wikitext] Wikitext to preview, defaults to current value
825 * @return {jQuery.Promise} Promise resolved when we're done
826 */
827 ReplyWidget.prototype.preparePreview = function ( wikitext ) {
828 if ( this.getMode() !== 'source' ) {
829 return $.Deferred().resolve().promise();
830 }
831
832 wikitext = wikitext !== undefined ? wikitext : this.getValue();
833 wikitext = utils.htmlTrim( wikitext );
834 const title = this.isNewTopic && this.commentController.sectionTitle.getValue();
835
836 if ( this.previewWikitext === wikitext && this.previewTitle === title ) {
837 return $.Deferred().resolve().promise();
838 }
839 this.previewWikitext = wikitext;
840 this.previewTitle = title;
841
842 if ( this.previewRequest ) {
843 this.previewRequest.abort();
844 this.previewRequest = null;
845 }
846
847 let parsePromise;
848 if ( !wikitext ) {
849 parsePromise = $.Deferred().resolve( null ).promise();
850 } else {
851 // Acquire a temporary user username before previewing, so that signatures and
852 // user-related magic words display the temp user instead of IP user in the preview. (T331397)
853 parsePromise = mw.user.acquireTempUserName().then( () => {
854 this.previewRequest = controller.getApi().post( {
855 action: 'discussiontoolspreview',
856 type: this.isNewTopic ? 'topic' : 'reply',
857 page: this.pageName,
858 wikitext: wikitext,
859 sectiontitle: title,
860 useskin: mw.config.get( 'skin' ),
861 mobileformat: OO.ui.isMobile()
862 } );
863 return this.previewRequest;
864 } );
865 }
866
867 return parsePromise.then( ( response ) => {
868 this.$preview.html( response ? response.discussiontoolspreview.parse.text : '' );
869
870 if ( response ) {
871 mw.config.set( response.discussiontoolspreview.parse.jsconfigvars );
872 mw.loader.load( response.discussiontoolspreview.parse.modulestyles );
873 mw.loader.load( response.discussiontoolspreview.parse.modules );
874 }
875
876 mw.hook( 'wikipage.content' ).fire( this.$preview );
877 } );
878 };
879
880 /**
881 * Update buttons when widget state has changed
882 */
883 ReplyWidget.prototype.updateButtons = function () {
884 this.replyButton.setDisabled( this.isEmpty() );
885 };
886
887 /**
888 * Handle the first change in the reply widget
889 *
890 * Currently only the first change in the body, used for logging.
891 */
892 ReplyWidget.prototype.onFirstChange = function () {
893 mw.track( 'editAttemptStep', { action: 'firstChange' } );
894 };
895
896 /**
897 * Bind the beforeunload handler, if needed and if not already bound.
898 *
899 * @private
900 */
901 ReplyWidget.prototype.bindBeforeUnloadHandler = function () {
902 $( window ).on( 'beforeunload', this.beforeUnloadHandler );
903 $( window ).on( 'unload', this.unloadHandler );
904 };
905
906 /**
907 * Unbind the beforeunload handler if it is bound.
908 *
909 * @private
910 */
911 ReplyWidget.prototype.unbindBeforeUnloadHandler = function () {
912 $( window ).off( 'beforeunload', this.beforeUnloadHandler );
913 $( window ).off( 'unload', this.unloadHandler );
914 };
915
916 /**
917 * Respond to beforeunload event.
918 *
919 * @private
920 * @param {jQuery.Event} e Event
921 * @return {string|undefined}
922 */
923 ReplyWidget.prototype.onBeforeUnload = function ( e ) {
924 if ( !this.isEmpty() ) {
925 e.preventDefault();
926 return '';
927 }
928 };
929
930 /**
931 * Respond to unload event.
932 *
933 * @private
934 * @param {jQuery.Event} e Event
935 */
936 ReplyWidget.prototype.onUnload = function () {
937 mw.track( 'editAttemptStep', {
938 action: 'abort',
939 type: this.isEmpty() ? 'nochange' : 'abandon',
940 mechanism: 'navigate'
941 } );
942 };
943
944 ReplyWidget.prototype.updateParentRemovedError = function ( parentRemoved ) {
945 if ( !parentRemoved ) {
946 if ( this.parentRemovedErrorMessage ) {
947 this.parentRemovedErrorMessage.$element.remove();
948 this.parentRemovedErrorMessage = null;
949 }
950 return;
951 }
952 if ( !this.parentRemovedErrorMessage ) {
953 this.parentRemovedErrorMessage = this.createErrorMessage( mw.msg( 'discussiontools-error-comment-disappeared' ) );
954 }
955 // Don't show the reload prompt if there is nothing to reply to
956 this.updateNewCommentsWarning( [] );
957 };
958
959 /**
960 * Update "new comments" warning based on list of new comments found
961 *
962 * @param {Object[]} comments Array of JSON-serialized CommentItem's
963 */
964 ReplyWidget.prototype.updateNewCommentsWarning = function ( comments ) {
965 if ( !comments.length ) {
966 if ( this.newCommentsWarning ) {
967 this.newCommentsWarning.toggle( false );
968 }
969 return;
970 }
971 // Don't show the reload prompt if there is nothing to reply to
972 if ( this.parentRemovedErrorMessage ) {
973 return;
974 }
975 if ( !this.newCommentsWarning ) {
976 this.newCommentsShow = new OO.ui.ButtonWidget( {
977 flags: [ 'progressive' ]
978 } );
979 this.newCommentsClose = new OO.ui.ButtonWidget( {
980 icon: 'close',
981 label: mw.msg( 'ooui-popup-widget-close-button-aria-label' ),
982 invisibleLabel: true
983 } );
984 this.newCommentsWarning = new OO.ui.ButtonGroupWidget( {
985 classes: [ 'ext-discussiontools-ui-replyWidget-newComments' ],
986 items: [
987 this.newCommentsShow,
988 this.newCommentsClose
989 ]
990 } );
991 this.newCommentsShow.connect( this, { click: 'onNewCommentsShowClick' } );
992 this.newCommentsClose.connect( this, { click: 'onNewCommentsCloseClick' } );
993 this.$bodyWrapper.append( this.newCommentsWarning.$element );
994 }
995
996 this.newCommentsShow.setLabel(
997 mw.msg( 'discussiontools-replywidget-newcomments-button', mw.language.convertNumber( comments.length ) )
998 );
999 if ( !this.hideNewCommentsWarning ) {
1000 this.newCommentsWarning.toggle( true );
1001 setTimeout( () => {
1002 this.newCommentsWarning.$element.addClass( 'ext-discussiontools-ui-replyWidget-newComments-open' );
1003 } );
1004 mw.track( 'visualEditorFeatureUse', {
1005 feature: 'notificationNewComments',
1006 action: 'show'
1007 } );
1008 }
1009 };
1010
1011 /**
1012 * Handle click events on the new comments show button
1013 */
1014 ReplyWidget.prototype.onNewCommentsShowClick = function () {
1015 this.emit( 'reloadPage' );
1016 mw.track( 'visualEditorFeatureUse', {
1017 feature: 'notificationNewComments',
1018 action: 'page-update'
1019 } );
1020 mw.track( 'editAttemptStep', {
1021 action: 'abort',
1022 mechanism: 'navigate',
1023 type: 'pageupdate'
1024 } );
1025 };
1026
1027 /**
1028 * Handle click events on the new comments close button
1029 */
1030 ReplyWidget.prototype.onNewCommentsCloseClick = function () {
1031 this.newCommentsWarning.toggle( false );
1032 // Hide the warning for the rest of the lifetime of the widget
1033 this.hideNewCommentsWarning = true;
1034 this.focus();
1035 mw.track( 'visualEditorFeatureUse', {
1036 feature: 'notificationNewComments',
1037 action: 'close'
1038 } );
1039 };
1040
1041 /**
1042 * Create an error message widget and attach it to the DOM
1043 *
1044 * @param {string} message Message string
1045 * @return {OO.ui.MessageWidget} Message widget
1046 */
1047 ReplyWidget.prototype.createErrorMessage = function ( message ) {
1048 const errorMessage = new OO.ui.MessageWidget( {
1049 type: 'error',
1050 label: message,
1051 classes: [ 'ext-discussiontools-ui-replyWidget-error' ]
1052 } );
1053 errorMessage.$element.insertBefore( this.replyBodyWidget.$element );
1054 errorMessage.scrollElementIntoView();
1055 return errorMessage;
1056 };
1057
1058 /**
1059 * Handle clicks on the reply button
1060 *
1061 * @fires submit
1062 */
1063 ReplyWidget.prototype.onReplyClick = function () {
1064 if ( this.pending || this.isEmpty() ) {
1065 return;
1066 }
1067
1068 this.emit( 'submit' );
1069 };
1070
1071 /**
1072 * Set the save error message
1073 *
1074 * @param {string} code Error code
1075 * @param {Object} data Error data
1076 */
1077 ReplyWidget.prototype.setSaveErrorMessage = function ( code, data ) {
1078 if ( !(
1079 // Don't duplicate the parentRemovedErrorMessage
1080 code === 'discussiontools-commentname-notfound' && this.parentRemovedErrorMessage
1081 ) ) {
1082 this.saveErrorMessage = this.createErrorMessage(
1083 code instanceof Error ? code.toString() : controller.getApi().getErrorMessage( data )
1084 );
1085 }
1086 };
1087
1088 /**
1089 * Clear the captcha input
1090 */
1091 ReplyWidget.prototype.clearCaptcha = function () {
1092 if ( this.captchaMessage ) {
1093 this.captchaMessage.$element.detach();
1094 }
1095 this.captchaInput = undefined;
1096 };
1097
1098 /**
1099 * Set the captcha input
1100 *
1101 * @param {Object} captchaData Captcha data
1102 */
1103 ReplyWidget.prototype.setCaptcha = function ( captchaData ) {
1104 this.captchaInput = new mw.libs.confirmEdit.CaptchaInputWidget( captchaData );
1105 // Save when pressing 'Enter' in captcha field as it is single line.
1106 this.captchaInput.on( 'enter', () => {
1107 this.emit( 'reply' );
1108 } );
1109
1110 this.captchaMessage = new OO.ui.MessageWidget( {
1111 type: 'notice',
1112 label: this.captchaInput.$element,
1113 classes: [ 'ext-discussiontools-ui-replyWidget-captcha' ]
1114 } );
1115 this.captchaMessage.$element.insertAfter( this.$preview );
1116
1117 this.captchaInput.focus();
1118 this.captchaInput.scrollElementIntoView();
1119 };
1120
1121 /**
1122 * Handle click events on one of the scroll back buttons
1123 */
1124 ReplyWidget.prototype.onScrollBackButtonClick = function () {
1125 this.commentController.showAndFocus();
1126 };
1127
1128 module.exports = ReplyWidget;