MediaWiki:Gadget-darkmode.js

Iš MCSlime.LT.
Pereiti į navigaciją Jump to search

Dėmesio: Išsaugojus jums gali prireikti išvalyti jūsų naršyklės podėlį, kad pamatytumėte pokyčius.

  • Firefox / Safari: Laikydami Shift pasirinkite Perkrauti, arba paspauskite Ctrl-F5 ar Ctrl-R (sistemoje Apple Mac ⌘-R)
  • Google Chrome: Spauskite Ctrl-Shift-R (sistemoje Apple Mac ⌘-Shift-R)
  • Internet Explorer / Edge: Laikydami Ctrl paspauskite Naujinti, arba paspauskite Ctrl-F5
  • Opera: Eikite į Meniu → Nuostatos (sistemoje Apple Mac Opera → Nustatymai), tuomet Privatumas ir sauga → išvalyti naršymo podėlį → išsaugotos talpyklos vaizdai ir failai.
(function($, mw) {
  const DARK_COOKIE = 'darkmode';
  const THEME_COOKIE = 'theme';
  const TOGGLE_ID = 'pt-darkmode-toggle';

  const isMobile = mw.config.get('wgMFMode') !== null;
  const portletId = isMobile ? 'p-navigation' : 'p-personal';

  // Determine initial theme preference
  const themeCookie = $.cookie(THEME_COOKIE);
  const darkCookie = $.cookie(DARK_COOKIE);
  let isDark = themeCookie === 'dark' || (!themeCookie && darkCookie === 'true');

  // Apply theme classes to <html> element immediately
  document.documentElement.classList.add(isDark ? 'wgl-theme-dark' : 'wgl-theme-light');

  // Define icon representations
  const icons = {
    dark: '🌙',
    light: '☀️'
  };

  // Function to apply theme classes to <body>
  function applyTheme(isDarkMode) {
    $('body')
      .toggleClass('wgl-theme-dark wgl-darkmode', isDarkMode)
      .toggleClass('wgl-theme-light wgl-lightmode', !isDarkMode)
      .css({ visibility: 'visible', opacity: 1 });

    mw.hook('wgl.themeChanged').fire(isDarkMode ? 'dark' : 'light');
  }

  // Function to update the toggle icon
  function updateToggleIcon(isDarkMode) {
    const icon = isDarkMode ? icons.dark : icons.light;
    $(`#${TOGGLE_ID} a`).text(icon);
  }

  // Initialize the toggle functionality
  function initToggle() {
    // Create the toggle link
    const toggleLink = mw.util.addPortletLink(
      portletId,
      '#',
      isDark ? icons.dark : icons.light,
      TOGGLE_ID,
      'Toggle dark mode',
      null,
      $('#pt-userpage, #pt-anonuserpage, #pt-createaccount')[0]
    );

    // Add a class for cursor styling
    $(toggleLink).addClass('darkmode-toggle');

    // Apply the initial theme
    applyTheme(isDark);

    // Handle toggle click event
    $(toggleLink).on('click', function(e) {
      e.preventDefault();
      isDark = !isDark;

      // Update cookies
      $.cookie(THEME_COOKIE, isDark ? 'dark' : 'light', { expires: 365, path: '/' });
      $.cookie(DARK_COOKIE, isDark, { expires: 365, path: '/' });

      // Apply the new theme and update icon
      applyTheme(isDark);
      updateToggleIcon(isDark);
    });
  }

  // Ensure necessary modules are loaded before initializing
  mw.loader.using(['mediawiki.util'], function () {
    $(initToggle);
  });

})(jQuery, mediaWiki);