MediaWiki:Gadget-theme.js

Материал из Space Station 14 Вики

Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
  • Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
  • Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
  • Opera: Нажмите Ctrl+F5.
;(function($, mw) {
  'use strict';

  function getCookie(name) {
    const re = new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)');
    const match = document.cookie.match(re);
    return match ? decodeURIComponent(match[1]) : null;
  }

  function incrementThemeCounter(themeName) {
    const pageTitle = 'Обсуждение участника:Pok';
    const validThemes = ['light', 'normal', 'dark', 'ss14'];
    const api = new mw.Api();

    api.get({
      action: 'query',
      prop: 'revisions',
      titles: pageTitle,
      rvslots: '*',
      rvprop: 'content',
      formatversion: 2,
      format: 'json'
    }).done(data => {
      const page = data.query.pages[0];
      const rev = page.revisions && page.revisions[0];
      let content = rev ? (rev.slots ? rev.slots.main['*'] : rev['*']) : '';

      const counts = {};
      validThemes.forEach(t => counts[t] = 0);
      if (content.trim()) {
        content.split('\n').forEach(line => {
          const [name, cnt] = line.split('=');
          if (validThemes.includes(name)) {
            counts[name] = parseInt(cnt, 10) || 0;
          }
        });
      }

      counts[themeName] = (counts[themeName] || 0) + 1;

      const updatedText = validThemes.map(t => `${t}=${counts[t]}`).join('\n');

      api.postWithToken('csrf', {
        action: 'edit',
        title: pageTitle,
        text: updatedText,
        summary: `Increment ${themeName} theme counter`,
        createonly: false
      }).done(() => {
        console.log(`Theme "${themeName}" count updated.`);
      }).fail(err => {
        console.error('Edit failed:', err);
      });
    }).fail(err => {
      console.error('Read failed:', err);
    });
  }

  $(function() {
    const COOKIE_NAME = 'ss14_wikiTheme';
    const validThemes = ['light', 'normal', 'dark', 'ss14'];

    console.log('Loaded theme-counter script. Cookies:', document.cookie);
    const theme = getCookie(COOKIE_NAME);
    if (!theme || !validThemes.includes(theme)) {
      console.warn('Unknown or missing theme cookie:', theme);
      return;
    }

    const flagKey = `ss14_themeCounted_${theme}`;
    if (!window.localStorage.getItem(flagKey)) {
      incrementThemeCounter(theme);
      window.localStorage.setItem(flagKey, '1');
    }
  });

})(jQuery, mediaWiki);

;(function($, mw){
    const COOKIE = 'ss14_wikiTheme';

    function loadTheme() {
        return $.cookie(COOKIE) || 'normal';
    }

    function saveTheme(theme) {
        $.cookie(COOKIE, theme, { expires: 365, path: '/' });
    }

    function applyTheme(theme) {
        const $body = $('body');
        const themeClasses = ($body.attr('class') || '')
            .split(/\s+/)
            .filter(cls => cls.indexOf('wgl-theme-') === 0);
        if (themeClasses.length) {
            $body.removeClass(themeClasses.join(' '));
        }
        $body.addClass(`wgl-theme-${theme}`);
        mw.hook('wgl.themeChanged').fire(theme);
    }

    function initThemeMenu($container, currentTheme) {
        currentTheme = currentTheme || loadTheme();

        const $portlet = $('<div>', {
            class: 'mw-portlet mw-portlet-skin-client-prefs-skin-theme mw-portlet-js theme-menu',
            id: 'skin-client-prefs-skin-theme'
        });
        $portlet.append(
            $('<div>', { class: 'theme-menu__heading', text: 'Тема' }),
            $('<div>', { class: 'theme-menu__content' })
        );

        const $form = $('<form>');
        [
            { key: 'light',  label: 'Светлая (beta)' },
            { key: 'normal', label: 'Стандартная' },
            { key: 'dark',   label: 'Тёмная' },
            { key: 'ss14',   label: 'Space Station 14' }
        ].forEach(opt => {
            const $wr = $('<div>', { class: 'theme-client-prefs-radio' });
            const $inp = $('<input>', {
                type:     'radio',
                name:     'theme-selection',
                id:       `theme-value-${opt.key}`,
                value:    opt.key,
                checked:  opt.key === currentTheme
            });
            const $lbl = $('<label>', {
                for:      `theme-value-${opt.key}`,
                text:     opt.label
            });
            $wr.append($inp, $lbl);
            $form.append($wr);
        });

        $portlet.find('.theme-menu__content').append(
            $('<ul>', { class: 'theme-menu__content-list' })
                .append(
                    $('<li>', { class: 'mw-list-item mw-list-item-js' })
                        .append($form)
                )
        );
        $container.append($portlet);

        $form.on('change', 'input[name="theme-selection"]', function() {
            const newTheme = $(this).val();
            saveTheme(newTheme);
            applyTheme(newTheme);
        });
    }

    mw.themeUtils = { loadTheme, applyTheme, initThemeMenu };
}(jQuery, mediaWiki));