مدیاویکی:Gadget-WordCount.js: تفاوت میان نسخه‌ها

بدون خلاصۀ ویرایش
برچسب: برگردانده‌شده
بدون خلاصۀ ویرایش
برچسب: واگردانی دستی
خط ۱: خط ۱:
/*  _____________________________________________________________________________
// wordcount
* |                                                                            |
//<nowiki>
* |                    === WARNING: GLOBAL GADGET FILE ===                      |
// This code is based on https://en.wikipedia.org/wiki/User:Dr_pda/prosesize.js
* |                  Changes to this page affect many users.                    |
// but adds CJK support (http://stackoverflow.com/questions/2315488) and support
* | Please discuss changes on the talk page or on [[WT:Gadget]] before editing. |
// for references and other lists.
* |_____________________________________________________________________________|
//
*
function getWordCount(html) {
*/
var str = html.innerHTML.replace(/(<([^>]+)>)/ig,"").trim();
/**
 
* Prosesize
var wordCount = 0;
* Documentation at en.wikipedia.org/wiki/Wikipedia:Prosesize
 
* Rewrite of [[User:Dr_pda/prosesize.js]].
var arr = str.match(/[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF]|\S+/g);
*/
 
'use strict';
if (arr) {
( function () {
wordCount = arr.length;
function sizeFormatter( size ) {
}
var nbsp = "\xA0"; // Equivalent to &nbsp;
 
if ( size > 10240 ) {
return wordCount;
return ( Math.round( size / 1024 ) + nbsp + 'kB' );
}
} else {
 
return ( size + nbsp + 'B' );
function getContentDiv() {
}
var contentDiv;
 
if (mw.config.get('wgAction') == 'edit') {
contentDiv = document.getElementById('wikiPreview');
}
else {
contentDiv = document.getElementById('mw-content-text');
}
 
return contentDiv;
}
 
function isValidListNode(node) {
if (node.parentElement.id == "word-count-stats") {
return false;
}
 
if (node.className.indexOf("toclevel-") > -1 ||
node.parentElement.parentElement.id == "toc") {
 
return false;
}
}


function sizeElement( id, text, size, extraText ) {
if (node.parentElement.parentElement.parentElement.className == "catlinks") {
return $( '<li>' )
return false;
.prop( 'id', id )
.append(
$( '<b>' ).text( text ),
document.createTextNode( ' ' + sizeFormatter( size ) + ( extraText || '' ) )
);
}
}


function getRevisionSize( proseValue ) {
var bodyContent = getContentDiv();
var Api = new mw.Api();
var curNode = node.parentElement.parentElement;
function appendResult( size ) {
 
var wikiValue = sizeElement( 'wiki-size', 'Wiki text:', size );
while (curNode && (curNode != bodyContent)) {
proseValue.before( wikiValue );
if (curNode.className.indexOf("infobox") > -1) {
return false;
}
}
if ( mw.config.get( 'wgAction' ) === 'submit' ) {
else if (curNode.className.indexOf("metadata") > -1) {
// Get size of text in edit box
return false;
// eslint-disable-next-line no-jquery/no-global-selector
appendResult( $( '#wpTextbox1' ).textSelection( 'getContents' ).length );
} else if ( mw.config.get( 'wgIsArticle' ) ) {
// Get revision size from API
Api.get( {
action: 'query',
prop: 'revisions',
rvprop: 'size',
revids: mw.config.get( 'wgRevisionId' ),
formatversion: 2
} ).then( function ( result ) {
appendResult( result.query.pages[ 0 ].revisions[ 0 ].size );
} );
}
}
else if (curNode.className.indexOf("navbox") > -1) {
return false;
}
else {
curNode = curNode.parentElement;
}
}
return true;
}
function isValidParagraphNode(node) {
if (node.parentNode.className == "mw-parser-output" ||
node.parentNode.parentNode.className == "mw-parser-output" ||
node.parentNode.nodeName == "BLOCKQUOTE") {
return true;
}
}
else {
return false;
}
}
function isValidReferenceNode(node) {
var bodyContent = getContentDiv();
var curNode = node.parentElement;
while (curNode && (curNode != bodyContent)) {
if (curNode.classList.contains("references") ||
curNode.classList.contains("reflist") ||
curNode.classList.contains("refbegin")) {


function getFileSize( proseHtmlValue ) {
return true;
// HTML document size not well defined for preview mode or section edit
if ( mw.config.get( 'wgAction' ) !== 'submit' ) {
$.get( location ).then( function ( result ) {
var fsize = sizeElement( 'total-size', 'HTML document size:', result.length );
proseHtmlValue.before( fsize );
} );
}
}
curNode = curNode.parentElement;
}
}


function getLength( id ) {
return false;
var i;
}
var textLength = 0;
 
for ( i = 0; i < id.childNodes.length; i++ ) {
function toggleWordCount() {
if ( id.childNodes[ i ].nodeType === Node.TEXT_NODE ) {
if (mw.config.get('wgAction') == 'edit') {
textLength += id.childNodes[ i ].nodeValue.length;
var wikiPreview = document.getElementById('wikiPreview');
} else if (
 
id.childNodes[ i ].nodeType === Node.ELEMENT_NODE &&
var wikiPreviewStyle = window.getComputedStyle(wikiPreview);
( id.childNodes[ i ].id === 'coordinates' || id.childNodes[ i ].className.indexOf( 'emplate' ) !== -1 )
 
) {
if (wikiPreviewStyle.display === 'none') {
// special case for {{coord}} and {{fact}}-like templates
alert("You need to preview the text for the word count script to work in edit mode.");
// Exclude from length, and don't set background yellow
 
id.childNodes[ i ].className += ' prosesize-special-template';
return;
            } else if (id.childNodes[ i ].tagName !== 'STYLE') {
                // Exclude style tags
textLength += getLength( id.childNodes[ i ] );
}
}
}
return textLength;
}
}


function getRefMarkLength( id, html ) {
var bodyContent = getContentDiv();
var i;
 
var textLength = 0;
var output = document.getElementById("word-count-stats");
for ( i = 0; i < id.childNodes.length; i++ ) {
 
if (
if (output) {
id.childNodes[ i ].nodeType === Node.ELEMENT_NODE &&
var oldStyle = output.className;
id.childNodes[ i ].className === 'reference'
 
) {
var i = 0;
textLength += ( html ) ?
 
id.childNodes[ i ].innerHTML.length :
// Cleanup background color
getLength( id.childNodes[ i ] );
var pList = bodyContent.getElementsByTagName("p");
 
if (pList) {
for (i=0; i < pList.length; i++){
if (isValidParagraphNode(pList[i])) {
pList[i].style.cssText = oldStyle;
}
}
}
}
}
return textLength;
}


function main() {
var listTypes = ["li", "dd"];
var prosePromise, proseValue, refValue, refHtmlValue, proseHtmlValue;
// eslint-disable-next-line no-jquery/no-global-selector
for (var j = 0; j < listTypes.length; j++) {
var parserOutput = $( '#mw-content-text .mw-parser-output' );
var liList = bodyContent.getElementsByTagName(listTypes[j]);
// eslint-disable-next-line no-jquery/no-global-selector
 
var prevStats = $( '#document-size-stats' );
if (liList) {
// eslint-disable-next-line no-jquery/no-global-selector
for (i=0; i < liList.length; i++) {
var prevHeader = $( '#document-size-header' );
liList[i].style.cssText = oldStyle;
var proseSize = 0;
}
var proseSizeHtml = 0;
}
var refmarksize = 0;
var refmarkSizeHtml = 0;
var wordCount = 0;
var refSize = 0;
var refSizeHtml = 0;
var header = $( '<span>' )
.prop( 'id', 'document-size-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 hList = bodyContent.getElementsByClassName("mw-headline");
parserOutput.children( 'p' ).each( function () {
$( this ).addClass( 'prosesize-highlight' );
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/>)
if (hList) {
parserOutput.find( 'ol.references' ).each( function () {
for (i=0; i < hList.length; i++) {
refSize = getLength( this );
hList[i].style.cssText = oldStyle;
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
);
}
}
// Remove nodes
output.parentNode.removeChild(output);
var header = document.getElementById("word-count-header");
header.parentNode.removeChild(header);
}
}
else {
getStatistics(bodyContent);
}
}
//
// Main counting function
//
function getStatistics(bodyContent) {
// Statistics
var output = document.createElement("ul");
output.id = "word-count-stats";
var main_body_value = document.createElement("li");
main_body_value.id = "main-body-stat";
output.appendChild(main_body_value);
output.className = bodyContent.getElementsByTagName("p").item(0).style.cssText;
var ref_value = document.createElement("li");
ref_value.id = "ref-stat";
output.appendChild(ref_value);
var total_value = document.createElement("li");
total_value.id = "total-stat";
output.appendChild(total_value);
bodyContent.insertBefore(output, bodyContent.firstChild);
// Header
var header = document.createElement("span");
header.id = "word-count-header";
header.innerHTML = "<br/><b>Word counts</b> (<a href='https://en.wikipedia.org/wiki/User:Caorongjin/wordcount'>doc</a>)<b>:</b>";
bodyContent.insertBefore(header,output);
// Create counters
var main_body_count = 0;
var ref_count = 0;
var i = 0;


if (
// Count within paragraphs
!mw.config.get( 'wgCanonicalSpecialPageName' )
var pList = bodyContent.getElementsByTagName("p");
) {
 
$.ready.then( function () {
if (pList) {
/**
for (i=0; i < pList.length; i++) {
* Depending on whether in edit mode or preview/view mode,
var para = pList[i];
* show the approppiate response upon clicking the portlet link
 
*/
if (isValidParagraphNode(para)) {
var func, $portlet, notEnabled = false;
var paraCount = getWordCount(para);
if (
 
mw.config.get( 'wgAction' ) === 'edit' ||
if (paraCount > 0) {
( mw.config.get( 'wgAction' ) === 'submit' && document.getElementById( 'wikiDiff' ) )
main_body_count += paraCount;
) {
para.style.cssText = "background-color:yellow";
notEnabled = true;
}
func = function () {
mw.notify( 'You need to preview the text for the prose size script to work in edit mode.' );
};
} else if ( [ 'view', 'submit', 'historysubmit', 'purge' ].indexOf( mw.config.get( 'wgAction' ) ) !== -1 ) {
func = main;
}
}
if ( func ) {
}
$portlet = $( mw.util.addPortletLink( 'p-tb', '#', 'تعداد کلمات', 't-page-size', 'Calculate page and prose size' ) );
}
if ( notEnabled ) {
 
$portlet.addClass( 'prosesize-portlet-link-edit-mode' );
// Count within lists
var listTypes = ["li", "dd"];
 
for (var j = 0; j < listTypes.length; j++) {
var liList = bodyContent.getElementsByTagName(listTypes[j]);
 
if (liList) {
for (i=0; i < liList.length; i++) {
var li = liList[i];
 
if (isValidReferenceNode(li)) {
ref_count += getWordCount(li);
li.style.cssText = "background-color:cyan";
}
else if (isValidListNode(li)) {
main_body_count += getWordCount(li);
li.style.cssText = "background-color:yellow";
}
}
$portlet.on( 'click', function ( e ) {
e.preventDefault();
if ( window.ve && ve.init && ve.init.target && ve.init.target.active ) {
mw.notify( 'Prosesize does not work with the Visual Editor.' );
} else {
func();
}
} );
}
}
} );
}
}
}
}() );
 
// Count within headings
var hList = bodyContent.getElementsByClassName("mw-headline");
 
if (hList) {
for (i=0; i < hList.length; i++) {
var h = hList[i];
 
if (h.id == "Contents") {
continue;
}
 
main_body_count += getWordCount(h);
h.style.cssText = "background-color:yellow";
}
}
 
main_body_value.innerHTML = "Main body: " + main_body_count + " words";
ref_value.innerHTML = "References: " + ref_count + " words";
total_value.innerHTML = "Total: " + (main_body_count + ref_count) + " words";
}
 
jQuery(function () {
mw.loader.using( ['mediawiki.util'], function () {
if($.inArray(mw.config.get('wgAction'), ['edit', 'view' , 'submit' , 'historysubmit' , 'purge']) !== -1) {
$( mw.util.addPortletLink('p-tb', '#', 'تعداد کلمات', 't-word-count', 'Calculate word count') )
.click( toggleWordCount );
}
});
});
 
//</nowiki>