MediaWiki:Rewire.js

(function (window, $, mw) {   'use strict';

window.dev = window.dev || {}; if (window.dev.rewire) { return; } // Guard against double loads.

var Array = window.Array, HTMLCollection = window.HTMLCollection, Node = window.Node, NodeList = window.NodeList, document = window.document;

// Given some potentially nested sequence of things, // flatten them into an array of disjoint `Node`s. function flattenNodes(sequence) { var nodes = []; checkNextObject: for (var i = 0; i < sequence.length; ++i) { var object = sequence[i]; if (object instanceof Node) { var candidates = [object]; } else if ((object instanceof $) || (object instanceof Array) || (object instanceof HTMLCollection) || (object instanceof NodeList)) { var candidates = flattenNodes(object); } else { continue checkNextObject; // Silently drop this mystery object. }

checkNextCandidate: for (var j = 0; j < candidates.length; ++j) { for (var k = nodes.length - 1; k > -1; --k) { if (candidates[j] === nodes[k]) { continue checkNextCandidate; // Candidate node has already been witnessed. }                   var mask = candidates[j].compareDocumentPosition(nodes[k]); if (mask & Node.DOCUMENT_POSITION_CONTAINS) { continue checkNextCandidate; // Candidate node is a descendant of a node that has already been witnessed. } else if (mask & Node.DOCUMENT_POSITION_CONTAINED_BY) { // Candidate node is an ancestor of a node that has already been witnessed. // We'll remove that node and add the candidate node instead. nodes.splice(k, 1); }               }                nodes.push(candidates[j]);  // Add candidate node. }       }        return nodes; }

// Edge/IE doesn't support `Node.isConnected`, so we'll approximate. // (We don't really care about the shadow DOM, to be honest.) function nodeIsConnected(node) { while (node) { if (node === document) return true; node = node.parentNode; }       return false; }

var rewire = {};

rewire.load = function { flattenNodes(arguments).filter(nodeIsConnected).forEach(function (node) {           // `twitter` parser tag:             if (node.querySelector('a[data-wikia-widget="twitter"]')) {                if (!(window.twttr && window.twttr.widgets)) {                    mw.loader.load(['ext.TwitterTag'], null, true);                } else {                    window.twttr.widgets.load(node);                }            }        }); };

window.dev.rewire = rewire;

mw.hook('wikipage.content').add(function ($content) {       rewire.load($content);    }); }(this, jQuery, mediaWiki));