4 config
= require( './config.json' );
6 require( './jquery.accessKeyLabel.js' );
9 * Encode the string like PHP's rawurlencode
12 * @param {string} str String to be encoded.
13 * @return {string} Encoded string
15 function rawurlencode( str
) {
16 return encodeURIComponent( String( str
) )
17 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
18 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
22 * Private helper function used by util.escapeId*()
25 * @param {string} str String to be encoded
26 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
27 * in DefaultSettings.php
28 * @return {string} Encoded string
30 function escapeIdInternal( str, mode ) {
35 return str.replace( / /g, '_
' );
37 return rawurlencode( str.replace( / /g, '_
' ) )
38 .replace( /%3A/g, ':' )
39 .replace( /%/g, '.' );
41 throw new Error( 'Unrecognized ID escaping mode
' + mode );
53 * Encode the string like PHP's rawurlencode
55 * @param
{string
} str String to be encoded
.
56 * @return {string
} Encoded string
58 rawurlencode
: rawurlencode
,
61 * Encode a string as CSS id, for use as HTML id attribute value.
63 * Analog to `Sanitizer::escapeIdForAttribute()` in PHP.
66 * @param {string} str String to encode
67 * @return {string} Encoded string
69 escapeIdForAttribute: function ( str
) {
70 return escapeIdInternal( str
, config
.FragmentMode
[ 0 ] );
74 * Encode a string as URL fragment, for use as HTML anchor link.
76 * Analog to `Sanitizer::escapeIdForLink()` in PHP.
79 * @param {string} str String to encode
80 * @return {string} Encoded string
82 escapeIdForLink: function ( str
) {
83 return escapeIdInternal( str
, config
.FragmentMode
[ 0 ] );
87 * Return a wrapper function that is debounced for the given duration.
89 * When it is first called, a timeout is scheduled. If before the timer
90 * is reached the wrapper is called again, it gets rescheduled for the
91 * same duration from now until it stops being called. The original function
92 * is called from the "tail" of such chain, with the last set of arguments.
95 * @param {number} delay Time in milliseconds
96 * @param {Function} callback
99 debounce: function ( delay
, callback
) {
102 clearTimeout( timeout
);
103 timeout
= setTimeout( Function
.prototype.apply
.bind( callback
, this, arguments
), delay
);
108 * Encode page titles for use in a URL
110 * We want / and : to be included as literal characters in our title URLs
111 * as they otherwise fatally break the title.
113 * The others are decoded because we can, it's prettier and matches behaviour
114 * of `wfUrlencode` in PHP.
116 * @param {string} str String to be encoded.
117 * @return {string} Encoded string
119 wikiUrlencode: function ( str
) {
120 return util
.rawurlencode( str
)
121 .replace( /%20/g, '_' )
122 // wfUrlencode replacements
123 .replace( /%3B/g, ';' )
124 .replace( /%40/g, '@' )
125 .replace( /%24/g, '$' )
126 .replace( /%21/g, '!' )
127 .replace( /%2A/g, '*' )
128 .replace( /%28/g, '(' )
129 .replace( /%29/g, ')' )
130 .replace( /%2C/g, ',' )
131 .replace( /%2F/g, '/' )
132 .replace( /%7E/g, '~' )
133 .replace( /%3A/g, ':' );
137 * Get the link to a page name (relative to `wgServer`),
139 * @param {string|null} [pageName=wgPageName] Page name
140 * @param {Object} [params] A mapping of query parameter names to values,
141 * e.g. `{ action: 'edit' }`
142 * @return {string} Url of the page with name of `pageName`
144 getUrl: function ( pageName
, params
) {
145 var fragmentIdx
, url
, query
, fragment
,
146 title
= typeof pageName
=== 'string' ? pageName
: mw
.config
.get( 'wgPageName' );
149 fragmentIdx
= title
.indexOf( '#' );
150 if ( fragmentIdx
!== -1 ) {
151 fragment
= title
.slice( fragmentIdx
+ 1 );
152 // Exclude the fragment from the page name
153 title
= title
.slice( 0, fragmentIdx
);
156 // Produce query string
158 query
= $.param( params
);
162 util
.wikiScript() + '?title=' + util
.wikiUrlencode( title
) + '&' + query
:
163 util
.wikiScript() + '?' + query
;
165 url
= mw
.config
.get( 'wgArticlePath' )
166 .replace( '$1', util
.wikiUrlencode( title
).replace( /\$/g, '$$$$' ) );
169 // Append the encoded fragment
170 if ( fragment
&& fragment
.length
) {
171 url
+= '#' + util
.escapeIdForLink( fragment
);
178 * Get URL to a MediaWiki entry point.
181 * @param {string} [str="index"] Name of MW entry point (e.g. 'index' or 'api')
182 * @return {string} URL to the script file (e.g. '/w/api.php' )
184 wikiScript: function ( str
) {
185 if ( !str
|| str
=== 'index' ) {
186 return mw
.config
.get( 'wgScript' );
187 } else if ( str
=== 'load' ) {
188 return config
.LoadScript
;
190 return mw
.config
.get( 'wgScriptPath' ) + '/' + str
+ '.php';
195 * Append a new style block to the head and return the CSSStyleSheet object.
196 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
197 * This function returns the styleSheet object for convience (due to cross-browsers
198 * difference as to where it is located).
200 * var sheet = util.addCSS( '.foobar { display: none; }' );
201 * $( foo ).click( function () {
202 * // Toggle the sheet on and off
203 * sheet.disabled = !sheet.disabled;
206 * @param {string} text CSS to be appended
207 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
209 addCSS: function ( text
) {
210 var s
= mw
.loader
.addStyleTag( text
);
215 * Grab the URL parameter value for the given parameter.
216 * Returns null if not found.
218 * @param {string} param The parameter name.
219 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
220 * @return {Mixed} Parameter value or null.
222 getParamValue: function ( param
, url
) {
223 // Get last match, stop at hash
224 var re
= new RegExp( '^[^#]*[&?]' + util
.escapeRegExp( param
) + '=([^&#]*)' ),
225 m
= re
.exec( url
!== undefined ? url
: location
.href
);
228 // Beware that decodeURIComponent is not required to understand '+'
229 // by spec, as encodeURIComponent does not produce it.
230 return decodeURIComponent( m
[ 1 ].replace( /\+/g, '%20' ) );
236 * The content wrapper of the skin (e.g. `.mw-body`).
238 * Populated on document ready. To use this property,
239 * wait for `$.ready` and be sure to have a module dependency on
240 * `mediawiki.util` which will ensure
241 * your document ready handler fires after initialization.
243 * Because of the lazy-initialised nature of this property,
244 * you're discouraged from using it.
246 * If you need just the wikipage content (not any of the
247 * extra elements output by the skin), use `$( '#mw-content-text' )`
248 * instead. Or listen to mw.hook#wikipage_content which will
249 * allow your code to re-run when the page changes (e.g. live preview
250 * or re-render after ajax save).
257 * Add a link to a portlet menu on the page, such as:
259 * p-cactions (Content actions), p-personal (Personal tools),
260 * p-navigation (Navigation), p-tb (Toolbox)
262 * The first three parameters are required, the others are optional and
263 * may be null. Though providing an id and tooltip is recommended.
265 * By default the new link will be added to the end of the list. To
266 * add the link before a given existing item, pass the DOM node
267 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
268 * (e.g. `'#foobar'`) for that item.
270 * util.addPortletLink(
271 * 'p-tb', 'https://www.mediawiki.org/',
272 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
275 * var node = util.addPortletLink(
277 * new mw.Title( 'Special:Example' ).getUrl(),
280 * $( node ).on( 'click', function ( e ) {
281 * console.log( 'Example' );
282 * e.preventDefault();
285 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
286 * @param {string} href Link URL
287 * @param {string} text Link text
288 * @param {string} [id] ID of the list item, should be unique and preferably have
289 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
290 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
291 * @param {string} [accesskey] Access key to activate this link. One character only,
292 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
293 * see if 'x' is already used.
294 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
295 * Must be another item in the same list, it will be ignored otherwise.
296 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
297 * @return {HTMLElement|null} The added list item, or null if no element was added.
299 addPortletLink: function ( portletId
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
300 var item
, link
, $portlet
, portlet
, portletDiv
, ul
, next
;
303 // Avoid confusing id="undefined" lookup
307 portlet
= document
.getElementById( portletId
);
309 // Invalid portlet ID
313 // Setup the anchor tag and set any the properties
314 link
= document
.createElement( 'a' );
316 link
.textContent
= text
;
318 link
.title
= tooltip
;
321 link
.accessKey
= accesskey
;
324 // Unhide portlet if it was hidden before
325 $portlet
= $( portlet
);
326 $portlet
.removeClass( 'emptyPortlet' );
328 // Setup the list item (and a span if $portlet is a Vector tab)
329 // eslint-disable-next-line no-jquery/no-class-state
330 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
331 item
= $( '<li>' ).append( $( '<span>' ).append( link
)[ 0 ] )[ 0 ];
333 item
= $( '<li>' ).append( link
)[ 0 ];
339 // Select the first (most likely only) unordered list inside the portlet
340 ul
= portlet
.querySelector( 'ul' );
342 // If it didn't have an unordered list yet, create one
343 ul
= document
.createElement( 'ul' );
344 portletDiv
= portlet
.querySelector( 'div' );
346 // Support: Legacy skins have a div (such as div.body or div.pBody).
347 // Append the <ul> to that.
348 portletDiv
.appendChild( ul
);
350 // Append it to the portlet directly
351 portlet
.appendChild( ul
);
355 if ( nextnode
&& ( typeof nextnode
=== 'string' || nextnode
.nodeType
|| nextnode
.jquery
) ) {
356 nextnode
= $( ul
).find( nextnode
);
357 if ( nextnode
.length
=== 1 && nextnode
[ 0 ].parentNode
=== ul
) {
358 // Insertion point: Before nextnode
359 nextnode
.before( item
);
362 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
363 // Else: Invalid nextnode type
367 // Insertion point: End of list (default)
368 ul
.appendChild( item
);
371 // Update tooltip for the access key after inserting into DOM
372 // to get a localized access key label (T69946).
374 $( link
).updateTooltipAccessKeys();
381 * Validate a string as representing a valid e-mail address
382 * according to HTML5 specification. Please note the specification
383 * does not validate a domain with one character.
385 * FIXME: should be moved to or replaced by a validation module.
387 * @param {string} mailtxt E-mail address to be validated.
388 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
389 * as determined by validation.
391 validateEmail: function ( mailtxt
) {
392 var rfc5322Atext
, rfc1034LdhStr
, html5EmailRegexp
;
394 if ( mailtxt
=== '' ) {
398 // HTML5 defines a string as valid e-mail address if it matches
400 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
402 // - atext : defined in RFC 5322 section 3.2.3
403 // - ldh-str : defined in RFC 1034 section 3.5
405 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
406 // First, define the RFC 5322 'atext' which is pretty easy:
407 // atext = ALPHA / DIGIT / ; Printable US-ASCII
408 // "!" / "#" / ; characters not including
409 // "$" / "%" / ; specials. Used for atoms.
418 rfc5322Atext
= 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
420 // Next define the RFC 1034 'ldh-str'
421 // <domain> ::= <subdomain> | " "
422 // <subdomain> ::= <label> | <subdomain> "." <label>
423 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
424 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
425 // <let-dig-hyp> ::= <let-dig> | "-"
426 // <let-dig> ::= <letter> | <digit>
427 rfc1034LdhStr
= 'a-z0-9\\-';
429 html5EmailRegexp
= new RegExp(
432 // User part which is liberal :p
433 '[' + rfc5322Atext
+ '\\.]+' +
437 '[' + rfc1034LdhStr
+ ']+' +
438 // Optional second part and following are separated by a dot
439 '(?:\\.[' + rfc1034LdhStr
+ ']+)*' +
442 // RegExp is case insensitive
445 return ( mailtxt
.match( html5EmailRegexp
) !== null );
449 * Note: borrows from IP::isIPv4
451 * @param {string} address
452 * @param {boolean} [allowBlock=false]
455 isIPv4Address: function ( address
, allowBlock
) {
457 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
458 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
460 if ( typeof address
!== 'string' ) {
464 block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
466 return ( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ).test( address
) );
470 * Note: borrows from IP::isIPv6
472 * @param {string} address
473 * @param {boolean} [allowBlock=false]
476 isIPv6Address: function ( address
, allowBlock
) {
477 var block
, RE_IPV6_ADD
;
479 if ( typeof address
!== 'string' ) {
483 block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
485 '(?:' + // starts with "::" (including "::")
489 '|' + // ends with "::" (except "::")
494 '|' + // contains no "::"
501 if ( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) ) {
505 // contains one "::" in the middle (single '::' check below)
513 new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ).test( address
) &&
514 /::/.test( address
) &&
515 !/::.*::/.test( address
)
520 * Check whether a string is an IP address
523 * @param {string} address String to check
524 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
527 isIPAddress: function ( address
, allowBlock
) {
528 return util
.isIPv4Address( address
, allowBlock
) ||
529 util
.isIPv6Address( address
, allowBlock
);
533 * Escape string for safe inclusion in regular expression
535 * The following characters are escaped:
537 * \ { } ( ) | . ? * + - ^ $ [ ]
539 * @since 1.26; moved to mw.util in 1.34
540 * @param {string} str String to escape
541 * @return {string} Escaped string
543 escapeRegExp: function ( str
) {
544 // eslint-disable-next-line no-useless-escape
545 return str
.replace( /([\\{}()|.?*+\-^$\[\]])/g, '\\$1' );
549 // Backwards-compatible alias for mediawiki.RegExp module.
550 // @deprecated since 1.34
552 mw
.log
.deprecate( mw
.RegExp
, 'escape', util
.escapeRegExp
, 'Use mw.util.escapeRegExp() instead.', 'mw.RegExp.escape' );
554 // Not allowed outside unit tests
555 if ( window
.QUnit
) {
556 util
.setOptionsForTest = function ( opts
) {
557 var oldConfig
= config
;
558 config
= $.extend( {}, config
, opts
);
564 * Initialisation of mw.util.$content
567 util
.$content
= ( function () {
568 var i
, l
, $node
, selectors
;
571 // The preferred standard is class "mw-body".
572 // You may also use class "mw-body mw-body-primary" if you use
573 // mw-body in multiple locations. Or class "mw-body-primary" if
574 // you use mw-body deeper in the DOM.
578 // If the skin has no such class, fall back to the parser output
582 for ( i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
583 $node
= $( selectors
[ i
] );
584 if ( $node
.length
) {
585 return $node
.first();
589 // Should never happen... well, it could if someone is not finished writing a
590 // skin and has not yet inserted bodytext yet.
598 module
.exports
= util
;