MediaWiki:Mobile.js

De Wikidébats, l'encyclopédie des débats et des arguments « pour » et « contre »
Aller à la navigation Aller à la recherche

Note : après avoir enregistré vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou pressez Ctrl-F5 ou Ctrl-R (⌘-R sur un Mac).
  • Google Chrome : appuyez sur Ctrl-Maj-R (⌘-Shift-R sur un Mac).
  • Internet Explorer : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
  • Opera : allez dans Menu → Settings (Opera → Préférences sur un Mac) et ensuite à Confidentialité et sécurité → Effacer les données d’exploration → Images et fichiers en cache.
$(function() {
	argumentMapContentCall();
	argumentMapColor();
	argumentContentCall();
	argumentContentDrop();
	moreContentCall();
	latestChangesCall();
	breadcrumbContentCall();
	fillEditSummaryForCheckbox();
	addthisBar();
});

/* <Dynamic API call> */

function loadContentFromTitle(titleElement){
	titleElement.addClass('expanded');
	var template = titleElement.data('template');
	var argument = titleElement.data('argument');
	var type = titleElement.data('type');
	var level = titleElement.data('level');
	var root = titleElement.data('root');
	var path = titleElement.data('path');
	var warnings = titleElement.data('warnings');
	var page = titleElement.data('page');
	var wrapper = titleElement.parent().find('.argument-content-wrapper');
	var query = '{{' + template + '|argument=' + argument + '|type=' + type + '|niveau=' + level + '|racine=' + root + '|chemin=' + path + '|avertissements=' + warnings + '|page=' + page + '}}';
	new mw.Api().post({
			action: "parse",
				contentmodel: "wikitext",
				text: query
			}).done( function( data ) {
		var text = data.parse.text['*'].replace(/<!--[\S\s]*?-->/gm, '' );
		wrapper.append(text);
	});
	
	// Création d'un bouton pour le fil d'Ariane
	if ($('#bouton-fil').length) {
        $('#bouton-fil').remove(); // Supprimez-le s'il existe déjà
    }  
	// Créez une balise img avec votre image comme source
    var image = $('<img>', {
        src: '/w/images/fr/4/4d/Bouton-fil-Ariane.svg',
        alt: 'Fil d\'Ariane',
        id: 'bouton-fil',
        style: 'position: fixed; bottom: 1em; right: 2em; width: 50px; height: 50px; cursor: pointer; z-index: 99;'
    });
    // Insérez l'image juste avant l'élément .argument-expandable-title
    image.insertBefore($(titleElement));
}

function argumentContentCall() {
  $(document).on('click', '.argument-expandable-title:not(.expanded)', function() {
	var scrollTop = $(this).offset().top - 5;
	$('html, body').animate({ scrollTop: scrollTop }, 'slow');
	loadContentFromTitle($(this));
  });
}

function argumentMapColor(){
	$('.ns-0').on('click', '.root-argument:not(.expanded)', function(){
		var id = $(this).attr('id');
		var element = $('#' + id + '_map');
		element.addClass('visited');
	});
}

function argumentMapContentCall(){
	$('.ns-0').on('click', '#Argument_map .titre-argument-carte', function(){
		$(this).addClass('visited');
		var title = $(this).text().replace(/\./g,'\\.').replace(/ /g,"_").replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/,/g,'\\,').replace(/\(/g,'\\(').replace(/\)/g,'\\)');
		var sectionContent = $('#' + title).closest('.collapsible-block');
		if (!sectionContent.attr('class').split(/\s+/).includes('open-block')) {
			$(sectionContent).addClass('open-block');
		}
		var sectionTitle = $(sectionContent).prev();
		if (!sectionTitle.attr('class').split(/\s+/).includes('open-block')) {
			$(sectionTitle).addClass('open-block');
		}
		var sectionArrow = $(sectionTitle).children(":first");
		if (!sectionArrow.attr('class').split(/\s+/).includes('mf-mw-ui-icon-rotate-flip')) {
			$(sectionArrow).addClass('mf-mw-ui-icon-rotate-flip');
		}
		var scrollTop = $('#' + title).offset().top - 5;
		$('html, body').animate({ scrollTop: scrollTop }, 'slow');
		var argumentTitle = $('#' + title);
		if (!argumentTitle.attr('class').split(/\s+/).includes('expanded')) {
			argumentTitle.addClass('expanded open-block');
			loadContentFromTitle(argumentTitle);
		}
	});
}

function argumentContentDrop(){
	$(document).on('click', '.argument-expandable-title.expanded', function(){
		// Vérifiez si #bouton-fil existe et supprimez-le s'il existe
		if ($('#bouton-fil').length) {
			$('#bouton-fil').remove();
		}
		
		$(this).removeClass('expanded');
		var wrapper = $(this).parent().find('.argument-content-wrapper');
		wrapper.empty();
	});
}

function moreContentCall(){
$(document).on('click', '.more-content-button', function(){
	$(this).hide();
	var page = $(this).data('page');
	var wrapper = $(this).parent().find('.more-content-wrapper');
	var query = '{{Contenu supplémentaire | page = ' + page + '}}';
	new mw.Api().post({
			action: "parse",
				contentmodel: "wikitext",
				text: query
			}).done( function( data ) {
		var text = data.parse.text['*'].replace(/<!--[\S\s]*?-->/gm, '' );
		wrapper.replaceWith('<div class="more-content-wrapper"><div class="more-content-drop show"></div>' + text + '</div>');
	});
});
}

function latestChangesCall(){
$('.ns-0').on('click', '.latest-changes-button', function(){
	var button = $(this).parent().find('.latest-changes-button.mw-ui-button');
	var page = button.data('page');
	button.hide();
	var wrapper = $(this).parent().find('.latest-changes-wrapper');
	var query = '{{Dernières modifications | page = ' + page + '}}';
	new mw.Api().post({
			action: "parse",
				contentmodel: "wikitext",
				text: query
			}).done( function( data ) {
		var text = data.parse.text['*'].replace(/<!--[\S\s]*?-->/gm, '' );
		wrapper.replaceWith('<div class="latest-changes-wrapper"><div class="latest-changes-drop show"></div>' + text + '</div>');
	});
});
}

/* Pour afficher le fil d'Ariane d'un argument */

function breadcrumbContentCall() {
    $(document).on('click', '#bouton-fil', function() {
        // Récupérez les données path et page à partir de l'élément suivant (.argument-expandable-title)
        var path = $(this).next('.argument-expandable-title').data('path');
        var page = $(this).next('.argument-expandable-title').data('page');
        var query = '{{Fil d\'Ariane | chemin = ' + path + ' | page = ' + page + ' }}';

        // Utilisez l'API de Mediawiki pour analyser le wikitexte
        new mw.Api().post({
            action: "parse",
            contentmodel: "wikitext",
            text: query
        }).done(function(data) {
            var text = data.parse.text['*'].replace(/<!--[\S\s]*?-->/gm, '');

            // Créez la boîte modale avec le texte wikitexte
            var modal = $('<div>', {
                id: 'modal'
            });

            var modalContent = $('<div>', {
                id: 'fil-ariane'
            });

            // Ajoutez le texte wikitexte à la boîte modale
            modalContent.html(text);

            // Ajoutez la boîte modale à la page
            modal.append(modalContent);
            $('body').append(modal);
        
            // Fermez la boîte modale lorsqu'un clic se produit en dehors de son contenu
            modal.click(function() {
                modal.remove();
            });
        });
    });
}

/* </Dynamic API call> */

function fillEditSummaryForCheckbox(object, section, addingMessage, removingMessage){
	if (typeof object === "undefined") {
		return;
	}
	var summary = $('input[name=wpSummary]').val();
	var checked = object.prop('checked');
	var bannerName = object.parent();
	var bannerName = $(bannerName).next();
	var bannerName = $(bannerName).text() + ' »';
	if (checked) {
		var actionDone = addingMessage + ' «';
	} else {
		var actionDone = removingMessage + ' «';
	}
	if (summary) {
	var condition = summary.substr(-3);
	if (condition == '*/ ') {
			var summary = summary + actionDone + bannerName;
			$('input[name=wpSummary]').val(summary);
	} else {
		var summary = summary + ' + ' + actionDone + bannerName;
			$('input[name=wpSummary]').val(summary);
	}
	} else {
			var summary = section + actionDone + bannerName;
			$('input[name=wpSummary]').val(summary);
	}
}

$('.mw-special-FormEdit').on('change', '.mw-special-FormEdit .zone-bandeaux .mandatoryField', function(){
	var summary = $('input[name=wpSummary]').val();
	var bannerName = $('select#input_2 option:selected').val() + ' »';
	var actionDone = ' Niveau d’avancement du débat changé à « ';
	if (summary) {
	var condition = summary.substr(-3);
	if (condition == '*/ ') {
			var summary = summary + actionDone + bannerName;
			$('input[name=wpSummary]').val(summary);
	} else {
		var summary = summary + ' +' + actionDone + bannerName;
			$('input[name=wpSummary]').val(summary);
	}
	} else {
			var summary = '/* Bandeaux d’avertissement */' + actionDone + bannerName;
			$('input[name=wpSummary]').val(summary);
	}
});

$('.mw-special-FormEdit').on('click', '.zone-bandeaux .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Bandeaux d’avertissement */ ', 'Ajout du bandeau', 'Retrait du bandeau');
});

$('.mw-special-FormEdit').on('click', '.zone-categories', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Catégories */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-resume', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Résumé de l’argument */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-resume .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Résumé de l’argument */', 'Ajout du bandeau d’avertissement', 'Retrait du bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-citations', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Citations */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-citations .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Citations */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-justifications', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Justifications */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-justifications .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Justifications */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-objections', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Objections */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-objections .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Objections */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-debat-detaille', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('Ajout de débat détaillé ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-references', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Références */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-references .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Références */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-introduction', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Pour comprendre le débat */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-introduction .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Pour comprendre le débat */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-voir-Wikipedia', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Voir aussi sur Wikipédia */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-arguments-pour', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Arguments « pour » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-arguments-pour .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Arguments « pour » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-arguments-contre', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Arguments « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-biblio-pour', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Bibliographie « pour » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-arguments-contre .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Arguments « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-biblio-pour .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Bibliographie « pour » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-biblio-contre', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Bibliographie « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-biblio-contre .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Bibliographie « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-biblio-nini', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Bibliographie ni « pour » ni « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-biblio-nini .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Bibliographie ni « pour » ni « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-sito-pour', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Sitographie « pour » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-sito-pour .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Sitographie « pour » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-sito-contre', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Sitographie « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-sito-contre .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Sitographie « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-sito-nini', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Sitographie ni « pour » ni « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-sito-nini .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Sitographie ni « pour » ni « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-video-pour', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Vidéographie « pour » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-video-pour .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Vidéographie « pour » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-video-contre', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Vidéographie « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-video-contre .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Vidéographie « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-video-nini', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Vidéographie ni « pour » ni « contre » */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.zone-video-nini .oo-ui-inputWidget-input', function(){
	fillEditSummaryForCheckbox($(this), '/* Vidéographie ni « pour » ni « contre » */', 'Ajout d’un bandeau d’avertissement', 'Retrait d’un bandeau d’avertissement');
});

$('.mw-special-FormEdit').on('click', '.zone-debats-connexes', function(){
	var summary = $('input[name=wpSummary]').val();
	if (!summary) {
		$('input[name=wpSummary]').val('/* Débats connexes */ ');
	}
});

$('.mw-special-FormEdit').on('click', '.resume-modifications', function(){
	var summary = $('input[name=wpSummary]').val();
	var newSummary = $(this).text();
	if (summary) {
	var condition = summary.substr(-3);
	if (condition == '*/ ') {
			var summary = summary + newSummary;
			$('input[name=wpSummary]').val(summary);
	} else {
		var summary = summary + ' + ' + newSummary;
			$('input[name=wpSummary]').val(summary);
	}
	} else {
			$('input[name=wpSummary]').val(newSummary);
	}
});


function addthisBar( $content ) {
	if ( $content && $content.find ) {
		var $span = $content.find( '#addthisbar' );
		if ( $span.length ) {
			$span.attr( 'id', 'addthisbar-tab' );
			$span.prepend( ' ' );
			$( '.minerva__tab-container' ).append( $span );
		}
	}
}
mw.hook( 'wikipage.content' ).add( addthisBar );

$(document).on('click', '.onglet-externe a', function(event) {
	event.preventDefault();
	var url = $(this).attr('href');
	window.open(url, '_blank');
});

$('.ns-3100').on('click', '.bouton-argument-suivant', function() {
	$('html, body').animate({ scrollTop: 0 }, 'slow'); // Fait défiler en douceur
});

$(document).ready(function() {
	$('.modifier-initial').each(function() {
		var $button = $(this);
		var $element = $button.closest('.collapsible-block').prev();
		$element.last().append($button);
		$button.removeClass('modifier-initial').addClass('modifier-section');
	});
});

$(document).on('click', '.remonter-argument, .remonter-fil', function(event) {
	event.preventDefault();
	var titleElement = $(this).find('a');
	var href = titleElement.attr('href');
	var anchorName = href.split('#')[1]; // On extrait le nom de l'ancre de l'attribut href
	var escapedTitleElement = document.getElementById(anchorName);
	var scrollTop = $(escapedTitleElement).offset().top - 5;
	$('html, body').animate({ scrollTop: scrollTop }, 'slow');
});

$(document).on('click', '.remonter-carte', function(event) {
	var target = $('#Argument_map');
	if (target.length) {
		$('html, body').animate({ scrollTop: target.offset().top }, 'slow');
	}
});

$(document).on('click', '.remonter-haut', function(event) {
	var target = $('#mw-mf-viewport');
	if (target.length) {
		$('html, body').animate({ scrollTop: target.offset().top }, 'slow');
	}
});

/**
 * Enables or disables the dark-mode gadget.
 *
 * Authors: [[User:SD0001]], [[User:Nardog]]
 */

// 'Dark mode' and 'Light mode' messages must match the ::before content in
// [[MediaWiki:Gadget-dark-mode-toggle-pagestyles.css]] and [[MediaWiki:Gadget-dark-mode.css]], respectively.
// Don't overwrite existing messages, if already set on a foreign wiki prior to loading this file
if (!mw.messages.get('darkmode-turn-on-label')) {
	mw.messages.set({
		'darkmode-turn-on-label': 'Thème sombre',
		'darkmode-turn-on-tooltip': 'Activer le thème sombre',
		'darkmode-turn-off-label': 'Thème clair',
		'darkmode-turn-off-tooltip': 'Activer le thème clair',
	});
}

var isOn = mw.loader.getState('ext.gadget.dark-mode') === 'ready';

var broadcastChannel = new BroadcastChannel('gadget-dark-mode');

function setThemeColor() {
	// Update the theme-color used by some browsers for coloration of the tab headers and surrounding UI
	$('meta[name="theme-color"]').attr('content', isOn ? '#000000' : '#eaecf0');
}

function setHtmlClass() {
	// CSS class for externally styling elements in dark mode via TemplateStyles (or CSS from other gadgets or common.css)
	// A brief flash of the original styles will occur, so this is only suitable for style changes for which flashes are tolerable.
	// For others, update Gadget-dark-mode.css directly which is loaded without FOUCs
	$(document.documentElement).toggleClass('client-dark-mode', isOn);
}

function vectorStickyCallback() {
	mw.hook('vector.page_title_scroll').remove(vectorStickyCallback);
	if (document.getElementById('pt-darkmode-sticky-header')) return;
	makePortletLink('p-personal-sticky-header', 'pt-darkmode-sticky-header', '#pt-watchlist-sticky-header');
}

function addPortlets() {
	makePortletLink('p-personal', 'pt-darkmode', '#pt-watchlist');

	if (mw.config.get('skin') === 'vector-2022') {
		mw.hook('vector.page_title_scroll').add(vectorStickyCallback);
	}
}

function getMsg(suffix) {
	var key = 'darkmode-turn-' + (isOn ? 'off' : 'on') + '-' + suffix;
	return mw.msg(key);
}

function makePortletLink(portletId, portletLinkId, nextnode) {
	var label = getMsg('label');
	var tooltip = getMsg('tooltip');
	$(mw.util.addPortletLink(portletId, '#', label, portletLinkId, tooltip, '', nextnode))
		.children().on('click', function (e) {
			e.preventDefault();
			toggleMode();
		});
}

function togglePortlets() {
	var labelSelector;
	switch (mw.config.get('skin')) {
		case 'vector':
		case 'vector-2022':
		case 'minerva':
			labelSelector = '#pt-darkmode span:not(:empty), #pt-darkmode-sticky-header span:not(:empty)';
			break;
		default:
			labelSelector = '#pt-darkmode a';
	}
	$(labelSelector).text(getMsg('label'));
	$('#pt-darkmode a, #pt-darkmode-sticky-header a')
		.attr('title', getMsg('tooltip'));
}

function actuallyToggleDarkMode() {
	// Modify the <link> element on the page to include/exclude dark-mode styles
	// We can't use mw.loader as it doesn't work both ways (see talk page)
	var scriptPath = mw.util.wikiScript('load');
	var $gadgetsLink = $('link[rel="stylesheet"][href^="' + scriptPath + '?"][href*="ext.gadget."]');
	if ($gadgetsLink.length) {
		var uri = new mw.Uri($gadgetsLink.prop('href'));
		if (isOn) {
			uri.query.modules += ',dark-mode';
		} else {
			if (uri.query.modules === 'ext.gadget.dark-mode') {
				// dark-mode is the only module in this link
				$gadgetsLink.remove();
				return;
			}
			uri.query.modules = uri.query.modules
				.replace('ext.gadget.dark-mode,', 'ext.gadget.') // dark-mode is first in the gadget list
				.replace(/,dark-mode(,|$)/, '$1'); // dark-mode is in middle or end of the list
		}
		$gadgetsLink.prop('href', uri.getRelativePath());
	} else {
		// No gadget-containing styles are enabled
		$('<link>').attr({
			rel: 'stylesheet',
			href: scriptPath + '?lang=' + mw.config.get('wgUserLanguage') +
				'&modules=ext.gadget.dark-mode&only=styles&skin=' + mw.config.get('skin')
		}).appendTo(document.head);
	}
}

function savePreference() {
	new mw.Api().saveOption('gadget-dark-mode', isOn ? '1' : '0');
}

function savePreferenceLocally() {
	mw.user.options.set('gadget-dark-mode', Number(isOn));

	// In case the user navigates to another page too quickly
	mw.storage.session.set('dark-mode-toggled', isOn ? '1' : '0');
}

function notifyOtherTabs() {
	// Broadcast state change to other tabs
	broadcastChannel.postMessage(isOn);
}

function toggleMode(offline) {
	isOn = !isOn;
	if (!offline) {
		savePreference();
		notifyOtherTabs();
	}
	setHtmlClass();
	setThemeColor();
	savePreferenceLocally();
	togglePortlets();
	actuallyToggleDarkMode();
}

function toggleBasedOnSystemColourScheme() {
	var systemSchemeNow = matchMedia('(prefers-color-scheme: dark)').matches;
	var systemSchemeLast = mw.storage.get('dark-mode-system-scheme') === '1';

	if (systemSchemeNow !== systemSchemeLast) {
		if (systemSchemeNow !== isOn) {
			toggleMode();
		}
		mw.requestIdleCallback(function () {
			mw.storage.set('dark-mode-system-scheme', systemSchemeNow ? '1' : '0');
		});
	}
}


$.when($.ready, mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.Uri', 'mediawiki.storage'])).then(function () {
	setHtmlClass();
	setThemeColor();
	addPortlets();

	// Recover state if the navigation was too quick
	var storageState = mw.storage.session.get('dark-mode-toggled');
	if (storageState && Number(storageState) !== Number(isOn)) {
		toggleMode(true);
	}

	// Listen to dark mode state change made on other tabs
	broadcastChannel.onmessage = function (msg) {
		if (msg.data !== isOn) {
			toggleMode(true);
		}
	};

	if (window.wpDarkModeAutoToggle) {
		toggleBasedOnSystemColourScheme();

		// If system colour scheme changes while user is viewing, toggle immediately
		var mediaQuery = matchMedia('(prefers-color-scheme: dark)');
		if (mediaQuery.addEventListener) {
			mediaQuery.addEventListener('change', toggleBasedOnSystemColourScheme);
		} else if (mediaQuery.addListener) { // Safari 13 and older
			mediaQuery.addListener(toggleBasedOnSystemColourScheme);
		}
	}
});