MediaWiki:Gadget-theme.js: различия между версиями

Материал из Space Station 14 Вики
м тесты
Метка: отменено
мНет описания правки
Метка: отменено
Строка 3: Строка 3:


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


   function incrementThemeCounter(themeName) {
   function incrementThemeCounter(themeName) {
    if (mw.user.isAnon && mw.user.isAnon()) {
      console.warn('123');
      return;
    }
     const pageTitle = 'Обсуждение участника:Pok';
     const pageTitle = 'Обсуждение участника:Pok';
     const api = new mw.Api();
     const api = new mw.Api();
Строка 19: Строка 21:
       prop: 'revisions',
       prop: 'revisions',
       titles: pageTitle,
       titles: pageTitle,
      rvslots: '*',
       rvprop: 'content',
       rvprop: 'content',
      formatversion: 2,
       format: 'json'
       format: 'json'
     }).done(data => {
     }).done(data => {
       const pages = data.query.pages;
       const pages = data.query.pages;
       const page = pages[Object.keys(pages)[0]];
       const page = pages[0];
       let content = page.revisions[0]['*'] || '';
      const rev = page.revisions && page.revisions[0];
       const content = rev
        ? (rev.slots ? rev.slots.main['*'] : rev['*'])
        : '';


       const lines = content.split('\n');
       const lines = content.split('\n');
       const updated = lines.map(line => {
       const updated = lines.map(line => {
         const [name, cnt] = line.split('=');
         const parts = line.split('=');
         if (name === themeName) {
         if (parts[0] === themeName) {
           const count = parseInt(cnt, 10) || 0;
           const count = parseInt(parts[1], 10) || 0;
           return `${name}=${count + 1}`;
           return `${themeName}=${count + 1}`;
         }
         }
         return line;
         return line;
       }).join('\n');
       }).join('\n');


       api.post({
       api.postWithToken('csrf', {
         action: 'edit',
         action: 'edit',
         title: pageTitle,
         title: pageTitle,
         text: updated,
         text: updated,
         summary: `Increment ${themeName} theme counter`,
         summary: `Increment ${themeName} theme counter`
        token: mw.user.tokens.get('editToken')
       }).done(() => {
       }).done(() => {
         console.log(`Theme "${themeName}" count updated.`);
         console.log(`Theme "${themeName}" count updated.`);
Строка 56: Строка 62:
     const validThemes = ['light', 'normal', 'dark', 'ss14'];
     const validThemes = ['light', 'normal', 'dark', 'ss14'];


    console.log('Current cookies:', document.cookie);
     const theme = getCookie(COOKIE_NAME);
     const theme = getCookie(COOKIE_NAME);
     if (!theme || validThemes.indexOf(theme) === -1) {
     if (!theme || validThemes.indexOf(theme) === -1) {
       console.warn('Unknown theme cookie:', theme);
       console.warn('Unknown or missing theme cookie:', theme);
       return;
       return;
     }
     }


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

Версия от 18:05, 19 мая 2025

;(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) {
    if (mw.user.isAnon && mw.user.isAnon()) {
      console.warn('123');
      return;
    }

    const pageTitle = 'Обсуждение участника:Pok';
    const api = new mw.Api();

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

      const lines = content.split('\n');
      const updated = lines.map(line => {
        const parts = line.split('=');
        if (parts[0] === themeName) {
          const count = parseInt(parts[1], 10) || 0;
          return `${themeName}=${count + 1}`;
        }
        return line;
      }).join('\n');

      api.postWithToken('csrf', {
        action: 'edit',
        title: pageTitle,
        text: updated,
        summary: `Increment ${themeName} theme counter`
      }).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('Current cookies:', document.cookie);
    const theme = getCookie(COOKIE_NAME);
    if (!theme || validThemes.indexOf(theme) === -1) {
      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));