User:Euphoria/common.js

From Test Wiki
Revision as of 10:36, 25 September 2025 by Euphoria (talk | contribs) (fix)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
//<nowiki>
mw.loader.using(['mediawiki.util', 'mediawiki.api'], function () {
    const pagePrefix = 'User:Euphoria/TestVfD';

    if (!mw.config.get('wgPageName').startsWith(pagePrefix) || mw.config.get('wgAction') !== 'view') return;

    $(async function () {
        const api = new mw.Api();

        $('#mw-content-text').find('h2, h3').each(function () {
            const heading = this;

            // Skip headings already inside a .vfd section
            if ($(heading).closest('.vfd').length) return;

            // Collect section text (everything until next h2/h3)
            let sectionText = '';
            $(heading).nextUntil('h2,h3').each(function () {
                sectionText += $(this).text();
            });

            // Only add buttons if section contains [[TargetPage]] link
            const linkMatch = heading.textContent.match(/\[\[([^\]]+)\]\]/) || sectionText.match(/\[\[([^\]]+)\]\]/);
            if (!linkMatch) return;

            const targetPage = linkMatch[1];

            const container = document.createElement('span');
            container.style.marginLeft = '6px';

            const actions = [
                { name: 'delete', color: '#e74c3c' },       // red
                { name: 'keep', color: '#27ae60' },         // green
                { name: 'no consensus', color: '#f1c40f' }  // yellow
            ];

            const buttons = [];

            actions.forEach(actionObj => {
                const btn = document.createElement('button');
                btn.textContent = actionObj.name.charAt(0).toUpperCase(); // D/K/N

                Object.assign(btn.style, {
                    width: '16px',
                    height: '16px',
                    fontSize: '65%',
                    padding: '0',
                    marginRight: '3px',
                    border: 'none',
                    borderRadius: '2px',
                    backgroundColor: actionObj.color,
                    color: '#fff',
                    cursor: 'pointer',
                    verticalAlign: 'middle',
                    transition: '0.15s'
                });

                btn.addEventListener('mouseenter', () => btn.style.filter = 'brightness(1.3)');
                btn.addEventListener('mouseleave', () => btn.style.filter = 'brightness(1)');

                btn.addEventListener('click', async function (e) {
                    e.preventDefault();
                    if (!confirm('Are you sure you want to close as ' + actionObj.name + '?')) return;

                    // Disable all buttons in this section
                    buttons.forEach(b => b.disabled = true);
                    btn.textContent = '…'; // processing indicator

                    try {
                        // 1️⃣ Get discussion page content
                        const data = await api.get({
                            action: 'query',
                            prop: 'revisions',
                            titles: mw.config.get('wgPageName'),
                            rvprop: 'content',
                            format: 'json'
                        });

                        const pages = data.query.pages;
                        const pageId = Object.keys(pages)[0];
                        let content = pages[pageId].revisions[0]['*'];
                        const discussionNewContent = `{{subst:vt|${actionObj.name}. --~~~~}}\n${content.trim()}\n{{subst:vb}}`;

                        // 2️⃣ Edit discussion page
                        await api.postWithToken('csrf', {
                            action: 'edit',
                            title: mw.config.get('wgPageName'),
                            text: discussionNewContent,
                            summary: 'Closed as ' + actionObj.name,
                            minor: true,
                            bot: true
                        });

                        // 3️⃣ Handle target page
                        if (actionObj.name === 'delete') {
                            await deletePageAndTalk(api, targetPage);
                        } else {
                            await keepOrNoConsensus(api, targetPage, actionObj.name);
                        }

                    } catch (err) {
                        alert('Error: ' + err);
                        buttons.forEach(b => b.disabled = false);
                        buttons.forEach(b => b.textContent = b.textContent.charAt(0).toUpperCase());
                    }
                });

                container.appendChild(btn);
                buttons.push(btn);
            });

            heading.appendChild(container);
        });

        // ===== Helper functions =====
        async function deletePageAndTalk(api, targetPage) {
            try {
                await api.postWithToken('csrf', {
                    action: 'delete',
                    title: targetPage,
                    reason: '[[' + mw.config.get('wgPageName') + ']]',
                    bot: true
                });

                const talkPage = 'Talk:' + targetPage;
                await api.postWithToken('csrf', {
                    action: 'delete',
                    title: talkPage,
                    reason: 'Parent page deleted via VfD closure [[' + mw.config.get('wgPageName') + ']]',
                    bot: true
                });

                alert('Discussion closed and "' + targetPage + '" along with its talk page deleted.');
                location.reload();
            } catch (err) {
                alert('Error deleting page/talk page: ' + err);
            }
        }

        async function keepOrNoConsensus(api, targetPage, actionName) {
            try {
                const articleData = await api.get({
                    action: 'query',
                    prop: 'revisions',
                    titles: targetPage,
                    rvprop: 'content',
                    format: 'json'
                });

                const articlePages = articleData.query.pages;
                const articleId = Object.keys(articlePages)[0];
                let articleContent = articlePages[articleId].revisions[0]['*'];
                articleContent = articleContent.replace(/\{\{vfd-new\}\}/gi, '').trim();

                await api.postWithToken('csrf', {
                    action: 'edit',
                    title: targetPage,
                    text: articleContent,
                    summary: 'VFD closed as ' + actionName,
                    minor: true,
                    bot: true
                });

                await updateTalkPage(api, targetPage, actionName);

            } catch (err) {
                alert('Error editing article: ' + err);
            }
        }

        async function updateTalkPage(api, targetPage, actionName) {
            try {
                const talkPage = 'Talk:' + targetPage;
                const talkData = await api.get({
                    action: 'query',
                    prop: 'revisions',
                    titles: talkPage,
                    rvprop: 'content',
                    format: 'json'
                });

                const talkPages = talkData.query.pages;
                const talkId = Object.keys(talkPages)[0];
                let talkContent = '';

                if (talkId !== '-1' && talkPages[talkId].revisions) {
                    talkContent = '{{vfd-kept-new}}\n' + talkPages[talkId].revisions[0]['*'].replace(/^\s+/, '');
                } else {
                    talkContent = '{{vfd-kept-new}}';
                }

                await api.postWithToken('csrf', {
                    action: 'edit',
                    title: talkPage,
                    text: talkContent,
                    summary: 'VFD closed as ' + actionName,
                    minor: true,
                    bot: true
                });

                alert('Discussion closed and "' + targetPage + '" updated. Talk page updated.');
                location.reload();

            } catch (err) {
                alert('Error editing talk page: ' + err);
            }
        }

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