Jump to content

User:Ajbura/anrfc-lister.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki>
var ANRFC = {
    init: function() {
        $("#p-cactions ul.vector-menu-content-list").append("<li id='ca-anrfc' style='color: unset' onclick='ANRFC.toggle();'><a>ANRFC lister</a></li>");
        console.log('ANRFC lister running...');
    },
    bindDiscussion: function(wikitext, rawData, initDate, discussionIndex) {
        var discussions = [
            '=== Administrative discussions ===',
            '=== Requests for comment ===',
            '=== Deletion discussions ===',
            '=== Other types of closing requests ==='
        ];

        var firstPart = wikitext.slice(0, wikitext.indexOf(discussions[discussionIndex]));
        wikitext = wikitext.slice(wikitext.indexOf(discussions[discussionIndex]));
        var isLastDiscussion = (discussionIndex == discussions.length - 1);
        var relventDiscussion = (isLastDiscussion)? wikitext: wikitext.slice(0, wikitext.indexOf(discussions[discussionIndex + 1]));
        wikitext = (isLastDiscussion)? '': wikitext.slice(wikitext.indexOf(discussions[discussionIndex + 1]));
   
        var initMatches = relventDiscussion.match(/((i|I)nitiated\|[\d]{1,2}:[\d]{1,2},\s[\d]{1,2}\s[\w]+\s[\d]{4}\s\([\w]+\))/g);

        function dateToObj(dateString) {
            var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
            var oDate = dateString.split(/, | /);
            oDate[0] = oDate[0].match(/[\d]{1,2}:[\d]{1,2}/)[0];
            var time = {
                hh: oDate[0].match(/([\d]{1,2}):/)[1],
                mm: oDate[0].match(/:([\d]{1,2})/)[1]
            }
            date = {
                time: time,
                day: parseInt(oDate[1]),
                month: months.indexOf(oDate[2]),
                year: parseInt(oDate[3])
            }
            return date;
        }

        function isInitDateLatest(matchDate, initDate) {
            if (initDate.year > matchDate.year) return true;
            if (initDate.year < matchDate.year) return false;
            if (initDate.month > matchDate.month) return true;
            if (initDate.month < matchDate.month) return false;
            if (initDate.day > matchDate.day) return true;
            if (initDate.day < matchDate.day) return false;
            if (initDate.time.hh > matchDate.time.hh) return true;
            if (initDate.time.hh < matchDate.time.hh) return false;
            if (initDate.time.mm > matchDate.time.mm) return true;
            if (initDate.time.mm < matchDate.time.mm) return false;
            return true;
        }

        var initDateObj = dateToObj(initDate);
        var matchIndex = (initMatches != null)? initMatches.length - 1: -1;
        if (initMatches != null) for (; matchIndex >= 0; matchIndex--) {
            if (isInitDateLatest(dateToObj(initMatches[matchIndex]), initDateObj)) break;
        }

        if (matchIndex === -1) {
            var left = relventDiscussion.slice(0, relventDiscussion.indexOf('===='));
            relventDiscussion = relventDiscussion.slice(relventDiscussion.indexOf('===='));
            relventDiscussion = left + rawData + '\n\n' + relventDiscussion;
        } else {
            var afterDate = initMatches[matchIndex];

            var left = relventDiscussion.slice(0, relventDiscussion.indexOf(afterDate));
            relventDiscussion = relventDiscussion.slice(relventDiscussion.indexOf(afterDate));
            left = left + relventDiscussion.slice(0, relventDiscussion.indexOf('===='));
            relventDiscussion = relventDiscussion.slice(relventDiscussion.indexOf('===='));

            relventDiscussion = left + rawData + '\n\n' + relventDiscussion;
        }

        return (firstPart + relventDiscussion + wikitext);
    },
    onSubmit: function(dropDown, messageInput, keyId) {
        if (dropDown.getMenu().findSelectedItem() == null) return OO.ui.alert( 'Please select discussion section from dropdown menu!' ).done(function() { dropDown.focus(); } );
        var discussionIndex = dropDown.getMenu().findSelectedItem().getData();
        var message = messageInput.getValue();

        var pageName = mw.config.get('wgPageName');
        var sectionTitle = $('#' + keyId).prev().children('.mw-headline').text();

        var initDateRegx = /([\d]{1,2}:[\d]{1,2},\s[\d]{1,2}\s[\w]+\s[\d]{4}\s\([\w]+\))/;
        var initDateMatches = null;
        var nextEl = $('#' + keyId);
        do {
            if (nextEl.next().hasClass('boilerplate')) nextEl = nextEl.next().children('p');
            else nextEl = nextEl.next();
            
            initDateMatches = nextEl.text().match(initDateRegx);
        } while (initDateMatches == null);

        var initDate = initDateMatches[0];
        var headlineRaw = "==== [[" + pageName + "#" + sectionTitle + "]] ====";
        var initRaw = "{{initiated|" + initDate + "}}";
        var rawData = headlineRaw + "\n" + initRaw + " " + message +" ~~~~";

        new mw.Api().get( {
            action: 'parse',
            page: "Wikipedia:Closure_requests",
            prop: 'wikitext'
        }).done(function(result) {
            var wikitext = result.parse.wikitext['*'];
            if (wikitext.replaceAll(' ', '_').match((pageName + "#" + sectionTitle).replaceAll(' ', '_')) != null) return OO.ui.alert('This discussion is already listed.')

            wikitext = ANRFC.bindDiscussion(wikitext, rawData, initDate, discussionIndex);

            new mw.Api().postWithEditToken( {
                action: 'edit',
                title: "Wikipedia:Closure_requests",
                text: wikitext,
                summary: 'Listing new discussion using [[User:Ajbura/anrfc-lister.js|anrfc-lister]]',
                nocreate: true
            }).done(function(result) {
                if ( result && result.edit && result.edit.result && result.edit.result === 'Success' ){
                    OO.ui.confirm( 'This discussion has been listed on WP:ANRFC. Would you like to see it?' ).done( function ( confirmed ) {
                        if ( confirmed ) {
                            window.open("https://en.wikipedia.org/wiki/Wikipedia:Closure_requests", "_blank");
                        }
                    } );
                    
                }
            });
        });
    },
    addForm: function(el) {
        var keyId = el.getAttribute('indexKey') + "-anrfcBox";
        if (document.getElementById(keyId) != null) {
            return document.getElementById(keyId).remove();
        }
        $(el.parentElement).after('<div id="' + keyId + '"></div>');
        $('#' + keyId).css({
            'margin': '16px 0',
            'padding': '16px',
            'background-color': '#f3f3f3',
            'border': '1px solid grey'
        });

        var dropDown = new OO.ui.DropdownWidget({
            label: 'Dropdown menu: Select discussion section',
            menu: {
                items: [
                    new OO.ui.MenuOptionWidget( {
                        data: 0,
                        label: 'Administrative discussions'
                    } ),
                    new OO.ui.MenuOptionWidget( {
                        data: 1,
                        label: 'Requests for comment'
                    } ),
                    new OO.ui.MenuOptionWidget( {
                        data: 2,
                        label: 'Deletion discussions'
                    } ),
                    new OO.ui.MenuOptionWidget( {
                        data: 3,
                        label: 'Other types of closing requests'
                    } )
                ]
            }
        });

        var messageInput = new OO.ui.MultilineTextInputWidget({
            placeholder: 'Custom message (optional)',
            multiline: true,
            autosize: true,
            maxRows: 4
        });

        var submitButton = new OO.ui.ButtonWidget({ 
            label: 'Submit',
            flags: [
                'primary',
                'progressive'
            ]
        });

        $('#' + keyId).append('<h3 style="margin: 0 0 16px;">List this discussion on <a href="https://en.wikipedia.org/wiki/Wikipedia:Closure_requests" target="_blank">Wikipedia:Closure requests</a></h3>');
        var wrapper = document.createElement('div');
        $(wrapper).append('<p>Under section: </p>');
        $(wrapper).append(dropDown.$element);
        $('#' + keyId).append(wrapper);
        
        var wrapper = document.createElement('div');
        $(wrapper).css({ 'margin-top': '8px' });
        $(wrapper).append(messageInput.$element);
        $(wrapper).append($(submitButton.$element).css({
            'margin-top': '8px',
        }));
        $('#' + keyId).append(wrapper);

        submitButton.on('click', function() { ANRFC.onSubmit(dropDown, messageInput, keyId); } );

    },
    addLabels: function () {
        $('span.mw-editsection').each(function(index) {
            $(this.parentElement).append("<a indexKey="+ index +" class='mw-ANRFC' onclick='ANRFC.addForm(this)'>List on ANRFC</a>");
            $('a.mw-ANRFC').css({ "margin-left": "8px", "font-size": "small", "font-family": "sans-serif" });
        });
    },
    removeLabels: function () {
        $('a.mw-ANRFC').each(function() {
            this.remove();
            var keyId = this.getAttribute('indexKey') + "-anrfcBox";
            if (document.getElementById(keyId) != null) {
                return document.getElementById(keyId).remove();
            }
        });
    },
    toggle: function () {
        if ($("#ca-anrfc a").css('color') == 'rgb(255, 0, 0)') {
            $("#ca-anrfc a").css('color', '');
            ANRFC.removeLabels();
        } else {
            $("#ca-anrfc a").css('color', 'red');
            ANRFC.addLabels()
        }
    },
};

mw.loader.using(['oojs-ui-widgets', 'oojs-ui-windows'], function() {
    ANRFC.init();    
});
// </nowiki>