Debian Codegraph @

extensions/DiscussionTools/modules/modifier.js

raw symbols SCIP
1 'use strict';
2 /* global $:off */
3
4 const
5 utils = require( './utils.js' );
6
7 /**
8 * Remove extra linebreaks from a wikitext string
9 *
10 * @param {string} wikitext Wikitext
11 * @return {string}
12 */
13 function sanitizeWikitextLinebreaks( wikitext ) {
14 return utils.htmlTrim( wikitext )
15 .replace( /\r/g, '\n' )
16 .replace( /\n+/g, '\n' );
17 }
18
19 /**
20 * Given a comment and a reply link, add the reply link to its document's DOM tree, at the end of
21 * the comment.
22 *
23 * @param {CommentItem} comment Comment item
24 * @param {HTMLElement} linkNode Reply link
25 */
26 function addReplyLink( comment, linkNode ) {
27 const target = comment.range.endContainer;
28
29 // Insert the link before trailing whitespace.
30 // In the MediaWiki parser output, <ul>/<dl> nodes are preceded by a newline. Normally it isn't
31 // visible on the page. But if we insert an inline element (the reply link) after it, it becomes
32 // meaningful and gets rendered, which results in additional spacing before some reply links.
33 // Split the text node, so that we can insert the link before the trailing whitespace.
34 if ( target.nodeType === Node.TEXT_NODE ) {
35 target.splitText( target.textContent.match( /\s*$/ ).index );
36 }
37
38 target.parentNode.insertBefore( linkNode, target.nextSibling );
39 }
40
41 /**
42 * Given a comment, add a list item to its document's DOM tree, inside of which a reply to said
43 * comment can be added.
44 *
45 * The DOM tree is suitably rearranged to ensure correct indentation level of the reply (wrapper
46 * nodes are added, and other nodes may be moved around).
47 *
48 * @param {CommentItem} comment Comment item
49 * @param {string} replyIndentation Reply indentation syntax to use, one of:
50 * - 'invisible' (use `<dl><dd>` tags to output `:` in wikitext)
51 * - 'bullet' (use `<ul><li>` tags to output `*` in wikitext)
52 * @return {HTMLElement}
53 */
54 function addListItem( comment, replyIndentation ) {
55 const listTypeMap = {
56 li: 'ul',
57 dd: 'dl'
58 };
59
60 // 1. Start at given comment
61 // 2. Skip past all comments with level greater than the given
62 // (or in other words, all replies, and replies to replies, and so on)
63 // 3. Add comment with level of the given comment plus 1
64
65 let curComment = comment;
66 while ( curComment.replies.length ) {
67 curComment = curComment.replies[ curComment.replies.length - 1 ];
68 }
69
70 // Tag names for lists and items we're going to insert
71 let itemType;
72 if ( replyIndentation === 'invisible' ) {
73 itemType = 'dd';
74 } else if ( replyIndentation === 'bullet' ) {
75 itemType = 'li';
76 } else {
77 throw new Error( "Invalid reply indentation syntax '" + replyIndentation + "'" );
78 }
79 const listType = listTypeMap[ itemType ];
80
81 const desiredLevel = comment.level + 1;
82 let target = curComment.range.endContainer;
83
84 // target is a text node or an inline element at the end of a "paragraph" (not necessarily paragraph node).
85 // First, we need to find a block-level parent that we can mess with.
86 // If we can't find a surrounding list item or paragraph (e.g. maybe we're inside a table cell
87 // or something), take the parent node and hope for the best.
88 let parent = utils.closestElement( target, [ 'li', 'dd', 'p' ] ) || target.parentNode;
89 while ( target.parentNode !== parent ) {
90 target = target.parentNode;
91 }
92 // parent is a list item or paragraph (hopefully)
93 // target is an inline node within it
94
95 // If the comment is fully covered by some wrapper element, insert replies outside that wrapper.
96 // This will often just be a paragraph node (<p>), but it can be a <div> or <table> that serves
97 // as some kind of a fancy frame, which are often used for barnstars and announcements.
98 const excludedWrapper = utils.closestElement( target, [ 'section' ] ) ||
99 curComment.rootNode;
100 const covered = utils.getFullyCoveredSiblings( curComment, excludedWrapper );
101 if ( curComment.level === 1 && covered ) {
102 target = covered[ covered.length - 1 ];
103 parent = target.parentNode;
104 }
105
106 // If the comment is in a transclusion, insert replies after the transclusion. (T313100)
107 // This method should never be called in cases where that would be a bad idea.
108 let transclusionNode = utils.getTranscludedFromElement( target );
109 if ( transclusionNode ) {
110 while (
111 transclusionNode.nextSibling &&
112 transclusionNode.nextSibling.nodeType === Node.ELEMENT_NODE &&
113 transclusionNode.nextSibling.getAttribute( 'about' ) === transclusionNode.getAttribute( 'about' )
114 ) {
115 transclusionNode = transclusionNode.nextSibling;
116 }
117 target = transclusionNode;
118 parent = target.parentNode;
119 }
120
121 // If we can't insert a list directly inside this element, insert after it.
122 // The covered wrapper check above handles most cases, but we still need this sometimes, such as:
123 // * If the comment starts in the middle of a list, then ends with an unindented p/pre, the
124 // wrapper check doesn't adjust the parent
125 // * If the comment consists of multiple list items (starting with a <dt>, so that the comment is
126 // considered to be unindented, that is level === 1), but not all of them, the wrapper check
127 // adjusts the parent to be the list, and the rest of the algorithm doesn't handle that well
128 if (
129 parent.tagName.toLowerCase() === 'p' ||
130 parent.tagName.toLowerCase() === 'pre' ||
131 parent.tagName.toLowerCase() === 'ul' ||
132 parent.tagName.toLowerCase() === 'dl'
133 ) {
134 parent = parent.parentNode;
135 target = target.parentNode;
136 }
137
138 // HACK: Skip past our own reply buttons
139 if ( target.nextSibling && target.nextSibling.nodeType === Node.ELEMENT_NODE && target.nextSibling.classList.contains( 'ext-discussiontools-init-replylink-buttons' ) ) {
140 target = target.nextSibling;
141 }
142
143 // Instead of just using curComment.level, consider indentation of lists within the
144 // comment (T252702)
145 let curLevel = utils.getIndentLevel( target, curComment.rootNode ) + 1;
146
147 let item, list;
148 if ( desiredLevel === 1 ) {
149 // Special handling for top-level comments
150 item = target.ownerDocument.createElement( 'div' );
151 item.discussionToolsModified = 'new';
152 parent.insertBefore( item, target.nextSibling );
153 // TODO: We should not insert a <div>, instead we need a function that returns parent and target,
154 // so that we can insert nodes in this place in other code
155
156 } else if ( curLevel < desiredLevel ) {
157 // Insert more lists after the target to increase nesting.
158
159 // Parsoid puts HTML comments (and other "rendering-transparent nodes", e.g. category links)
160 // which appear at the end of the line in wikitext outside the paragraph,
161 // but we usually shouldn't insert replies between the paragraph and such comments. (T257651)
162 // Skip over comments and whitespace, but only update target when skipping past comments.
163 let pointer = target;
164 while (
165 pointer.nextSibling && (
166 utils.isRenderingTransparentNode( pointer.nextSibling ) ||
167 (
168 pointer.nextSibling.nodeType === Node.TEXT_NODE &&
169 utils.htmlTrim( pointer.nextSibling.textContent ) === '' &&
170 // If at least two lines of whitespace are detected, the following HTML
171 // comments are not considered to be part of the reply (T264026, T301214)
172 !/\n[^\n]*\n/.test( pointer.nextSibling.textContent )
173 )
174 )
175 ) {
176 pointer = pointer.nextSibling;
177 if ( utils.isRenderingTransparentNode( pointer ) ) {
178 target = pointer;
179 }
180 }
181
182 // Insert required number of wrappers
183 while ( curLevel < desiredLevel ) {
184 list = target.ownerDocument.createElement( listType );
185 list.discussionToolsModified = 'new';
186 item = target.ownerDocument.createElement( itemType );
187 item.discussionToolsModified = 'new';
188
189 parent.insertBefore( list, target.nextSibling );
190 list.appendChild( item );
191
192 target = item;
193 parent = list;
194 curLevel++;
195 }
196 } else {
197 // Split the ancestor nodes after the target to decrease nesting.
198
199 let newNode;
200 do {
201 if ( !target || !parent ) {
202 throw new Error( 'Can not decrease nesting any more' );
203 }
204
205 // If target is the last child of its parent, no need to split it
206 if ( target.nextSibling ) {
207 // Create new identical node after the parent
208 newNode = parent.cloneNode( false );
209 parent.discussionToolsModified = 'split';
210 parent.parentNode.insertBefore( newNode, parent.nextSibling );
211
212 // Move nodes following target to the new node
213 while ( target.nextSibling ) {
214 newNode.appendChild( target.nextSibling );
215 }
216 }
217
218 target = parent;
219 parent = parent.parentNode;
220
221 // Decrease nesting level if we escaped outside of a list
222 if ( listTypeMap[ target.tagName.toLowerCase() ] ) {
223 curLevel--;
224 }
225 } while ( curLevel >= desiredLevel );
226
227 // parent is now a list, target is a list item
228 if ( itemType === target.tagName.toLowerCase() ) {
229 item = target.ownerDocument.createElement( itemType );
230 item.discussionToolsModified = 'new';
231 parent.insertBefore( item, target.nextSibling );
232
233 } else {
234 // This is the wrong type of list, split it one more time
235
236 // If target is the last child of its parent, no need to split it
237 if ( target.nextSibling ) {
238 // Create new identical node after the parent
239 newNode = parent.cloneNode( false );
240 parent.discussionToolsModified = 'split';
241 parent.parentNode.insertBefore( newNode, parent.nextSibling );
242
243 // Move nodes following target to the new node
244 while ( target.nextSibling ) {
245 newNode.appendChild( target.nextSibling );
246 }
247 }
248
249 target = parent;
250 parent = parent.parentNode;
251
252 // Insert a list of the right type in the middle
253 list = target.ownerDocument.createElement( listType );
254 list.discussionToolsModified = 'new';
255 item = target.ownerDocument.createElement( itemType );
256 item.discussionToolsModified = 'new';
257
258 parent.insertBefore( list, target.nextSibling );
259 list.appendChild( item );
260 }
261 }
262
263 return item;
264 }
265
266 /**
267 * Undo the effects of #addListItem, also removing or merging any affected parent nodes.
268 *
269 * @param {HTMLElement} node
270 */
271 function removeAddedListItem( node ) {
272 while ( node && node.discussionToolsModified ) {
273 let nextNode;
274 if ( node.discussionToolsModified === 'new' ) {
275 nextNode = node.previousSibling || node.parentNode;
276
277 // Remove this node
278 delete node.discussionToolsModified;
279 node.parentNode.removeChild( node );
280
281 } else if ( node.discussionToolsModified === 'split' ) {
282 // Children might be split too, if so, descend into them afterwards
283 if ( node.lastChild && node.lastChild.discussionToolsModified === 'split' ) {
284 node.discussionToolsModified = 'done';
285 nextNode = node.lastChild;
286 } else {
287 delete node.discussionToolsModified;
288 nextNode = node.parentNode;
289 }
290 // Merge the following sibling node back into this one
291 while ( node.nextSibling.firstChild ) {
292 node.appendChild( node.nextSibling.firstChild );
293 }
294 node.parentNode.removeChild( node.nextSibling );
295
296 } else {
297 nextNode = node.parentNode;
298 }
299
300 node = nextNode;
301 }
302 }
303
304 /**
305 * Unwrap a top level list, converting list item text to paragraphs
306 *
307 * Assumes that the list has a parent node.
308 *
309 * @param {Node} list DOM node, will be wrapped if it is a list element (dl/ol/ul)
310 * @param {DocumentFragment|null} fragment Containing document fragment if list has no parent
311 */
312 function unwrapList( list, fragment ) {
313 if ( !(
314 list.nodeType === Node.ELEMENT_NODE && (
315 list.tagName.toLowerCase() === 'dl' ||
316 list.tagName.toLowerCase() === 'ol' ||
317 list.tagName.toLowerCase() === 'ul'
318 )
319 ) ) {
320 // Not a list, leave alone (e.g. auto-generated ref block)
321 return;
322 }
323
324 // If the whole list is a template return it unmodified (T253150)
325 if ( utils.getTranscludedFromElement( list ) ) {
326 return;
327 }
328
329 const doc = list.ownerDocument;
330 const container = fragment || list.parentNode;
331 let referenceNode = list;
332 while ( list.firstChild ) {
333 if ( list.firstChild.nodeType === Node.ELEMENT_NODE ) {
334 // Move <dd> contents to <p>
335 let p = doc.createElement( 'p' );
336 while ( list.firstChild.firstChild ) {
337 // If contents is a block element, place outside the paragraph
338 // and start a new paragraph after
339 if ( utils.isBlockElement( list.firstChild.firstChild ) ) {
340 if ( p.firstChild ) {
341 const insertBefore2 = referenceNode.nextSibling;
342 referenceNode = p;
343 container.insertBefore( p, insertBefore2 );
344 }
345 const insertBefore = referenceNode.nextSibling;
346 referenceNode = list.firstChild.firstChild;
347 container.insertBefore( list.firstChild.firstChild, insertBefore );
348 p = doc.createElement( 'p' );
349 } else {
350 p.appendChild( list.firstChild.firstChild );
351 }
352 }
353 if ( p.firstChild ) {
354 const insertBefore = referenceNode.nextSibling;
355 referenceNode = p;
356 container.insertBefore( p, insertBefore );
357 }
358 list.removeChild( list.firstChild );
359 } else {
360 // Text node / comment node, probably empty
361 const insertBefore = referenceNode.nextSibling;
362 referenceNode = list.firstChild;
363 container.insertBefore( list.firstChild, insertBefore );
364 }
365 }
366 container.removeChild( list );
367 }
368
369 /**
370 * Add another list item after the given one.
371 *
372 * @param {HTMLElement} previousItem
373 * @return {HTMLElement}
374 */
375 function addSiblingListItem( previousItem ) {
376 const listItem = previousItem.ownerDocument.createElement( previousItem.tagName );
377 previousItem.parentNode.insertBefore( listItem, previousItem.nextSibling );
378 return listItem;
379 }
380
381 module.exports = {
382 addReplyLink: addReplyLink,
383 addListItem: addListItem,
384 removeAddedListItem: removeAddedListItem,
385 addSiblingListItem: addSiblingListItem,
386 unwrapList: unwrapList,
387 sanitizeWikitextLinebreaks: sanitizeWikitextLinebreaks
388 };