Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/preinit/ve.utils.parsoid.js

raw symbols SCIP
1 /*!
2 * Parsoid utilities.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 mw.libs.ve = mw.libs.ve || {};
8
9 /**
10 * Decode a URI component into a mediawiki article title
11 *
12 * N.B. Illegal article titles can result from fairly reasonable input (e.g. "100%25beef");
13 * see https://phabricator.wikimedia.org/T137847 .
14 *
15 * @param {string} s String to decode
16 * @param {boolean} [preserveUnderscores=false] Don't convert underscores to spaces
17 * @return {string} Decoded string, or original string if decodeURIComponent failed
18 */
19 mw.libs.ve.decodeURIComponentIntoArticleTitle = function ( s, preserveUnderscores ) {
20 try {
21 s = decodeURIComponent( s );
22 } catch ( e ) {
23 return s;
24 }
25 if ( preserveUnderscores ) {
26 return s;
27 }
28 return s.replace( /_/g, ' ' );
29 };
30
31 /**
32 * Unwrap Parsoid sections
33 *
34 * data-mw-section-id attributes are copied to the first child (the heading) during
35 * this step so that we can place the cursor in the correct place when section editing.
36 * These attributes **must be removed** before being sent back to Parsoid to avoid
37 * unnecessary re-serialization.
38 *
39 * @param {HTMLElement} element Parent element, e.g. document body
40 * @param {string} [keepSection] Section to keep
41 */
42 mw.libs.ve.unwrapParsoidSections = function ( element, keepSection ) {
43 Array.prototype.forEach.call( element.querySelectorAll( 'section[data-mw-section-id]' ), ( section ) => {
44 const parent = section.parentNode,
45 sectionId = section.getAttribute( 'data-mw-section-id' );
46 // Copy section ID to first child (should be a heading)
47 // Pseudo-sections (with negative section IDs) may not have a heading
48 if ( sectionId !== null && +sectionId > 0 ) {
49 section.firstChild.setAttribute( 'data-mw-section-id', sectionId );
50 }
51 if ( keepSection !== undefined && sectionId === keepSection ) {
52 return;
53 }
54 while ( section.firstChild ) {
55 parent.insertBefore( section.firstChild, section );
56 }
57 parent.removeChild( section );
58 } );
59 };
60
61 /**
62 * Strip legacy (non-HTML5) IDs; typically found as section IDs inside
63 * headings.
64 *
65 * @param {HTMLElement} element Parent element, e.g. document body
66 */
67 mw.libs.ve.stripParsoidFallbackIds = function ( element ) {
68 Array.prototype.forEach.call( element.querySelectorAll( 'span[typeof="mw:FallbackId"][id]:empty' ), ( legacySpan ) => {
69 legacySpan.parentNode.removeChild( legacySpan );
70 } );
71 };
72
73 mw.libs.ve.restbaseIdRegExp = /^mw[a-zA-Z0-9\-_]{2,6}$/;
74
75 mw.libs.ve.stripRestbaseIds = function ( doc ) {
76 const restbaseIdRegExp = mw.libs.ve.restbaseIdRegExp;
77 Array.prototype.forEach.call( doc.querySelectorAll( '[id^="mw"]' ), ( element ) => {
78 if ( restbaseIdRegExp.test( element.id ) ) {
79 element.removeAttribute( 'id' );
80 }
81 } );
82 };
83
84 /**
85 * Re-duplicate deduplicated TemplateStyles, for correct rendering when editing a section or
86 * when templates are removed during the edit.
87 *
88 * @param {HTMLElement} element Parent element, e.g. document body
89 */
90 mw.libs.ve.reduplicateStyles = function ( element ) {
91 Array.prototype.forEach.call( element.querySelectorAll( 'link[rel~="mw-deduplicated-inline-style"]' ), ( link ) => {
92 const href = link.getAttribute( 'href' );
93 if ( !href || href.slice( 0, 'mw-data:'.length ) !== 'mw-data:' ) {
94 return;
95 }
96 const key = href.slice( 'mw-data:'.length );
97 const style = element.querySelector( 'style[data-mw-deduplicate="' + key + '"]' );
98 if ( !style ) {
99 return;
100 }
101
102 const newStyle = link.ownerDocument.createElement( 'style' );
103 newStyle.setAttribute( 'data-mw-deduplicate', key );
104
105 // Copy content from the old `style` node (for rendering)
106 for ( let i = 0; i < style.childNodes.length; i++ ) {
107 newStyle.appendChild( style.childNodes[ i ].cloneNode( true ) );
108 }
109 // Copy attributes from the old `link` node (for selser)
110 Array.prototype.forEach.call( link.attributes, ( attr ) => {
111 if ( attr.name !== 'rel' && attr.name !== 'href' ) {
112 newStyle.setAttribute( attr.name, attr.value );
113 }
114 } );
115
116 link.parentNode.replaceChild( newStyle, link );
117 } );
118
119 Array.prototype.forEach.call( element.querySelectorAll( 'style[data-mw-deduplicate]:empty' ), ( style ) => {
120 const key = style.getAttribute( 'data-mw-deduplicate' );
121 const firstStyle = element.querySelector( 'style[data-mw-deduplicate="' + key + '"]' );
122 if ( !firstStyle || firstStyle === style ) {
123 return;
124 }
125
126 // Copy content from the first matching `style` node (for rendering)
127 for ( let i = 0; i < firstStyle.childNodes.length; i++ ) {
128 style.appendChild( firstStyle.childNodes[ i ].cloneNode( true ) );
129 }
130 } );
131 };
132
133 /**
134 * De-duplicate TemplateStyles, like Parsoid does.
135 *
136 * @param {HTMLElement} element Parent element, e.g. document body
137 */
138 mw.libs.ve.deduplicateStyles = function ( element ) {
139 /**
140 * Check whether `node` is in a fosterable position. (Nodes in these positions may be moved
141 * elsewhere in the DOM by the HTML5 parsing algorithm, if they don't have the right tag name.)
142 * https://html.spec.whatwg.org/#appropriate-place-for-inserting-a-node
143 *
144 * @private
145 * @param {Node|null} node
146 * @return {boolean}
147 */
148 function isFosterablePosition( node ) {
149 const fosterablePositions = [ 'table', 'thead', 'tbody', 'tfoot', 'tr' ];
150 return node && fosterablePositions.indexOf( node.parentNode.nodeName.toLowerCase() ) !== -1;
151 }
152
153 const styleTagKeys = {};
154
155 Array.prototype.forEach.call( element.querySelectorAll( 'style[data-mw-deduplicate]' ), ( style ) => {
156 const key = style.getAttribute( 'data-mw-deduplicate' );
157
158 if ( !styleTagKeys[ key ] ) {
159 // Not a dupe
160 styleTagKeys[ key ] = true;
161 return;
162 }
163
164 if ( !isFosterablePosition( style ) ) {
165 // Dupe - replace with a placeholder <link> reference
166 const link = style.ownerDocument.createElement( 'link' );
167 link.setAttribute( 'rel', 'mw-deduplicated-inline-style' );
168 link.setAttribute( 'href', 'mw-data:' + key );
169
170 // Copy attributes from the old `link` node (for selser)
171 Array.prototype.forEach.call( style.attributes, ( attr ) => {
172 if ( attr.name !== 'rel' && attr.name !== 'data-mw-deduplicate' ) {
173 link.setAttribute( attr.name, attr.value );
174 }
175 } );
176
177 style.parentNode.replaceChild( link, style );
178 } else {
179 // Duplicate style tag found in fosterable position.
180 // Not deduping it (to avoid corruption when the resulting HTML is parsed: T299767),
181 // but emptying out the style tag for consistency with Parsoid.
182 // Parsoid says it does this for performance reasons.
183 style.innerHTML = '';
184 }
185 } );
186 };
187
188 /**
189 * Fix fragment links which should be relative to the current document
190 *
191 * This prevents these links from trying to navigate to another page,
192 * or open in a new window.
193 *
194 * Call this after ve.targetLinksToNewWindow, as it removes the target attribute.
195 * Call this after LinkCache.styleParsoidElements, as it breaks that method by including the query string.
196 *
197 * @param {HTMLElement} container Parent element, e.g. document body
198 * @param {mw.Title} docTitle Current title, only links to this title will be normalized
199 * @param {string} [prefix] Prefix to add to fragment and target ID to avoid collisions
200 */
201 mw.libs.ve.fixFragmentLinks = function ( container, docTitle, prefix ) {
202 const docTitleText = docTitle.getPrefixedText();
203 prefix = prefix || '';
204 Array.prototype.forEach.call( container.querySelectorAll( 'a[href*="#"]' ), ( el ) => {
205 let fragment = null;
206 if ( el.getAttribute( 'href' )[ 0 ] === '#' ) {
207 // Legacy parser
208 fragment = el.getAttribute( 'href' ).slice( 1 );
209 } else {
210 // Parsoid HTML
211 const targetData = mw.libs.ve.getTargetDataFromHref( el.href, el.ownerDocument );
212
213 if ( targetData.isInternal ) {
214 const title = mw.Title.newFromText( targetData.title );
215 if ( title && title.getPrefixedText() === docTitleText ) {
216 fragment = new URL( el.href ).hash.slice( 1 );
217 }
218 }
219 }
220
221 if ( fragment !== null ) {
222 if ( !fragment ) {
223 // Special case for empty fragment, even if prefix set
224 el.setAttribute( 'href', '#' );
225 } else {
226 if ( prefix ) {
227 const target = container.querySelector( '#' + $.escapeSelector( fragment ) );
228 // There may be multiple links to a specific target, so check the target
229 // hasn't already been fixed (in which case it would be null)
230 if ( target ) {
231 target.setAttribute( 'id', prefix + fragment );
232 target.setAttribute( 'data-mw-id-fixed', '' );
233 }
234 }
235 el.setAttribute( 'href', '#' + prefix + fragment );
236 }
237 el.removeAttribute( 'target' );
238 }
239 } );
240 // Remove any section heading anchors which weren't fixed above (T218492)
241 Array.prototype.forEach.call( container.querySelectorAll( 'h1, h2, h3, h4, h5, h6' ), ( el ) => {
242 if ( el.hasAttribute( 'id' ) && !el.hasAttribute( 'data-mw-id-fixed' ) ) {
243 el.removeAttribute( 'id' );
244 }
245 } );
246 };
247
248 /**
249 * @typedef {Object} TargetData
250 * @memberof mw.libs.ve
251 * @property {string} title The title of the internal link (if the href is internal)
252 * @property {boolean} isInternal True if the href pointed to the local wiki, false if href is external
253 */
254
255 /**
256 * Parse URL to get title it points to.
257 *
258 * @param {string} href
259 * @param {HTMLDocument} doc Document whose base URL to use
260 * @return {mw.libs.ve.TargetData} Information about the given href
261 */
262 mw.libs.ve.getTargetDataFromHref = function ( href, doc ) {
263 function regexEscape( str ) {
264 return str.replace( /([.?*+^$[\]\\(){}|-])/g, '\\$1' );
265 }
266
267 function returnExternalData() {
268 return { isInternal: false };
269 }
270
271 function returnInternalData( titleish ) {
272 // This value doesn't necessarily come from Parsoid (and it might not have the "./" prefix), but
273 // this method will work fine.
274 const data = mw.libs.ve.parseParsoidResourceName( titleish );
275 data.isInternal = true;
276 return data;
277 }
278
279 let url;
280 try {
281 url = new URL( href, doc.baseURI );
282 } catch ( e ) {
283 // An invalid URL was provided (e.g. `https://`)
284 return returnExternalData();
285 }
286
287 // Equivalent to `ve.init.platform.getExternalLinkUrlProtocolsRegExp()`, which can not be called here
288 const externalLinkUrlProtocolsRegExp = new RegExp( '^(' + mw.config.get( 'wgUrlProtocols' ) + ')', 'i' );
289 // We don't want external links that don't start with a registered external URL protocol
290 // (to avoid generating 'javascript:' URLs), so treat it as internal
291 if ( !externalLinkUrlProtocolsRegExp.test( url.toString() ) ) {
292 return returnInternalData( url.toString() );
293 }
294
295 // Strip red link query parameters
296 if ( url.searchParams.get( 'action' ) === 'edit' && url.searchParams.get( 'redlink' ) === '1' ) {
297 url.searchParams.delete( 'action' );
298 url.searchParams.delete( 'redlink' );
299 }
300 // Count remaining query parameters
301 const keys = [];
302 url.searchParams.forEach( ( val, key ) => {
303 keys.push( key );
304 } );
305 const queryLength = keys.length;
306
307 const relativeHref = url.toString().replace( /^https?:/i, '' );
308 // Check if this matches the server's script path (as used by red links)
309 const scriptBase = new URL( mw.config.get( 'wgScript' ), doc.baseURI ).toString().replace( /^https?:/i, '' );
310 if ( relativeHref.indexOf( scriptBase ) === 0 ) {
311 if ( queryLength === 1 && url.searchParams.get( 'title' ) ) {
312 return returnInternalData( url.searchParams.get( 'title' ) + url.hash );
313 }
314 }
315
316 // Check if this matches the server's article path
317 const articleBase = new URL( mw.config.get( 'wgArticlePath' ), doc.baseURI ).toString().replace( /^https?:/i, '' );
318 const articleBaseRegex = new RegExp( regexEscape( articleBase ).replace( regexEscape( '$1' ), '(.*)' ) );
319 const matches = relativeHref.match( articleBaseRegex );
320 if ( matches ) {
321 if ( queryLength === 0 && matches && matches[ 1 ].split( '#' )[ 0 ].indexOf( '?' ) === -1 ) {
322 // Take the relative path
323 return returnInternalData( matches[ 1 ] );
324 }
325 }
326
327 // Doesn't match any of the known URL patterns, or has extra parameters
328 return returnExternalData();
329 };
330
331 /**
332 * Encode a page title into a Parsoid resource name.
333 *
334 * @param {string} title
335 * @return {string}
336 */
337 mw.libs.ve.encodeParsoidResourceName = function ( title ) {
338 // Parsoid: Sanitizer::sanitizeTitleURI, Env::makeLink
339 const idx = title.indexOf( '#' );
340 let anchor = null;
341 if ( idx !== -1 ) {
342 anchor = title.slice( idx + 1 );
343 title = title.slice( 0, idx );
344 }
345 let encodedTitle = title.replace( /[%? [\]#|<>]/g, ( match ) => mw.util.wikiUrlencode( match ) );
346 if ( anchor !== null ) {
347 encodedTitle += '#' + mw.util.escapeIdForLink( anchor );
348 }
349 return './' + encodedTitle;
350 };
351
352 /**
353 * @typedef ParsedResource
354 * @memberof mw.libs.ve
355 * @property {string} title Full page title in text form (with namespace, and spaces instead of underscores)
356 */
357
358 /**
359 * Split Parsoid resource name into the href prefix and the page title.
360 *
361 * @param {string} resourceName Resource name, from a `href` or `resource` attribute
362 * @return {mw.libs.ve.ParsedResource} Parsed resource name
363 */
364 mw.libs.ve.parseParsoidResourceName = function ( resourceName ) {
365 // Resource names are always prefixed with './' to prevent the MediaWiki namespace from being
366 // interpreted as a URL protocol, consider e.g. 'href="./File:Foo.png"'.
367 // (We accept input without the prefix, so this can also take plain page titles.)
368 const matches = resourceName.match( /^(\.\/|)(.*)$/ );
369 return {
370 // '%' and '?' are valid in page titles, but normally URI-encoded. This also changes underscores
371 // to spaces.
372 title: mw.libs.ve.decodeURIComponentIntoArticleTitle( matches[ 2 ] )
373 };
374 };
375
376 /**
377 * Extract the page title from a Parsoid resource name.
378 *
379 * @param {string} resourceName Resource name, from a `href` or `resource` attribute
380 * @return {string} Full page title in text form (with namespace, and spaces instead of underscores)
381 */
382 mw.libs.ve.normalizeParsoidResourceName = function ( resourceName ) {
383 return mw.libs.ve.parseParsoidResourceName( resourceName ).title;
384 };