Debian Codegraph @

extensions/DiscussionTools/modules/controller.js

raw symbols SCIP
1 'use strict';
2
3 const featuresEnabled = mw.config.get( 'wgDiscussionToolsFeaturesEnabled' ) || {},
4 MemoryStorage = require( './MemoryStorage.js' ),
5 STORAGE_EXPIRY = 60 * 60 * 24 * 30,
6 Parser = require( './Parser.js' ),
7 ThreadItemSet = require( './ThreadItemSet.js' ),
8 CommentDetails = require( './CommentDetails.js' ),
9 HeadingItem = require( './HeadingItem.js' ),
10 ReplyLinksController = require( './ReplyLinksController.js' ),
11 utils = require( './utils.js' ),
12 highlighter = require( './highlighter.js' ),
13 topicSubscriptions = require( './topicsubscriptions.js' ),
14 permalinks = require( './permalinks.js' ),
15 defaultEditMode = mw.user.options.get( 'discussiontools-editmode' ) || mw.config.get( 'wgDiscussionToolsFallbackEditMode' ),
16 defaultVisual = defaultEditMode === 'visual',
17 enable2017Wikitext = featuresEnabled.sourcemodetoolbar,
18 overflowMenu = require( './overflowMenu.js' );
19 let
20 $pageContainer, linksController,
21 pageThreads,
22 lastControllerScrollOffset,
23 pageDataCache = {},
24 pageHandlersSetup = false;
25
26 let mobile = null;
27 if ( OO.ui.isMobile() && mw.config.get( 'skin' ) === 'minerva' ) {
28 mobile = require( './mobile.js' );
29 }
30 if ( mw.loader.getState( 'ext.thanks' ) ) {
31 require( './thanks.js' );
32 }
33
34 mw.messages.set( require( './controller/contLangMessages.json' ) );
35
36 /**
37 * Get an MW API instance
38 *
39 * @return {mw.Api} API instance
40 */
41 function getApi() {
42 return new mw.Api( {
43 parameters: {
44 formatversion: 2,
45 uselang: mw.config.get( 'wgUserLanguage' )
46 }
47 } );
48 }
49
50 /**
51 * Get various pieces of page metadata.
52 *
53 * This method caches responses. If you call it again with the same parameters, you'll get the exact
54 * same Promise object, and no API request will be made.
55 *
56 * @param {string} pageName Page title
57 * @param {number} oldId Revision ID
58 * @param {Object} [apiParams] Additional parameters for the API
59 * @return {jQuery.Promise}
60 */
61 function getPageData( pageName, oldId, apiParams ) {
62 const api = getApi();
63 apiParams = apiParams || {};
64
65 pageDataCache[ pageName ] = pageDataCache[ pageName ] || {};
66 if ( pageDataCache[ pageName ][ oldId ] && $.isEmptyObject( apiParams ) ) {
67 return pageDataCache[ pageName ][ oldId ];
68 }
69
70 let lintPromise, transcludedFromPromise;
71 if ( oldId ) {
72 lintPromise = api.get( {
73 action: 'query',
74 list: 'linterrors',
75 lntcategories: 'fostered',
76 lntlimit: 1,
77 lnttitle: pageName
78 } ).then( ( response ) => OO.getProp( response, 'query', 'linterrors' ) || [] );
79
80 transcludedFromPromise = api.get( {
81 action: 'discussiontoolspageinfo',
82 page: pageName,
83 oldid: oldId
84 } ).then( ( response ) => OO.getProp( response, 'discussiontoolspageinfo', 'transcludedfrom' ) || {} );
85 } else {
86 lintPromise = $.Deferred().resolve( [] ).promise();
87 transcludedFromPromise = $.Deferred().resolve( {} ).promise();
88 }
89
90 const veMetadataPromise = api.get( Object.assign( {
91 action: 'visualeditor',
92 paction: 'metadata',
93 page: pageName
94 }, apiParams ) ).then( ( response ) => OO.getProp( response, 'visualeditor' ) || [] );
95
96 const promise = $.when( lintPromise, transcludedFromPromise, veMetadataPromise )
97 .then( ( linterrors, transcludedfrom, metadata ) => ( {
98 linterrors: linterrors,
99 transcludedfrom: transcludedfrom,
100 metadata: metadata
101 } ), () => {
102 // Clear on failure
103 pageDataCache[ pageName ][ oldId ] = null;
104 // Let caller handle the error
105 return $.Deferred().rejectWith( this, arguments );
106 } );
107
108 if ( $.isEmptyObject( apiParams ) ) {
109 pageDataCache[ pageName ][ oldId ] = promise;
110 }
111
112 return promise;
113 }
114
115 /**
116 * Check if a given thread item on a page can be replied to
117 *
118 * @param {string} pageName Page title
119 * @param {number} oldId Revision ID
120 * @param {ThreadItem} threadItem Thread item
121 * @return {jQuery.Promise} Resolved with a CommentDetails object if the comment appears on the page.
122 * Rejects with error data if the comment is transcluded, or there are lint errors on the page.
123 */
124 function checkThreadItemOnPage( pageName, oldId, threadItem ) {
125 const isNewTopic = threadItem.id === utils.NEW_TOPIC_COMMENT_ID;
126 const defaultMode = mw.user.options.get( 'discussiontools-editmode' ) || mw.config.get( 'wgDiscussionToolsFallbackEditMode' );
127 let apiParams = null;
128 if ( isNewTopic ) {
129 apiParams = {
130 section: 'new',
131 editintro: threadItem.editintro,
132 preload: threadItem.preload,
133 preloadparams: threadItem.preloadparams,
134 paction: defaultMode === 'source' ? 'wikitext' : 'parse'
135 };
136 }
137
138 return getPageData( pageName, oldId, apiParams )
139 .then( ( response ) => {
140 const metadata = response.metadata,
141 lintErrors = response.linterrors,
142 transcludedFrom = response.transcludedfrom;
143
144 if ( !isNewTopic ) {
145 // First look for data by the thread item's ID. If not found, also look by name.
146 // Data by ID may not be found due to differences in headings (e.g. T273413, T275821),
147 // or if a thread item's parent changes.
148 // Data by name might be combined from two or more thread items, which would only allow us to
149 // treat them both as transcluded from unknown source, unless we check ID first.
150 let isTranscludedFrom = transcludedFrom[ threadItem.id ];
151 if ( isTranscludedFrom === undefined ) {
152 isTranscludedFrom = transcludedFrom[ threadItem.name ];
153 }
154 if ( isTranscludedFrom === undefined ) {
155 // The thread item wasn't found when generating the "transcludedfrom" data,
156 // so we don't know where the reply should be posted. Just give up.
157 return $.Deferred().reject( 'discussiontools-commentid-notfound-transcludedfrom', { errors: [ {
158 code: 'discussiontools-commentid-notfound-transcludedfrom',
159 html: mw.message( 'discussiontools-error-comment-disappeared' ).parse() +
160 '<br>' +
161 mw.message( 'discussiontools-error-comment-disappeared-reload' ).parse()
162 } ] } ).promise();
163 } else if ( isTranscludedFrom ) {
164 const mwTitle = isTranscludedFrom === true ? null : mw.Title.newFromText( isTranscludedFrom );
165 // If this refers to a template rather than a subpage, we never want to edit it
166 const follow = mwTitle && mwTitle.getNamespaceId() !== mw.config.get( 'wgNamespaceIds' ).template;
167
168 let transcludedErrMsg;
169 if ( follow ) {
170 transcludedErrMsg = mw.message(
171 'discussiontools-error-comment-is-transcluded-title',
172 mwTitle.getPrefixedText()
173 ).parse();
174 } else if ( metadata.canEdit ) {
175 // If the user can edit, advise them to use the edit button
176 transcludedErrMsg = mw.message(
177 'discussiontools-error-comment-is-transcluded',
178 // eslint-disable-next-line no-jquery/no-global-selector
179 $( '#ca-edit' ).text()
180 ).parse();
181 } else {
182 // Otherwise, tell them why they can't edit
183 transcludedErrMsg = metadata.notices[ 'permissions-error' ];
184 }
185
186 return $.Deferred().reject( 'comment-is-transcluded', { errors: [ {
187 data: {
188 transcludedFrom: isTranscludedFrom,
189 follow: follow
190 },
191 code: 'comment-is-transcluded',
192 html: transcludedErrMsg
193 } ] } ).promise();
194 }
195
196 if ( lintErrors.length ) {
197 // We currently only request the first error
198 const lintType = lintErrors[ 0 ].category;
199
200 return $.Deferred().reject( 'lint', { errors: [ {
201 code: 'lint',
202 html: mw.message( 'discussiontools-error-lint',
203 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Lint_errors/' + lintType,
204 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help_talk:Lint_errors/' + lintType,
205 mw.util.getUrl( pageName, { action: 'edit', lintid: lintErrors[ 0 ].lintId } ) ).parse()
206 } ] } ).promise();
207 }
208 }
209
210 if ( !metadata.canEdit ) {
211 return $.Deferred().reject( 'permissions-error', { errors: [ {
212 code: 'permissions-error',
213 html: metadata.notices[ 'permissions-error' ]
214 } ] } ).promise();
215 }
216
217 return new CommentDetails( pageName, oldId, metadata.notices, metadata.wouldautocreate, metadata.content, defaultMode );
218 } );
219 }
220
221 /**
222 * Get a promise which resolves with editor checkbox data
223 *
224 * @param {string} pageName Page title
225 * @param {number} oldId Revision ID
226 * @return {jQuery.Promise} See ve.init.mw.ArticleTargetLoader#createCheckboxFields
227 */
228 function getCheckboxesPromise( pageName, oldId ) {
229 return getPageData(
230 pageName,
231 oldId
232 ).then( ( pageData ) => {
233 const data = pageData.metadata,
234 checkboxesDef = {};
235
236 mw.messages.set( data.checkboxesMessages );
237
238 // Only show the watch checkbox for now
239 if ( 'wpWatchthis' in data.checkboxesDef ) {
240 checkboxesDef.wpWatchthis = data.checkboxesDef.wpWatchthis;
241 // Override the label with a more verbose one to distinguish this from topic subscriptions (T290712)
242 checkboxesDef.wpWatchthis[ 'label-message' ] = 'discussiontools-replywidget-watchthis';
243 }
244 return mw.loader.using( 'ext.visualEditor.targetLoader' )
245 .then( () => mw.libs.ve.targetLoader.createCheckboxFields( checkboxesDef ) );
246 // TODO: createCheckboxField doesn't make links in the label open in a new
247 // window as that method currently lives in ve.utils
248 } );
249 }
250
251 /**
252 * Get the resourceloader modules required for a mode of the reply widget
253 *
254 * @return {string[]}
255 */
256 function getReplyWidgetModules() {
257 const modules = [];
258 if ( OO.ui.isMobile() ) {
259 modules.push(
260 'ext.visualEditor.core.mobile',
261 'ext.visualEditor.mwextensions'
262 );
263 } else {
264 modules.push(
265 'ext.visualEditor.core.desktop',
266 'ext.visualEditor.desktopTarget',
267 'ext.visualEditor.mwextensions.desktop'
268 );
269 }
270 modules.push( 'ext.discussionTools.ReplyWidget' );
271
272 const veConf = mw.config.get( 'wgVisualEditorConfig' );
273 modules.push( ...veConf.pluginModules.filter( mw.loader.getState ) );
274
275 return modules;
276 }
277
278 /**
279 * Initialize Discussion Tools features
280 *
281 * @param {jQuery} $container Page container
282 * @param {Object<string,any>} [state] Page state data object
283 * @param {string} [state.repliedTo] The comment ID that was just replied to
284 * @param {boolean} [state.tempUserCreated] Whether a temp user was just created
285 */
286 function init( $container, state ) {
287 let
288 activeCommentId = null,
289 activeController = null;
290 // Loads later to avoid circular dependency
291 const CommentController = require( './CommentController.js' ),
292 NewTopicController = require( './NewTopicController.js' );
293
294 // We may be re-initializing after posting a new comment, so clear the cache, because
295 // wgCurRevisionId will not change if we posted to a transcluded page (T266275).
296 // This also applies when another tool has posted a comment and reloaded page contents (T323661).
297 pageDataCache = {};
298
299 // Lazy-load postEdit module, may be required later (on desktop)
300 mw.loader.using( 'mediawiki.action.view.postEdit' );
301
302 if ( linksController ) {
303 linksController.teardown();
304 linksController = null;
305 }
306
307 $pageContainer = $container;
308 linksController = new ReplyLinksController( $pageContainer );
309 permalinks.init( $pageContainer );
310
311 linksController.on( 'link-interact', () => {
312 // Preload page metadata when the user is about to use a link, to make the tool load faster.
313 // NOTE: As of January 2023, this is an EXPENSIVE API CALL. It must not be done on every
314 // pageview, as that would generate enough load to take down Wikimedia sites (T325477).
315 // It would be barely acceptable to do it on every *discussion* pageview, but we're trying
316 // to be better and only do it when really needed (T325598).
317 getPageData(
318 mw.config.get( 'wgRelevantPageName' ),
319 mw.config.get( 'wgCurRevisionId' )
320 );
321 } );
322
323 const parser = new Parser( require( './parser/data.json' ) );
324
325 const commentNodes = $pageContainer[ 0 ].querySelectorAll( '[data-mw-thread-id]' );
326 pageThreads = ThreadItemSet.static.newFromJSON( mw.config.get( 'wgDiscussionToolsPageThreads' ) || [], $pageContainer[ 0 ], parser );
327
328 if ( featuresEnabled.topicsubscription ) {
329 topicSubscriptions.initTopicSubscriptions( $container, pageThreads );
330 }
331
332 overflowMenu.init( $container, pageThreads );
333
334 if ( mobile ) {
335 mobile.init( $container, pageThreads );
336 }
337
338 if ( linksController.pageHasReplyLinks() || linksController.pageHasNewTopicLink() ) {
339 // Start loading reply widget code
340 // The worst-case here is that we might be on a page with no comments
341 // and the add-topic link suppressed, *but* which has valid links to
342 // trigger the new topic tool within the content. If that happens,
343 // the modules will still be loaded when those links are interacted with.
344 mw.loader.using( getReplyWidgetModules() );
345 }
346
347 /**
348 * Setup comment controllers for each comment, and the new topic controller
349 *
350 * @param {ThreadItem} comment
351 * @param {jQuery} $link Add section link for new topic controller
352 * @param {Object} [options] Options, see CommentController
353 * @param {string} [options.mode] Optionally force a mode, 'visual' or 'source'
354 * @param {boolean} [options.hideErrors] Suppress errors, e.g. when restoring auto-save
355 * @param {boolean} [options.suppressNotifications] Don't notify the user if recovering auto-save
356 * @param {MemoryStorage} [storage] Storage object for autosave
357 */
358 function setupController( comment, $link, options, storage ) {
359 if ( !storage ) {
360 storage = new MemoryStorage( mw.storage, 'mw-ext-DiscussionTools-reply/' + comment.id, STORAGE_EXPIRY );
361 }
362
363 let commentController, $addSectionLink;
364 if ( comment.id === utils.NEW_TOPIC_COMMENT_ID ) {
365 // eslint-disable-next-line no-jquery/no-global-selector
366 $addSectionLink = $( '#ca-addsection' ).find( 'a' );
367 // When opening new topic tool using any link, always activate the link in page tabs too
368 $link = $link.add( $addSectionLink );
369 commentController = new NewTopicController( $pageContainer, comment, pageThreads, storage );
370 } else {
371 commentController = new CommentController( $pageContainer, comment, pageThreads, storage );
372 }
373
374 activeCommentId = comment.id;
375 activeController = commentController;
376 linksController.setActiveLink( $link );
377
378 commentController.on( 'teardown', ( teardownMode ) => {
379 activeCommentId = null;
380 activeController = null;
381
382 if ( teardownMode !== 'refresh' ) {
383 linksController.clearActiveLink();
384 }
385
386 if ( teardownMode === 'abandoned' ) {
387 linksController.focusLink( $link );
388 }
389 } );
390 commentController.on( 'reloadPage', () => {
391 mw.dt.initState.newCommentIds = commentController.newComments.map( ( cmt ) => cmt.id );
392 // Teardown active reply widget(s)
393 commentController.replyWidgetPromise.then( ( replyWidget ) => {
394 lastControllerScrollOffset = $( commentController.newListItem ).offset().top;
395 replyWidget.teardown( 'refresh' );
396 // Only fetch the last now "good" revision, on which we know the parent comment still exists.
397 // As we poll frequently, this will almost always be the lastet revision.
398 refreshPageContents( commentController.oldId );
399 } );
400 } );
401
402 commentController.setup( options );
403 if ( lastControllerScrollOffset ) {
404 $( document.documentElement ).scrollTop(
405 $( document.documentElement ).scrollTop() +
406 ( $( commentController.newListItem ).offset().top - lastControllerScrollOffset )
407 );
408 lastControllerScrollOffset = null;
409 }
410 }
411
412 function newTopicComment( data ) {
413 const comment = new HeadingItem( {}, 2 );
414 comment.id = utils.NEW_TOPIC_COMMENT_ID;
415 comment.isNewTopic = true;
416 Object.assign( comment, data );
417 return comment;
418 }
419
420 // Hook up each link to open a reply widget
421 //
422 // TODO: Allow users to use multiple reply widgets simultaneously.
423 // Currently submitting a reply from one widget would also destroy the other ones.
424 linksController.on( 'link-click', ( commentId, $link, data ) => {
425 // If the reply widget is already open, activate it.
426 // Reply links are also made unclickable using 'pointer-events' in CSS, but that doesn't happen
427 // for new section links, because we don't have a good way of visually disabling them.
428 if ( activeCommentId === commentId ) {
429 activeController.showAndFocus();
430 return;
431 }
432
433 let teardownPromise = $.Deferred().resolve();
434 if ( commentId === utils.NEW_TOPIC_COMMENT_ID ) {
435 // If this is a new topic link, and a reply widget is open, attempt to close it first.
436 if ( activeController ) {
437 teardownPromise = activeController.tryTeardown();
438 } else if ( OO.getProp( window, 've', 'init', 'target', 'tryTeardown' ) ) {
439 // If VE or 2017WTE is open, attempt to close it as well. (T317035#8590357)
440 // FIXME This should be generalized, using some global router or something,
441 // so that we don't try to open while something else is open on full screen.
442 // Another example is the MultimediaViewer extension.
443 teardownPromise = ve.init.target.tryTeardown() || $.Deferred().resolve();
444 }
445 }
446
447 if ( mobile ) {
448 teardownPromise = teardownPromise.then( () => mobile.closeLedeSectionDialog() );
449 }
450
451 teardownPromise.then( () => {
452 // If another reply widget is open (or opening), do nothing.
453 if ( activeController ) {
454 return;
455 }
456 let comment;
457 if ( commentId !== utils.NEW_TOPIC_COMMENT_ID ) {
458 comment = pageThreads.findCommentById( commentId );
459 } else {
460 comment = newTopicComment( data );
461 }
462 if ( comment ) {
463 setupController( comment, $link );
464 } else {
465 // We couldn't find the comment, so express that there's an issue
466 mw.notify( mw.msg( 'discussiontools-error-comment-disappeared' ) );
467 }
468 } );
469 } );
470
471 const mobilePromise = OO.ui.isMobile() && mw.loader.getState( 'mobile.init' ) ?
472 mw.loader.using( 'mobile.init' ) :
473 $.Deferred().resolve().promise();
474
475 // Restore autosave
476 // Don't do anything when we're editing/previewing
477 if ( mw.config.get( 'wgAction' ) === 'view' ) {
478 pageThreads.threadItems.every( ( comment, i ) => {
479 const replyStorage = new MemoryStorage( mw.storage, 'mw-ext-DiscussionTools-reply/' + comment.id, STORAGE_EXPIRY );
480 if ( replyStorage.get( 'saveable' ) ) {
481 const mode = replyStorage.get( 'mode' );
482 const $link = $( commentNodes[ i ] );
483 // Wait for mobile section toggling code to be ready
484 mobilePromise.then( () => {
485 if ( OO.ui.isMobile() ) {
486 const urlFragment = mw.util.escapeIdForLink( comment.id );
487 // Force the section to expand on mobile (T338920)
488 location.hash = '#' + urlFragment;
489 }
490 // Wait for the 'hashchange' event to be handled by the mobile code
491 setTimeout( () => {
492 setupController( comment, $link, {
493 mode: mode,
494 hideErrors: true,
495 suppressNotifications: !state.firstLoad
496 }, replyStorage );
497 } );
498 } );
499 return false;
500 }
501 return true;
502 } );
503 const newTopicStorage = new MemoryStorage( mw.storage, 'mw-ext-DiscussionTools-reply/' + utils.NEW_TOPIC_COMMENT_ID, STORAGE_EXPIRY );
504 if ( newTopicStorage.get( 'saveable' ) || newTopicStorage.get( 'title' ) ) {
505 const mode = newTopicStorage.get( 'mode' );
506 setupController( newTopicComment(), $( [] ), {
507 mode: mode,
508 hideErrors: true,
509 suppressNotifications: !state.firstLoad
510 }, newTopicStorage );
511 } else if ( mw.config.get( 'wgDiscussionToolsStartNewTopicTool' ) ) {
512 const data = linksController.parseNewTopicLink( location.href );
513 setupController( newTopicComment( data ), $( [] ) );
514 }
515 }
516
517 // For debugging (now unused in the code)
518 mw.dt.pageThreads = pageThreads;
519
520 mobilePromise.then( () => {
521 if ( state.repliedTo ) {
522 highlighter.highlightPublishedComment( pageThreads, state.repliedTo );
523
524 if ( state.repliedTo === utils.NEW_TOPIC_COMMENT_ID ) {
525 mw.hook( 'postEdit' ).fire( {
526 tempUserCreated: state.tempUserCreated,
527 message: mw.msg( 'discussiontools-postedit-confirmation-topicadded', mw.user )
528 } );
529 } else {
530 mw.hook( 'postEdit' ).fire( {
531 tempUserCreated: state.tempUserCreated,
532 message: mw.msg( 'discussiontools-postedit-confirmation-published', mw.user )
533 } );
534 }
535 } else if ( state.newCommentIds ) {
536 highlighter.highlightNewComments( pageThreads, true, state.newCommentIds );
537 }
538
539 // Check topic subscription states if the user has automatic subscriptions enabled
540 // and has recently edited this page.
541 if ( featuresEnabled.autotopicsub && mw.user.options.get( 'discussiontools-autotopicsub' ) ) {
542 topicSubscriptions.updateAutoSubscriptionStates( $container, pageThreads, state.repliedTo );
543 }
544 } );
545
546 let dismissableNotificationPromise = null;
547 // Page-level handlers only need to be setup once
548 if ( !pageHandlersSetup ) {
549 $( window ).on( 'popstate', () => {
550 // Delay with setTimeout() because "the Document's target element" (corresponding to the :target
551 // selector in CSS) is not yet updated to match the URL when handling a 'popstate' event.
552 setTimeout( () => {
553 highlighter.highlightTargetComment( pageThreads, true );
554 } );
555 } );
556 // eslint-disable-next-line no-jquery/no-global-selector
557 $( 'body' ).on( 'click', ( e ) => {
558 if ( utils.isUnmodifiedLeftClick( e ) && !e.target.closest( 'a' ) ) {
559 // Remove the highlight and the hash from the URL, unless clicking on another link
560 highlighter.clearHighlightTargetComment( pageThreads );
561 }
562 if ( dismissableNotificationPromise ) {
563 dismissableNotificationPromise.then( ( notif ) => {
564 notif.close();
565 } );
566 dismissableNotificationPromise = null;
567 }
568 } );
569 pageHandlersSetup = true;
570 }
571 if ( state.firstLoad ) {
572 mobilePromise.then( () => {
573 let findCommentQuery;
574 let isHeading = false;
575 const highlightResult = highlighter.highlightTargetComment( pageThreads );
576
577 // Hash contains a non-replaced space (should be underscore), maybe due to
578 // manual creation or a broken third party tool. Just replace the spaces
579 // and navigate to the new URL.
580 // Ideally we'd use history.replaceState but that wouldn't scroll the page.
581 // Only do the replacement if the original hash doesn't correspond to a target
582 // element, but the fixed hash does, to avoid affects on other apps which
583 // may use fragments with spaces.
584 if ( location.hash && !mw.util.getTargetFromFragment() && location.hash.indexOf( '%20' ) !== -1 ) {
585 const fixedHash = location.hash.slice( 1 ).replace( /%20/g, '_' );
586 if ( mw.util.getTargetFromFragment( fixedHash ) ) {
587 location.hash = fixedHash;
588 }
589 }
590 if (
591 // Fragment doesn't correspond to an element on the page
592 location.hash &&
593 !mw.util.getTargetFromFragment() &&
594 // Not a DT comment
595 highlightResult.highlighted.length === 0 && highlightResult.requested.length === 0
596 ) {
597 const fragment = location.hash.slice( 1 );
598 const ignorePatterns = [
599 // A leading '/' or '!/' usually means a application route, e.g. /media, or /editor.
600 // We can't rule out a heading title (T349498), but they are unlikely
601 /^!?\//,
602 // "top" is a magic value in the WHATWG spec that goes to the top of the
603 // document (unless there's an actual id=top element on the page), see:
604 // https://html.spec.whatwg.org/multipage/browsing-the-web.html#scrolling-to-a-fragment:top-of-the-document-2
605 // There's a very rare edge case of actual headings named "top" that we'll
606 // be missing here, but they're far less common than the top-of-page usage.
607 /^top$/i,
608 // Gadget: ConvenientDiscussions
609 /^\d{12}_/,
610 // Gadget: RedWarn
611 /^noticeApplied-/
612 ];
613 if ( ignorePatterns.every( ( pattern ) => !pattern.test( fragment ) ) ) {
614 findCommentQuery = {
615 heading: mw.util.percentDecodeFragment( fragment ).replace( / /g, '_' ),
616 page: mw.config.get( 'wgRelevantPageName' )
617 };
618 isHeading = true;
619 }
620 } else if ( highlightResult.highlighted.length === 0 && highlightResult.requested.length === 1 ) {
621 findCommentQuery = {
622 idorname: mw.util.percentDecodeFragment( highlightResult.requested[ 0 ] )
623 };
624 isHeading = highlightResult.requested[ 0 ].slice( 0, 1 ) === 'h';
625 }
626 if ( findCommentQuery ) {
627 // TODO: Support multiple commentIds being requested and not all being found
628 const dtConf = require( './config.json' );
629 const findCommentRequest = dtConf.enablePermalinksFrontend ?
630 getApi().get( Object.assign( {
631 action: 'discussiontoolsfindcomment'
632 }, findCommentQuery ) ) :
633 $.Deferred().resolve( [ {} ] ).promise();
634 dismissableNotificationPromise = $.when(
635 findCommentRequest,
636 mw.loader.using( 'mediawiki.notification' )
637 ).then( ( results ) => {
638 const result = results[ 0 ];
639 let titles = [];
640 if ( result.discussiontoolsfindcomment ) {
641 titles = result.discussiontoolsfindcomment.map( ( threadItemData ) => {
642 // Only show items that appear on the current revision of their page
643 // and are not transcluded from another page
644 if ( threadItemData.couldredirect ) {
645 const title = mw.Title.newFromText(
646 threadItemData.title + '#' +
647 mw.util.escapeIdForLink( threadItemData.id )
648 );
649 return title;
650 }
651 return null;
652 } ).filter( ( url ) => url );
653 }
654 if ( titles.length ) {
655 const $list = $( '<ul>' );
656 const $notification = $( '<div>' ).append(
657 $( '<p>' ).text( mw.message(
658 isHeading ?
659 'discussiontools-target-heading-found-moved' :
660 'discussiontools-target-comment-found-moved',
661 titles.length
662 ).text() ),
663 $list
664 );
665 titles.forEach( ( title ) => {
666 $list.append(
667 $( '<li>' ).append(
668 $( '<a>' ).attr( 'href', title.getUrl() ).text( title.getPrefixedText() )
669 )
670 );
671 } );
672 mw.notification.notify(
673 $notification,
674 { type: 'warn', autoHide: false }
675 );
676 // This notification should not be accidentally dismissable
677 return $.Deferred().reject().promise();
678 } else {
679 return mw.notification.notify(
680 mw.message( isHeading ?
681 'discussiontools-target-heading-missing' :
682 'discussiontools-target-comment-missing'
683 ).text(),
684 { type: 'warn', autoHide: false }
685 );
686 }
687 } );
688 }
689 if ( highlightResult.highlighted.length === 0 && ( highlightResult.requested.length > 1 || highlightResult.requestedSince ) ) {
690 dismissableNotificationPromise = mw.loader.using( 'mediawiki.notification' ).then( () => mw.notification.notify(
691 mw.message( 'discussiontools-target-comments-missing' ).text(),
692 { type: 'warn', autoHide: false }
693 ) );
694 }
695 } );
696 }
697 }
698
699 /**
700 * Update the contents of the page with the data from an action=parse API response.
701 *
702 * @param {jQuery} $container Page container
703 * @param {Object} data Data from action=parse API
704 */
705 function updatePageContents( $container, data ) {
706 $container.find( '.mw-parser-output' ).first().replaceWith( data.parse.text );
707
708 mw.util.clearSubtitle();
709 mw.util.addSubtitle( data.parse.subtitle );
710
711 // eslint-disable-next-line no-jquery/no-global-selector
712 if ( $( '#catlinks' ).length ) {
713 const $categories = $( $.parseHTML( data.parse.categorieshtml ) );
714 mw.hook( 'wikipage.categories' ).fire( $categories );
715 // eslint-disable-next-line no-jquery/no-global-selector
716 $( '#catlinks' ).replaceWith( $categories );
717 }
718
719 mw.config.set( data.parse.jsconfigvars );
720 mw.loader.load( data.parse.modulestyles );
721 mw.loader.load( data.parse.modules );
722
723 mw.config.set( {
724 wgCurRevisionId: data.parse.revid,
725 wgRevisionId: data.parse.revid
726 } );
727
728 // TODO: update displaytitle, lastmodified
729 // We may not be able to use prop=displaytitle without making changes in the action=parse API,
730 // VE API has some confusing code that changes the HTML escaping on it before returning???
731
732 // We need our init code to run after everyone else's handlers for this hook,
733 // so that all changes to the page layout have been completed (e.g. collapsible elements),
734 // and we can measure things and display the highlight in the right place.
735 mw.hook( 'wikipage.content' ).remove( mw.dt.init );
736 mw.hook( 'wikipage.content' ).fire( $container );
737 // The hooks have "memory" so calling add() after fire() actually fires the handler,
738 // and calling add() before fire() would actually fire it twice.
739 mw.hook( 'wikipage.content' ).add( mw.dt.init );
740
741 mw.hook( 'wikipage.tableOfContents' ).fire(
742 data.parse.showtoc ? data.parse.sections : []
743 );
744
745 // Copied from ve.init.mw.DesktopArticleTarget.prototype.saveComplete
746 // TODO: Upstream this to core/skins, triggered by a hook (wikipage.content?)
747 // eslint-disable-next-line no-jquery/no-global-selector
748 $( '#t-permalink' ).add( '#coll-download-as-rl' ).find( 'a' ).each( ( i, link ) => {
749 const permalinkUrl = new URL( link.href );
750 permalinkUrl.searchParams.set( 'oldid', data.parse.revid );
751 $( link ).attr( 'href', permalinkUrl.toString() );
752 } );
753
754 const url = new URL( location.href );
755 url.searchParams.delete( 'oldid' );
756
757 // If there are any other query parameters left, re-use that URL object.
758 // Otherwise use the canonical style view url (T44553, T102363).
759 const keys = [];
760 url.searchParams.forEach( ( val, key ) => {
761 keys.push( key );
762 } );
763
764 if ( !keys.length || ( keys.length === 1 && keys[ 0 ] === 'title' ) ) {
765 const viewUrl = new URL( mw.util.getUrl( mw.config.get( 'wgRelevantPageName' ) ), document.baseURI );
766 viewUrl.hash = location.hash;
767 history.pushState( null, '', viewUrl );
768 } else {
769 history.pushState( null, '', url );
770 }
771 }
772
773 /**
774 * Load the latest revision of the page and display its contents.
775 *
776 * @param {number} [oldId] Revision ID to fetch, latest if not specified
777 * @return {jQuery.Promise} Promise which resolves when the refresh is complete
778 */
779 function refreshPageContents( oldId ) {
780 // This should approximately match the API call in ApiVisualEditorEditor#parseWikitext
781 return getApi().get( {
782 action: 'parse',
783 // HACK: 'useskin' triggers a different code path that runs our OutputPageBeforeHTML hook,
784 // adding our reply links in the HTML (T266195)
785 useskin: mw.config.get( 'skin' ),
786 mobileformat: OO.ui.isMobile(),
787 uselang: mw.config.get( 'wgUserLanguage' ),
788 // Pass through dtenable query string param from original request
789 dtenable: new URLSearchParams( location.search ).get( 'dtenable' ) ? '1' : undefined,
790 prop: [ 'text', 'revid', 'categorieshtml', 'sections', 'displaytitle', 'subtitle', 'modules', 'jsconfigvars' ],
791 page: !oldId ? mw.config.get( 'wgRelevantPageName' ) : undefined,
792 oldid: oldId || undefined
793 } ).then( ( parseResp ) => {
794 updatePageContents( $pageContainer, parseResp );
795 } );
796 }
797
798 /**
799 * Update the page after a comment is published/saved
800 *
801 * @param {Object} data Edit API response data
802 * @param {ThreadItem} threadItem Parent thread item
803 * @param {string} pageName Page title
804 * @param {mw.dt.ReplyWidget} replyWidget ReplyWidget
805 */
806 function update( data, threadItem, pageName, replyWidget ) {
807 function logSaveSuccess() {
808 mw.track( 'editAttemptStep', {
809 action: 'saveSuccess',
810 timing: mw.now() - replyWidget.commentController.saveInitiated,
811 // eslint-disable-next-line camelcase
812 revision_id: data.newrevid
813 } );
814 }
815
816 if (
817 ( pageName === mw.config.get( 'wgRelevantPageName' ) && data.nocontent ) ||
818 data.tempusercreated
819 ) {
820 // Reload if the page didn't exist before this update, or we just became logged in
821 // as a temporary user. We'd handle setting up the content just fine (assuming there's
822 // a mw-parser-output), but fixing up the UI tabs/behavior is outside our scope.
823 replyWidget.unbindBeforeUnloadHandler();
824 replyWidget.clearStorage();
825 replyWidget.setPending( true );
826 const params = { dtrepliedto: threadItem.id };
827 if ( data.tempusercreated ) {
828 params.dttempusercreated = '1';
829 }
830 window.location = data.tempusercreatedredirect || mw.util.getUrl( pageName, params );
831 logSaveSuccess();
832 return;
833 }
834
835 replyWidget.teardown();
836 // TODO: Tell controller to teardown all other open widgets
837
838 // Highlight the new reply after re-initializing
839 mw.dt.initState.repliedTo = threadItem.id;
840 mw.dt.initState.tempUserCreated = data.tempusercreated;
841
842 // Update page state
843 const pageUpdated = $.Deferred();
844 if ( pageName === mw.config.get( 'wgRelevantPageName' ) ) {
845 // We can use the result from the VisualEditor API
846 updatePageContents( $pageContainer, {
847 parse: {
848 text: data.content,
849 subtitle: data.contentSub,
850 categorieshtml: data.categorieshtml,
851 jsconfigvars: data.jsconfigvars,
852 revid: data.newrevid,
853 // Note: VE API merges 'modules' and 'modulestyles'
854 modules: data.modules,
855 modulestyles: [],
856 // Note: VE API drops 'showtoc' and changes 'sections' depending on it
857 showtoc: true,
858 sections: data.sections
859 }
860 } );
861
862 mw.config.set( {
863 wgCurRevisionId: data.newrevid,
864 wgRevisionId: data.newrevid
865 } );
866
867 pageUpdated.resolve();
868
869 } else {
870 // We saved to another page, we must purge and then fetch the current page
871 const api = getApi();
872 api.post( {
873 action: 'purge',
874 titles: mw.config.get( 'wgRelevantPageName' )
875 } ).then( () => refreshPageContents() ).then( () => {
876 pageUpdated.resolve();
877 } ).catch( () => {
878 // We saved the reply, but couldn't purge or fetch the updated page. Seems difficult to
879 // explain this problem. Redirect to the page where the user can at least see their reply…
880 window.location = mw.util.getUrl( pageName, { dtrepliedto: threadItem.id } );
881 // We're confident the saving portion succeeded, so still log this:
882 logSaveSuccess();
883 } );
884 }
885
886 // User logged in if module loaded.
887 if ( mw.loader.getState( 'mediawiki.page.watch.ajax' ) === 'ready' ) {
888 const watch = require( 'mediawiki.page.watch.ajax' );
889
890 watch.updateWatchLink(
891 mw.Title.newFromText( pageName ),
892 data.watched ? 'unwatch' : 'watch',
893 'idle',
894 data.watchlistexpiry
895 );
896 }
897
898 pageUpdated.then( logSaveSuccess );
899 }
900
901 module.exports = {
902 init: init,
903 update: update,
904 updatePageContents: updatePageContents,
905 refreshPageContents: refreshPageContents,
906 checkThreadItemOnPage: checkThreadItemOnPage,
907 getCheckboxesPromise: getCheckboxesPromise,
908 getApi: getApi,
909 getReplyWidgetModules: getReplyWidgetModules,
910 defaultVisual: defaultVisual,
911 enable2017Wikitext: enable2017Wikitext
912 };