صارف:Yethrosh/تختۂ مشق.js

آزاد دائرۃ المعارف، ویکیپیڈیا سے

تفصیل کے لیے کھولیں کے بٹن پر کلک کریں یاددہانی: محفوظ کرنے کے بعد تازہ ترین تبدیلیوں کو دیکھنے کے لیے آپ کو اپنے براؤزر کا کیش صاف کرنا ہوگا۔

  • فائرفاکس/ سفاری: جب Reload پر کلک کریں تو Shift دبا کر رکھیں، یا Ctrl-F5 یا Ctrl-R دبائیں (Mac پر R- )
  • گوگل کروم: Ctrl-Shift-R دبائیں (Mac پر Shift-R-⌘)
  • انٹرنیٹ ایکسپلورر: جب Refresh پر کلک کریں تو Ctrl یا Ctrl-F5 دبائیں
  • اوپیرا: Tools → Preferences میں جائیں اور کیش صاف کریں

mw.loader.using(['mediawiki.api', 'mediawiki.util', 'jquery'], function() {
    $(function() {

        // صفحہ کھولنے کے لیے
        async function loadPage(title) {
            try {
                const data = await new mw.Api().get({
                    action: 'query',
                    prop: 'revisions',
                    titles: title,
                    rvprop: 'content',
                    format: 'json'
                });
                const pageId = Object.keys(data.query.pages)[0];
                return data.query.pages[pageId].revisions[0]['*'];
            } catch (error) {
                throw new Error('صفحہ کے مندرجات اخذ نہیں کیے جا سکے: ' + error);
            }
        }

        // صفحہ محفوظ کرنے کے لیے
        async function savePage(title, newText) {
            try {
                const data = await new mw.Api().post({
                    action: 'edit',
                    title: title,
                    text: newText,
                    summary: 'تجربہ',
                    token: mw.user.tokens.get('csrfToken')
                });
                if (data.error && data.error.info) {
                    throw new Error(data.error.info);
                } else {
                    return 'ترمیم مکمل ہوئی!';
                }
            } catch (error) {
                throw new Error('ترمیم نہیں کی جا سکی: ' + error);
            }
        }

        // بعض الفاظ کے آخر میں دو زبر لگانے کے لیے
        function addDoZabar(words, text) {
            words.forEach(word => {
                const DOZABAR = '\u064B';
                const regex = new RegExp('(?<!\\S)' + word + '(?!\\S)(?!' + DOZABAR + ')', 'g');
                text = text.replace(regex, word + DOZABAR);
            });
            return text;
        }

        // جن الفاظ کے آخر میں دو زبر لگانے ہیں
        const doZabarWords = [
            'اتفاقا', 'الزاما', 'فوقتا', 'اتفاقا'
        ];

        // چند ضروری فارمیٹنگ کا نفاذ
        function formatText(text) {
    // Add space before opening brackets if not preceded by space, <, >, [, ], {, }, or start of line
    text = text.replace(/(?<!\s)(?<![<>\[\]\{\}])(?<!^)(\()/gm, ' $1')
        .replace(/(?<!\s)(?<![<>\[\]\{\}])(?<!^)(\[)/gm, ' $1')
        .replace(/(?<!\s)(?<![<>\[\]\{\}])(?<!^)(\{)/gm, ' $1');

    // Remove space after opening brackets
    text = text.replace(/(\(+)\s+/g, '$1')
        .replace(/(\[+)\s+/g, '$1')
        .replace(/(\{+)\s+/g, '$1');

    // Remove space before closing brackets unless it starts from a new line
    text = text.replace(/([^\S\r\n])+(\)+)/g, '$2')
        .replace(/([^\S\r\n])+(\]+)/g, '$2')
        .replace(/([^\S\r\n])+(\}+)/g, '$2');

            // Add space after closing brackets in specific cases
            text = text.replace(/(\)+)(?=[^\s\.,،؛۔<>\[\]\{\}])/g, '$1 ')
                .replace(/(\]+)(?=[^\s\.,،؛۔<>\[\]\{\}])/g, '$1 ')
                .replace(/(\}+)(?=[^\s\.,،؛۔<>\[\]\{\}])/g, '$1 ');

            // Add space after period, comma, asterisk, and hash symbols if not followed by space and other symbols
            text = text.replace(/(\۔)(?![\s\d\[\]\{\}\(\)<>»﴾\'\"\%])/g, '$1 ')
                .replace(/(\،)(?![\s\d\[\]\{\}\(\)<>»﴾\'\"\%])/g, '$1 ')
                .replace(/(^|\n)(\*)(?=[^\s])/g, '$1$2 ')
                .replace(/(^|\n)(\#)(?=[^\s])/g, '$1$2 ');

    // Remove space before comma and period
    text = text.replace(/\s+(\،)/g, '$1')
        .replace(/\s+(\۔)/g, '$1');
    
    // Remove spaces between ۔ or ، and <ref   
    // Add a space after </ref> if not followed by space or newline
    text = text.replace(/(\۔|\،)\s+(?=<ref)/g, '$1')
        .replace(/(<\/ref>)(?![\s\n\[\]\{\}\(\)<>\'\"\%])/g, '$1 ');


    return text;
}

        // مندرجات صفحہ کے ہر جز پر کام کرنے کے لیے
        const processPart = (part, replacements) => {
            replacements.forEach(([incorrect, correct]) => {
                const regex = new RegExp(incorrect, 'g');
                part = part.replace(regex, correct);
            });
            part = peshkarFunctions.formatText(part); // چند ضروری فارمیٹنگ کے نفاذ کے فنکشن کے سنگ
            return part;
        };

        // سانچوں اور روابط کو اصلاح سے مستثنیٰ رکھنے کے لیے
        const replaceOutside = function(text, replacements) {
            const parts = text.split(/(\[\[[\s\S]*?\]\]|\{\{[\s\S]*?\}\})/); // ریجیکس براے سانچہ و روابط
            for (let i = 0; i < parts.length; i++) {
                // محض ان الفاظ کی اصلاح کی جائے جو ویکی ربط یا سانچوں سے خارج ہوں
                if (!parts[i].startsWith('[[') && !parts[i].startsWith('{{')) {
                    parts[i] = processPart(parts[i], replacements);
                }
            }
            return parts.join('');
        };

const infoboxIdentifiers = ['infobox', 'Infobox'];

const infoboxTranslations = [
  ['Active', 'فعال'],
  ['No', 'نہیں']
];

async function extractInfobox(text) {
    let startIndex = -1;
    let endIndex = -1;
    let count = 0;
    let infoboxContent = '';

    for (const identifier of infoboxIdentifiers) {
        const pattern = new RegExp('{{\\s*' + identifier + '\\s*', 'i');
        startIndex = text.search(pattern);
        if (startIndex !== -1) {
            break;
        }
    }

    if (startIndex === -1) return '';

    for (let i = startIndex; i < text.length; i++) {
        if (text[i] === '{' && text[i + 1] === '{') {
            count++;
            i++;
        } else if (text[i] === '}' && text[i + 1] === '}') {
            count--;
            if (count === 0) {
                endIndex = i + 2;
                break;
            }
            i++;
        }
    }

    while (endIndex < text.length && /\s/.test(text[endIndex])) {
        endIndex++;
    }

    infoboxContent = count === 0 ? text.substring(startIndex, endIndex) : '';

    infoboxContent += '\n';

  const wikilinkRegex = /\[\[([^\]]+)\]\]/g;
  let matches = [...infoboxContent.matchAll(wikilinkRegex)];
  
  for (const match of matches) {
    const pageTitle = match[1].replace(/ /g, '_');
    const params = new URLSearchParams({
      action: 'query',
      titles: pageTitle,
      prop: 'langlinks',
      lllang: 'ur',
      format: 'json',
      origin: '*'
    });

    const apiUrl = `https://en.wikipedia.org/w/api.php?${params}`;

    try {
      const response = await fetch(apiUrl);
      const data = await response.json();
if (data.query && data.query.pages) {
      const page = data.query.pages;
      const pageId = Object.keys(page)[0];

      if (pageId !== "-1" && page[pageId].langlinks) {
        const urduTitle = page[pageId].langlinks[0]['*'];
        infoboxContent = infoboxContent.replace(match[0], `[[${urduTitle}]]`);
}
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }

  return infoboxContent;
}

async function getInfobox(pageContent) {
  if (infoboxIdentifiers.some(identifier => pageContent.includes(identifier))) {
    return pageContent;
  }
  const currentPage = mw.config.get('wgPageName');
  try {
    const data = await new mw.Api().get({
      action: 'query',
      prop: 'langlinks',
      titles: currentPage,
      lllang: 'en',
      formatversion: 2
    });

    if (data.query.pages.length > 0 && data.query.pages[0].langlinks && data.query.pages[0].langlinks.length > 0) {
      const englishTitle = data.query.pages[0].langlinks[0].title;

      const endpoint = 'https://en.wikipedia.org/w/api.php';
      const params = new URLSearchParams({
        action: 'query',
        prop: 'revisions',
        titles: englishTitle,
        rvprop: 'content',
        rvslots: 'main',
        formatversion: 2,
        format: 'json'
      });

      const response = await fetch(`${endpoint}?origin=*&${params.toString()}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const responseData = await response.json();
      if (responseData.query.pages.length > 0 && responseData.query.pages[0].revisions && responseData.query.pages[0].revisions.length > 0) {
        let content = responseData.query.pages[0].revisions[0].slots.main.content;
        content = content.replace(/\r/g, '');
content = content.replace(/\|\s*name\s*=\s*\w+/gi, '| name = Yethrosh/تختۂ مشق.js');
content = content.replace(/\r/g, '');
    content = content.replace(/<ref.*?\/ref>/g, '');
    content = content.replace(/]]s /g, ']] ').replace(/]] and \[\[/g, ']] اور [[').replace(/\]\], \[\[/g, ']], [[');
    content = content.replace(/–present\n/g, '-تا حال\n').replace(/– present\n/g, '- تاحال\n').replace(/–present /g, '-تا حال\n');
    content = content.replace(/– present /g, '- تاحال ');
    
        let infoboxContent = await extractInfobox(content);

        if (infoboxContent) {
          for (const [english, urdu] of infoboxTranslations) {
            const regex = new RegExp(`(\\|\\s*[^|=]+\\s*=\\s*)(${english})([^|}]*)`, 'gi');
            infoboxContent = infoboxContent.replace(regex, `$1${urdu}$3`);
          }
  
  const maintenanceTemplatesEndRegex = /(?:\r?\n|\r)(?=\{\{[^{]*\}\}(?:\r?\n|\r)*[\u0600-\u06FF])/;
  let match = maintenanceTemplatesEndRegex.exec(pageContent);
  let lastIndex = 0;

  while (match) {
    lastIndex = match.index + match[0].length;
    match = maintenanceTemplatesEndRegex.exec(pageContent.substring(lastIndex));
  }

  if (lastIndex > 0) {
    pageContent = pageContent.slice(0, lastIndex) + infoboxContent + pageContent.slice(lastIndex);
  } else {
    pageContent = infoboxContent + pageContent;
  }
        }
      } else {
        console.error('No content found for the English page');
      }
    } else {
    }
    return pageContent;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
        // اصل فنکشن
        async function imla(imlaWords, correctInfobox) {
    try {
        const pageTitle = mw.config.get('wgPageName');
        let pageContent = await loadPage(pageTitle);
        const originalContent = pageContent;

        if (correctInfobox) {
            pageContent = extractTemplates(pageContent, keywords);
        }

                pageContent = await getInfobox(pageContent);

				pageContent = await peshkarTranslateLinks.translateEnlinks(pageContent);
				//console.log(pageContent);
				
				
        		// پہلے دو زبر لگائے جائیں
        		pageContent = addDoZabar(doZabarWords, pageContent);

                // بعد ازاں صفحہ کے بقیہ مندرجات پر اصلاح کا عمل ہو
                pageContent = replaceOutside(pageContent, imlaWords);
				pageContent = peshkarFunctions.sortCategories(pageContent);


        const imlaCorrected = originalContent !== pageContent;
        if (imlaCorrected) {
            await savePage(pageTitle, pageContent); // اصلاحات کو صفحہ میں محفوظ کیا جا رہا ہے
            openDiffPage(pageTitle); // اصلاحات کے بعد فرق صفحہ کھولنے کے لیے
        } else { // اگر اصلاح کی ضرورت نہ ہو تو
            peshkarFunctions.removeStatusAnimation(); 
            mw.notify('اِس صفحہ میں اصلاح کی ضرورت محسوس نہیں ہوئی۔', {
    autoHide: false,
    tag: 'peshkar-notification',
    className: 'peshkar-notice'
});
        }
    } catch (error) {
            peshkarFunctions.removeStatusAnimation(); 
        mw.notify(error.message);
    }
}

        function openDiffPage(page) {
            const diffUrl = mw.util.getUrl(page, {
                diff: 'cur',
                oldid: 'prev'
            });
            window.location.href = diffUrl;
        }


// Function to create and show a peshkar dialog
function showPeshkarDialog() {
    // Create the modal container
    let peshkar = document.createElement('div');
    peshkar.id = 'peshkarModal';

    // Create the modal content
    let peshkarContent = document.createElement('div');
    peshkarContent.id = 'peshkarContent';
    peshkarContent.className = 'clearfix'; // Clearfix class to clear the floats

    // Create the title bar
    let peshkarName = document.createElement('div');
    peshkarName.id = 'peshkarTitle';
    let peshkarText = document.createTextNode('ویکی پیش کار (نسخۂ اولیں)');
    peshkarName.appendChild(peshkarText);
    peshkarContent.appendChild(peshkarName);


    let peshkarHeader = document.createElement('div');
    peshkarHeader.id = 'peshkarHeader';
    let titleText = document.createTextNode('کیا آپ واقعی املا کی غلطیوں کو خودکار طور پر درست کرنا چاہتے ہیں؟');
    peshkarHeader.appendChild(titleText);
    peshkarContent.appendChild(peshkarHeader);

    // Create a checkbox
    let checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = 'infoboxCheckbox';
    let label = document.createElement('label');
    label.htmlFor = 'infoboxCheckbox';
    label.appendChild(document.createTextNode('اور ساتھ ہی خانۂ معلومات کی تنظیم و ترتیب بھی مقصود ہے؟'));
    label.id = 'infoboxCheckboxText';
    peshkarContent.appendChild(checkbox);
    peshkarContent.appendChild(label);
    let br = document.createElement('br');
    br.id = 'lineBreakSpace';
    peshkarContent.appendChild(br);

    //Create list items
    let listHeader = document.createElement('div');
    listHeader.id = 'listHeader';
    let headerText = document.createTextNode('اگر آپ خانۂ معلومات کو مرتب کرنے کی غرض سے اس آپشن کو استعمال کر رہے ہیں تو درج ذیل ہدایات کو بغور ملاحظہ فرمائیں:');
    listHeader.appendChild(headerText);
    peshkarContent.appendChild(listHeader);
    
    let ul = document.createElement('ul');
    ul.id = 'durustiList';
    
    let li1 = document.createElement('li');
    li1.textContent = 'اس آپشن کو اسی وقت استعمال کریں جب خانۂ معلومات کے تمام پیرامیٹر علاحدہ سطروں کی بجائے ایک ہی سطر میں درج ہوں اور خانۂ معلومات کی حالت ابتر ہو۔';
    ul.appendChild(li1);
    
    let li2 = document.createElement('li');
    li2.textContent = 'اسے استعمال کرتے وقت یہ ملحوظ رکھیں کہ خانہ معلومات میں موجود دوسرے سانچوں کی فارمیٹنگ میں بھی تبدیلی ہو جاتی ہے جس کی بنا پر بعض سانچے درست نظر نہیں آتے۔';
    ul.appendChild(li2);
    
    let li3 = document.createElement('li');
    li3.textContent = 'اگر ایسا ہو تو اس آلہ سے ترمیم کے بعد آپ دوبارہ خانۂ ترمیم میں جا کر ان تبدیل شدہ سانچوں کے پیرامیٹر کو بدست خود درست کر دیں۔';
    ul.appendChild(li3);

	peshkarContent.appendChild(ul);
	
    // Add a button to close the modal
    let closeButton = document.createElement('button');
    closeButton.textContent = 'منسوخ کریں';
    closeButton.className = 'closeButton';
    closeButton.onclick = function() {
        peshkar.style.display = 'none';
        document.body.removeChild(peshkar);
    };
    peshkarContent.appendChild(closeButton);

    // Add a button to accept and perform the action
    let acceptButton = document.createElement('button');
    acceptButton.textContent = 'جی ہاں';
    acceptButton.className = 'acceptButton';
    acceptButton.onclick = function() {
        let checkboxValue = document.getElementById('infoboxCheckbox').checked;
        imla(imlaWords, checkboxValue); // Call the imla function with the checkbox value
peshkar.style.display = 'none';
        document.body.removeChild(peshkar);
            peshkarFunctions.showStatusAnimation();
    };
    peshkarContent.appendChild(acceptButton);

    // Append the modal content to the modal container
    peshkar.appendChild(peshkarContent);

    // Append the modal container to the document body
    document.body.appendChild(peshkar);
    
    $("#peshkarModal").draggable().resizable();
}


function addPortletLink() {
    const portlet = mw.util.addPortletLink(
        'p-cactions',
        '#',
        'املا درست کریں',
        'ca-durusti-imla',
        'پیش نظر صفحہ میں موجود املا کی غلطیوں کو خودکار طور پر درست کریں',
        null,
        '#ca-protect'
    );

    portlet.addEventListener('click', function(event) {
        event.preventDefault();
        showPeshkarDialog();
    });
}

        addPortletLink();

        const imlaWords = [
            [/(?<!\S)آبساز(?!\S)/, 'ہائیڈروجن'],
            [/(?<!\S)کرکت(?!\S)/, 'کرکٹ']
        ];
    });
});