mediawiki-extensions-Popups/src/title.js
joakin 807100bcca Limit line length to 80 characters
Enforce it with eslint.

Ignore:
* Comment lines with eslint disable directives
* QUnit test lines as they contain long subjects (QUnit.* (only, test,
  module, skip, etc)
* Strings, since long strings are used extensively in tests
  * Ignore template literals for similar reasons
* Regex literals as they may be too long, but can't be easily
  split in several lines
* Long urls

See bug for more general proposal for eslint-wikimedia-config.

Bug: T185295
Change-Id: I3aacaf46e61a4d96547c513073e179ef997deb09
2018-01-19 14:20:39 +01:00

86 lines
1.9 KiB
JavaScript

/**
* @module title
*/
var mw = window.mediaWiki;
/**
* Gets the title of a local page from an href given some configuration.
*
* @param {String} href
* @param {mw.Map} config
* @return {String|undefined}
*/
export function getTitle( href, config ) {
var linkHref,
matches,
queryLength,
titleRegex = new RegExp( mw.RegExp.escape( config.get( 'wgArticlePath' ) )
.replace( '\\$1', '(.+)' ) );
// Skip every URI that mw.Uri cannot parse
try {
linkHref = new mw.Uri( href );
} catch ( e ) {
return undefined;
}
// External links
if ( linkHref.host !== location.hostname ) {
return undefined;
}
queryLength = Object.keys( linkHref.query ).length;
// No query params (pretty URL)
if ( !queryLength ) {
matches = titleRegex.exec( linkHref.path );
return matches ? decodeURIComponent( matches[ 1 ] ) : undefined;
} else if ( queryLength === 1 && linkHref.query.hasOwnProperty( 'title' ) ) {
// URL is not pretty, but only has a `title` parameter
return linkHref.query.title;
}
return undefined;
}
/**
* Given a page title it will return the mediawiki.Title if it is an eligible
* link for showing page previews, null otherwise
*
* @param {String} title page title to check if it should show preview
* @param {Number[]} contentNamespaces contentNamespaces as specified in
* wgContentNamespaces
* @return {mw.Title|null}
*/
export function isValid( title, contentNamespaces ) {
var mwTitle;
if ( !title ) {
return null;
}
// Is title in a content namespace?
mwTitle = mw.Title.newFromText( title );
if ( mwTitle && ( $.inArray( mwTitle.namespace, contentNamespaces ) >= 0 ) ) {
return mwTitle;
}
return null;
}
/**
* Return a mw.Title from a HTMLElement if valid for hovercards. Convenience
* method
*
* @param {Element} el
* @param {mw.Map} config
* @return {mw.Title|null}
*/
export function fromElement( el, config ) {
return isValid(
getTitle( el.href, config ),
config.get( 'wgContentNamespaces' )
);
}