Debian Codegraph @

extensions/DiscussionTools/modules/highlighter.js

raw symbols SCIP
1 const
2 featuresEnabled = mw.config.get( 'wgDiscussionToolsFeaturesEnabled' ) || {},
3 CommentItem = require( './CommentItem.js' ),
4 HeadingItem = require( './HeadingItem.js' ),
5 utils = require( './utils.js' );
6 let lastHighlightedPublishedComment = null;
7
8 /**
9 * Draw a semi-transparent rectangle on the page to highlight the given thread item.
10 *
11 * @class
12 * @param {ThreadItem|ThreadItem[]} items Thread item(s) to highlight
13 */
14 function Highlight( items ) {
15 const highlightNodes = [];
16 const ranges = [];
17
18 this.topmostElement = null;
19
20 items = Array.isArray( items ) ? items : [ items ];
21
22 this.rootNode = items[ 0 ] ? items[ 0 ].rootNode : null;
23
24 items.forEach( ( item ) => {
25 const $highlight = $( '<div>' ).addClass( 'ext-discussiontools-init-highlight' );
26
27 // We insert the highlight in the DOM near the thead item, so that it remains positioned correctly
28 // when it shifts (e.g. collapsing the table of contents), and disappears when it is hidden (e.g.
29 // opening visual editor).
30 const range = item.getRange();
31 // Support: Firefox
32 // The highlight node must be inserted after the start marker node (data-mw-comment-start), not
33 // before, otherwise Node#getBoundingClientRect() returns wrong results.
34 range.insertNode( $highlight[ 0 ] );
35
36 // If the item is a top-level comment wrapped in a frame, highlight outside that frame
37 if ( item.level === 1 ) {
38 const coveredSiblings = utils.getFullyCoveredSiblings( item, item.rootNode );
39 if ( coveredSiblings ) {
40 range.setStartBefore( coveredSiblings[ 0 ] );
41 range.setEndAfter( coveredSiblings[ coveredSiblings.length - 1 ] );
42 }
43 }
44
45 // If the item is a heading, highlight the full extent of it (not only the text)
46 if ( item instanceof HeadingItem && !item.placeholderHeading ) {
47 range.selectNode(
48 $highlight.closest( '.mw-heading' )[ 0 ] ||
49 $highlight.closest( 'h1, h2, h3, h4, h5, h6' )[ 0 ]
50 );
51 }
52
53 ranges.push( range );
54 highlightNodes.push( $highlight[ 0 ] );
55 } );
56
57 this.ranges = ranges;
58 this.$element = $( highlightNodes );
59
60 // Events
61 this.updateDebounced = OO.ui.debounce( this.update.bind( this ), 500 );
62 window.addEventListener( 'resize', this.updateDebounced );
63
64 if ( OO.ui.isMobile() ) {
65 // In MobileFrontend, ensure the section we are highlighting within is expanded. This is
66 // often the case as we add the hash fragment to our notification URLs, but not when we highlight
67 // comments across multiple threads.
68 // HACK: Ideally MF would expose Toggler as a public API, but for now just find the correct DOM
69 // node and trigger a fake click.
70 this.$element.parents( '.collapsible-block' ).prev( '.collapsible-heading:not( .open-block )' ).trigger( 'click' );
71 }
72
73 this.update();
74 }
75
76 OO.initClass( Highlight );
77
78 /**
79 * Update position of highlights, e.g. after window resize
80 */
81 Highlight.prototype.update = function () {
82 this.$element.css( {
83 'margin-top': '',
84 'margin-left': '',
85 'margin-right': '',
86 width: '',
87 height: ''
88 } );
89 const rootRect = this.rootNode.getBoundingClientRect();
90 this.topmostElement = null;
91 let topmostTop = Infinity;
92 this.ranges.forEach( ( range, i ) => {
93 const $element = this.$element.eq( i );
94 const baseRect = $element[ 0 ].getBoundingClientRect();
95 const rect = RangeFix.getBoundingClientRect( range );
96 // rect may be null if the range is in a detached or hidden node
97 if ( rect ) {
98 // Draw the highlight over the full width of the page, except for very short comments
99 // (less than 1/3 of the available width).
100 //
101 // This lets the far edges of almost all comments align nicely (T309444#7968858),
102 // while still accurately highlighting comments in narrow floating boxes, such as
103 // image captions or {{archive top}}.
104 //
105 // It seems difficult to distinguish the floating boxes from comments that are just
106 // very short or very deeply indented, and this seems to work well enough in practice.
107 const useFullWidth = rect.width > rootRect.width / 3;
108
109 let headingTopAdj = 0;
110 if (
111 featuresEnabled.visualenhancements &&
112 $element.closest( '.ext-discussiontools-init-section' ).length
113 ) {
114 // Shift the highlight a little to avoid drawing over the separator border at the top,
115 // and to cover the gap to the first comment at the bottom.
116 headingTopAdj = 10;
117 }
118
119 const top = rect.top - baseRect.top;
120 let width = rect.width;
121 const height = rect.height;
122 let left, right;
123 if ( $element.css( 'direction' ) === 'ltr' ) {
124 left = rect.left - baseRect.left;
125 if ( useFullWidth ) {
126 width = rootRect.width - ( rect.left - rootRect.left );
127 }
128 } else {
129 right = ( baseRect.left + baseRect.width ) - ( rect.left + rect.width );
130 if ( useFullWidth ) {
131 width = rootRect.width - ( ( rootRect.left + rootRect.width ) - ( rect.left + rect.width ) );
132 }
133 }
134 const padding = 5;
135 $element.css( {
136 'margin-top': top - padding + headingTopAdj,
137 'margin-left': left !== undefined ? left - padding : '',
138 'margin-right': right !== undefined ? right - padding : '',
139 width: width + ( padding * 2 ),
140 height: height + ( padding * 2 )
141 } );
142
143 if ( rect.top < topmostTop ) {
144 this.topmostElement = $element[ 0 ];
145 topmostTop = rect.top;
146 }
147 }
148 } );
149 };
150
151 /**
152 * Scroll the topmost highlight into view
153 */
154 Highlight.prototype.scrollIntoView = function () {
155 if ( this.topmostElement ) {
156 this.topmostElement.scrollIntoView();
157 }
158 };
159
160 /**
161 * Destroy the highlight
162 */
163 Highlight.prototype.destroy = function () {
164 this.$element.remove();
165 window.removeEventListener( 'resize', this.updateDebounced );
166 };
167
168 let highlightedTarget = null;
169 /**
170 * Highlight the thread item(s) on the page associated with the URL hash or query string
171 *
172 * @param {ThreadItemSet} threadItemSet
173 * @param {boolean} [noScroll] Don't scroll to the topmost highlight, e.g. on popstate
174 * @return {Object} Object containing 'requested' IDs, 'requestedSince' ID, and successfully 'highligted' IDs
175 */
176 function highlightTargetComment( threadItemSet, noScroll ) {
177 if ( highlightedTarget ) {
178 highlightedTarget.destroy();
179 highlightedTarget = null;
180 }
181
182 const targetElement = mw.util.getTargetFromFragment();
183
184 if ( targetElement && targetElement.hasAttribute( 'data-mw-comment-start' ) ) {
185 const threadItemId = targetElement.getAttribute( 'id' );
186 const threadItem = threadItemSet.findCommentById( targetElement.getAttribute( 'id' ) );
187 if ( threadItem ) {
188 highlightedTarget = new Highlight( threadItem );
189 highlightedTarget.$element.addClass( 'ext-discussiontools-init-targetcomment' );
190 highlightedTarget.$element.addClass( 'ext-discussiontools-init-highlight-fadein' );
191 }
192 return {
193 requested: [ threadItemId ],
194 highlighted: [ threadItemId ]
195 };
196 }
197
198 // Single thread item not highlighted yet
199 if ( location.hash.match( /^#(c|h)-/ ) ) {
200 return {
201 requested: [ location.hash.slice( 1 ) ],
202 highlighted: []
203 };
204 }
205
206 const url = new URL( location.href );
207 return highlightNewComments(
208 threadItemSet,
209 noScroll,
210 url.searchParams.get( 'dtnewcomments' ) && url.searchParams.get( 'dtnewcomments' ).split( '|' ),
211 {
212 newCommentsSinceId: url.searchParams.get( 'dtnewcommentssince' ),
213 inThread: url.searchParams.get( 'dtinthread' ),
214 sinceThread: url.searchParams.get( 'dtsincethread' )
215 }
216 );
217 }
218
219 /**
220 * Highlight a just-published comment/topic
221 *
222 * These highlights show for a short period of time then tear themselves down.
223 *
224 * @param {ThreadItemSet} threadItemSet Thread item set
225 * @param {string} threadItemId Thread item ID (NEW_TOPIC_COMMENT_ID for the a new topic)
226 */
227 function highlightPublishedComment( threadItemSet, threadItemId ) {
228 const highlightComments = [];
229
230 if ( threadItemId === utils.NEW_TOPIC_COMMENT_ID ) {
231 // Highlight the last comment on the page
232 const lastComment = threadItemSet.threadItems[ threadItemSet.threadItems.length - 1 ];
233 lastHighlightedPublishedComment = lastComment;
234 highlightComments.push( lastComment );
235
236 // If it's the only comment under its heading, highlight the heading too.
237 // (It might not be if the new discussion topic was posted without a title: T272666.)
238 if (
239 lastComment.parent &&
240 lastComment.parent.type === 'heading' &&
241 lastComment.parent.replies.length === 1
242 ) {
243 highlightComments.push( lastComment.parent );
244 lastHighlightedPublishedComment = lastComment.parent;
245 // Change URL to point to this section, like the old section=new wikitext editor does.
246 // This also expands collapsed sections on mobile (T301840).
247 const sectionTitle = lastHighlightedPublishedComment.getLinkableTitle();
248 const urlFragment = mw.util.escapeIdForLink( sectionTitle );
249 // Navigate to fragment without scrolling
250 location.hash = '#' + urlFragment + '-DoesNotExist-DiscussionToolsHack';
251 history.replaceState( null, '', '#' + urlFragment );
252 }
253 } else {
254 // Find the comment we replied to, then highlight the last reply
255 const repliedToComment = threadItemSet.threadItemsById[ threadItemId ];
256 highlightComments.push( repliedToComment.replies[ repliedToComment.replies.length - 1 ] );
257 lastHighlightedPublishedComment = highlightComments[ 0 ];
258 }
259
260 // We may have changed the location hash on mobile, so wait for that to cause
261 // the section to expand before drawing the highlight.
262 setTimeout( () => {
263 const highlight = new Highlight( highlightComments );
264 highlight.$element.addClass( 'ext-discussiontools-init-publishedcomment' );
265
266 // Show a highlight with the same timing as the post-edit message (mediawiki.action.view.postEdit):
267 // show for 3000ms, fade out for 250ms (animation duration is defined in CSS).
268 OO.ui.Element.static.scrollIntoView(
269 highlight.topmostElement,
270 {
271 padding: {
272 // Add padding to avoid overlapping the post-edit notification (above on desktop, below on mobile)
273 top: OO.ui.isMobile() ? 10 : 60,
274 bottom: OO.ui.isMobile() ? 85 : 10
275 },
276 // Specify scrollContainer for compatibility with MobileFrontend.
277 // Apparently it makes `<dd>` elements scrollable and OOUI tried to scroll them instead of body.
278 scrollContainer: OO.ui.Element.static.getRootScrollableElement( highlight.topmostElement )
279 }
280 ).then( () => {
281 highlight.$element.addClass( 'ext-discussiontools-init-highlight-fadein' );
282 setTimeout( () => {
283 highlight.$element.addClass( 'ext-discussiontools-init-highlight-fadeout' );
284 setTimeout( () => {
285 // Remove the node when no longer needed, because it's using CSS 'mix-blend-mode', which
286 // affects the text rendering of the whole page, disabling subpixel antialiasing on Windows
287 highlight.destroy();
288 }, 250 );
289 }, 3000 );
290 } );
291 } );
292 }
293
294 /**
295 * Highlight the new comments on the page associated with the query string
296 *
297 * @param {ThreadItemSet} threadItemSet
298 * @param {boolean} [noScroll] Don't scroll to the topmost highlighted comment, e.g. on popstate
299 * @param {string[]} [newCommentIds] A list of comment IDs to highlight
300 * @param {Object} [options] Extra options
301 * @param {string} [options.newCommentsSinceId] Highlight all comments after the comment with this ID
302 * @param {boolean} [options.inThread] When using newCommentsSinceId, only highlight comments in the same thread
303 * @param {boolean} [options.sinceThread] When using newCommentsSinceId, only highlight comments in threads
304 * created since that comment was posted.
305 * @return {Object} Object containing 'requested' comment IDs, 'requestedSince' ID, and successfully 'highligted' IDs
306 */
307 function highlightNewComments( threadItemSet, noScroll, newCommentIds, options ) {
308 if ( highlightedTarget ) {
309 highlightedTarget.destroy();
310 highlightedTarget = null;
311 }
312
313 newCommentIds = newCommentIds || [];
314 options = options || {};
315
316 if ( options.newCommentsSinceId ) {
317 const newCommentsSince = threadItemSet.findCommentById( options.newCommentsSinceId );
318 if ( newCommentsSince && newCommentsSince instanceof CommentItem ) {
319 const sinceTimestamp = newCommentsSince.timestamp;
320 let threadItems;
321 if ( options.inThread ) {
322 const heading = newCommentsSince.getSubscribableHeading() || newCommentsSince.getHeading();
323 threadItems = heading.getThreadItemsBelow();
324 } else {
325 threadItems = threadItemSet.getCommentItems();
326 }
327 threadItems.forEach( ( threadItem ) => {
328 if (
329 threadItem instanceof CommentItem &&
330 threadItem.timestamp >= sinceTimestamp
331 ) {
332 if ( options.sinceThread ) {
333 // Check that we are in a thread that is newer than `sinceTimestamp`.
334 // Thread age is determined by looking at getOldestReply.
335 const itemHeading = threadItem.getSubscribableHeading() || threadItem.getHeading();
336 const oldestReply = itemHeading.getOldestReply();
337 if ( !( oldestReply && oldestReply.timestamp >= sinceTimestamp ) ) {
338 return;
339 }
340 }
341 newCommentIds.push( threadItem.id );
342 }
343 } );
344 }
345 }
346
347 let comments;
348 if ( newCommentIds.length ) {
349 comments = newCommentIds
350 .map( ( id ) => threadItemSet.findCommentById( id ) )
351 .filter( ( cmt ) => !!cmt );
352 if ( comments.length ) {
353 highlightedTarget = new Highlight( comments );
354 highlightedTarget.$element.addClass( 'ext-discussiontools-init-targetcomment' );
355 highlightedTarget.$element.addClass( 'ext-discussiontools-init-highlight-fadein' );
356
357 if ( !noScroll ) {
358 highlightedTarget.scrollIntoView();
359 }
360 }
361 }
362 return {
363 requested: newCommentIds,
364 requestedSince: options.newCommentsSinceId,
365 highlighted: comments || []
366 };
367 }
368
369 /**
370 * Clear the highlighting of the comment in the URL hash
371 *
372 * @param {ThreadItemSet} threadItemSet
373 */
374 function clearHighlightTargetComment( threadItemSet ) {
375 const url = new URL( location.href );
376
377 const targetElement = mw.util.getTargetFromFragment();
378
379 if ( targetElement && targetElement.hasAttribute( 'data-mw-comment-start' ) ) {
380 // Clear the hash from the URL, triggering the 'hashchange' event and updating the :target
381 // selector (so that our code to clear our highlight works), but without scrolling anywhere.
382 // This is tricky because:
383 // * Using history.pushState() does not trigger 'hashchange' or update the :target selector.
384 // https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#description
385 // https://github.com/whatwg/html/issues/639
386 // * Using location.hash does, but it also scrolls to the target, which is the top of the
387 // page for the empty hash.
388 // Instead, we first use location.hash to navigate to a *different* hash (whose target
389 // doesn't exist on the page, hopefully), and then use history.pushState() to clear it.
390 location.hash += '-DoesNotExist-DiscussionToolsHack';
391 url.hash = '';
392 history.replaceState( null, '', url );
393 } else if (
394 url.searchParams.has( 'dtnewcomments' ) ||
395 url.searchParams.has( 'dtnewcommentssince' )
396 ) {
397 url.searchParams.delete( 'dtnewcomments' );
398 url.searchParams.delete( 'dtnewcommentssince' );
399 url.searchParams.delete( 'dtinthread' );
400 url.searchParams.delete( 'dtsincethread' );
401 history.pushState( null, '', url );
402 highlightTargetComment( threadItemSet );
403 } else if ( highlightedTarget ) {
404 // Highlights were applied without changing the URL, e.g. when showing
405 // new comments while drafting. Just clear the highlights.
406 highlightedTarget.destroy();
407 highlightedTarget = null;
408 }
409 }
410
411 /**
412 * Get the last highlighted just-published comment, if any
413 *
414 * Used to show an auto-subscription popup to first-time users
415 *
416 * @return {ThreadItem|null}
417 */
418 function getLastHighlightedPublishedComment() {
419 return lastHighlightedPublishedComment;
420 }
421
422 module.exports = {
423 highlightTargetComment: highlightTargetComment,
424 highlightPublishedComment: highlightPublishedComment,
425 highlightNewComments: highlightNewComments,
426 clearHighlightTargetComment: clearHighlightTargetComment,
427 getLastHighlightedPublishedComment: getLastHighlightedPublishedComment
428 };