MediaWiki:Common.js

From Dead Cells Wiki
Jump to navigation Jump to search

In other languages: Español • Polski • Русский • Українська


CSS and Javascript changes must comply with the wiki design rules.


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: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences
/* Any JavaScript here will be loaded for all users on every page load. */

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
floating-scroll v3.2.0
https://amphiluke.github.io/floating-scroll/
(c) 2022 Amphiluke
*/
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).jQuery)}(this,(function(t){"use strict";var i="horizontal",n="vertical",e={init:function(t,n){var e=this;e.orientationProps=function(t){var n=t===i;return{ORIENTATION:t,SIZE:n?"width":"height",X_SIZE:n?"height":"width",OFFSET_SIZE:n?"offsetWidth":"offsetHeight",OFFSET_X_SIZE:n?"offsetHeight":"offsetWidth",CLIENT_SIZE:n?"clientWidth":"clientHeight",CLIENT_X_SIZE:n?"clientHeight":"clientWidth",INNER_X_SIZE:n?"innerHeight":"innerWidth",SCROLL_SIZE:n?"scrollWidth":"scrollHeight",SCROLL_POS:n?"scrollLeft":"scrollTop",START:n?"left":"top",X_START:n?"top":"left",X_END:n?"bottom":"right"}}(n);var o=t.closest(".fl-scrolls-body");o.length&&(e.scrollBody=o),e.container=t[0],e.visible=!0,e.initWidget(),e.updateAPI(),e.addEventHandlers(),e.skipSyncContainer=e.skipSyncWidget=!1},initWidget:function(){var i=this,n=i.orientationProps,e=n.ORIENTATION,o=n.SIZE,r=n.SCROLL_SIZE,c=i.widget=t('<div class="fl-scrolls" data-orientation="'+e+'"></div>');t("<div></div>").appendTo(c)[o](i.container[r]),c.appendTo(i.container)},addEventHandlers:function(){var i=this;(i.eventHandlers=[{$el:t(window),handlers:{"destroyDetached.fscroll":function(t){"fscroll"===t.namespace&&i.destroyDetachedAPI()}}},{$el:i.scrollBody||t(window),handlers:{scroll:function(){i.updateAPI()},resize:function(){i.updateAPI()}}},{$el:i.widget,handlers:{scroll:function(){i.visible&&!i.skipSyncContainer&&i.syncContainer(),i.skipSyncContainer=!1}}},{$el:t(i.container),handlers:{scroll:function(){i.skipSyncWidget||i.syncWidget(),i.skipSyncWidget=!1},focusin:function(){setTimeout((function(){i.widget&&i.syncWidget()}),0)},"update.fscroll":function(t){"fscroll"===t.namespace&&i.updateAPI()},"destroy.fscroll":function(t){"fscroll"===t.namespace&&i.destroyAPI()}}}]).forEach((function(t){var i=t.$el,n=t.handlers;return i.bind(n)}))},checkVisibility:function(){var t=this,i=t.widget,n=t.container,e=t.scrollBody,o=t.orientationProps,r=o.SCROLL_SIZE,c=o.OFFSET_SIZE,l=o.X_START,s=o.X_END,d=o.INNER_X_SIZE,a=o.CLIENT_X_SIZE,f=i[0][r]<=i[0][c];if(!f){var h=n.getBoundingClientRect(),u=e?e[0].getBoundingClientRect()[s]:window[d]||document.documentElement[a];f=h[s]<=u||h[l]>u}t.visible===f&&(t.visible=!f,i.toggleClass("fl-scrolls-hidden"))},syncContainer:function(){var t=this,i=t.orientationProps.SCROLL_POS,n=t.widget[0][i];t.container[i]!==n&&(t.skipSyncWidget=!0,t.container[i]=n)},syncWidget:function(){var t=this,i=t.orientationProps.SCROLL_POS,n=t.container[i];t.widget[0][i]!==n&&(t.skipSyncContainer=!0,t.widget[0][i]=n)},updateAPI:function(){var i=this,n=i.orientationProps,e=n.SIZE,o=n.X_SIZE,r=n.OFFSET_X_SIZE,c=n.CLIENT_SIZE,l=n.CLIENT_X_SIZE,s=n.SCROLL_SIZE,d=n.START,a=i.widget,f=i.container,h=i.scrollBody,u=f[c],S=f[s];a[e](u),h||a.css(d,f.getBoundingClientRect()[d]+"px"),t("div",a)[e](S),S>u&&a[o](a[0][r]-a[0][l]+1),i.syncWidget(),i.checkVisibility()},destroyAPI:function(){var t=this;t.eventHandlers.forEach((function(t){var i=t.$el,n=t.handlers;return i.unbind(n)})),t.widget.remove(),t.eventHandlers=t.widget=t.container=t.scrollBody=null},destroyDetachedAPI:function(){t.contains(document.body,this.container)||this.destroyAPI()}};t.fn.floatingScroll=function(o,r){if(void 0===o&&(o="init"),void 0===r&&(r={}),"init"===o){var c=r.orientation,l=void 0===c?i:c;if(l!==i&&l!==n)throw new Error("Scrollbar orientation should be either “horizontal” or “vertical”");this.each((function(i,n){return Object.create(e).init(t(n),l)}))}else Object.prototype.hasOwnProperty.call(e,o+"API")&&this.trigger(o+".fscroll");return this},t((function(){t("body [data-fl-scrolls]").each((function(i,n){var e=t(n);e.floatingScroll("init",e.data("flScrolls")||{})}))}))}));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* Style backbutton dev wiki */
window.BackToTopModern = true;

///////////////////////////////////////////////////////////////////////////////

/* Slider quotes */
if($('.hslider')[0]){
    var multiItemhslider = (function () {
      return function (selector, config) {
        var
          _mainElement = document.querySelector(selector), // основный элемент блока
          _hsliderWrapper = _mainElement.querySelector('.hslider__wrapper'), // обертка для .hslider-item
          _hsliderItems = _mainElement.querySelectorAll('.hslider__item'), // элементы (.hslider-item)
          _hsliderControls = _mainElement.querySelectorAll('.hslider__control'), // элементы управления
          _hsliderControlLeft = _mainElement.querySelector('.hslider__control_left'), // кнопка "LEFT"
          _hsliderControlRight = _mainElement.querySelector('.hslider__control_right'), // кнопка "RIGHT"
          _wrapperWidth = parseFloat(getComputedStyle(_hsliderWrapper).width), // ширина обёртки
          _itemWidth = parseFloat(getComputedStyle(_hsliderItems[0]).width), // ширина одного элемента    
          _positionLeftItem = 0, // позиция левого активного элемента
          _transform = 0, // значение транфсофрмации .hslider_wrapper
          _step = _itemWidth / _wrapperWidth * 100, // величина шага (для трансформации)
          _items = [], // массив элементов
          _interval = 0,
          _config = {
            isCycling: false, // автоматическая смена слайдов
            direction: 'right', // направление смены слайдов
            interval: 5000, // интервал между автоматической сменой слайдов
            pause: true // устанавливать ли паузу при поднесении курсора к слайдеру
          };

        for (var key in config) {
          if (key in _config) {
            _config[key] = config[key];
          }
        }

        // наполнение массива _items
        _hsliderItems.forEach(function (item, index) {
          _items.push({ item: item, position: index, transform: 0 });
        });

        var position = {
          getItemMin: function () {
            var indexItem = 0;
            _items.forEach(function (item, index) {
              if (item.position < _items[indexItem].position) {
                indexItem = index;
              }
            });
            return indexItem;
          },
          getItemMax: function () {
            var indexItem = 0;
            _items.forEach(function (item, index) {
              if (item.position > _items[indexItem].position) {
                indexItem = index;
              }
            });
            return indexItem;
          },
          getMin: function () {
            return _items[position.getItemMin()].position;
          },
          getMax: function () {
            return _items[position.getItemMax()].position;
          }
        }

        var _transformItem = function (direction) {
          var nextItem;
          if (direction === 'right') {
            _positionLeftItem++;
            if ((_positionLeftItem + _wrapperWidth / _itemWidth - 1) > position.getMax()) {
              nextItem = position.getItemMin();
              _items[nextItem].position = position.getMax() + 1;
              _items[nextItem].transform += _items.length * 100;
              _items[nextItem].item.style.transform = 'translateX(' + _items[nextItem].transform + '%)';
            }
            _transform -= _step;
          }
          if (direction === 'left') {
            _positionLeftItem--;
            if (_positionLeftItem < position.getMin()) {
              nextItem = position.getItemMax();
              _items[nextItem].position = position.getMin() - 1;
              _items[nextItem].transform -= _items.length * 100;
              _items[nextItem].item.style.transform = 'translateX(' + _items[nextItem].transform + '%)';
            }
            _transform += _step;
          }
          _hsliderWrapper.style.transform = 'translateX(' + _transform + '%)';
        }

        var _cycle = function (direction) {
          if (!_config.isCycling) {
            return;
          }
          _interval = setInterval(function () {
            _transformItem(direction);
          }, _config.interval);
        }

        // обработчик события click для кнопок "назад" и "вперед"
        var _controlClick = function (e) {
          var direction = this.classList.contains('hslider__control_right') ? 'right' : 'left';
          e.preventDefault();
          _transformItem(direction);
          clearInterval(_interval);
          _cycle(_config.direction);
        };

        var _setUpListeners = function () {
          // добавление к кнопкам "назад" и "вперед" обрботчика _controlClick для событя click
          _hsliderControls.forEach(function (item) {
            item.addEventListener('click', _controlClick);
          });
          if (_config.pause && _config.isCycling) {
            _mainElement.addEventListener('mouseenter', function () {
              clearInterval(_interval);
            });
            _mainElement.addEventListener('mouseleave', function () {
              clearInterval(_interval);
              _cycle(_config.direction);
            });
          }
        }

        // инициализация
        _setUpListeners();
        _cycle(_config.direction);

        return {
          right: function () { // метод right
            _transformItem('right');
          },
          left: function () { // метод left
            _transformItem('left');
          },
          stop: function () { // метод stop
            _config.isCycling = false;
            clearInterval(_interval);
          },
          cycle: function () { // метод cycle 
            _config.isCycling = true;
            clearInterval(_interval);
            _cycle();
          }
        }

      }
    }());

    var hslider = multiItemhslider('.hslider', {
      isCycling: true
    })
}

///////////////////////////////////////////////////////////////////////////////

/* Hide spoiler replacement script */
$(function() {
	$.when( 
		$('.spoiler').each(function() {
			$(this).css({'position': 'relative'});
			$(this).append(
				$('<div>').append(
					$('<div>', {
						text: ' Spoiler alert!'
					}).prepend(
						$('<img>', {
							'src': '/images/c/c0/Exclamation.png'
						})
					).css({'color': '#d1394e', 'font-weight': 'bold', 'font-size': '20px'}),
					$('<a>', {
						'class': 'spoiler-text',
						href: 'javascript:void(0)',
						text: 'Tap to reveal'
					})
				).css({'position': 'absolute', 'inset': '0px', 'background-color': 'black', 'display': 'flex', 'justify-content': 'center', 'flex-flow': 'column wrap', 'align-items': 'center'})
			);
		})
	).done(function() {
       $('.spoiler-text').click(function() {
			$(this).parent().fadeOut("400", function() {
        		$(this).remove();
    		});
		});
	});
} );

///////////////////////////////////////////////////////////////////////////////

/* Tooltips configuration */
window.tooltips_config = {
    offsetX: 7,
    offsetY: 7,
    // noCSS: true,
}

///////////////////////////////////////////////////////////////////////////////

/* Copied from https://terraria.wiki.gg/wiki/MediaWiki:Common.js */
/* Make sidebar sections collapsible */
$(function(){
	$panel = $('#mw-panel');
	$("#mw-panel .portal").each(function(index, el){
		var $el = $(el);
		var $id = $el.attr("id");
		if(!$id){
			return;
		}
		// for < 1366px
		$el.removeClass('expanded');
		// for >= 1366px
		if(localStorage.getItem('sidebar_c_'+$id) === "y"){
			$el.addClass('collapsed').find('.body').slideUp(0);
		}
	});
	$("#mw-panel .portal").on("click", "h3", function(event){
		var $el = $(this).parent();
		var $id = $el.attr("id");
		if(!$id){
			return;
		}
		event.stopPropagation();
		if($panel.width() < 200){
			$el.toggleClass('collapsed');
			if($el.hasClass('collapsed')){ // more consistent between class and slide status.
				localStorage.setItem('sidebar_c_'+$id, "y");
				$el.find('.body').slideUp('fast');
			}
			else{
				localStorage.setItem('sidebar_c_'+$id, "n");
				$el.find('.body').slideDown('fast');
			}
		}
		else{
			$("#mw-panel .portal").not($el).removeClass('expanded');
			$el.toggleClass('expanded');
		}
	});
});

///////////////////////////////////////////////////////////////////////////////

/* Copied from https://terraria.wiki.gg/wiki/MediaWiki:Common.js */
/**
 * Handle wide tables
 *
 * Display a horizontal floating scroll bar when the table width exceeds the page width.
 */
$.when($.ready, mw.loader.using(['mediawiki.util'])).then( function() {
	var TABLE_WIDE_CLASS = "table-wide";
	var TABLE_WIDE_INNER_CLASS = "table-wide-inner";

	var handleWideTables = function(tables) {
		var handler = mw.util.debounce(100, function() {
			if(!tables){
				return;
			}
			tables.forEach(function(table) {
				var $table = $(table);
				if(!$table.data('container')){
					$table.data('container', table.parentNode);
				}
				var container = $table.data('container');
				if(!container){
					return;
				}
				var $innerBox = $table.parent();
				var $outerBox = $innerBox.parent();
				var overwide = table.getBoundingClientRect().width > container.getBoundingClientRect().width;
				if($outerBox.hasClass(TABLE_WIDE_CLASS)){
					if(overwide){
						$innerBox.floatingScroll("update");
					}else{
						$outerBox.before($table).remove();
					}
				}else{
					if(overwide) {
						$('<div/>').addClass(TABLE_WIDE_INNER_CLASS).appendTo(
							$('<div/>').addClass(TABLE_WIDE_CLASS).insertBefore($table)
						).append($table).floatingScroll("init").floatingScroll("update");
					}
				}
			});
		});
		handler();
		window.addEventListener("resize", handler);
	};

	var isEditorActive  = function() {
		var e = new URLSearchParams(window.location.search);
		return "edit" === e.get("action") || "submit" === e.get("action") || ("edit" === e.get("veaction")
			|| "submit" === e.get("veaction") || "editsource" === e.get("veaction"));
	}

	mw.hook("wikipage.content").add(function() {
		if (!isEditorActive()) {
			var el = document.querySelector("#bodyContent");
			if (el) {
				handleWideTables(el.querySelectorAll("table"));
			}
		}
	});
});

///////////////////////////////////////////////////////////////////////////////

/* Copied from https://terraria.wiki.gg/wiki/MediaWiki:Common.js */
/**
 * content width toggle
 */
$(function(){
	$body = $('body');
	$('<div>', { id: 'nav-content-size-toggle' } ).append(
		$('<span>')
		).prependTo($('#mw-head'))
	.on('click', function(){
		$body.toggleClass('content-size-expanded');
	});
});