User:Asked42/QuickCat.js

(function {   if (typeof createCategories === 'undefined') {        var createCategories = {};    }    createCategories.api = new mw.Api;

$(document).ready(function {       var formHtml = `                            Create Category and Lists Pages                     Year:                                         Select Month(s):                          January                          February                          March                          April                          May  June  July  August  September  October  November <input type="checkbox" value="12"> December <label for="category-type" style="display: block; margin-bottom: 5px;">Select Type: <select id="category-type" style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 5px;"> Date Category Month Category <option value="wikinews-month">Wikinews Month List <option value="wikinews-date">Wikinews Date List <button id="preview-categories-button" style="background-color: #3366cc; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">Preview Pages <div id="preview-section" style="display: none; margin-top: 20px; padding: 20px; border: 1px solid #ccc; border-radius: 5px; max-width: 500px; margin: 20px auto;"> <h2 style="margin-bottom: 10px; text-align: center;">Preview Targeted Pages <button id="create-categories-button" style="background-color: #3366cc; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">Good to go        `;

$('#category-create-form').html(formHtml);

$('#preview-categories-button').click(function {           var year = $('#year').val.trim;            var months = $('#month-checkboxes input:checked').map(function { return $(this).val; }).get;            var categoryType = $('#category-type').val;

if (year && months.length > 0) { $('#preview-list').empty; var previewPromises = []; if (categoryType === 'date') { previewPromises = getPreviewDateCategories(year, months); } else if (categoryType === 'month') { previewPromises = getPreviewMonthCategories(year, months); } else if (categoryType === 'wikinews-month') { previewPromises = getPreviewWikinewsMonthList(year, months); } else if (categoryType === 'wikinews-date') { previewPromises = getPreviewWikinewsDateList(year, months); }               Promise.all(previewPromises).then(function(previewItems) {                    previewItems.forEach(function(monthItems) { monthItems.forEach(function(item) {                           var content = item.content;                            var checkbox = `                                    <input type="checkbox" value="${item.title}" checked> ${item.title}                                     <textarea style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 5px;" data-title="${item.title}">${content}                             `;                            $('#preview-list').append(checkbox);                        }); });                   $('#preview-section').show;                }).catch(function(error) {                    console.error('Error generating preview:', error);                    alert('An error occurred while generating the preview.');                }); } else { alert('Please fill in both Year and Month fields.'); }       });

$('#create-categories-button').click(function {           var year = $('#year').val.trim;            var selectedTitles = $('#preview-list input:checked').map(function { return $(this).val; }).get;            var categoryType = $('#category-type').val;

if (selectedTitles.length > 0) { var promises = selectedTitles.map(function(title) {                   return checkCategoryExists(title).then(function(exists) { var content = $(`textarea[data-title="${title}"]`).val; return { title: title, exists: exists, content: content }; });               });                handlePromises(promises, categoryType); } else { alert('Please select at least one page to create/update.'); }       });    });

function getPreviewDateCategories(year, months) { var previewPromises = [];

months.forEach(function(month) {           var promise = new Promise(function(resolve, reject) { var daysInMonth = getDaysInMonth(month, year); var previewItems = []; var monthName = getMonthName(month);

for (var day = 1; day <= daysInMonth; day++) { var title = `Category:${monthName} ${day}, ${year}`; var content = ''; previewItems.push({ title: title, content: content }); }

resolve(previewItems); });

previewPromises.push(promise); });

return previewPromises; }

function getPreviewMonthCategories(year, months) { var previewPromises = [];

months.forEach(function(month) {           var promise = new Promise(function(resolve, reject) { var monthName = getMonthName(month); var title = `Category:${monthName} ${year}`; var content = ''; resolve([{ title: title, content: content }]); });

previewPromises.push(promise); });

return previewPromises; }

function getPreviewWikinewsMonthList(year, months) { var previewPromises = [];

months.forEach(function(month) {           var promise = new Promise(function(resolve, reject) { var monthName = getMonthName(month); var title = `Wikinews:${year}/${monthName}`; var content = ''; resolve([{ title: title, content: content }]); });

previewPromises.push(promise); });

return previewPromises; }

function getPreviewWikinewsDateList(year, months) { var previewPromises = [];

months.forEach(function(month) {           var promise = new Promise(function(resolve, reject) { var daysInMonth = getDaysInMonth(month, year); var previewItems = []; var monthName = getMonthName(month);

for (var day = 1; day <= daysInMonth; day++) { var title = `Wikinews:${year}/${monthName}/${day}`; var content = ``; previewItems.push({ title: title, content: content }); }

resolve(previewItems); });

previewPromises.push(promise); });

return previewPromises; }

function getDaysInMonth(month, year) { return new Date(year, month, 0).getDate; }

function checkCategoryExists(title) { return createCategories.api.get({           action: 'query',            format: 'json',            prop: 'revisions',            titles: title,            formatversion: '2',            rvprop: 'content',            rvslots: '*'        }).then(function(data) {            var page = data.query.pages[0];            return page.missing === '' ? false : true;        }); }

function handlePromises(promises, categoryType) { Promise.all(promises).then(function(results) {           var totalPages = results.length;            var message = `There are total ${totalPages} pages targeted. Do you want to create or update them?`;            if (confirm(message)) {                updateCategories(results, categoryType);            } else {                alert('Operation cancelled.');            }        }).catch(function(error) {            console.error('Error checking categories:', error);            alert('An error occurred while checking the categories.');        }); }

function updateCategories(results, categoryType) { var summary; if (categoryType === 'date' || categoryType === 'month') { summary = 'Creating/updating category, using QuickCat.'; } else { summary = 'Creating/updating list page, using QuickCat.'; }

var updatePromises = results.map(function(result) {           return createCategories.api.postWithToken('csrf', { action: 'edit', format: 'json', title: result.title, formatversion: '2', text: result.content, summary: summary }).then(function(response) { console.log(`Processed ${result.title}`); }).catch(function(error) { console.error(`Error processing ${result.title}:`, error); });       });

Promise.all(updatePromises).then(function {           alert(`${categoryType === 'date' || categoryType === 'month' ? 'Categories' : 'List pages'} created/updated successfully.`);       }).catch(function(error) {            console.error('Error creating/updating categories:', error);            alert(`An error occurred while creating/updating the ${categoryType === 'date' || categoryType === 'month' ? 'categories' : 'list pages'}.`);       }); }

function getMonthName(month) { var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];       return monthNames[month - 1]; } });