User:Wookipan/common.js

From Team Fortress Wiki
Jump to: navigation, search

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
var system = system || {};
system.Notification = (function() {
	   var id = 0;
       function Notification(page, inGroup, autoHide) {
        this.init = function() {
            var isAction = 0;
            this.id = id++;
            this.instance = '_notif_' + page + '-' + this.id.toString();
            this.prefix = 'User:Wookipan/';
            this.page = this.prefix + page;
            this.pageName = page;
            this.inGroup = inGroup.split(', ');

            if (autoHide !== undefined) {
                this.options = { autoHide: autoHide };
            }

            this.setAction = function(action, regex) {
                isAction = 1;
                if (action !== undefined && window.location.href.indexOf(action) > -1) {
                    if (regex !== undefined) {
                        var selectors = {
                            input: document.getElementById('wpSummary'),
                            textarea: document.getElementById('wpTextbox1')
                        };

                        var regExp = new RegExp('(?:.+' + regex + '.+)');
                        var value = selectors.input.value;
                        var text = selectors.textarea.textContent;
                        var isMatch = !!(value.match(regExp) || text.match(regExp));

                        if (isMatch) {
                            this.userGroup(this.inGroup);
                        }
                    } else {
                        this.userGroup(this.inGroup);
                    }
                }
            };

            setTimeout(function() {
                if (!isAction) {
                    this.userGroup(this.inGroup);
                }
            }.bind(this), 1000);
        };

        if (page !== undefined) {
            this.init();
        }
    }

    Notification.prototype = Object.assign({}, Notification.prototype, {
        query: function(page, options) {
            if (page) {
                var params = {
                    action: 'parse',
                    page: page,
                    prop: 'text',
                    format: 'json'
                };

                var api = new mw.Api();
                api.get(params).done(function(data) {
                    var content = data.parse.text['*'];

                    var getMarkup = function (html) {
                        var parser = new DOMParser();
                        var markup = parser.parseFromString(html, 'text/html');
                        var table = markup.body.querySelector('table');
                        var links = table.querySelectorAll('a');

                        function localeHandler() {
                            var locales = table.querySelector('pre');

                            if (locales) {
                                var userLang = mw.config.get('wgUserLanguage');
                                var text = table.querySelector('.ambox-text');

                                locales = JSON.parse(locales.innerHTML);
                                if (locales.title[userLang] === undefined) {
                                    return;
                                }

                                title = text.childNodes[0];
                                text = text.childNodes[2];
                                title.innerHTML = locales.title[userLang];
                                text.innerHTML = locales.text[userLang];
                            }
                        }

                        if (links.length) {
                            links.forEach(function(link) {
                                // Open links in a new tab to avoid forcing the user to save or leave their edit.
                                link.setAttribute('target', '_blank');
                            });
                        }

                        table.addEventListener('click', function() {
                            this.setCookie(this.instance, '1', 7 * 24);
                        }.bind(this));

                        if (this.pageName === 'system') {
                            table.classList.add('notif-system');
                            this.setCookie(this.instance, '1', 30 * 24);
                        }

                        if (!table) {
                            return;
                        } else {
                            localeHandler();
                            return table;
                        }
                    }.bind(this);

                    mw.notify(getMarkup(content), options);
                }.bind(this));
            }
        },

        userGroup: function(group) {
            if (!this.getCookie(this.instance)) {
                this.groups = mw.config.get('wgUserGroups');
                var inGroup = group.every(function(e) {
                    return this.groups.indexOf(e) > -1;
                }.bind(this));

                return this.validateGroup(group, inGroup);
            }
        },

        validateGroup: function(group, inGroup) {
            var userId = !!mw.config.get('wgUserId');
            var isNew = !this.groups.includes('autoconfirmed') && userId;

            // Exclusive page for special system announcements
            if (this.pageName === 'system') {
                var alert = new Audio('/w/images/b/bb/System_message_alert.wav');
                var timeout = function() {
                    setTimeout(function() {
                        alert.play();
                    }, 500);
                };

                alert.volume = 0.1;
                if (inGroup || group[0] === 'all') {
                    this.query(this.page, this.options);
                    timeout();
                }

            } else {

                if (inGroup || group[0] === 'all') {
                    this.query(this.page, this.options);
                }

                if (isNew && group[0] === 'new') {
                    this.query(this.page, this.options);
                }

                return isNew;
            }
        },

        setCookie: function(name, value, hours) {
            if (this.getCookie(name)) {
                return;
            }

            var date = new Date();
            var prefix = mw.config.get('wgCookiePrefix');
            date.setTime(date.getTime() + (hours * 60 * 60 * 1000));

            var expiration = 'expires=' + date.toUTCString() + ';';
            document.cookie = prefix + name + '=' + value + ';' + expiration + 'path=/';
        },

        getCookie: function(name) {
            return document.cookie.indexOf(name) > -1;
        }
    });

    return Notification;
})();

var notification = {
	init: function() {
		new system.Notification('NotifTest', 'all', false); // global notice
		new system.Notification('NotifTest', 'sysop', false).setAction('section', 'Trivia'); // section-based notice, targeted user group
	},
};
$(notification.init);

// Start custom username highlighting -----
/*
var uGroupHighlight = {
  init: function() {
    if ($('.mw-userlink')[0]) {
      var params = {
        action: 'query',
        list: 'allusers',
        augroup: ['sysop', 'moderator', 'bot'],
        auprop: 'groups',
        aulimit: 100,
        format: 'json'
      };

      var api = new mw.Api();

      api.get(params).done(function(data) {
        var uGroups = data.query.allusers, user;
        for (user in uGroups) {
          var group = uGroups[user].groups;
          var name = uGroups[user].name;

          $('bdi').each(function() {
            if ($(this).text().match('\\b' + name + '\\b')) {
              $(this).closest('.mw-userlink').addClass(group.includes('bot') ? 'bot' : 'staff');
            }
          });
        }
      });
    }
  },
};
$(uGroupHighlight.init);
// End custom username highlighting -----
*/
/*
var apfools22 = {
  init: function() {
    if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
    	
   // var randomSeed = Math.floor(Math.random() * 50)
   // console.log(randomSeed);
      if (
        !$('body').hasClass('action-edit') &&
        !mw.storage.get('skeletonFired') // && randomSeed === 0
      ) {
        var $skeleton = document.createElement('audio');
        var $lootbox = document.createElement('img');

        $skeleton.src = '/w/images/9/93/User_Wookipan_theskeletonappears.wav';

        $lootbox.classList.add('lootbox');
        $lootbox.src = '/w/images/b/b8/User_Wookipan_lootcrate.png';
        $lootbox.title = 'Click me!';

        $('.apfools22').detach().prependTo('.mediawiki');
        $('.mediawiki').prepend($lootbox);

        $('.lootbox').click(function() {
          $('.lootbox').fadeOut();
          $('html, body').animate({scrollTop: '0px'}, 0).css('overflow', 'hidden');

          $skeleton.play();

          $($skeleton).on('ended', function() {
            window.location.reload(true);
          });

          $('.thewikiskeleton').fadeIn('slow');
          setTimeout(function() {
            $('.thewikiskeleton-bg').fadeIn(1000, function () {
              $('.apfools22 p').fadeIn(1000);
            });
          }, 2500);
          mw.storage.set('skeletonFired', 'true');
        });
      } else {
      	$('.apfools22').remove();
      }
    }
  },
};
$(apfools22.init);
*/