User:PleaseStand/highlight-comments-dev.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | Documentation for this user script can be added at User:PleaseStand/highlight-comments-dev. |
/**
* Highlights specific users' posts to discussion pages using a CSS class.
*
* Originally written by PleaseStand in 2010, updated for MediaWiki 1.17 in 2011
* Rewrite completed in 2012
*
* Released to the public domain; see http://en.wikipedia.org/wiki/Template:PD-self
*/
( function( mw, $ ) {
"use strict";
// Default settings
var settings = {
highlighterFunction: function( hc ) {
// Default highlighter function
hc.addColorForUsers( '#ff7', [mw.config.get( 'wgUserName' )] );
hc.wrapComments();
hc.addMenuItem();
}
};
/**
* Messages displayed by this script (in English).
* Any translations (see below) replace these at runtime.
*/
var msg = {
highlightText: 'Highlight',
highlightTooltip: 'Enable highlighting of your own comments on this page',
unhighlightText: 'Unhighlight',
unhighlightTooltip: 'Disable highlighting of your own comments on this page'
};
/**
* Translations for messages displayed by this script.
* To have your translations added, please contact this script's maintainer.
*/
var translations = {
};
// Load translations.
$.extend( msg, translations[document.documentElement.lang] );
// Initialize other enclosed variables.
var linkMap = {}, classNumber = 0, pageRE = null, commentsAreHighlighted = false;
/**
* Build pageRE, a regexp for the use of findPageNameFromHref().
*/
function buildPageRE() {
var articlePathParts = mw.config.get( 'wgArticlePath' ).split( '$1' );
var articlePathStartRE = mw.RegExp.escape( articlePathParts[0] );
var articlePathEndRE = mw.RegExp.escape( articlePathParts[1] );
var indexPathRE = mw.RegExp.escape( mw.util.wikiScript( 'index' ) );
return new RegExp(
'^(?:' + articlePathStartRE + '([^?#]+)' + articlePathEndRE + '|' +
indexPathRE + '\\?(?:[^&#]*&)*title=([^&#]+))'
);
}
/**
* Find a linked page's name (with underscores, not spaces) given a relative URL.
* This assumes the page is linked using a normal, intra-wiki link.
*/
function findPageNameFromHref( href ) {
var m = pageRE.exec( href );
return m ? decodeURIComponent(
( m[1] || m[2] ).replace( /\+/g, '%20' )
).replace( / /g, '_' ) : null;
}
/**
* @todo document
*/
function wrapComments() {
$( '.highlight-comments-content' ).each( function ( i, $content ) {
wrapElementContents( $content );
} );
commentsAreHighlighted = true;
addMenuItem( true );
}
/**
* Give comments linking to any given page a specific CSS class.
* Essentially, we need to find the comment's container and wrap (except where unnecessary)
* everything inside except replies to that comment. We can filter the replies out in that
* they are inside other element types that have the effect of indenting the text.
* @param $content The element containing the content
* @see unwrapElementComments
*/
function wrapElementComments( $content ) {
// Elements containing comments or indented text (replies to those comments)
var commentTags = 'dd, li, p', indentTags = 'dl, ol, ul';
var undoLog = [];
$content.find( 'a' ).each( function() {
var pageName = findPageNameFromHref( this.getAttribute( 'href' ) );
// linkMap is from linked page names to CSS class names.
if ( pageName && linkMap.hasOwnProperty( '$' + pageName ) ) {
var className = linkMap['$' + pageName];
$(this).closest( commentTags ).contents().not( indentTags ).each( function() {
var undoEntry = {className: className};
if ( this.nodeType === 1 ) {
var $elem = $( this );
if ( !$elem.hasClass( className ) ) {
undoEntry.type = 'addClass';
undoEntry.$elem = $elem.addClass( className );
}
} else {
undoEntry.type = 'wrap';
undoEntry.$elem = $( this ).wrap( $( '<span/>', {'class': className} ) );
}
undoLog.push( undoEntry );
} );
}
} );
$content.data( 'highlight-comments-undo-log', undoLog );
}
/**
* @todo document
*/
function unwrapComments() {
$( '.highlight-comments-content' ).each( function ( i, $content ) {
unwrapElementComments( $content );
} );
commentsAreHighlighted = false;
addMenuItem( true );
}
/**
* Undo the actions performed by wrapComments() using the undo log saved by wrapComments().
* @param $content The element containing the content
*/
function unwrapElementComments( $content ) {
var undoLog = $content.data( 'highlight-comments-undo-log' );
$content.removeData( 'highlight-comments-undo-log' );
for ( var i = 0; i < undoLog.length; ++i ) {
var undoEntry = undoLog[i];
if ( undoEntry.type === 'addClass' ) {
undoEntry.$elem.removeClass( undoEntry.className );
} else if ( undoEntry.type === 'wrap' ) {
undoEntry.$elem.unwrap( undoEntry.$elem );
}
}
}
/**
* Add a group of users whose comments should be given the same CSS class.
* @param className The CSS class name to use
* @param users An array of usernames
*/
function addClassForUsers( className, users ) {
var ns = mw.config.get( 'wgFormattedNamespaces' );
for ( var i = 0; i < users.length; ++i ) {
var userName = users[i].replace( / /g, '_' );
var userPage = ns[2] + ':' + userName, userTalkPage = ns[3] + ':' + userName;
linkMap['$' + userPage] = className;
linkMap['$' + userTalkPage] = className;
}
}
/**
* Add a group of users whose comments should be highlighted in the same color.
* @param color The CSS background-color to use
* @param users An array of usernames
* @return The resulting CSSStyleSheet object
*/
function addColorForUsers( color, users ) {
var className = 'highlighted-comment-' + classNumber++;
addClassForUsers( className, users );
return mw.util.addCSS( '.' + className + ' { background-color: ' + color + '; }' );
}
/**
* Adds or updates a "Highlight" or "Unhighlight" option in the content action menu.
* @param updateOnly Do nothing if the menu item does not already exist?
*/
function addMenuItem( updateOnly ) {
var text, tooltip, $oldItem = $( '#ca-highlightcomments' );
if ( updateOnly && !$oldItem.length ) {
return;
}
if ( commentsAreHighlighted ) {
text = msg.unhighlightText;
tooltip = msg.unhighlightTooltip;
} else {
text = msg.highlightText;
tooltip = msg.highlightTooltip;
}
var link = mw.util.addPortletLink(
'p-cactions', '#', text, 'ca-highlightcomments', tooltip, null, $oldItem[0]
);
$oldItem.remove();
$( link ).click(function() {
if ( commentsAreHighlighted ) {
unwrapComments();
} else {
wrapComments();
}
});
}
// Members exposed to custom highlighter functions
var hc = {
addClassForUsers: addClassForUsers,
addColorForUsers: addColorForUsers,
addMenuItem: addMenuItem,
wrapComments: wrapComments
};
mw.loader.using( [ 'mediawiki.util', 'mediawiki.RegExp' ], function() {
// Cache pageRE for performance.
pageRE = buildPageRE();
// Run either the user's highlighter function or the default one.
$( function() {
$.extend( settings, window.highlightCommentsSettings );
settings.highlighterFunction( hc );
} );
// Handle each content element.
mw.hook( 'wikipage.content' ).add( function ( $content ) {
$content.addClass( 'highlight-comments-content' );
if ( commentsAreHighlighted ) {
wrapElementContents( $content );
}
} );
} );
} )( mediaWiki, jQuery );