User:Euphoria/common.js: Difference between revisions

From Test Wiki
Jump to navigation Jump to search
Content deleted Content added
fix
fix
Line 3: Line 3:
const pagePrefix = 'User:Euphoria/Test VfD';
const pagePrefix = 'User:Euphoria/Test VfD';
const currentPage = mw.config.get('wgPageName').replace(/_/g, ' ');
const currentPage = mw.config.get('wgPageName').replace(/_/g, ' ');

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


const api = new mw.Api();
const api = new mw.Api();


// --- API helpers ---
// --- API Helpers ---
const apiHelper = {
function apiEdit(title, content, summary, callback) {
api.postWithToken('csrf', { action: 'edit', title, text: content, summary, minor: true })
edit(title, content, summary, callback) {
api.postWithToken('csrf', { action: 'edit', title, text: content, summary, minor: true })
.done(callback)
.done(callback)
.fail(err => mw.notify(`Error editing "${title}": ${JSON.stringify(err)}`, { title: 'VfDcloser', type: 'error', timeout: 1500 }));
.fail(err => mw.notify(`Error editing "${title}": ${JSON.stringify(err)}`, { title: 'VfDcloser', type: 'error', timeout: 1500 }));
}
},
delete(title, reason, callback) {
api.postWithToken('csrf', { action: 'delete', title, reason })
.done(callback)
.fail(err => mw.notify(`Error deleting "${title}": ${JSON.stringify(err)}`, { title: 'VfDcloser', type: 'error', timeout: 1500 }));
},
fetch(title, callback) {
api.get({ action: 'query', prop: 'revisions', titles: title, rvslots: 'main', rvprop: 'content', format: 'json' })
.done(data => {
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
const content = (pageId !== '-1' && pages[pageId].revisions) ? pages[pageId].revisions[0].slots.main['*'] : '';
callback(content.trim());
});
}
};


// --- VfD Action Handler ---
function apiDelete(title, reason, callback) {
api.postWithToken('csrf', { action: 'delete', title, reason })
.done(callback)
.fail(err => mw.notify(`Error deleting "${title}": ${JSON.stringify(err)}`, { title: 'VfDcloser', type: 'error', timeout: 1500 }));
}

function fetchPage(title, callback) {
api.get({ action: 'query', prop: 'revisions', titles: title, rvslots: 'main', rvprop: 'content', format: 'json' })
.done(data => {
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
const content = (pageId !== '-1' && pages[pageId].revisions) ? pages[pageId].revisions[0].slots.main['*'] : '';
callback(content.trim());
});
}

// --- Action handler ---
function handleAction(targetPage, actionName) {
function handleAction(targetPage, actionName) {
fetchPage(currentPage, discussionContent => {
apiHelper.fetch(currentPage, discussionContent => {
const newDiscussion = `{{subst:vt|${actionName}. --~~~~}}\n${discussionContent}\n{{subst:vb}}`;
const newDiscussion = `{{subst:vt|${actionName}. --~~~~}}\n${discussionContent}\n{{subst:vb}}`;

apiEdit(currentPage, newDiscussion, `Closed as ${actionName}`, () => {
apiHelper.edit(currentPage, newDiscussion, `Closed as ${actionName}`, () => {


if (actionName === 'delete') {
if (actionName === 'delete') {
apiDelete(targetPage, `[[${currentPage}]]`, () => {
deletePageAndTalk(targetPage);
fetchPage('Talk:' + targetPage, talkContent => {
if (talkContent) {
apiDelete('Talk:' + targetPage, 'Parent page deleted via VfD', () => {
mw.notify('Discussion closed. Page and talk page deleted.', { title: 'VfDcloser', type: 'success', timeout: 1500 });
setTimeout(() => location.reload(), 1500);
});
} else {
mw.notify('Discussion closed. Page deleted.', { title: 'VfDcloser', type: 'success', timeout: 1500 });
setTimeout(() => location.reload(), 1500);
}
});
});
} else {
} else {
fetchPage(targetPage, targetContent => {
keepOrNoConsensus(targetPage, actionName);
targetContent = targetContent.replace(/\{\{vfd-new\}\}/gi, '').trim();
apiEdit(targetPage, targetContent, `VFD closed as ${actionName}`, () => {
const talkTemplate = '{{vfd-kept-new}}';
fetchPage('Talk:' + targetPage, talkContent => {
talkContent = talkContent ? `${talkTemplate}\n${talkContent}` : talkTemplate;
apiEdit('Talk:' + targetPage, talkContent, `VFD closed as ${actionName}`, () => {
mw.notify('Discussion closed. Page and talk page updated.', { title: 'VfDcloser', type: 'success', timeout: 1500 });
setTimeout(() => location.reload(), 1500);
});
});
});
});
}
}


Line 70: Line 48:
}
}


function deletePageAndTalk(title) {
// --- Build gadget-style buttons ---
apiHelper.delete(title, `[[${currentPage}]]`, () => {
$(function () {
apiHelper.fetch('Talk:' + title, talkContent => {
$('#mw-content-text').find('h2').each(function () {
const heading = this;
if (talkContent) {
apiHelper.delete('Talk:' + title, 'Parent page deleted via VfD', () => {
notifyAndReload('Discussion closed. Page and talk page deleted.');
});
} else {
notifyAndReload('Discussion closed. Page deleted.');
}
});
});
}


function keepOrNoConsensus(title, actionName) {
const categories = mw.config.get('wgCategories') || [];
apiHelper.fetch(title, content => {
if (categories.includes('VfD archive entries')) return;
const updatedContent = content.replace(/\{\{vfd-new\}\}/gi, '').trim();
apiHelper.edit(title, updatedContent, `VFD closed as ${actionName}`, () => {
updateTalkPage(title, actionName);
});
});
}


function updateTalkPage(title, actionName) {
// Get target page from heading text
const headingText = $(heading).text().trim();
const talkTemplate = '{{vfd-kept-new}}';
apiHelper.fetch('Talk:' + title, talkContent => {
if (!headingText) return;
const targetPage = headingText;
const updatedTalk = talkContent ? `${talkTemplate}\n${talkContent}` : talkTemplate;
apiHelper.edit('Talk:' + title, updatedTalk, `VFD closed as ${actionName}`, () => {
notifyAndReload('Discussion closed. Page and talk page updated.');
});
});
}


function notifyAndReload(message) {
// Container for buttons
mw.notify(message, { title: 'VfDcloser', type: 'success', timeout: 1500 });
const container = document.createElement('span');
container.style.marginLeft = '6px';
setTimeout(() => location.reload(), 1500);
}


// --- UI Button Creation ---
const actions = [
function createButtonsForHeading(heading, targetPage) {
{ name: 'delete', color: '#e74c3c', symbol: '✖' },
const container = document.createElement('span');
{ name: 'keep', color: '#27ae60', symbol: '✔' },
container.style.marginLeft = '6px';
{ name: 'no consensus', color: '#f1c40f', symbol: '⚖' }
];


actions.forEach(actionObj => {
const actions = [
const btn = document.createElement('a');
{ name: 'delete', color: '#e74c3c', symbol: '' },
btn.href = '#';
{ name: 'keep', color: '#27ae60', symbol: '' },
btn.textContent = actionObj.symbol;
{ name: 'no consensus', color: '#f1c40f', symbol: '⚖' }
];
btn.title = 'Close as ' + actionObj.name;
btn.className = 'vfd-action-link';


Object.assign(btn.style, {
actions.forEach(actionObj => {
display: 'inline-block',
const btn = document.createElement('a');
width: '18px',
btn.href = '#';
height: '18px',
btn.textContent = actionObj.symbol;
textAlign: 'center',
btn.title = 'Close as ' + actionObj.name;
lineHeight: '18px',
btn.className = 'vfd-action-link';
fontSize: '12px',
btn.dataset.disabled = 'false';
fontWeight: 'bold',
borderRadius: '2px',
backgroundColor: actionObj.color,
color: '#fff',
marginRight: '4px',
textDecoration: 'none',
cursor: 'pointer',
transition: '0.15s'
});


btn.addEventListener('mouseenter', () => {
Object.assign(btn.style, {
btn.style.filter = 'brightness(1.3)';
display: 'inline-block',
btn.style.transform = 'scale(1.2)';
width: '18px',
});
height: '18px',
btn.addEventListener('mouseleave', () => {
textAlign: 'center',
btn.style.filter = 'brightness(1)';
lineHeight: '18px',
btn.style.transform = 'scale(1)';
fontSize: '12px',
});
fontWeight: 'bold',
borderRadius: '2px',
backgroundColor: actionObj.color,
color: '#fff',
marginRight: '4px',
textDecoration: 'none',
cursor: 'pointer',
transition: '0.15s'
});


btn.addEventListener('click', e => {
btn.addEventListener('mouseenter', () => {
e.preventDefault();
if (btn.dataset.disabled === 'true') return;
btn.style.filter = 'brightness(1.3)';
if (!confirm(`Are you sure you want to close as ${actionObj.name}?`)) return;
btn.style.transform = 'scale(1.2)';
});


btn.addEventListener('mouseleave', () => {
// Disable all buttons in this heading
$(heading).find('.vfd-action-link').each((i, b) => {
if (btn.dataset.disabled === 'true') return;
b.style.opacity = '0.5';
btn.style.filter = 'brightness(1)';
b.style.cursor = 'not-allowed';
btn.style.transform = 'scale(1)';
});
});

btn.addEventListener('click', e => {
e.preventDefault();
if (btn.dataset.disabled === 'true') return;
if (!confirm(`Are you sure you want to close as ${actionObj.name}?`)) return;


handleAction(targetPage, actionObj.name);
// Disable all buttons under this heading
$(heading).find('.vfd-action-link').each((i, b) => {
b.style.opacity = '0.5';
b.style.cursor = 'not-allowed';
b.dataset.disabled = 'true';
b.style.filter = 'brightness(1)';
b.style.transform = 'scale(1)';
});
});


container.appendChild(btn);
handleAction(targetPage, actionObj.name);
});
});


heading.appendChild(container);
container.appendChild(btn);
});
});
});


heading.appendChild(container);
}

// --- Initialize ---
$(function () {
const categories = mw.config.get('wgCategories') || [];
if (categories.includes('VfD archive entries')) return;

$('#mw-content-text').find('h2').each(function () {
const headingText = $(this).text().trim();
if (!headingText) return;
createButtonsForHeading(this, headingText);
});
});
});
});
//</nowiki>
//</nowiki>

Revision as of 05:58, 1 October 2025

//<nowiki>
mw.loader.using(['mediawiki.util', 'mediawiki.api'], function () {
    const pagePrefix = 'User:Euphoria/Test VfD';
    const currentPage = mw.config.get('wgPageName').replace(/_/g, ' ');

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

    const api = new mw.Api();

    // --- API Helpers ---
    const apiHelper = {
        edit(title, content, summary, callback) {
            api.postWithToken('csrf', { action: 'edit', title, text: content, summary, minor: true })
                .done(callback)
                .fail(err => mw.notify(`Error editing "${title}": ${JSON.stringify(err)}`, { title: 'VfDcloser', type: 'error', timeout: 1500 }));
        },
        delete(title, reason, callback) {
            api.postWithToken('csrf', { action: 'delete', title, reason })
                .done(callback)
                .fail(err => mw.notify(`Error deleting "${title}": ${JSON.stringify(err)}`, { title: 'VfDcloser', type: 'error', timeout: 1500 }));
        },
        fetch(title, callback) {
            api.get({ action: 'query', prop: 'revisions', titles: title, rvslots: 'main', rvprop: 'content', format: 'json' })
                .done(data => {
                    const pages = data.query.pages;
                    const pageId = Object.keys(pages)[0];
                    const content = (pageId !== '-1' && pages[pageId].revisions) ? pages[pageId].revisions[0].slots.main['*'] : '';
                    callback(content.trim());
                });
        }
    };

    // --- VfD Action Handler ---
    function handleAction(targetPage, actionName) {
        apiHelper.fetch(currentPage, discussionContent => {
            const newDiscussion = `{{subst:vt|${actionName}. --~~~~}}\n${discussionContent}\n{{subst:vb}}`;

            apiHelper.edit(currentPage, newDiscussion, `Closed as ${actionName}`, () => {

                if (actionName === 'delete') {
                    deletePageAndTalk(targetPage);
                } else {
                    keepOrNoConsensus(targetPage, actionName);
                }

            });
        });
    }

    function deletePageAndTalk(title) {
        apiHelper.delete(title, `[[${currentPage}]]`, () => {
            apiHelper.fetch('Talk:' + title, talkContent => {
                if (talkContent) {
                    apiHelper.delete('Talk:' + title, 'Parent page deleted via VfD', () => {
                        notifyAndReload('Discussion closed. Page and talk page deleted.');
                    });
                } else {
                    notifyAndReload('Discussion closed. Page deleted.');
                }
            });
        });
    }

    function keepOrNoConsensus(title, actionName) {
        apiHelper.fetch(title, content => {
            const updatedContent = content.replace(/\{\{vfd-new\}\}/gi, '').trim();
            apiHelper.edit(title, updatedContent, `VFD closed as ${actionName}`, () => {
                updateTalkPage(title, actionName);
            });
        });
    }

    function updateTalkPage(title, actionName) {
        const talkTemplate = '{{vfd-kept-new}}';
        apiHelper.fetch('Talk:' + title, talkContent => {
            const updatedTalk = talkContent ? `${talkTemplate}\n${talkContent}` : talkTemplate;
            apiHelper.edit('Talk:' + title, updatedTalk, `VFD closed as ${actionName}`, () => {
                notifyAndReload('Discussion closed. Page and talk page updated.');
            });
        });
    }

    function notifyAndReload(message) {
        mw.notify(message, { title: 'VfDcloser', type: 'success', timeout: 1500 });
        setTimeout(() => location.reload(), 1500);
    }

    // --- UI Button Creation ---
    function createButtonsForHeading(heading, targetPage) {
        const container = document.createElement('span');
        container.style.marginLeft = '6px';

        const actions = [
            { name: 'delete', color: '#e74c3c', symbol: '✖' },
            { name: 'keep', color: '#27ae60', symbol: '✔' },
            { name: 'no consensus', color: '#f1c40f', symbol: '⚖' }
        ];

        actions.forEach(actionObj => {
            const btn = document.createElement('a');
            btn.href = '#';
            btn.textContent = actionObj.symbol;
            btn.title = 'Close as ' + actionObj.name;
            btn.className = 'vfd-action-link';
            btn.dataset.disabled = 'false';

            Object.assign(btn.style, {
                display: 'inline-block',
                width: '18px',
                height: '18px',
                textAlign: 'center',
                lineHeight: '18px',
                fontSize: '12px',
                fontWeight: 'bold',
                borderRadius: '2px',
                backgroundColor: actionObj.color,
                color: '#fff',
                marginRight: '4px',
                textDecoration: 'none',
                cursor: 'pointer',
                transition: '0.15s'
            });

            btn.addEventListener('mouseenter', () => {
                if (btn.dataset.disabled === 'true') return;
                btn.style.filter = 'brightness(1.3)';
                btn.style.transform = 'scale(1.2)';
            });

            btn.addEventListener('mouseleave', () => {
                if (btn.dataset.disabled === 'true') return;
                btn.style.filter = 'brightness(1)';
                btn.style.transform = 'scale(1)';
            });

            btn.addEventListener('click', e => {
                e.preventDefault();
                if (btn.dataset.disabled === 'true') return;
                if (!confirm(`Are you sure you want to close as ${actionObj.name}?`)) return;

                // Disable all buttons under this heading
                $(heading).find('.vfd-action-link').each((i, b) => {
                    b.style.opacity = '0.5';
                    b.style.cursor = 'not-allowed';
                    b.dataset.disabled = 'true';
                    b.style.filter = 'brightness(1)';
                    b.style.transform = 'scale(1)';
                });

                handleAction(targetPage, actionObj.name);
            });

            container.appendChild(btn);
        });

        heading.appendChild(container);
    }

    // --- Initialize ---
    $(function () {
        const categories = mw.config.get('wgCategories') || [];
        if (categories.includes('VfD archive entries')) return;

        $('#mw-content-text').find('h2').each(function () {
            const headingText = $(this).text().trim();
            if (!headingText) return;
            createButtonsForHeading(this, headingText);
        });
    });
});
//</nowiki>