مدیاویکی:Gadget-CheckDictation.js

ویکی‌پدیادان، آچیق بیلیک‌لیک‌دن

' 'قئید:' یازدیق‌دان سونرا دییشیک‌لیک‌لری گؤرمک اوچون براوزئرینیزین کئش یادداشیندا تمیزلمه‌نیز لازیم اولا بیلر.

  • 'فایرفاکس / سافاری:Shift دویمه‌سینه باسین "یئنی‌دن یوکله"-ا داخیل اولون یا دا Ctrl-F5 یا Ctrl-R ائدین (ماج اوچون ⌘-R).
  • 'گووگل کروم:'Ctrl+Shift+R باسین. (ماج اوچون ⌘-Shift-R)
  • 'اینترنت ایکسپئلور: کلید Ctrl باسین یئنی‌لئ 'یئ داخیل اولون یا دا Ctrl-F5 ائدین.
  • 'اوپئرا:' آلت‌لری → سئچیملر 'دن اؤنبئللیغی Tools → Preferences تمیزلیین.
$(function () {
  if (mw.config.get('wgAction') !== 'view' && mw.config.get('wgAction') !== 'edit') { return; }
  if (mw.config.get('wgNamespaceNumber') !== 0 && mw.config.get('wgNamespaceNumber') !== 12) { return; }
  if (mw.util.getParamValue('diff') || mw.util.getParamValue('oldid')) { return; }
  if ($('.noarticletext').length) { return; }

  $.getJSON('//tools.wmflabs.org/checkdictation-fa/check/' + mw.config.get('wgPageName')).then(function (result) {
    if (!Array.isArray(result.result)) { mw.notify(result.error); return; }
    var issues = result.result;
    if (issues.length === 0) {
      console.log('ابزار بررسی املاء اشکالی در صفحه پیدا نکرد.');
      return;
    }
    var availableTypes = {};
    issues.forEach(function (x) {
      availableTypes[x.type] = true;
    });
    var types = result.types, legend;

    legend = Object.keys(types).filter(function (x) { return availableTypes[x]; }).map(function (i) {
      var x = types[i];
      return '<div style="width: 12px; height: 12px; display: inline-block; background-color:' + x.color + '"></div> <span style="font-size: 10pt";>' + x.title + "</span>";
    }).join('،&nbsp;');

    $('#checkdictation-tool').remove();

    $('h1').after('<div id="checkdictation-tool" style="margin-bottom:8px; border:2px solid #b3000b; padding:1em; background-color:#fefce3;color:#000; -moz-border-radius:15px; -webkit-border-radius:15px; overflow:hidden;"><big>&nbsp;&nbsp;&nbsp;<em>' + issues.length.toLocaleString('fa') + ' مورد مشکوک به اشتباه نوشتاری یا شیوه‌نامه‌ای یافت شد!</em></big>&nbsp;&nbsp;<span style="font-size: 10pt";>(</span>' + legend + '<span style="font-size: 10pt";>)</span><div id="spellmarkedwords">&nbsp;&nbsp;&nbsp;&nbsp;موارد مشکوک به اشتباه:&nbsp;</div><br><div></div><div style="font-size: 8pt";>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;نکتهٔ ۱: بعضی از این موارد، فقط در حالت ویرایش دیده‌ می‌شوند!<div></div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;نکتهٔ ۲: با کلیک کردن بر روی کلمات بالا بدون رفتن به پنجرهٔ ویرایش به صورت خودکار می‌توانید دوْغرۇ سؤزله ديَیشدیرین .</div></div>');

    var main_regex = '\[؛؟\\s\\n\\r\\•●⚫⬤\\„\\”\\‚\\’\\‘\\“\\[\\]\\{\\}\\t\\<\\>\\.\\,\\"'+"\\'\\+\\!\\?\\-\\»«،\\:\\|\\(\\)\]";
    var start_regex = '\(\^\|' + main_regex + '\)';
    var end_regex = '\(\$\|' + main_regex + '\)';
    var articleBody = $('#bodyContent, #article')[0];

    var markedItems = [];
    issues.forEach(function (item, i) {
      if (i !== 0) { markedItems.push('، '); }
      var word = item.word, type = types[item.type], suggestions = item.suggestions, regexp, preparedId;
      regexp = type.syntax ?
        word.replace(/([\[\]\{\}])/g, '\\$1') :
        new RegExp(start_regex + '(' +
          word.replace(/([ء-يٓ-ٕپچژگکكڪﻙﻚیﻱﻲكﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ-ﻴ])/g, '$1\[ً-ِْٰٔ\]\*') +
          ')' + end_regex, 'g');
      preparedId = "tool" + encodeURI(word).replace(/%/g, '.');
      markWord(articleBody, regexp, suggestions[0] || type.hint, type.color, preparedId);
      var element = $('<span>', {
        style: "background-color: " + type.color,
        text: word,
        title: suggestions[0] || type.hint
      });
      element.css('cursor', 'pointer');
      element.click(function () {
          if (!type.autofix) { location.hash = preparedId; return; }
        dictationReplaceDialog(
          suggestions[0] ?
            ('آیا می‌خواهید «' + word + '» را با «' + suggestions[0] + '» جایگزین کنید؟') :
            ('«' + word + '» ایستیرسیز یئنی بیر سوزله دَیشدیرین؟'),
          suggestions[0] || word
        ).then(function (toWord) {
          toWord = toWord.replace(/\200c /g, ' ').replace(/ \200c/g, ' ');
          loadPage(mw.config.get('wgPageName')).then(function (text) {
            return savePage(
              mw.config.get('wgPageName'),
              text.replace(regexp, '$1' + toWord + '$3'),
              'جایگزینی خودکار اشتباه نوشتاری «' + word + '» با «' + toWord + '» ([[ویکی‌پدیا:اشتباه‌یاب|ابزار بررسی املائی]])'
            );
          }).then(function () {
            mw.notify('انجام شد، لطفاً بررسی کنید');
            location.href = mw.util.getUrl(mw.config.get('wgPageName'), { diff: 'last'} );
          });
        });
      });
      markedItems.push(element[0]);
    });
    $('#spellmarkedwords').append(markedItems);
  });
});

// Copyedited from https://de.wikipedia.org/wiki/MediaWiki:Gadget-Rechtschreibpruefung.js
function markWord(node, text, hint, color, preparedId)
{
  var pos, len, newnodes = 0;
  var newnode, middlenode, endnode;
 
  // textnode - search for word
  if (node.nodeType == 3)
  {
    pos = node.data.search(text);
    if(pos >= 0)
    {
      // create new span-element
      newnode = $('<span>', {
        style: "background-color: " + color,
        title: hint,
        id: preparedId
      })[0];
 
      // get length of the matching part
      len = node.data.match(text)[0].length;
 
      // splits content in three parts: begin, middle and end
      middlenode = node.splitText(pos);
      endnode = middlenode.splitText(len);
 
      // appends a copy of the middle to the new span-node
      newnode.appendChild(middlenode.cloneNode(true));
      // replace middlenode with the new span-node
      middlenode.parentNode.replaceChild(newnode, middlenode);
 
      newnodes = 1;
    }
  }
  else if ((node.nodeType == 1)  // element node
           && (node.hasChildNodes()) // with child nodes
           && (node.tagName.toLowerCase() != "script") // no script, style and form
           && (node.tagName.toLowerCase() != "style")
           && (node.tagName.toLowerCase() != "form"))
  {
    var this_child;
    for (this_child = 0; this_child < node.childNodes.length; this_child++)
    {
      this_child = this_child + markWord(node.childNodes[this_child], text, hint, color, preparedId);
    }
  }
  return newnodes;
}

function loadPage(title) {
  return new mw.Api().get({
    action: 'query',
    prop: 'revisions',
    titles: title,
    rvprop: 'content',
    format: 'json'
  }).then(function (data) {
    return $.map(data.query.pages, function (value) { return value; })[0].revisions[0]['*'];
  });
}

function savePage(title, text, summary) {
  return new mw.Api().post({
    action: 'edit',
    title: title,
    text: text,
    summary: summary,
    nocreate: '',
    minor: '',
    token: mw.user.tokens.get('csrfToken')
  }).then(function (data) {
    if (data.error && data.error.info) {
      mw.notify(data.error.info);
    }
  }, function (data) {
    mw.notify(data);
  });
}

function dictationReplaceDialog(title, suggestion) {
  var defer = $.Deferred();
  $('#dictationform').remove();
  $('<div>', { text: title }).append(
    '<br><br>',
    $('<input>', { id: 'dictationform-input', value: suggestion })
  ).dialog({
    width: 500,
    title: 'اصلاح کلی در متن',
    modal: true,
    buttons: [{
      text: 'ایصلاح اولسون',
      class: 'ui-button-green',
      click: function () { defer.resolve($('#dictationform-input', this).val()); $(this).dialog('close'); }
    }],
    close: function () {
      $('#dictationform').remove();
    }
  }).parent().prop('id', 'dictationform');
  return defer;
}