Debian Codegraph @

extensions/DiscussionTools/modules/topicsubscriptions.js

raw symbols SCIP
1 /* global moment */
2 const
3 STATE_UNSUBSCRIBED = 0,
4 STATE_SUBSCRIBED = 1,
5 STATE_AUTOSUBSCRIBED = 2,
6 utils = require( './utils.js' ),
7 CommentItem = require( './CommentItem.js' ),
8 HeadingItem = require( './HeadingItem.js' );
9 let api,
10 seenAutoTopicSubPopup = !!+mw.user.options.get( 'discussiontools-seenautotopicsubpopup' ),
11 linksByName = {},
12 buttonsByName = {};
13
14 /**
15 * Update a subscribe link
16 *
17 * @param {HTMLElement} element Subscribe link
18 * @param {number|null} state State constant (STATE_UNSUBSCRIBED, STATE_SUBSCRIBED or STATE_AUTOSUBSCRIBED)
19 * @param {HTMLElement|null} labelElement Subscribe link, if different to element
20 * @param {boolean} isNewTopics Is a subscribe link for new topics subscriptions
21 */
22 function updateSubscribeLink( element, state, labelElement, isNewTopics ) {
23 labelElement = labelElement || element;
24 if ( state !== null ) {
25 element.setAttribute( 'data-mw-subscribed', String( state ) );
26 }
27 if ( state ) {
28 labelElement.textContent = mw.msg( isNewTopics ?
29 'discussiontools-newtopicssubscription-button-unsubscribe-label' :
30 'discussiontools-topicsubscription-button-unsubscribe' );
31 element.setAttribute( 'title', mw.msg( isNewTopics ?
32 'discussiontools-newtopicssubscription-button-unsubscribe-tooltip' :
33 'discussiontools-topicsubscription-button-unsubscribe-tooltip' )
34 );
35 } else {
36 labelElement.textContent = mw.msg( isNewTopics ?
37 'discussiontools-newtopicssubscription-button-subscribe-label' :
38 'discussiontools-topicsubscription-button-subscribe' );
39 element.setAttribute( 'title', mw.msg( isNewTopics ?
40 'discussiontools-newtopicssubscription-button-subscribe-tooltip' :
41 'discussiontools-topicsubscription-button-subscribe-tooltip' )
42 );
43 }
44 }
45
46 /**
47 * Update a subscribe button
48 *
49 * @param {OO.ui.ButtonWidget} button Subscribe button
50 * @param {number|null} state State constant (STATE_UNSUBSCRIBED, STATE_SUBSCRIBED or STATE_AUTOSUBSCRIBED)
51 */
52 function updateSubscribeButton( button, state ) {
53 if ( state !== null ) {
54 button.$element[ 0 ].setAttribute( 'data-mw-subscribed', String( state ) );
55 }
56 if ( state ) {
57 button.setIcon( 'bell' );
58 button.setLabel( mw.msg( 'discussiontools-topicsubscription-button-unsubscribe-label' ) );
59 button.setTitle( mw.msg( 'discussiontools-topicsubscription-button-unsubscribe-tooltip' ) );
60 } else {
61 button.setIcon( 'bellOutline' );
62 button.setLabel( mw.msg( 'discussiontools-topicsubscription-button-subscribe-label' ) );
63 button.setTitle( mw.msg( 'discussiontools-topicsubscription-button-subscribe-tooltip' ) );
64 }
65 }
66
67 /**
68 * Change the subscription state of a topic subscription
69 *
70 * @param {string} title Page title
71 * @param {string} commentName Comment name
72 * @param {boolean} subscribe Subscription state
73 * @param {boolean} isNewTopics Subscription is for new topics
74 * @return {jQuery.Promise} Promise which resolves after change of state
75 */
76 function changeSubscription( title, commentName, subscribe, isNewTopics ) {
77 const promise = api.postWithToken( 'csrf', {
78 action: 'discussiontoolssubscribe',
79 page: title,
80 commentname: commentName,
81 subscribe: subscribe
82 } ).then( ( response ) => OO.getProp( response, 'discussiontoolssubscribe' ) || {} );
83
84 promise.then( ( result ) => {
85 mw.notify(
86 mw.msg(
87 result.subscribe ?
88 (
89 isNewTopics ?
90 'discussiontools-newtopicssubscription-notify-subscribed-body' :
91 'discussiontools-topicsubscription-notify-subscribed-body'
92 ) :
93 (
94 isNewTopics ?
95 'discussiontools-newtopicssubscription-notify-unsubscribed-body' :
96 'discussiontools-topicsubscription-notify-unsubscribed-body'
97 )
98 ),
99 {
100 title: mw.msg(
101 result.subscribe ?
102 (
103 isNewTopics ?
104 'discussiontools-newtopicssubscription-notify-subscribed-title' :
105 'discussiontools-topicsubscription-notify-subscribed-title'
106 ) :
107 (
108 isNewTopics ?
109 'discussiontools-newtopicssubscription-notify-unsubscribed-title' :
110 'discussiontools-topicsubscription-notify-unsubscribed-title'
111 )
112 )
113 }
114 );
115 }, ( code, data ) => {
116 mw.notify( api.getErrorMessage( data ), { type: 'error' } );
117 } );
118
119 return promise;
120 }
121
122 function getSubscribedStateFromElement( element ) {
123 return element.hasAttribute( 'data-mw-subscribed' ) ? Number( element.getAttribute( 'data-mw-subscribed' ) ) : null;
124 }
125
126 /**
127 * Lazy load API to avoid circular dependency
128 */
129 function initApi() {
130 if ( !api ) {
131 api = require( './controller.js' ).getApi();
132 }
133 }
134
135 /**
136 * Initialize topic subscriptions feature
137 *
138 * @param {jQuery} $container Page container
139 * @param {ThreadItemSet} threadItemSet
140 */
141 function initTopicSubscriptions( $container, threadItemSet ) {
142 linksByName = {};
143 buttonsByName = {};
144
145 initApi();
146
147 // Subscription buttons (visual enhancements)
148 $container.find( '.ext-discussiontools-init-section-subscribeButton' ).each( ( i, element ) => {
149 // These attributes will be lost when infusing
150 // TODO: Could also be fixed by subclassing ButtonWidget in PHP
151 const subscribedStateTemp = getSubscribedStateFromElement( element );
152
153 const id = $( element ).closest( '.ext-discussiontools-init-section' )
154 .find( '[data-mw-comment-start]' ).attr( 'id' );
155 const headingItem = threadItemSet.findCommentById( id );
156
157 if ( !( headingItem instanceof HeadingItem ) ) {
158 // This should never happen
159 return;
160 }
161
162 const name = headingItem.name;
163 const button = OO.ui.infuse( element );
164 buttonsByName[ name ] = button;
165
166 // Restore data attribute
167 if ( subscribedStateTemp !== null ) {
168 button.$element[ 0 ].setAttribute( 'data-mw-subscribed', String( subscribedStateTemp ) );
169 }
170
171 const title = mw.config.get( 'wgRelevantPageName' ) + '#' + headingItem.getLinkableTitle();
172
173 button.on( 'click', () => {
174 // Get latest subscribedState
175 const subscribedState = getSubscribedStateFromElement( button.$element[ 0 ] );
176
177 button.setDisabled( true );
178 changeSubscription( title, name, !subscribedState )
179 .then( ( result ) => {
180 updateSubscribeButton( button, result.subscribe ? STATE_SUBSCRIBED : STATE_UNSUBSCRIBED );
181 } )
182 .always( () => {
183 button.setDisabled( false );
184 } );
185 } );
186 } );
187
188 // Subscription links (no visual enhancements)
189 $container.find( '.ext-discussiontools-init-section-subscribe-link' ).each( ( i, link ) => {
190 const $link = $( link );
191 const id = $link.closest( '.ext-discussiontools-init-section' )
192 .find( '[data-mw-comment-start]' ).attr( 'id' );
193 const headingItem = threadItemSet.findCommentById( id );
194
195 if ( !( headingItem instanceof HeadingItem ) ) {
196 // This should never happen
197 return;
198 }
199
200 const itemName = headingItem.name;
201 const title = mw.config.get( 'wgRelevantPageName' ) + '#' + headingItem.getLinkableTitle();
202
203 linksByName[ itemName ] = link;
204
205 $link.on( 'click keypress', ( e ) => {
206 if ( e.type === 'keypress' && e.which !== OO.ui.Keys.ENTER && e.which !== OO.ui.Keys.SPACE ) {
207 // Only handle keypresses on the "Enter" or "Space" keys
208 return;
209 }
210 if ( e.type === 'click' && !utils.isUnmodifiedLeftClick( e ) ) {
211 // Only handle unmodified left clicks
212 return;
213 }
214
215 e.preventDefault();
216
217 // Get latest subscribedState
218 const subscribedState = getSubscribedStateFromElement( $link[ 0 ] );
219
220 $link.addClass( 'ext-discussiontools-init-section-subscribe-link-pending' );
221 changeSubscription( title, itemName, !subscribedState )
222 .then( ( result ) => {
223 updateSubscribeLink( $link[ 0 ], result.subscribe ? STATE_SUBSCRIBED : STATE_UNSUBSCRIBED );
224 } )
225 .always( () => {
226 $link.removeClass( 'ext-discussiontools-init-section-subscribe-link-pending' );
227 } );
228 } );
229 } );
230
231 initNewTopicsSubscription();
232 }
233
234 /**
235 * Bind new topics subscription button
236 *
237 * Note: because this function can get called from `wikipage.content`,
238 * and we're interacting with elements outside of $container, make
239 * sure to account for this possibly being run multiple times on a
240 * pageload. Calls from DT's own previews are filtered out, but other
241 * page actions like live-preview can still reach this point.
242 */
243 function initNewTopicsSubscription() {
244 let $button, $label, $icon;
245
246 initApi();
247
248 if ( mw.config.get( 'skin' ) === 'minerva' ) {
249 // eslint-disable-next-line no-jquery/no-global-selector
250 $button = $( '.menu__item--page-actions-overflow-t-page-subscribe' );
251 $label = $button.find( '.toggle-list-item__label' );
252 $icon = $button.find( '.minerva-icon' );
253 // HACK: We can't set data-mw-subscribed intially in Minerva, so work it out from the icon
254 // eslint-disable-next-line no-jquery/no-class-state
255 const initialState = $icon.hasClass( 'minerva-icon--bell' ) ? STATE_SUBSCRIBED : STATE_UNSUBSCRIBED;
256 $button.attr( 'data-mw-subscribed', String( initialState ) );
257 } else {
258 // eslint-disable-next-line no-jquery/no-global-selector
259 $button = $( '#ca-dt-page-subscribe > a' );
260 $label = $button.find( 'span' );
261 $icon = $( [] );
262 }
263
264 const titleObj = mw.Title.newFromText( mw.config.get( 'wgRelevantPageName' ) );
265 const name = utils.getNewTopicsSubscriptionId( titleObj );
266
267 $button.off( '.mw-dt-topicsubscriptions' ).on( 'click.mw-dt-topicsubscriptions', ( e ) => {
268 e.preventDefault();
269 // Get latest subscribedState
270 const subscribedState = getSubscribedStateFromElement( $button[ 0 ] );
271
272 changeSubscription( titleObj.getPrefixedText(), name, !subscribedState, true )
273 .then( ( result ) => {
274 updateSubscribeLink( $button[ 0 ], result.subscribe ? STATE_SUBSCRIBED : STATE_UNSUBSCRIBED, $label[ 0 ], true );
275 $icon.toggleClass( 'minerva-icon--bell', !!result.subscribe );
276 $icon.toggleClass( 'minerva-icon--bellOutline', !result.subscribe );
277 } );
278 } );
279 }
280
281 function initSpecialTopicSubscriptions() {
282 api = require( './controller.js' ).getApi();
283
284 // Unsubscribe links on special page
285 // eslint-disable-next-line no-jquery/no-global-selector
286 $( '.ext-discussiontools-special-unsubscribe-button' ).each( ( i, element ) => {
287 const button = OO.ui.infuse( element );
288 const data = button.getData();
289 let subscribedState = STATE_SUBSCRIBED;
290
291 button.on( 'click', () => {
292 button.setDisabled( true );
293 changeSubscription( data.title, data.item, !subscribedState )
294 .then( ( result ) => {
295 button.setLabel( mw.msg(
296 result.subscribe ?
297 'discussiontools-topicsubscription-button-unsubscribe-label' :
298 'discussiontools-topicsubscription-button-subscribe-label'
299 ) );
300 button.clearFlags();
301 button.setFlags( [ result.subscribe ? 'destructive' : 'progressive' ] );
302 subscribedState = result.subscribe ? STATE_SUBSCRIBED : STATE_UNSUBSCRIBED;
303 } ).always( () => {
304 button.setDisabled( false );
305 } );
306 } );
307 } );
308 }
309
310 /**
311 * Show the first time popup for auto topic subscriptions, if required
312 */
313 function maybeShowFirstTimeAutoTopicSubPopup() {
314 const lastHighlightComment = require( './highlighter.js' ).getLastHighlightedPublishedComment();
315
316 if ( !lastHighlightComment || seenAutoTopicSubPopup ) {
317 return;
318 }
319
320 seenAutoTopicSubPopup = true;
321 mw.user.options.set( 'discussiontools-seenautotopicsubpopup', '1' );
322 api.saveOption( 'discussiontools-seenautotopicsubpopup', '1' );
323
324 let popup = null;
325
326 function close() {
327 popup.$element.removeClass( 'ext-discussiontools-autotopicsubpopup-fadein' );
328 setTimeout( () => {
329 popup.$element.detach();
330 }, 1000 );
331 }
332
333 const $popupContent = $( '<div>' )
334 .append(
335 $( '<strong>' )
336 .addClass( 'ext-discussiontools-autotopicsubpopup-title' )
337 .text( mw.msg( 'discussiontools-autotopicsubpopup-title' ) ),
338 $( '<div>' )
339 .addClass( 'ext-discussiontools-autotopicsubpopup-image' ),
340 $( '<div>' )
341 .addClass( 'ext-discussiontools-autotopicsubpopup-body' )
342 .text( mw.msg( 'discussiontools-autotopicsubpopup-body' ) ),
343 $( '<div>' )
344 .addClass( 'ext-discussiontools-autotopicsubpopup-actions' )
345 .append( new OO.ui.ButtonWidget( {
346 label: mw.msg( 'discussiontools-autotopicsubpopup-dismiss' ),
347 flags: [ 'primary', 'progressive' ]
348 } ).on( 'click', close ).$element )
349 .append( new OO.ui.ButtonWidget( {
350 label: mw.msg( 'discussiontools-autotopicsubpopup-preferences' ),
351 href: mw.util.getUrl( 'Special:Preferences#mw-prefsection-editing-discussion' ),
352 flags: [ 'progressive' ],
353 framed: false
354 } ).$element )
355 );
356
357 popup = new OO.ui.PopupWidget( {
358 // Styles and dimensions
359 width: '',
360 height: '',
361 anchor: false,
362 autoClose: false,
363 head: false,
364 padded: false,
365 classes: [ 'ext-discussiontools-autotopicsubpopup' ],
366 hideWhenOutOfView: false,
367 // Content
368 $content: $popupContent.contents()
369 } );
370
371 // Like in highlight()
372 lastHighlightComment.getRange().insertNode( popup.$element[ 0 ] );
373 // Pull it outside of headings to avoid silly fonts
374 if ( popup.$element.closest( 'h1, h2, h3, h4, h5, h6' ).length ) {
375 popup.$element.closest( 'h1, h2, h3, h4, h5, h6' ).after( popup.$element );
376 }
377 if ( popup.$element.closest( '.mw-heading' ).length ) {
378 popup.$element.closest( '.mw-heading' ).after( popup.$element );
379 }
380
381 // Disable positioning, the popup is positioned in CSS, above the highlight
382 popup.toggle( true ).toggleClipping( false ).togglePositioning( false );
383
384 // If the page is very short, there might not be enough space above the highlight,
385 // causing the popup to overlap the skin navigation or even be off-screen.
386 // Position it on top of the highlight in that case...
387 // eslint-disable-next-line no-jquery/no-global-selector
388 if ( popup.$popup[ 0 ].getBoundingClientRect().top < $( '.mw-body' )[ 0 ].getBoundingClientRect().top ) {
389 popup.$popup.addClass( 'ext-discussiontools-autotopicsubpopup-overlap' );
390 }
391
392 // Scroll into view, leave some space above to avoid overlapping .postedit-container
393 OO.ui.Element.static.scrollIntoView(
394 popup.$popup[ 0 ],
395 {
396 padding: {
397 // Add padding to avoid overlapping the post-edit notification (above on desktop, below on mobile)
398 top: OO.ui.isMobile() ? 10 : 60,
399 bottom: OO.ui.isMobile() ? 85 : 10
400 },
401 // Specify scrollContainer for compatibility with MobileFrontend.
402 // Apparently it makes `<dd>` elements scrollable and OOUI tried to scroll them instead of body.
403 scrollContainer: OO.ui.Element.static.getRootScrollableElement( popup.$popup[ 0 ] )
404 }
405 );
406
407 popup.$element.addClass( 'ext-discussiontools-autotopicsubpopup-fadein' );
408 }
409
410 /**
411 * Update the subscription state of various topics
412 *
413 * @param {jQuery} $container Page container
414 * @param {Object.<string, HeadingItem>} headingsToUpdate Headings of topics where subscription state has changed
415 */
416 function updateSubscriptionStates( $container, headingsToUpdate ) {
417 // This method is called when we recently edited this page, and auto-subscriptions might have been
418 // added for some topics. It updates the [subscribe] buttons to reflect the new subscriptions.
419
420 // If the topic is already marked as auto-subscribed, there's nothing to do.
421 // (Except maybe show the first-time popup.)
422 // If the topic is marked as having never been subscribed, check if they are auto-subscribed now.
423 const topicsToCheck = [];
424 const pendingLinks = [];
425 const pendingButtons = [];
426 for ( const headingName in headingsToUpdate ) {
427 const link = linksByName[ headingName ];
428 const button = buttonsByName[ headingName ];
429 const subscribedState = getSubscribedStateFromElement( link || button.$element[ 0 ] );
430
431 if ( subscribedState === STATE_AUTOSUBSCRIBED ) {
432 maybeShowFirstTimeAutoTopicSubPopup();
433 } else if ( subscribedState === null || subscribedState === STATE_UNSUBSCRIBED ) {
434 topicsToCheck.push( headingName );
435 if ( link ) {
436 pendingLinks.push( link );
437 }
438 if ( button ) {
439 pendingButtons.push( button );
440 }
441 }
442 }
443 $( pendingLinks ).addClass( 'ext-discussiontools-init-section-subscribe-link-pending' );
444 pendingButtons.forEach( ( b ) => {
445 b.setDisabled( true );
446 } );
447
448 if ( !topicsToCheck.length ) {
449 return;
450 }
451
452 api.get( {
453 action: 'discussiontoolsgetsubscriptions',
454 commentname: topicsToCheck
455 } ).then( ( response ) => {
456 if ( $.isEmptyObject( response.subscriptions ) ) {
457 // If none of the topics has an auto-subscription yet, wait a moment and check again.
458 // updateSubscriptionStates() method is only called if we're really expecting one to be there.
459 // (There are certainly neater ways to implement this, involving push notifications or at
460 // least long-polling or something. But this is the simplest one!)
461 const wait = $.Deferred();
462 setTimeout( wait.resolve, 5000 );
463 return wait.then( () => api.get( {
464 action: 'discussiontoolsgetsubscriptions',
465 commentname: topicsToCheck
466 } ) );
467 }
468 return response;
469 } ).then( ( response ) => {
470 // Update state of each topic for which there is a subscription
471 for ( const subItemName in response.subscriptions ) {
472 const state = response.subscriptions[ subItemName ];
473 if ( linksByName[ subItemName ] ) {
474 updateSubscribeLink( linksByName[ subItemName ], state );
475 }
476 if ( buttonsByName[ subItemName ] ) {
477 updateSubscribeButton( buttonsByName[ subItemName ], state );
478 }
479 if ( state === STATE_AUTOSUBSCRIBED ) {
480 maybeShowFirstTimeAutoTopicSubPopup();
481 }
482 }
483 } ).always( () => {
484 $( pendingLinks ).removeClass( 'ext-discussiontools-init-section-subscribe-link-pending' );
485 pendingButtons.forEach( ( b ) => {
486 b.setDisabled( false );
487 } );
488 } );
489 }
490
491 /**
492 * Update subscription state of just-posted new topics
493 *
494 * @param {jQuery} $container Page container
495 * @param {ThreadItemSet} threadItemSet
496 * @param {string} [threadItemId] Just-posted comment ID (or NEW_TOPIC_COMMENT_ID)
497 */
498 function updateAutoSubscriptionStates( $container, threadItemSet, threadItemId ) {
499 const recentComments = [];
500 const headingsToUpdate = {};
501 if ( threadItemId ) {
502 // Edited by using the reply tool or new topic tool. Only check the edited topic.
503 if ( threadItemId === utils.NEW_TOPIC_COMMENT_ID ) {
504 recentComments.push( threadItemSet.threadItems[ threadItemSet.threadItems.length - 1 ] );
505 } else {
506 recentComments.push( threadItemSet.threadItemsById[ threadItemId ] );
507 }
508 } else if ( mw.config.get( 'wgPostEdit' ) ) {
509 // Edited by using wikitext editor. Check topics with their own comments within last minute.
510 for ( let i = 0; i < threadItemSet.threadItems.length; i++ ) {
511 if (
512 threadItemSet.threadItems[ i ] instanceof CommentItem &&
513 threadItemSet.threadItems[ i ].author === mw.user.getName() &&
514 threadItemSet.threadItems[ i ].timestamp.isSameOrAfter( moment().subtract( 1, 'minute' ), 'minute' )
515 ) {
516 recentComments.push( threadItemSet.threadItems[ i ] );
517 }
518 }
519 }
520 recentComments.forEach( ( recentComment ) => {
521 const headingItem = recentComment.getSubscribableHeading();
522 if ( headingItem ) {
523 // Use names as object keys to deduplicate if there are multiple comments in a topic.
524 headingsToUpdate[ headingItem.name ] = headingItem;
525 }
526 } );
527 updateSubscriptionStates( $container, headingsToUpdate );
528 }
529
530 module.exports = {
531 initTopicSubscriptions: initTopicSubscriptions,
532 initSpecialTopicSubscriptions: initSpecialTopicSubscriptions,
533 initNewTopicsSubscription: initNewTopicsSubscription,
534 updateAutoSubscriptionStates: updateAutoSubscriptionStates
535 };