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

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


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


var bodyContent = getContentDiv();
function getRevisionSize( proseValue ) {
var curNode = node.parentElement.parentElement;
var Api = new mw.Api();
 
function appendResult( size ) {
while (curNode && (curNode != bodyContent)) {
var wikiValue = sizeElement( 'wiki-size', 'Wiki text:', size );
if (curNode.className.indexOf("infobox") > -1) {
proseValue.before( wikiValue );
return false;
}
}
else if (curNode.className.indexOf("metadata") > -1) {
if ( mw.config.get( 'wgAction' ) === 'submit' ) {
return false;
// Get size of text in edit box
// 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")) {


return true;
function getFileSize( proseHtmlValue ) {
// 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;
}
}


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


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


var listTypes = ["li", "dd"];
function main() {
var prosePromise, proseValue, refValue, refHtmlValue, proseHtmlValue;
for (var j = 0; j < listTypes.length; j++) {
// eslint-disable-next-line no-jquery/no-global-selector
var liList = bodyContent.getElementsByTagName(listTypes[j]);
var parserOutput = $( '#mw-content-text .mw-parser-output' );
 
// eslint-disable-next-line no-jquery/no-global-selector
if (liList) {
var prevStats = $( '#document-size-stats' );
for (i=0; i < liList.length; i++) {
// eslint-disable-next-line no-jquery/no-global-selector
liList[i].style.cssText = oldStyle;
var prevHeader = $( '#document-size-header' );
}
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' ) );


var hList = bodyContent.getElementsByClassName("mw-headline");
// Calculate prose size and size of reference markers ([1] etc)
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;
} );


if (hList) {
// Calculate size of references (i.e. output of <references/>)
for (i=0; i < hList.length; i++) {
parserOutput.find( 'ol.references' ).each( function () {
hList[i].style.cssText = oldStyle;
refSize = getLength( this );
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;


// Count within paragraphs
if (
var pList = bodyContent.getElementsByTagName("p");
!mw.config.get( 'wgCanonicalSpecialPageName' )
 
) {
if (pList) {
$.ready.then( function () {
for (i=0; i < pList.length; i++) {
/**
var para = pList[i];
* Depending on whether in edit mode or preview/view mode,
 
* show the approppiate response upon clicking the portlet link
if (isValidParagraphNode(para)) {
*/
var paraCount = getWordCount(para);
var func, $portlet, notEnabled = false;
 
if (
if (paraCount > 0) {
mw.config.get( 'wgAction' ) === 'edit' ||
main_body_count += paraCount;
( mw.config.get( 'wgAction' ) === 'submit' && document.getElementById( 'wikiDiff' ) )
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', '#', 'Page size', 't-page-size', 'Calculate page and prose size' ) );
 
if ( notEnabled ) {
// Count within lists
$portlet.addClass( 'prosesize-portlet-link-edit-mode' );
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>