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

از مشروطه
پرش به ناوبری پرش به جستجو

نکته: پس از ذخیره کردن ممکن است برای دیدن تغییرات نیاز باشد که حافظهٔ نهانی مرورگر خود را پاک کنید.

  • فایرفاکس / سافاری: کلید Shift را نگه دارید و روی دکمهٔ Reload کلیک کنید، یا کلید‌های Ctrl-F5 یا Ctrl-R را با هم فشار دهید (در رایانه‌های اپل مکینتاش کلید‌های ⌘-R)
  • گوگل کروم: کلیدهای Ctrl+Shift+R را با هم فشار دهید (در رایانه‌های اپل مکینتاش کلید‌های ⌘-Shift-R)
  • اینترنت اکسپلورر: کلید Ctrl را نگه‌دارید و روی دکمهٔ Refresh کلیک کنید، یا کلید‌های Ctrl-F5 را با هم فشار دهید
  • اپرا: بروید به Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
/*!
 * Developed by: [[User:Ebraminio]]
 * Distributed under the terms of the CC-BY-SA 3.0
 */
/*jslint browser: true, regexp: true */
/*global jQuery, mediaWiki*/
(function ($, mw) {
    'use strict';

    function displayProgress(form, message) {
        $('#' + form + ' div').hide();
        $('#' + form).append($('<div />', {
            'style': 'text-align:center; margin:3em 0;',
            'html': message + '<br/><img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'
        }));
    }

    function displayError(form, error) {
        $('#' + form + ' div').hide();

        $('#' + form).append($('<div />', {
            'style': 'color: #990000; margin-top: 0.4em;',
            'html': 'Error: ' + error
        }));
    }

    function editThePage(form, summary, content) {
        new mw.Api().post({
            'action': 'edit',
            'title': mw.config.get('wgPageName'),
            'summary': summary,
            'text': content,
            'format': 'json',
            'token': mw.user.tokens.get('editToken')
        }).done(function (data) {
            if (data.edit.result === 'Success') {
                window.location.reload();
            } else {
                displayError(form, 'Unknown result from API.');
            }
        }).fail(function () {
            displayError(form, 'Edit failed.');
        });
    }

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

    /**
     * This will help on better sorting on Persian string array
     */
    function dePersian(input) { // solve persian problem on sorting by replace characters in strings
        return input.replace(/ی/g, "ي")
            .replace(/ک/g, "ك")
            .replace(/گ/g, "كی")
            .replace(/ژ/g, "زی")
            .replace(/چ/g, "جی")
            .replace(/پ/g, "بی");
    }

    /**
     * String comparator for Persian
     */
    function customComparator(a, b) {
        var keyA = dePersian(a),
            keyB = dePersian(b);

        if (keyA < keyB) {
            return -1;
        }
        if (keyA > keyB) {
            return 1;
        }
        return 0;
    }

    /**
     * Escape string for regex
     */
    function escape(text) {
        return text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
    }

    /**
     * Will launch stub template adder
     */
    function launchDialog(arr) {
        arr.sort(customComparator);

        // remove any
        $('#stubForm').remove();
        // Define stub interface
        var stubs = $('<div />', {
            'id': 'stubForm',
            'style': 'position: relative;'
        }).append($('<div />', {
            'style': 'margin-top: 0.4em;',
            'html': 'انتخاب الگوی خرد: '
        }).append($('<select />', {
            'id': 'stubselect',
            'style': 'padding: 1px; vertical-align: baseline;'
        }))).dialog({
            width: 500,
            autoOpen: false,
            title: 'افزودن الگوی خرد',
            modal: true,
            buttons: {
                "افزودن": function () {
                    $(this).dialog({
                        buttons: {}
                    });
                    displayProgress('stubForm', 'افزودن الگوی خرد...');
                    fetchThePage(function (content) {
                        var template = $('#stubselect').val();

                        content = content.replace(
                            new RegExp('{{\\s*([^:}]*:)?(خرد|ناقص|' + escape(template) + ')\\s*}}\\n*', 'g'),
                            ''
                        );

                        if (!/خرد\}\}$/.test(content)) {
                            content = content + '\n\n';
                        }
                        editThePage('stubForm', 'افزودن الگوی خرد به کمک ابزار', content + '\n' + '{{' + template + '}}');
                    });
                }
            },
            "close": function () {
                $("#stubForm").remove();
            }
        });

        $('#stubselect').append($.map(arr, function (value) {
            return $('<option />', {
                html: value.replace(/^[^:]*:/, ""),
                val: value.replace(/^[^:]*:/, "")
            });
        }));

        stubs.dialog('open');
    }

    /**
     * Is a recursive function to retrieve all stub templates consequently
     */
    function getAllStubTemplates(callback, arr, eicontinue) {
        new mw.Api().get({
            'action': 'query',
            'list': 'embeddedin',
            'eititle': 'Template:Asbox',
            'eilimit': 500,
            'einamespace': 10,
            'format': 'json',
            'continue': '',
            'eicontinue': eicontinue
        }).done(function (data) {
            arr = arr.concat($.map(data.query.embeddedin, function (value) {
                return value.title;
            }));
            if (data['continue'] !== undefined) {
                getAllStubTemplates(callback, arr, data['continue'].eicontinue);
            } else {
                callback(arr);
            }
        });
    }

    /**
     * Initialize the tool
     */
    function initialize() {
        $(mw.util.addPortletLink('p-cactions', '#', 'خرد', 'ca-stub-adder', 'افزودن الگوی خرد')).click(function (e) {
            e.preventDefault();
            getAllStubTemplates(launchDialog, []);
        });
    }

    mw.loader.using('jquery.ui.dialog', function() {
        if (mw.config.get('wgNamespaceNumber') === 0
                && mw.config.get('skin') === 'vector'
                && mw.config.get('wgAction') === 'view') {
            initialize();
        }
    });
}(jQuery, mediaWiki));