Utilisateur:Alexisdepris/Mes scripts/test.js

Note : après avoir enregistré la page, vous devrez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

Mozilla / Firefox / Konqueror / Safari : maintenez la touche Majuscule (Shift) en cliquant sur le bouton Actualiser (Reload) ou pressez Maj-Ctrl-R (Cmd-R sur Apple Mac) ;

Firefox (sur GNU/Linux) / Chrome / Internet Explorer / Opera : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
//<nowiki>

$('head').append(`
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
`);
$.getScript('https://cdn.jsdelivr.net/npm/sweetalert2@10').done(function() {
    // Fonction pour créer et ajouter le lien de la nouvelle catégorie
    $(document).ready(function() {
        // Vérifier si l'élément #p-tb existe pour ajouter une nouvelle catégorie
        var $toolbox = $('#p-tb');
        if ($toolbox.length) {
            // Ajouter la nouvelle section "Č v2" avec un ID spécifique
            var $newSection = $('<div>', {
                id: 'p-cv2',
                'class': 'vector-menu vector-menu-portal portal',
                append: [
                    $('<p>').text('Č²'),
                    $('<hr>'),
                    $('<div>', {
                        'class': 'body vector-menu-content',
                        append: [
                            $('<ul>', {
                                'class': 'vector-menu-content-list',
                                append: $('<li>', {
                                    'class': 'mw-list-item',
                                    append: $('<a>', {
                                        href: '#',
                                        text: 'Ajouter un bandeau',
                                        click: function(e) {
                                            e.preventDefault();
                                            openBannerPopup();
                                        }
                                    })
                                })
                            })
                        ]
                    })
                ]
            });

            // Ajouter la nouvelle section après l'élément #p-tb
            $newSection.insertAfter($toolbox);
        }

        // Définir les catégories de bandeaux
        var categories = [
            { display: "Sourçage", node: null }, //0
            { display: "Mise en forme", node: null }, //1
            { display: "Neutralité", node: null }, //2
            { display: "Admissibilité", node: null }, //3
            { display: "Promotionnel", node: null }, //4
            { display: "Liens internes/externes", node: null }, //5
            { display: "Images", node: null }, //6
            { display: "Encyclopédique", node: null }, //7
            { display: "Copyright", node: null }, //8
            { display: "Autre projet", node: null }, //9
            { display: "Informations", node: null }, //10
            { display: "Traduction", node: null }, //11
            { display: "Les plus utilisés", node: null } //12
        ];

        // Définir les bandeaux avec leurs catégories respectives
        var banners = [
            // Sourçage
            { category: 0, display: 'À sourcer', template: '{{À sourcer|date=$(month) $(year)}}' },
            { category: 0, display: 'Détournement de sources', template: '{{Détournement de sources|date=$(month) $(year)}}' },
            { category: 0, display: 'Vérifiabilité', template: '{{Vérifiabilité|date=$(month) $(year)}}' },
            { category: 0, display: 'Sources secondaires', template: '{{Sources secondaires|date=$(month) $(year)}}' },
            { category: 0, display: 'Sans source', template: '{{Sans source|date=$(month) $(year)}}' },
            { category: 0, display: 'À prouver', template: '{{À prouver|date=$(month) $(year)}}' },
            { category: 0, display: 'BPV à sourcer', template: '{{BPV à sourcer|date=$(month) $(year)}}' },
            { category: 0, display: 'Sources à lier', template: '{{Sources à lier|date=$(month) $(year)}}' },
            { category: 0, display: 'Source unique', template: '{{Source unique|date=$(month) $(year)}}' },
            { category: 0, display: 'Trop de sources', template: '{{Trop de sources|date=$(month) $(year)}}' },
            { category: 0, display: 'Contradiction', template: '{{Contradiction|date=$(month) $(year)}}' },
            { category: 0, display: 'Avis de canular', template: '{{Avis de canular|date=$(month) $(year)}}' },
            { category: 0, display: 'Pas de lien externe', template: '{{Pas de liens externes|date=$(month) $(year)}}' },
            { category: 0, display: 'Lien internet incomplet', template: '{{Lien internet incomplet|date=$(month) $(year)}}' },
            { category: 0, display: 'Conventions bibliographiques', template: '{{Conventions bibliographiques|date=$(month) $(year)}}' },
            { category: 0, display: 'Source obsolète', template: '{{Source obsolète|1=$(reason)|date=$(month) $(year)}}', reason: 'Référence (obligatoire) :' },

            // Mise en forme
            { category: 1, display: 'À wikifier', template: '{{À wikifier|date=$(month) $(year)}}' },
            { category: 1, display: 'À recycler', template: '{{À recycler|date=$(month) $(year)}}' },
            { category: 1, display: 'À décoloriser', template: '{{À décoloriser|date=$(month) $(year)}}' },
            { category: 1, display: 'À déjargoniser', template: '{{À déjargoniser|date=$(month) $(year)}}' },
            { category: 1, display: 'À délister', template: '{{À délister|date=$(month) $(year)}}' },
            { category: 1, display: 'À désacadémiser', template: '{{À désacadémiser|date=$(month) $(year)}}' },
            { category: 1, display: 'À désangliciser', template: '{{À désangliciser|date=$(month) $(year)}}' },
            { category: 1, display: 'À TeXifier', template: '{{À TeXifier|date=$(month) $(year)}}' },
            { category: 1, display: 'À dater', template: '{{À dater|date=$(month) $(year)}}' },
            { category: 1, display: 'Style non encyclopédique', template: '{{Style non encyclopédique|date=$(month) $(year)}}' },
            { category: 1, display: 'Orthographe', template: '{{Orthographe|date=$(month) $(year)}}' },
            { category: 1, display: 'Typographie', template: '{{Typographie|date=$(month) $(year)}}' },
            { category: 1, display: 'À catégoriser', template: '{{À catégoriser|date=$(month) $(year)}}' },
            { category: 1, display: 'Erreur syntaxe', template: '{{Erreur syntaxe|date=$(month) $(year)|modèle=$(reason)}}', reason: 'Modèle' },
            { category: 1, display: 'Conventions bibliographiques', template: '{{Conventions bibliographiques|date=$(month) $(year)}}' },
            { category: 1, display: 'Accessibilité à revoir', template: '{{Accessibilité à revoir|date=$(month) $(year)}}' },
            { category: 1, display: 'Désaccord de pertinence', template: '{{Désaccord de pertinence|date=$(month) $(year)}}' },

            // Neutralité
            { category: 2, display: 'Article non neutre', template: '{{Article non neutre|date=$(month) $(year)}}' },
            { category: 2, display: 'Anecdotes', template: '{{Anecdotes|date=$(month) $(year)}}' },
            { category: 2, display: 'POV fork', template: '{{POV fork}}' },
            { category: 2, display: 'Anthropocentrisme', template: '{{Anthropocentrisme|date=$(month) $(year)}}' },
            { category: 2, display: 'Désaccord de neutralité', template: '{{Désaccord de neutralité|date=$(month) $(year)}}' },
            { category: 2, display: 'Désaccord de pertinence', template: '{{Désaccord de pertinence|date=$(month) $(year)}}' },
            { category: 2, display: 'Point de vue interne', template: '{{Point de vue interne|date=$(month) $(year)}}' },
            { category: 2, display: 'Ton journalistique', template: '{{Ton journalistique|date=$(month) $(year)}}' },
            { category: 2, display: 'Controverses', template: '{{Controverses|date=$(month) $(year)}}' },
            { category: 2, display: 'À internationaliser', template: '{{À internationaliser|date=$(month) $(year)}}' },
            { category: 2, display: 'Article mal proportionné', template: '{{Article mal proportionné|date=$(month) $(year)}}' },
            { category: 2, display: 'Biais de genre', template: '{{Biais de genre|date=$(month) $(year)}}' },

            // Admissibilité
            { category: 3, display: 'Admissibilité à vérifier', template: '{{Admissibilité à vérifier|date=$(month) $(year)|motif=$(reason)}}', reason: 'Motif :' },
            { category: 3, display: 'Admissibilité', template: '{{Admissibilité}}' },
            { category: 3, display: 'Suppression image', template: '{{Suppression image}}' },
            { category: 3, display: 'Travail inédit', template: '{{Travail inédit|date=$(month) $(year)}}' },
            { category: 3, display: 'Admissibilité à revoir', template: '{{Admissibilité à revoir|1=$(reason)|user=$(user)}}', reason: 'Commentaire', user: 'Utilisateur' },

            // Promotionnel
            { category: 4, display: 'Dithyrambe', template: '{{Dithyrambe|date=$(month) $(year)}}' },
            { category: 4, display: 'Curriculum vitae', template: '{{Curriculum vitae|date=$(month) $(year)}}' },
            { category: 4, display: 'Hagiographique', template: '{{Hagiographique|date=$(month) $(year)}}' },
            { category: 4, display: 'Tribune', template: '{{Tribune|date=$(month) $(year)}}' },
            { category: 4, display: 'Catalogue de vente', template: '{{Catalogue de vente|date=$(month) $(year)}}' },
            { category: 4, display: 'Autobiographie', template: '{{Autobiographie|date=$(month) $(year)}}' },
            { category: 4, display: 'Promotionnel', template: '{{Promotionnel|date=$(month) $(year)}}' },
            { category: 4, display: 'Name dropping', template: '{{Name dropping|date=$(month) $(year)}}' },
            { category: 4, display: 'Avantage non déclaré', template: '{{Avantage non déclaré|date=$(month) $(year)|pre16Jun2014=oui}}' },
            { category: 4, display: 'Contributions promotionnelles/Articles', template: '{{Contributions promotionnelles/Articles|date=$(month) $(year)}}' },

            // Liens internes/externes
            { category: 5, display: 'Pas de lien externe', template: '{{Pas de liens externes|date=$(month) $(year)}}' },
            { category: 5, display: 'Lien internet incomplet', template: '{{Lien internet incomplet|date=$(month) $(year)}}' },
            { category: 5, display: 'Trop de wikiliens', template: '{{Trop de wikiliens|date=$(month) $(year)}}' },
            { category: 5, display: 'Trop de liens', template: '{{Trop de liens|date=$(month) $(year)}}' },
            { category: 5, display: 'Orphelin', template: '{{Orphelin|date=$(month) $(year)}}' },

            // Images
            { category: 6, display: 'À illustrer', template: '{{À illustrer|date=$(month) $(year)}}' },
            { category: 6, display: 'Image à légender', template: '{{Image à légender|date=$(month) $(year)}}' },
            { category: 6, display: 'Logo à vectoriser', template: '{{Logo à vectoriser|date=$(month) $(year)}}' },
            { category: 6, display: "Trop d'images", template: "{{Trop d'images|date=$(month) $(year)}}" },

            // Encyclopédique
            { category: 7, display: "Titre non encyclopédique", template: "{{Titre non encyclopédique|date=$(month) $(year)}}" },
            { category: 7, display: "Vie privée", template: "{{Vie privée|date=$(month) $(year)}}" },
            { category: 7, display: 'Guide pratique', template: '{{Désaccord de pertinence|date=$(month) $(year)}}' },
            { category: 7, display: 'Trop de citations', template: '{{Trop de citations|date=$(month) $(year)}}' },
            
            // Copyright
            { category: 8, display: 'Copie à vérifier', template: '{{Copie à vérifier|date=$(month) $(year)|site=$(reason)}}', reason: 'Site copyviolé' },
            { category: 8, display: 'Synopsis', template: '{{Synopsis|date=$(month) $(year)}}' },
            { category: 8, display: 'Image copyvio', template: '{{Image copyvio|date=$(month) $(year)}}' },

            // Autre projet
            { category: 9, display: 'Pour Wikiquote', template: '{{Pour Wikiquote}}' },
            { category: 9, display: 'Pour Wikinews', template: '{{Pour Wikinews}}' },
            { category: 9, display: 'Pour Wiktionnaire', template: '{{Pour Wiktionnaire}}' },
            { category: 9, display: 'Pour Wikisource', template: '{{Pour Wikisource}}' },
            { category: 9, display: 'Pour Wikibooks', template: '{{Pour Wikibooks}}' },
            { category: 9, display: 'Pour Wikivoyage', template: '{{Pour Wikivoyage}}' },
            { category: 9, display: 'Image sur Commons', template: '{{Image sur Commons|1=$(reason}}', reason: 'Nom de l\'image sur Commons' },

            // Informations
            { category: 10, display: 'Info ruby', template: '{{Info ruby}}' },
            { category: 10, display: "Création automatique", template: "{{Création automatique|date=$(month) $(year)|1=$(user)}}", user: 'Utilisateur' },
            { category: 10, display: "Avertissement filiations franques", template: "{{Avertissement filiations franques||1=$(article)}}", article: 'Article' },
			
			// Traduction
			{ category: 11, display: 'En cours de traduction', template: '{{En cours de traduction|date=$(month) $(year)|art1=$(article)|lang1=$(langue)}}', article: 'Article d\'origine', langue: 'Code de langue de l\'article d\'origine' },
            { category: 11, display: 'Traduction incomplète', template: '{{Traduction incomplète|date=$(month) $(year)|motif=$(reason)|lang1=$(langue)}}', reason: 'Motif de la pose du bandeau', langue: 'Code de langue de l\'article d\'origine' },

            // Autres
            { category: 12, display: 'Avertissement copyvio', template: '{{Avertissement copyvio|site=$(extra)}}', extra: 'URL du site' }
        ];

        // Fonction pour créer la fenêtre de dialogue avec SweetAlert2 et des onglets
        function createBannerDialog() {
            var formHtml = '<form id="bannerForm">';
            
            formHtml += '<div class="swal2-tabs" style="margin-bottom: 20px;">';
            categories.forEach(function(category, index) {
                formHtml += '<button type="button" class="swal2-tab" data-tab-index="' + index + '" style="background-color: #3085d6; color: white; border: none; padding: 10px 20px; margin: 2px; border-radius: 5px; cursor: pointer;">' + category.display + '</button>';
            });
            formHtml += '</div><div class="swal2-tab-content">';

            categories.forEach(function(category, index) {
                formHtml += '<div class="swal2-tab-pane" data-tab-index="' + index + '" style="display: none;">';
                formHtml += '<fieldset class="form-group" style="margin-bottom: 20px; padding: 10px; border: 1px solid #ccc; border-radius: 5px;">';
                formHtml += '<legend class="col-form-label col-sm-2 pt-0" style="font-weight: bold;">' + category.display + '</legend>';
                formHtml += '<select class="form-control mb-2" data-category="' + index + '" style="width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 5px;">';
                formHtml += '<option value="">Sélectionner...</option>';
                banners.filter(function(banner) {
                    return banner.category === index;
                }).forEach(function(banner) {
                    formHtml += '<option value="' + banner.template + '">' + banner.display + '</option>';
                });
                formHtml += '</select>';
                formHtml += '</fieldset>';
                formHtml += '</div>';
            });

            formHtml += '</div></form>';

            Swal.fire({
                title: 'Ajouter des bandeaux',
                html: formHtml,
                showCancelButton: true,
                confirmButtonText: 'Ajouter',
                cancelButtonText: 'Annuler',
                didOpen: () => {
                    $('.swal2-tab').on('click', function() {
                        var tabIndex = $(this).data('tab-index');
                        $('.swal2-tab-pane').hide();
                        $('.swal2-tab-pane[data-tab-index="' + tabIndex + '"]').show();
                        $('.swal2-tab').removeClass('active');
                        $(this).addClass('active');
                    });

                    $('.swal2-tab').first().click();

                    $('#bannerForm').find('select').on('change', function() {
                        var $select = $(this);
                        var selectedBanner = banners.find(function(banner) {
                            return banner.template === $select.val();
                        });

                        $select.siblings('.extra-input').remove();

                        if (selectedBanner) {
                            if (selectedBanner.reason) {
                                var $input = $('<input>', {
                                    type: 'text',
                                    placeholder: selectedBanner.reason,
                                    'class': 'form-control extra-input mb-2',
                                    style: 'width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 5px;',
                                    required: true
                                }).insertAfter($select);
                            }
                            if (selectedBanner.user) {
                                var $input = $('<input>', {
                                    type: 'text',
                                    placeholder: selectedBanner.user,
                                    'class': 'form-control extra-input mb-2',
                                    style: 'width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 5px;',
                                    required: true
                                }).insertAfter($select);
                            }
                            if (selectedBanner.article) {
                                var $input = $('<input>', {
                                    type: 'text',
                                    placeholder: selectedBanner.article,
                                    'class': 'form-control extra-input mb-2',
                                    style: 'width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 5px;',
                                    required: true
                                }).insertAfter($select);
                            }
                            if (selectedBanner.langue) {
                                var $input = $('<input>', {
                                    type: 'text',
                                    placeholder: selectedBanner.langue,
                                    'class': 'form-control extra-input mb-2',
                                    style: 'width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 5px;',
                                    required: true
                                }).insertAfter($select);
                            }
                            if (selectedBanner.extra) {
                                var $input = $('<input>', {
                                    type: 'text',
                                    placeholder: selectedBanner.extra,
                                    'class': 'form-control extra-input mb-2',
                                    style: 'width: 100%; padding: 8px; margin-top: 10px; border: 1px solid #ccc; border-radius: 5px;'
                                }).insertAfter($select);
                            }
                        }
                    });
                },
                preConfirm: () => {
                    var selectedBanners = [];
                    $('#bannerForm').find('select').each(function() {
                        var $select = $(this);
                        var template = $select.val();
                        if (template) {
                            var replacements = {
                                '$(reason)': '',
                                '$(user)': '',
                                '$(article)': '',
                                '$(langue)': '',
                                '$(extra)': ''
                            };
                            $select.siblings('.extra-input').each(function() {
                                var placeholder = $(this).attr('placeholder');
                                var value = $(this).val();
                                for (var key in replacements) {
                                    if (placeholder === replacements[key] || placeholder.includes(replacements[key])) {
                                        replacements[key] = value;
                                        break;
                                    }
                                }
                            });
                            for (var key in replacements) {
                                template = template.replace(key, replacements[key]);
                            }
                            var currentDate = new Date();
                            var monthNames = [
                                "janvier", "février", "mars",
                                "avril", "mai", "juin", "juillet",
                                "août", "septembre", "octobre",
                                "novembre", "décembre"
                            ];
                            var currentMonthName = monthNames[currentDate.getMonth()];
                            var currentYear = currentDate.getFullYear();
                            template = template.replace('$(month)', currentMonthName).replace('$(year)', currentYear);
                            selectedBanners.push(template);
                        }
                    });

                    if (selectedBanners.length === 0) {
                        Swal.showValidationMessage('Veuillez sélectionner au moins un bandeau.');
                    }

                    return selectedBanners;
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    var selectedBanners = result.value;
                    addBannersToPage(selectedBanners);
                }
            });
        }

        // Fonction pour ouvrir la fenêtre de dialogue
        function openBannerPopup() {
            createBannerDialog();
        }

        // Fonction pour ajouter les bandeaux sélectionnés à la page
        function addBannersToPage(banners) {
            var api = new mw.Api();
            var pageName = mw.config.get('wgPageName');

            api.get({
                action: 'query',
                prop: 'revisions',
                titles: pageName,
                rvprop: 'content',
                formatversion: 2
            }).done(function(data) {
                var page = data.query.pages[0];
                var content = page.revisions[0].content;
                var newContent = banners.filter(b => b.trim()).join('\n') + '\n' + content;

                api.postWithToken('csrf', {
                    action: 'edit',
                    title: pageName,
                    text: newContent,
                    summary: 'Ajout des bandeaux: ' + banners.map(function(b) {
                        var match = b.match(/{{(\w+)/);
                        return match ? match[1] : 'bandeau';
                    }).join(', ')
                }).done(function() {
                    mw.notify('Bandeaux ajoutés avec succès.', { type: 'success' });
                    location.reload();
                }).fail(function() {
                    mw.notify('Erreur lors de l\'ajout des bandeaux.', { type: 'error' });
                });
            }).fail(function() {
                mw.notify('Erreur lors de la récupération du contenu de la page.', { type: 'error' });
            });
        }
    });
});


// </nowiki>