User:RedShellMomentum/script/MOSTIES templates.js

// <nowiki>
/**
 * MOSTIES English-variety script
 */

(function () {
    'use strict';

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

        const varieties = [
            "South African English",
            "American English",
            "Australian English",
            "New Zealand English",
            "Hiberno-English",
            "Namibian English",
            "British English",
            "Nigerian English",
            "Pakistani English",
            "Indian English",
            "Canadian English",
            "Hong Kong English"
        ];

        const TEMPLATE_PREFIX = "Use ";
        const MONTH = "{{subst:CURRENTMONTHNAME}}";
        const YEAR = "{{subst:CURRENTYEAR}}";

        // Add button to actions menu
        const link = mw.util.addPortletLink(
            'p-cactions',
            '#',
            'MOSTIES templates',
            'ca-mosties',
            'Insert or update English-variety template'
        );

        $(link).on('click', function (e) {
            e.preventDefault();
            openPanel();
        });

        // Floating panel UI
        function openPanel() {
            const $panel = $('<div>')
                .css({
                    background: '#fff',
                    border: '1px solid #aaa',
                    padding: '12px',
                    position: 'fixed',
                    top: '80px',
                    right: '40px',
                    zIndex: 9999
                })
                .append('<strong>Select English variety:</strong><br><br>');

            varieties.forEach(function (variety) {
                $('<button>')
                    .text(variety)
                    .css({ margin: '3px' })
                    .on('click', () => applyTemplate(variety))
                    .appendTo($panel);
            });

            $('<button>')
                .text("Close")
                .css({ marginTop: '10px', display: 'block' })
                .on('click', () => $panel.remove())
                .appendTo($panel);

            $('body').append($panel);
        }

        // Main logic
        async function applyTemplate(variety) {
            const api = new mw.Api();
            const title = mw.config.get('wgPageName');

            const pageData = await api.get({
                action: 'query',
                prop: 'revisions',
                rvprop: 'content',
                titles: title,
                formatversion: 2
            });

            const text = pageData.query.pages[0].revisions[0].content;
            const namespace = mw.config.get('wgNamespaceNumber');

            const newTemplate =
                `{{${TEMPLATE_PREFIX}${variety}|date=${MONTH} ${YEAR}}}`;

            // Detect any existing Use [X] English template
            const reg = /\{\{Use\s+[^\}|]+English[^\}]*\}\}/i;
            const found = text.match(reg);

            // If the SAME variety already exists → do nothing
            if (found && found[0].includes(variety)) {
                mw.notify("MOSTIES: Template for this variety already present — no changes made.");
                return;
            }

            let updatedText;

            // Case 1: Replace existing template
            if (found) {
                updatedText = text.replace(reg, newTemplate);

            // Case 2: Draftspace (namespace 118) → insert after {{Draft article}}
            } else if (namespace === 118) {
                const draftRegex = /\{\{[Dd]raft article[^\}]*\}\}\s*/;

                if (draftRegex.test(text)) {
                    updatedText = text.replace(draftRegex, m => m + newTemplate + "\n");
                } else {
                    // Fallback if Draft article template not found
                    updatedText = newTemplate + "\n" + text;
                }

            // Case 3: Mainspace or other → insert at top
            } else {
                updatedText = newTemplate + "\n" + text;
            }

            // Save edit to Wikipedia
            await api.postWithToken('csrf', {
                action: 'edit',
                title: title,
                text: updatedText,
                summary: `[[User:RedShellMomentum/script/MOSTIES templates.js|script]]-assisted English-variety template addition per [[MOS:TIES]]`,
                minor: true
            });

            mw.notify(`Success!`);
            location.reload();
        }

    });
})();
// </nowiki>

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.