MediaWiki:Gadget-missingLabels.js

Վիքիպեդիայից՝ ազատ հանրագիտարանից

Ծանուցում. Հիշելուց հետո կատարված փոփոխությունները տեսնելու համար մաքրեք ձեր զննարկիչի հիշապահեստը. Mozilla / Firefox / Safari՝ Ctrl+Shift+R (Cmd+Shift+R Mac OS X-ում) Konqueror՝ F5 Opera՝ Tools→Preferences ընտրացանկից։ Internet Explorer՝ Ctrl+F5

$.when($.ready).then(function() {
    mw.loader.using(['mediawiki.util', 'oojs-ui'], function() {

        function start(qList) {
            function MainDialog(config) {
                MainDialog.super.call(this, config);
            }
            OO.inheritClass(MainDialog, OO.ui.ProcessDialog);

            MainDialog.static.name = 'myDialog';
            MainDialog.static.title = 'Թարգմանել Վիքիտվյլաների պիտակները';

            MainDialog.static.actions = [
                {
                    action: 'save',
                    label: 'Փակել',
                    flags: 'destructive'
                }
            ];

            MainDialog.prototype.getActionProcess = function ( action ) {
                var dialog = this;
                if ( action ) {
                    return new OO.ui.Process( function () {
                        dialog.close( {
                            action: action
                        } );
                    } );
                }
                return MainDialog.super.prototype.getActionProcess.call( this, action );
            };
            
            MainDialog.prototype.initialize = function() {
                MainDialog.super.prototype.initialize.call(this);
                this.content = new OO.ui.PanelLayout({
                    padded: true,
                    expanded: false
                });
                var that = this;
                this.skipBtn.on('click', function() {
                    that.next(qList);
                    that.labelInput.setValue('');
                    that.descriptionInput.setValue('');
                });
                this.saveBtn.on('click', function() {
                    var label = that.labelInput.value;
                    var description = that.descriptionInput.value;
                    var id = that.CurrentQ;
                    var labelRequest = {
                        "action": "wbsetlabel",
                        "id": id,
                        "language": "hy",
                        "value": label,
                        "summary": "with [[:hy:MediaWiki:Gadget-missingLabels.js|missingLabels.js]]"
                    };
                    var descriptionRequest = {
                        "action": "wbsetdescription",
                        "id": id,
                        "language": "hy",
                        "value": description,
                        "summary": "with [[:hy:MediaWiki:Gadget-missingLabels.js|missingLabels.js]]"
                    };
                    if (label) {
                        wbApi.postWithToken('csrf', labelRequest).then(function() {
                            if (description) {
                                wbApi.postWithToken('csrf', descriptionRequest);
                            }
                        });
                    } else if (description) {
                        wbApi.postWithToken('csrf', descriptionRequest);
                    }

                    that.labelInput.setValue('');
                    that.descriptionInput.setValue('');
                    that.next(qList);
                });

                var headerRow = $('<tr>').append('<th>Լեզու</th>', '<th>Պիտակ</th>', '<th>Նկարագրություն</th>');
                var bodyRows = [];

                this.table.$element.append(headerRow, bodyRows);

                this.content.$element.append(
                    [
                        this.labelInput.$element,
                        this.descriptionInput.$element,
                        this.openQBtn.$element,
                        this.skipBtn.$element,
                        this.saveBtn.$element,
                        this.table.$element
                    ]);
                this.$body.append(this.content.$element);
                this.next(qList);
            };

            MainDialog.prototype.CurrentQ = '';

            MainDialog.prototype.getBodyHeight = function() {
                return window.innerHeight;
            };

            MainDialog.prototype.getSize = function() {
                return 'larger';
            };

            MainDialog.prototype.labelInput = new OO.ui.TextInputWidget({
                placeholder: 'Պիտակ'
            });

            MainDialog.prototype.descriptionInput = new OO.ui.TextInputWidget({
                placeholder: 'Նկարագրություն'
            });

            MainDialog.prototype.openQBtn = new OO.ui.ButtonWidget({
                label: 'Բացել Վիքիդատայում',
                href: "https://www.wikidata.org/wiki/" + this.CurrentQ,
                target: "_blank"
            });

            MainDialog.prototype.skipBtn = new OO.ui.ButtonWidget({
                label: 'Չգիտեմ',
                flags: [
                    'primary',
                    'destructive'
                ]
            });

            MainDialog.prototype.saveBtn = new OO.ui.ButtonWidget({
                label: 'Պահել',
                flags: [
                    'primary',
                    'progressive'
                ]
            });

            MainDialog.prototype.table = new OO.ui.Widget({
                $element: $('<table class="wikitable">')
            });

            MainDialog.prototype.next = function(l) {
                if (l.length == 0) {
                    this.close();
                    OO.ui.alert( 'Չթարգմանված տարր չկա։' );
                    return;
                }
                var q = getRandomItemFromList(l);
                this.CurrentQ = q;
                this.openQBtn.setHref("https://www.wikidata.org/wiki/" + this.CurrentQ);
                return nextFromList(this, q);
            };
            
            var preferredLangs = ["en", "ru", "es", "de", "fr"];

			function customSort(a, b) {
			    var indexA = preferredLangs.indexOf(a);
			    var indexB = preferredLangs.indexOf(b);
			
				if (indexA === -1 && indexB === -1) {
					return a.localeCompare(b);
				}
			    if (indexA !== -1 && indexB !== -1) {
			        return indexA < indexB ? -1 : 1;
			    }
			
			    return indexA !== -1 ? -1 : 1;
			}

            function nextFromList(that, q) {
                wbApi.get({
                    "action": "wbgetentities",
                    "format": "json",
                    "ids": q,
                    "props": "sitelinks|labels|descriptions|sitelinks/urls",
                    "formatversion": "2"
                }).then(function(res) {
                    if (!res.success) {
                        return;
                    }
                    var labels = res.entities[q].labels;
                    var descriptions = res.entities[q].descriptions;
                    var siteLinks = res.entities[q].sitelinks;
                    var langs = Array.from(new Set(Array.prototype.concat.apply([], [Object.keys(labels), Object.keys(descriptions), Object.keys(siteLinks).map(function(s) {
                        return s.split('wiki')[0];
                    })])));
                    langs.sort(customSort);
                    var headerRow = $('<tr>').append('<th>Լեզու</th>', '<th>Պիտակ</th>', '<th>Նկարագրություն</th>');
                    var bodyRows = [];
                    for (var i = 0; i < langs.length; i++) {
                        var lang = langs[i];
                        var label = '';
                        var description = '';
                        var link = lang;
                        if (lang == 'hy') {
                            that.labelInput.setValue(label);
                            that.descriptionInput.setValue(description);
                        }
                        if (labels[lang]) {
                            label = labels[lang].value;
                        }
                        if (descriptions[lang]) {
                            description = descriptions[lang].value;
                        }
                        if (siteLinks[lang + 'wiki']) {
                            link = '<a target="_blank" href="' + siteLinks[lang + 'wiki'].url + '">' + lang + '</a>';
                        }
                        bodyRows.push($('<tr>').append(
                            '<td>' + link + '</td>',
                            '<td>' + label + '</td>',
                            '<td>' + description + '</td>'));
                    }
                    $(that.table.$element).empty();
                    that.table.$element.append(headerRow, bodyRows);
                });
                return q;
            }

            var myDialog = new MainDialog({
                size: 'medium'
            });

            var windowManager = new OO.ui.WindowManager();
            $(document.body).append(windowManager.$element);

            windowManager.addWindows([myDialog]);
            windowManager.openWindow(myDialog);
        }

        var listTitle = 'Վիքիպեդիա:Ցանկեր/շատ_օգտագործվող_չթարգմանված_տարրեր';
        var myApi = new mw.Api();
        var wbApi = new mw.ForeignApi('https://www.wikidata.org/w/api.php');
        
        if (mw.config.get('wgPageName') == listTitle && (new URLSearchParams(window.location.search)).size === 0) {
            var links = document.querySelectorAll('#mw-content-text tbody a');
            var qs = [];
            links.forEach(function (l) {
                qs.push(l.innerText.replace('d:', ''));
            });
            start(qs);
        }
        else if (mw.config.get( 'wgNamespaceNumber' ) == 0)
        {
            var node = mw.util.addPortletLink(
                'p-cactions',
                null,
                mw.config.get( 'skin' ) === 'vector' || mw.config.get( 'skin' ) === 'vector-2022' ? 'Թարգմանել տարրերը' : '*',
                'ca-missingLabels',
                'Թարգմանել էջում օգտագործվող Վիքիտվյալների չթարգմանված տարրերը',
                '*'
            );
            $(node).on( 'click', function (e) {
                myApi.get({
                    "action": "query",
                    "prop": "wbentityusage",
                    "wbeulimit": "max",
                    "formatversion": "2",
                    "titles": mw.config.get('wgPageName')
                }).then(function(res) {
                    var data = res.query.pages[0].wbentityusage;
                    if (data == undefined) {
                    	data = {};
                    }
                    var missingQs = [];
                    var qs = Object.keys(data);
                    qs.forEach(function(q) {
                        var aspects = data[q].aspects.filter(function (val) {
                            return val.startsWith('L.');
                        });
    
                        if (aspects.length > 1 && aspects.includes('L.hy')) {
                            missingQs.push(q);
                        }
                    });
                    if (missingQs.length == 0) {
                        OO.ui.alert( 'Չթարգմանված տարր չկա։' );
                        return;
                    }
                    start(missingQs);
                });
                e.preventDefault();
            });
        }

        function getRandomItemFromList(list) {
            var index = getRandomInt(0, list.length-1);
            var rItem = list[index];
            list.splice(index, 1);
            return rItem;
        }

        function getRandomInt(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    });
});