MediaWiki:Gadget-Prosesize.js: Difference between revisions

Content deleted Content added
+
fix
 
(40 intermediate revisions by 2 users not shown)
Line 1:
/* _____________________________________________________________________________
//copy of [[User:Dr_pda/prosesize.js]]
* | |
//TODO: fix script to use API and modernize
* | === WARNING: GLOBAL GADGET FILE === |
//<nowiki>
* | Changes to this page affect many users. |
//This function adds a link to the toolbox which, when clicked, displays the size of the page
//and * the| sizePlease ofdiscuss thechanges prose. Seeon the talk page foror moreon details[[WT:Gadget]] before editing. |
* |_____________________________________________________________________________|
//
*
//To use this function add {{subst:js|User:Dr pda/prosesize.js}} to your monobook.js
/ */
/**
function loadXMLDocPassingTemplate(url,handler, page)
* Prosesize
{
* Documentation at en.wikipedia.org/wiki/Wikipedia:Prosesize
// branch for native XMLHttpRequest object
* Rewrite of [[User:Dr_pda/prosesize.js]].
if (window.XMLHttpRequest) {
*/
var req = new XMLHttpRequest();
'use strict';
}
( function () {
// branch for IE/Windows ActiveX version
function sizeFormatter( size ) {
else if (window.ActiveXObject) {
var nbsp = "\xA0"; // Equivalent to &nbsp;
var req = new ActiveXObject("Microsoft.XMLHTTP");
if ( size > 10240 ) {
}
return ( Math.round( size / 1024 ) + nbsp + 'kB' );
if (req) {
} else {
req.onreadystatechange = function () {handler(req, page)};
return ( size + nbsp + 'B' );
req.open("GET", url, true);
}
req.send("");
}
}
 
function getWikiTextsizeElement(req id, pagetext, size, extraText ) {
return $( '<li>' )
// only if req shows "loaded"
.prop( 'id', id )
if (req.readyState == 4) {
.append(
// only if "OK"
$( '<b>' ).text( text ),
if (req.status == 200) {
document.createTextNode( ' ' + sizeFormatter( size ) + ( extraText || '' ) )
// ...processing statements go here...
);
response = req.responseXML.documentElement;
}
var rev = response.getElementsByTagName('rev');
if(rev.length > 0){
result = rev[0].getAttribute('size');
if(result > 10240){
result = (result/1024).toFixed(0)+'&nbsp;kB';
}
else{
result = result+'&nbsp;B';
}
wiki_value = document.createElement("li");
wiki_value.id = "wiki-size";
wiki_value.innerHTML = '<b>Wiki text: </b>'+result;
var output = document.getElementById("document-size-stats");
prose_value = document.getElementById("prose-size");
output.insertBefore(wiki_value,prose_value);
}
else{
//alert("There was a problem using the Wikipedia Search to find the wiki text size\nEither the search is not working or the correct article did not appear on the first page of results");
wiki_value = document.createElement("li");
wiki_value.id = "wiki-size";
wiki_value.innerHTML = '<b>Wiki text: </b>Problem getting wiki text size';
var output = document.getElementById("document-size-stats");
prose_value = document.getElementById("prose-size");
output.insertBefore(wiki_value,prose_value);
}
} else {
alert("There was a problem retrieving the XML data:\n" +
req.statusText);
}
}
}
 
function getFileSizegetRevisionSize(req, pageproseValue ) {
var Api = new mw.Api();
// only if req shows "loaded"
function appendResult( size ) {
if (req.readyState == 4) {
var wikiValue = sizeElement( 'wiki-size', 'Wiki text:', size );
// only if "OK"
proseValue.before( wikiValue );
if (req.status == 200) {
}
// ...processing statements go here...
if ( mw.config.get( 'wgAction' ) === 'submit' ) {
var fsize = req.responseText.length;
// Get size of text in edit box
window.status = fsize;
// eslint-disable-next-line no-jquery/no-global-selector
var total_value = document.createElement("li");
appendResult( $( '#wpTextbox1' ).textSelection( 'getContents' ).length );
total_value.id = "total-size";
} else if ( mw.config.get( 'wgIsArticle' ) ) {
total_value.innerHTML='<b>File size: </b>'+(fsize/1024).toFixed(0)+'&nbsp;kB';
// Get revision size from API
var output = document.getElementById("document-size-stats");
Api.get( {
var prose_html_value = document.getElementById("prose-size-html");
action: 'query',
output.insertBefore(total_value,prose_html_value);
prop: 'revisions',
} else {
rvprop: 'size',
alert("There was a problem retrieving the XML data:\n" +
revids: mw.config.get( 'wgRevisionId' ),
req.statusText + "\n(" + url + ")");
formatversion: 2
}
} ).then( function ( result ) {
}
appendResult( result.query.pages[ 0 ].revisions[ 0 ].size );
}
} );
}
}
 
function getLengthgetFileSize(id proseHtmlValue ) {
// HTML document size not well defined for preview mode or section edit
var textLength = 0;
if ( mw.config.get( 'wgAction' ) !== 'submit' ) {
for(var i=0;i<id.childNodes.length; i++){
$.get( ___location ).then( function ( result ) {
if(id.childNodes[i].nodeType === Node.TEXT_NODE){
var fsize = sizeElement( 'total-size', 'HTML document size:', result.length );
textLength += id.childNodes[i].nodeValue.length;
proseHtmlValue.before( fsize );
}
} );
else if(id.childNodes[i].nodeType === Node.ELEMENT_NODE &&
}
(id.childNodes[i].id == 'coordinates' || id.childNodes[i].className.indexOf('emplate') != -1)){
}
//special case for {{coord}} and {{fact}}-like templates
//Exclude from length, and don't set background yellow
id.childNodes[i].style.cssText = 'background-color:white';
}
else{
textLength += getLength(id.childNodes[i]);
}
}
return textLength;
}
 
function getRefMarkLengthgetLength( id,html ) {
var i;
var textLength = 0;
for (var i = 0; i < id.childNodes.length; i++ ) {
if ( if(id.childNodes[ i ].nodeType === Node.ELEMENT_NODETEXT_NODE &&) id.childNodes[i].className == 'reference'){
textLength += (html)? id.childNodes[ i ].innerHTMLnodeValue.length : getLength(id.childNodes[i]);
} else if (
}
id.childNodes[ i ].nodeType === Node.ELEMENT_NODE &&
}
( id.childNodes[ i ].id === 'coordinates' || id.childNodes[ i ].className.indexOf( 'emplate' ) !== -1 )
return textLength;
) {
}
// special case for {{coord}} and {{fact}}-like templates
// Exclude from length, and don't set background yellow
id.childNodes[ i ].className += ' prosesize-special-template';
} else if (id.childNodes[ i ].tagName !== 'STYLE') {
// Exclude style tags
textLength += getLength( id.childNodes[ i ] );
}
}
return textLength;
}
 
function getDocumentSizegetRefMarkLength( id, html ) {
var bodyContenti;
var textLength = 0;
if($.inArray(mw.config.get('skin'), ['vector' , 'monobook' ]) !== -1){
for ( i = 0; i < id.childNodes.length; i++ ) {
bodyContent = $('#mw-content-text .mw-parser-output');
if (
}
id.childNodes[ i ].nodeType === Node.ELEMENT_NODE &&
//Same for all skins if previewing page
id.childNodes[ i ].className === 'reference'
if(mw.config.get('wgAction') == 'submit') {
) {
bodyContent = $('#wikiPreview .mw-parser-output');
textLength += ( html ) ?
}
id.childNodes[ i ].innerHTML.length :
getLength( id.childNodes[ i ] );
if (bodyContent.length === 0) {
}
return;
}
return textLength;
bodyContent = bodyContent[0];
}
 
function main() {
if(document.getElementById("document-size-stats")){
var prosePromise, proseValue, refValue, refHtmlValue, proseHtmlValue;
//if statistics already exist, turn them off and remove highlighting
// eslint-disable-next-line no-jquery/no-global-selector
var output = document.getElementById("document-size-stats");
var parserOutput = $( '#mw-content-text .mw-parser-output' );
var oldStyle = output.className;
// eslint-disable-next-line no-jquery/no-global-selector
var pList = bodyContent.getElementsByTagName("p");
var prevStats = $( '#document-size-stats' );
for(var i=0;i<pList.length; i++){
// eslint-disable-next-line no-jquery/no-global-selector
if( pList[i].parentNode == bodyContent ) {
var prevHeader = $( '#document-size-header' );
pList[i].style.cssText = oldStyle;
var proseSize = 0;
}
var proseSizeHtml = 0;
}
var refmarksize = 0;
output.parentNode.removeChild(output);
var refmarkSizeHtml = 0;
var header = document.getElementById("document-size-header");
var wordCount = 0;
header.parentNode.removeChild(header);
var refSize = 0;
}
var refSizeHtml = 0;
else{
var header = $( '<span>' )
var output = document.createElement("ul");
output .prop( 'id', = "'document-size-stats";header' )
.html( 'Document statistics <small>(<a href="//en.wikipedia.org/wiki/Wikipedia:Prosesize">more information</a>)</small>:' );
var output = $( '<ul>' )
.prop( 'id', 'document-size-stats' );
var combined = $( '<div>' )
.prop( 'id', 'document-size' )
.append( header, output );
if ( parserOutput.length === 0 ) {
return;
}
if ( prevStats.length ) {
// If statistics already exist, turn them off and remove highlighting
prevStats.remove();
prevHeader.remove();
parserOutput.children( 'p' ).removeClass( 'prosesize-highlight' );
} else {
// Use prosesize API to get a more accurate prose size account
// The calculations below are left in for the highlighting
prosePromise = $.getJSON( 'https://prosesize.toolforge.org/api/' + mw.config.get( 'wgServerName' ) + '/'
+ encodeURIComponent( mw.config.get( 'wgPageName' ) ) + '?revision=' + mw.config.get( 'wgRevisionId' ) );
 
// Calculate prose size and size of reference markers ([1] etc)
var prose_html_value = document.createElement("li");
parserOutput.children( 'p' ).each( function () {
prose_html_value.id = "prose-size-html";
$( this ).addClass( 'prosesize-highlight' );
output.appendChild(prose_html_value);
proseSize += getLength( this );
proseSizeHtml += this.innerHTML.length;
refmarksize += getRefMarkLength( this, false );
refmarkSizeHtml += getRefMarkLength( this, true );
wordCount += this.innerHTML.replace( /(<([^>]+)>)/ig, '' ).split( ' ' ).length;
} );
 
// Calculate size of references (i.e. output of <references/>)
var ref_html_value = document.createElement("li");
parserOutput.find( 'ol.references' ).each( function () {
ref_html_value.id = "ref-size-html";
refSize = getLength( this );
output.appendChild(ref_html_value);
refSizeHtml = this.innerHTML.length;
} );
proseSize -= refmarksize;
function show_output() {
proseValue = sizeElement( 'prose-size', 'Prose size (text only):', proseSize, ' (' + wordCount + ' words) "readable prose size"' );
refValue = sizeElement( 'ref-size', 'References (text only):', refSize + refmarksize );
refHtmlValue = sizeElement( 'ref-size-html', 'References (including all HTML code):', refSizeHtml + refmarkSizeHtml );
proseHtmlValue = sizeElement( 'prose-size-html', 'Prose size (including all HTML code):', proseSizeHtml - refmarkSizeHtml );
output.append( proseHtmlValue, refHtmlValue, proseValue, refValue );
parserOutput.prepend( combined );
getFileSize( proseHtmlValue );
getRevisionSize( proseValue );
}
// Add the relevant outputs once we have fetched the prose size.
prosePromise.then(
function( data ) {
if ( mw.config.get( 'wgIsArticle' ) ) {
// Tool doesn't work on previews
proseSize = data.prose_size;
wordCount = data.word_count;
}
show_output();
},
// If tool is down fallback to our prose count
show_output
);
}
}
 
if (
var prose_value = document.createElement("li");
!mw.config.get( 'wgCanonicalSpecialPageName' )
prose_value.id = "prose-size";
) {
output.appendChild(prose_value);
$.ready.then( function () {
output.className = bodyContent.getElementsByTagName("p").item(0).style.cssText;
/**
 
* Depending on whether in edit mode or preview/view mode,
var ref_value = document.createElement("li");
* show the approppiate response upon clicking the portlet link
ref_value.id = "ref-size";
*/
output.appendChild(ref_value);
var func, $portlet, notEnabled = false;
 
if (
bodyContent.insertBefore(output, bodyContent.firstChild);
mw.config.get( 'wgAction' ) === 'edit' ||
 
( mw.config.get( 'wgAction' ) === 'submit' && document.getElementById( 'wikiDiff' ) )
var header = document.createElement("span");
) {
header.id = "document-size-header";
notEnabled = true;
header.innerHTML = '<br/>Document statistics: <small><i>(See <a href="//en.wikipedia.org/wiki/User_talk:Dr_pda/prosesize.js">here</a> for details.)<i></small>';
func = function () {
bodyContent.insertBefore(header,output);
mw.notify( 'You need to preview the text for the prose size script to work in edit mode.' );
 
};
//File size not well defined for preview mode or section edit
} else if ( [ 'view', 'submit', 'historysubmit', 'purge' ].indexOf( mw.config.get( 'wgAction' ) ) !== 'submit'-1 ) {
func = main;
loadXMLDocPassingTemplate(___location.pathname,getFileSize,'');
}
if ( func ) {
$portlet = $( mw.util.addPortletLink( 'p-tb', '#', 'Page size', 't-page-size', 'Calculate page and prose size' ) );
//Get size of images only if browser supports filesize property (IE)
if ( notEnabled ) {
var iList = bodyContent.getElementsByTagName("img");
$portlet.addClass( 'prosesize-portlet-link-edit-mode' );
if(iList.length >0 && iList[0].fileSize){
}
//Get size of images included in document
$portlet.on( 'click', function ( e ) {
var image_size = 0;
e.preventDefault();
var first_magnify = true;
if ( window.ve && ve.init && ve.init.target && ve.init.target.active ) {
 
mw.notify( 'Prosesize does not work with the Visual Editor.' );
for (var i=0;i<iList.length; i++){
} else {
var im = iList[i];
func();
if(im.getAttribute("src").indexOf("magnify-clip.png") != -1){
}
if(first_magnify){
} );
image_size += im.fileSize*1;
}
first_magnify = false;
} );
}
}
else{
image_size += im.fileSize*1;
}
}
var image_value = document.createElement("li");
image_value.id = "image-size";
image_value.innerHTML='<b>Images: </b>'+(image_size/1024).toFixed(0)+'&nbsp;kB';
output.appendChild(image_value);
 
}
//Calculate prose size and size of reference markers ([1] etc)
var pList = bodyContent.getElementsByTagName("p");
 
prose_size = 0;
prose_size_html = 0;
refmark_size = 0;
refmark_size_html = 0;
word_count = 0;
for(var i=0;i<pList.length; i++){
var para = pList[i];
if( para.parentNode == bodyContent ){
prose_size += getLength(para);
prose_size_html += para.innerHTML.length;
refmark_size += getRefMarkLength(para,false);
refmark_size_html += getRefMarkLength(para,true);
word_count += para.innerHTML.replace(/(<([^>]+)>)/ig,"").split(' ').length;
para.style.cssText = "background-color:yellow";
}
}
 
if((prose_size-refmark_size)>10240){
prose_value.innerHTML='<b>Prose size (text only): </b>'+((prose_size-refmark_size)/1024).toFixed(0)+'&nbsp;kB ('+word_count+' words) "readable prose size"';
}
else{
prose_value.innerHTML='<b>Prose size (text only): </b>'+(prose_size-refmark_size)+'&nbsp;B ('+word_count+' words) "readable prose size"';
}
 
if((prose_size_html-refmark_size_html)>10240){
prose_html_value.innerHTML='<b>Prose size (including all HTML code): </b>'+((prose_size_html-refmark_size_html)/1024).toFixed(0)+'&nbsp;kB';
}
else{
prose_html_value.innerHTML='<b>Prose size (including all HTML code): </b>'+(prose_size_html-refmark_size_html)+'&nbsp;B';
}
 
//Calculate size of references (i.e. output of <references/>)
var rList = bodyContent.getElementsByTagName("ol");
var ref_size = 0;
var ref_size_html = 0;
for (var i=0; i<rList.length; i++){
if(rList[i].parentNode.className == "references"){
ref_size = getLength(rList[i]);
ref_size_html = rList[i].innerHTML.length;
}
}
 
if((ref_size+refmark_size)>10240){
ref_value.innerHTML='<b>References (text only): </b>'+((ref_size+refmark_size)/1024).toFixed(0)+'&nbsp;kB';
}
else{
ref_value.innerHTML='<b>References (text only): </b>'+(ref_size+refmark_size)+'&nbsp;B';
}
 
if((ref_size_html+refmark_size_html)>10240){
ref_html_value.innerHTML='<b>References (including all HTML code): </b>'+((ref_size_html+refmark_size_html)/1024).toFixed(0)+'&nbsp;kB';
}
else{
ref_html_value.innerHTML='<b>References (including all HTML code): </b>'+(ref_size_html+refmark_size_html)+'&nbsp;B';
}
 
//get correct name of article from wikipedia-defined global variables
var pageNameUnderscores = mw.config.get('wgPageName');
var pageNameSpaces = pageNameUnderscores.replace(/_/g,' ');
 
//if page is a permalink, diff, etc don't try to search
if(!___location.pathname.match('/w/index.php')){
//Get revision size from API
var searchURL = mw.config.get('wgScriptPath') + '/api.php?action=query&prop=revisions&rvprop=size&format=xml&revids=' + mw.config.get('wgCurRevisionId');
loadXMLDocPassingTemplate(searchURL,getWikiText,pageNameSpaces);
}
else if(mw.config.get('wgAction') == 'submit'){
//Get size of text in edit box
result = document.getElementById('wpTextbox1').value.length;
if(result > 10240){
result = (result/1024).toFixed(0)+'&nbsp;kB';
}
else{
result = result+'&nbsp;B';
}
wiki_value = document.createElement("li");
wiki_value.id = "wiki-size";
wiki_value.innerHTML = '<b>Wiki text: </b>'+result;
var output = document.getElementById("document-size-stats");
prose_value = document.getElementById("prose-size");
output.insertBefore(wiki_value,prose_value);
}
}
}
 
jQuery(function () {
if($.inArray(mw.config.get('skin'), ['vector' , 'monobook' ]) === -1){
return;
}
}() );
mw.loader.using( ['mediawiki.util'], function () {
if(mw.config.get('wgAction') == 'edit' || (mw.config.get('wgAction') == 'submit' && document.getElementById('wikiDiff')) ){
$( mw.util.addPortletLink('p-tb', '#', 'Page size', 't-page-size', 'Calculate page and prose size') )
.click( function(e){
e.preventDefault();
alert("You need to preview the text for the prose size script to work in edit mode.");
} );
document.getElementById("t-page-size").firstChild.style.cssText = "color:black;";
}
else if($.inArray(mw.config.get('wgAction'), ['view' , 'submit' , 'historysubmit' , 'purge']) !== -1){
$( mw.util.addPortletLink('p-tb', '#', 'Page size', 't-page-size', 'Calculate page and prose size') )
.click( function(e) {
e.preventDefault();
getDocumentSize();
} );
}
});
});
 
//</nowiki>