MediaWiki:Gadget-Wordcount.js: Difference between revisions

From wikishia
(Reverted edits by Alavi (talk) to last revision by Admin)
Tag: Rollback
No edit summary
Tag: Reverted
Line 1: Line 1:
//<nowiki>
function getWordCount(html) {
function getWordCount(html) {
var str = html.innerHTML.replace(/(<([^>]+)>)/ig,"").trim();
    const text = html.innerHTML.replace(/(<([^>]+)>)/ig, "").trim();
 
    const words = text.match(/[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF]|\S+/g);
var wordCount = 0;
    return words ? words.length : 0;
 
var arr = str.match(/[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF]|\S+/g);
 
if (arr) {
wordCount = arr.length;
}
 
return wordCount;
}
}


function getContentDiv() {
function getContentDiv() {
var contentDiv;
    return mw.config.get('wgAction') === 'edit'
 
        ? document.getElementById('wikiPreview')
if (mw.config.get('wgAction') == 'edit') {
        : document.getElementById('mw-content-text');
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") {
return false;
}
 
var bodyContent = getContentDiv();
var curNode = node.parentElement.parentElement;
 
while (curNode && (curNode != bodyContent)) {
if (curNode.className.indexOf("infobox") > -1) {
return false;
}
else if (curNode.className.indexOf("metadata") > -1) {
return false;
}
else if (curNode.className.indexOf("navbox") > -1) {
return false;
}
else {
curNode = curNode.parentElement;
}
}
 
return true;
}
}


function isValidParagraphNode(node) {
function isValidNode(node, conditions) {
if (node.parentNode.className == "mw-parser-output" ||
    const bodyContent = getContentDiv();
node.parentNode.parentNode.className == "mw-parser-output" ||
    let currentNode = node.parentElement;
node.parentNode.nodeName == "BLOCKQUOTE") {


return true;
    while (currentNode && currentNode !== bodyContent) {
}
        if (conditions.some(cls => currentNode.classList.contains(cls))) {
else {
            return false;
return false;
        }
}
        currentNode = currentNode.parentElement;
}
    }
 
    return true;
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;
}
 
curNode = curNode.parentElement;
}
 
return false;
}
}


function toggleWordCount() {
function toggleWordCount() {
if (mw.config.get('wgAction') == 'edit') {
    const bodyContent = getContentDiv();
var wikiPreview = document.getElementById('wikiPreview');
    let output = document.getElementById("word-count-stats");
 
var wikiPreviewStyle = window.getComputedStyle(wikiPreview);
 
if (wikiPreviewStyle.display === 'none') {
alert("باید متن را به حالت پیش‌نمایش ببرید تا اسکریپت شمارش کلمات در حالت ویرایش هم کار کند.");
 
return;
}
}
 
var bodyContent = getContentDiv();
 
var output = document.getElementById("word-count-stats");
 
if (output) {
var oldStyle = output.className;
 
var i = 0;
 
// Cleanup background color
var pList = bodyContent.getElementsByTagName("p");
 
if (pList) {
for (i=0; i < pList.length; i++){
if (isValidParagraphNode(pList[i])) {
pList[i].style.cssText = oldStyle;
}
}
}
 
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++) {
liList[i].style.cssText = oldStyle;
}
}
}
 
var hList = bodyContent.getElementsByClassName("mw-headline");
 
if (hList) {
for (i=0; i < hList.length; i++) {
hList[i].style.cssText = oldStyle;
}
}
 
// Remove nodes
output.parentNode.removeChild(output);
 
var header = document.getElementById("word-count-header");


header.parentNode.removeChild(header);
    if (output) {
}
        // Clean up
else {
        output.remove();
getStatistics(bodyContent);
        document.getElementById("word-count-header")?.remove();
}
    } else {
        generateStatistics(bodyContent);
    }
}
}


//
function generateStatistics(bodyContent) {
// Main counting function
    const output = document.createElement("div");
//
    output.id = "word-count-stats";
function getStatistics(bodyContent) {
    output.innerHTML = `
 
        <div id="word-count-header"><b>شمارشگر کلمات</b></div>
// Statistics
        <table class="word-count-table">
var output = document.createElement("ul");
            <tr><td>محتوای اصلی:</td><td id="main-body-stat"></td></tr>
output.id = "word-count-stats";
            <tr><td>ارجاعات:</td><td id="ref-stat"></td></tr>
 
            <tr><td>جمع کل:</td><td id="total-stat"></td></tr>
var main_body_value = document.createElement("li");
        </table>`;
main_body_value.id = "main-body-stat";
    bodyContent.prepend(output);
output.appendChild(main_body_value);
output.className = bodyContent.getElementsByTagName("p").item(0).style.cssText;


var ref_value = document.createElement("li");
    let mainBodyCount = 0, refCount = 0;
ref_value.id = "ref-stat";
output.appendChild(ref_value);


var total_value = document.createElement("li");
    const processNodes = (nodes, isReference) => {
total_value.id = "total-stat";
        nodes.forEach(node => {
output.appendChild(total_value);
            const count = getWordCount(node);
            if (count > 0) {
                if (isReference(node)) {
                    refCount += count;
                    node.style.backgroundColor = "cyan";
                } else {
                    mainBodyCount += count;
                    node.style.backgroundColor = "yellow";
                }
            }
        });
    };


bodyContent.insertBefore(output, bodyContent.firstChild);
    const paragraphs = Array.from(bodyContent.getElementsByTagName("p"));
    processNodes(paragraphs, node => false);


// Header
    document.getElementById("main-body-stat").innerText = `${mainBodyCount} واژه`;
var header = document.createElement("span");
    document.getElementById("ref-stat").innerText = `${refCount} واژه`;
header.id = "word-count-header";
    document.getElementById("total-stat").innerText = `${mainBodyCount + refCount} واژه`;
header.innerHTML = "<br/><b>شمارشگر کلمات</b> (<a href='https://fa.wikishia.net/view/صفحهٔ_اصلی'>راهنما</a>)<b>:</b>";
bodyContent.insertBefore(header,output);
 
// Create counters
var main_body_count = 0;
var ref_count = 0;
 
var i = 0;
 
// Count within paragraphs
var pList = bodyContent.getElementsByTagName("p");
 
if (pList) {
for (i=0; i < pList.length; i++) {
var para = pList[i];
 
if (isValidParagraphNode(para)) {
var paraCount = getWordCount(para);
 
if (paraCount > 0) {
main_body_count += paraCount;
para.style.cssText = "background-color:yellow";
}
}
}
}
 
// 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";
}
}
}
}
 
// 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_count + " واژه";
ref_value.innerHTML = "ارجاعات: " + ref_count + " واژه";
total_value.innerHTML = "جمع کل: " + (main_body_count + ref_count) + " واژه";
}
}
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', 'محاسبه تعداد کلمات') )
.click( toggleWordCount );
}
});
});
//</nowiki>

Revision as of 09:06, 16 November 2024

function getWordCount(html) {
    const text = html.innerHTML.replace(/(<([^>]+)>)/ig, "").trim();
    const words = text.match(/[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF]|\S+/g);
    return words ? words.length : 0;
}

function getContentDiv() {
    return mw.config.get('wgAction') === 'edit'
        ? document.getElementById('wikiPreview')
        : document.getElementById('mw-content-text');
}

function isValidNode(node, conditions) {
    const bodyContent = getContentDiv();
    let currentNode = node.parentElement;

    while (currentNode && currentNode !== bodyContent) {
        if (conditions.some(cls => currentNode.classList.contains(cls))) {
            return false;
        }
        currentNode = currentNode.parentElement;
    }
    return true;
}

function toggleWordCount() {
    const bodyContent = getContentDiv();
    let output = document.getElementById("word-count-stats");

    if (output) {
        // Clean up
        output.remove();
        document.getElementById("word-count-header")?.remove();
    } else {
        generateStatistics(bodyContent);
    }
}

function generateStatistics(bodyContent) {
    const output = document.createElement("div");
    output.id = "word-count-stats";
    output.innerHTML = `
        <div id="word-count-header"><b>شمارشگر کلمات</b></div>
        <table class="word-count-table">
            <tr><td>محتوای اصلی:</td><td id="main-body-stat"></td></tr>
            <tr><td>ارجاعات:</td><td id="ref-stat"></td></tr>
            <tr><td>جمع کل:</td><td id="total-stat"></td></tr>
        </table>`;
    bodyContent.prepend(output);

    let mainBodyCount = 0, refCount = 0;

    const processNodes = (nodes, isReference) => {
        nodes.forEach(node => {
            const count = getWordCount(node);
            if (count > 0) {
                if (isReference(node)) {
                    refCount += count;
                    node.style.backgroundColor = "cyan";
                } else {
                    mainBodyCount += count;
                    node.style.backgroundColor = "yellow";
                }
            }
        });
    };

    const paragraphs = Array.from(bodyContent.getElementsByTagName("p"));
    processNodes(paragraphs, node => false);

    document.getElementById("main-body-stat").innerText = `${mainBodyCount} واژه`;
    document.getElementById("ref-stat").innerText = `${refCount} واژه`;
    document.getElementById("total-stat").innerText = `${mainBodyCount + refCount} واژه`;
}