dom-minimap
Version:
simply lovely dom minimap
2,695 lines • 91.7 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('assert')) :
typeof define === 'function' && define.amd ? define(['assert'], factory) :
(global = global || self, global.Minimap = factory(global.assert));
}(this, function (assert) { 'use strict';
assert = assert && assert.hasOwnProperty('default') ? assert['default'] : assert;
function _taggedTemplateLiteral(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var slice = Array.prototype.slice;
var domWalk = iterativelyWalk;
function iterativelyWalk(nodes, cb) {
if (!('length' in nodes)) {
nodes = [nodes];
}
nodes = slice.call(nodes);
while(nodes.length) {
var node = nodes.shift(),
ret = cb(node);
if (ret) {
return ret
}
if (node.childNodes && node.childNodes.length) {
nodes = slice.call(node.childNodes).concat(nodes);
}
}
}
var domComment = Comment;
function Comment(data, owner) {
if (!(this instanceof Comment)) {
return new Comment(data, owner)
}
this.data = data;
this.nodeValue = data;
this.length = data.length;
this.ownerDocument = owner || null;
}
Comment.prototype.nodeType = 8;
Comment.prototype.nodeName = "#comment";
Comment.prototype.toString = function _Comment_toString() {
return "[object Comment]"
};
var domText = DOMText;
function DOMText(value, owner) {
if (!(this instanceof DOMText)) {
return new DOMText(value)
}
this.data = value || "";
this.length = this.data.length;
this.ownerDocument = owner || null;
}
DOMText.prototype.type = "DOMTextNode";
DOMText.prototype.nodeType = 3;
DOMText.prototype.nodeName = "#text";
DOMText.prototype.toString = function _Text_toString() {
return this.data
};
DOMText.prototype.replaceData = function replaceData(index, length, value) {
var current = this.data;
var left = current.substring(0, index);
var right = current.substring(index + length, current.length);
this.data = left + value + right;
this.length = this.data.length;
};
var dispatchEvent_1 = dispatchEvent;
function dispatchEvent(ev) {
var elem = this;
var type = ev.type;
if (!ev.target) {
ev.target = elem;
}
if (!elem.listeners) {
elem.listeners = {};
}
var listeners = elem.listeners[type];
if (listeners) {
return listeners.forEach(function (listener) {
ev.currentTarget = elem;
if (typeof listener === 'function') {
listener(ev);
} else {
listener.handleEvent(ev);
}
})
}
if (elem.parentNode) {
elem.parentNode.dispatchEvent(ev);
}
}
var addEventListener_1 = addEventListener;
function addEventListener(type, listener) {
var elem = this;
if (!elem.listeners) {
elem.listeners = {};
}
if (!elem.listeners[type]) {
elem.listeners[type] = [];
}
if (elem.listeners[type].indexOf(listener) === -1) {
elem.listeners[type].push(listener);
}
}
var removeEventListener_1 = removeEventListener;
function removeEventListener(type, listener) {
var elem = this;
if (!elem.listeners) {
return
}
if (!elem.listeners[type]) {
return
}
var list = elem.listeners[type];
var index = list.indexOf(listener);
if (index !== -1) {
list.splice(index, 1);
}
}
var serialize = serializeNode;
var voidElements = ["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];
function serializeNode(node) {
switch (node.nodeType) {
case 3:
return escapeText(node.data)
case 8:
return "<!--" + node.data + "-->"
default:
return serializeElement(node)
}
}
function serializeElement(elem) {
var strings = [];
var tagname = elem.tagName;
if (elem.namespaceURI === "http://www.w3.org/1999/xhtml") {
tagname = tagname.toLowerCase();
}
strings.push("<" + tagname + properties(elem) + datasetify(elem));
if (voidElements.indexOf(tagname) > -1) {
strings.push(" />");
} else {
strings.push(">");
if (elem.childNodes.length) {
strings.push.apply(strings, elem.childNodes.map(serializeNode));
} else if (elem.textContent || elem.innerText) {
strings.push(escapeText(elem.textContent || elem.innerText));
} else if (elem.innerHTML) {
strings.push(elem.innerHTML);
}
strings.push("</" + tagname + ">");
}
return strings.join("")
}
function isProperty(elem, key) {
var type = typeof elem[key];
if (key === "style" && Object.keys(elem.style).length > 0) {
return true
}
return elem.hasOwnProperty(key) &&
(type === "string" || type === "boolean" || type === "number") &&
key !== "nodeName" && key !== "className" && key !== "tagName" &&
key !== "textContent" && key !== "innerText" && key !== "namespaceURI" && key !== "innerHTML"
}
function stylify(styles) {
if (typeof styles === 'string') return styles
var attr = "";
Object.keys(styles).forEach(function (key) {
var value = styles[key];
key = key.replace(/[A-Z]/g, function(c) {
return "-" + c.toLowerCase();
});
attr += key + ":" + value + ";";
});
return attr
}
function datasetify(elem) {
var ds = elem.dataset;
var props = [];
for (var key in ds) {
props.push({ name: "data-" + key, value: ds[key] });
}
return props.length ? stringify(props) : ""
}
function stringify(list) {
var attributes = [];
list.forEach(function (tuple) {
var name = tuple.name;
var value = tuple.value;
if (name === "style") {
value = stylify(value);
}
attributes.push(name + "=" + "\"" + escapeAttributeValue(value) + "\"");
});
return attributes.length ? " " + attributes.join(" ") : ""
}
function properties(elem) {
var props = [];
for (var key in elem) {
if (isProperty(elem, key)) {
props.push({ name: key, value: elem[key] });
}
}
for (var ns in elem._attributes) {
for (var attribute in elem._attributes[ns]) {
var prop = elem._attributes[ns][attribute];
var name = (prop.prefix ? prop.prefix + ":" : "") + attribute;
props.push({ name: name, value: prop.value });
}
}
if (elem.className) {
props.push({ name: "class", value: elem.className });
}
return props.length ? stringify(props) : ""
}
function escapeText(s) {
var str = '';
if (typeof(s) === 'string') {
str = s;
} else if (s) {
str = s.toString();
}
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
}
function escapeAttributeValue(str) {
return escapeText(str).replace(/"/g, """)
}
var htmlns = "http://www.w3.org/1999/xhtml";
var domElement = DOMElement;
function DOMElement(tagName, owner, namespace) {
if (!(this instanceof DOMElement)) {
return new DOMElement(tagName)
}
var ns = namespace === undefined ? htmlns : (namespace || null);
this.tagName = ns === htmlns ? String(tagName).toUpperCase() : tagName;
this.nodeName = this.tagName;
this.className = "";
this.dataset = {};
this.childNodes = [];
this.parentNode = null;
this.style = {};
this.ownerDocument = owner || null;
this.namespaceURI = ns;
this._attributes = {};
if (this.tagName === 'INPUT') {
this.type = 'text';
}
}
DOMElement.prototype.type = "DOMElement";
DOMElement.prototype.nodeType = 1;
DOMElement.prototype.appendChild = function _Element_appendChild(child) {
if (child.parentNode) {
child.parentNode.removeChild(child);
}
this.childNodes.push(child);
child.parentNode = this;
return child
};
DOMElement.prototype.replaceChild =
function _Element_replaceChild(elem, needle) {
// TODO: Throw NotFoundError if needle.parentNode !== this
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
var index = this.childNodes.indexOf(needle);
needle.parentNode = null;
this.childNodes[index] = elem;
elem.parentNode = this;
return needle
};
DOMElement.prototype.removeChild = function _Element_removeChild(elem) {
// TODO: Throw NotFoundError if elem.parentNode !== this
var index = this.childNodes.indexOf(elem);
this.childNodes.splice(index, 1);
elem.parentNode = null;
return elem
};
DOMElement.prototype.insertBefore =
function _Element_insertBefore(elem, needle) {
// TODO: Throw NotFoundError if referenceElement is a dom node
// and parentNode !== this
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
var index = needle === null || needle === undefined ?
-1 :
this.childNodes.indexOf(needle);
if (index > -1) {
this.childNodes.splice(index, 0, elem);
} else {
this.childNodes.push(elem);
}
elem.parentNode = this;
return elem
};
DOMElement.prototype.setAttributeNS =
function _Element_setAttributeNS(namespace, name, value) {
var prefix = null;
var localName = name;
var colonPosition = name.indexOf(":");
if (colonPosition > -1) {
prefix = name.substr(0, colonPosition);
localName = name.substr(colonPosition + 1);
}
if (this.tagName === 'INPUT' && name === 'type') {
this.type = value;
}
else {
var attributes = this._attributes[namespace] || (this._attributes[namespace] = {});
attributes[localName] = {value: value, prefix: prefix};
}
};
DOMElement.prototype.getAttributeNS =
function _Element_getAttributeNS(namespace, name) {
var attributes = this._attributes[namespace];
var value = attributes && attributes[name] && attributes[name].value;
if (this.tagName === 'INPUT' && name === 'type') {
return this.type;
}
if (typeof value !== "string") {
return null
}
return value
};
DOMElement.prototype.removeAttributeNS =
function _Element_removeAttributeNS(namespace, name) {
var attributes = this._attributes[namespace];
if (attributes) {
delete attributes[name];
}
};
DOMElement.prototype.hasAttributeNS =
function _Element_hasAttributeNS(namespace, name) {
var attributes = this._attributes[namespace];
return !!attributes && name in attributes;
};
DOMElement.prototype.setAttribute = function _Element_setAttribute(name, value) {
return this.setAttributeNS(null, name, value)
};
DOMElement.prototype.getAttribute = function _Element_getAttribute(name) {
return this.getAttributeNS(null, name)
};
DOMElement.prototype.removeAttribute = function _Element_removeAttribute(name) {
return this.removeAttributeNS(null, name)
};
DOMElement.prototype.hasAttribute = function _Element_hasAttribute(name) {
return this.hasAttributeNS(null, name)
};
DOMElement.prototype.removeEventListener = removeEventListener_1;
DOMElement.prototype.addEventListener = addEventListener_1;
DOMElement.prototype.dispatchEvent = dispatchEvent_1;
// Un-implemented
DOMElement.prototype.focus = function _Element_focus() {
return void 0
};
DOMElement.prototype.toString = function _Element_toString() {
return serialize(this)
};
DOMElement.prototype.getElementsByClassName = function _Element_getElementsByClassName(classNames) {
var classes = classNames.split(" ");
var elems = [];
domWalk(this, function (node) {
if (node.nodeType === 1) {
var nodeClassName = node.className || "";
var nodeClasses = nodeClassName.split(" ");
if (classes.every(function (item) {
return nodeClasses.indexOf(item) !== -1
})) {
elems.push(node);
}
}
});
return elems
};
DOMElement.prototype.getElementsByTagName = function _Element_getElementsByTagName(tagName) {
tagName = tagName.toLowerCase();
var elems = [];
domWalk(this.childNodes, function (node) {
if (node.nodeType === 1 && (tagName === '*' || node.tagName.toLowerCase() === tagName)) {
elems.push(node);
}
});
return elems
};
DOMElement.prototype.contains = function _Element_contains(element) {
return domWalk(this, function (node) {
return element === node
}) || false
};
var domFragment = DocumentFragment;
function DocumentFragment(owner) {
if (!(this instanceof DocumentFragment)) {
return new DocumentFragment()
}
this.childNodes = [];
this.parentNode = null;
this.ownerDocument = owner || null;
}
DocumentFragment.prototype.type = "DocumentFragment";
DocumentFragment.prototype.nodeType = 11;
DocumentFragment.prototype.nodeName = "#document-fragment";
DocumentFragment.prototype.appendChild = domElement.prototype.appendChild;
DocumentFragment.prototype.replaceChild = domElement.prototype.replaceChild;
DocumentFragment.prototype.removeChild = domElement.prototype.removeChild;
DocumentFragment.prototype.toString =
function _DocumentFragment_toString() {
return this.childNodes.map(function (node) {
return String(node)
}).join("")
};
var event = Event;
function Event(family) {}
Event.prototype.initEvent = function _Event_initEvent(type, bubbles, cancelable) {
this.type = type;
this.bubbles = bubbles;
this.cancelable = cancelable;
};
Event.prototype.preventDefault = function _Event_preventDefault() {
};
var document$1 = Document;
function Document() {
if (!(this instanceof Document)) {
return new Document();
}
this.head = this.createElement("head");
this.body = this.createElement("body");
this.documentElement = this.createElement("html");
this.documentElement.appendChild(this.head);
this.documentElement.appendChild(this.body);
this.childNodes = [this.documentElement];
this.nodeType = 9;
}
var proto = Document.prototype;
proto.createTextNode = function createTextNode(value) {
return new domText(value, this)
};
proto.createElementNS = function createElementNS(namespace, tagName) {
var ns = namespace === null ? null : String(namespace);
return new domElement(tagName, this, ns)
};
proto.createElement = function createElement(tagName) {
return new domElement(tagName, this)
};
proto.createDocumentFragment = function createDocumentFragment() {
return new domFragment(this)
};
proto.createEvent = function createEvent(family) {
return new event(family)
};
proto.createComment = function createComment(data) {
return new domComment(data, this)
};
proto.getElementById = function getElementById(id) {
id = String(id);
var result = domWalk(this.childNodes, function (node) {
if (String(node.id) === id) {
return node
}
});
return result || null
};
proto.getElementsByClassName = domElement.prototype.getElementsByClassName;
proto.getElementsByTagName = domElement.prototype.getElementsByTagName;
proto.contains = domElement.prototype.contains;
proto.removeEventListener = removeEventListener_1;
proto.addEventListener = addEventListener_1;
proto.dispatchEvent = dispatchEvent_1;
var minDocument = new document$1();
var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal :
typeof window !== 'undefined' ? window : {};
var doccy;
if (typeof document !== 'undefined') {
doccy = document;
} else {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDocument;
}
}
var document_1 = doccy;
var hyperscriptAttributeToProperty = attributeToProperty;
var transform = {
'class': 'className',
'for': 'htmlFor',
'http-equiv': 'httpEquiv'
};
function attributeToProperty (h) {
return function (tagName, attrs, children) {
for (var attr in attrs) {
if (attr in transform) {
attrs[transform[attr]] = attrs[attr];
delete attrs[attr];
}
}
return h(tagName, attrs, children)
}
}
var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4;
var ATTR_KEY = 5, ATTR_KEY_W = 6;
var ATTR_VALUE_W = 7, ATTR_VALUE = 8;
var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10;
var ATTR_EQ = 11, ATTR_BREAK = 12;
var COMMENT = 13;
var hyperx = function (h, opts) {
if (!opts) opts = {};
var concat = opts.concat || function (a, b) {
return String(a) + String(b)
};
if (opts.attrToProp !== false) {
h = hyperscriptAttributeToProperty(h);
}
return function (strings) {
var state = TEXT, reg = '';
var arglen = arguments.length;
var parts = [];
for (var i = 0; i < strings.length; i++) {
if (i < arglen - 1) {
var arg = arguments[i+1];
var p = parse(strings[i]);
var xstate = state;
if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE;
if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE;
if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE;
if (xstate === ATTR) xstate = ATTR_KEY;
if (xstate === OPEN) {
if (reg === '/') {
p.push([ OPEN, '/', arg ]);
reg = '';
} else {
p.push([ OPEN, arg ]);
}
} else if (xstate === COMMENT && opts.comments) {
reg += String(arg);
} else if (xstate !== COMMENT) {
p.push([ VAR, xstate, arg ]);
}
parts.push.apply(parts, p);
} else parts.push.apply(parts, parse(strings[i]));
}
var tree = [null,{},[]];
var stack = [[tree,-1]];
for (var i = 0; i < parts.length; i++) {
var cur = stack[stack.length-1][0];
var p = parts[i], s = p[0];
if (s === OPEN && /^\//.test(p[1])) {
var ix = stack[stack.length-1][1];
if (stack.length > 1) {
stack.pop();
stack[stack.length-1][0][2][ix] = h(
cur[0], cur[1], cur[2].length ? cur[2] : undefined
);
}
} else if (s === OPEN) {
var c = [p[1],{},[]];
cur[2].push(c);
stack.push([c,cur[2].length-1]);
} else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) {
var key = '';
var copyKey;
for (; i < parts.length; i++) {
if (parts[i][0] === ATTR_KEY) {
key = concat(key, parts[i][1]);
} else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) {
if (typeof parts[i][2] === 'object' && !key) {
for (copyKey in parts[i][2]) {
if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) {
cur[1][copyKey] = parts[i][2][copyKey];
}
}
} else {
key = concat(key, parts[i][2]);
}
} else break
}
if (parts[i][0] === ATTR_EQ) i++;
var j = i;
for (; i < parts.length; i++) {
if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) {
if (!cur[1][key]) cur[1][key] = strfn(parts[i][1]);
else parts[i][1]==="" || (cur[1][key] = concat(cur[1][key], parts[i][1]));
} else if (parts[i][0] === VAR
&& (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) {
if (!cur[1][key]) cur[1][key] = strfn(parts[i][2]);
else parts[i][2]==="" || (cur[1][key] = concat(cur[1][key], parts[i][2]));
} else {
if (key.length && !cur[1][key] && i === j
&& (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) {
// https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes
// empty string is falsy, not well behaved value in browser
cur[1][key] = key.toLowerCase();
}
if (parts[i][0] === CLOSE) {
i--;
}
break
}
}
} else if (s === ATTR_KEY) {
cur[1][p[1]] = true;
} else if (s === VAR && p[1] === ATTR_KEY) {
cur[1][p[2]] = true;
} else if (s === CLOSE) {
if (selfClosing(cur[0]) && stack.length) {
var ix = stack[stack.length-1][1];
stack.pop();
stack[stack.length-1][0][2][ix] = h(
cur[0], cur[1], cur[2].length ? cur[2] : undefined
);
}
} else if (s === VAR && p[1] === TEXT) {
if (p[2] === undefined || p[2] === null) p[2] = '';
else if (!p[2]) p[2] = concat('', p[2]);
if (Array.isArray(p[2][0])) {
cur[2].push.apply(cur[2], p[2]);
} else {
cur[2].push(p[2]);
}
} else if (s === TEXT) {
cur[2].push(p[1]);
} else if (s === ATTR_EQ || s === ATTR_BREAK) ; else {
throw new Error('unhandled: ' + s)
}
}
if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) {
tree[2].shift();
}
if (tree[2].length > 2
|| (tree[2].length === 2 && /\S/.test(tree[2][1]))) {
if (opts.createFragment) return opts.createFragment(tree[2])
throw new Error(
'multiple root elements must be wrapped in an enclosing tag'
)
}
if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string'
&& Array.isArray(tree[2][0][2])) {
tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2]);
}
return tree[2][0]
function parse (str) {
var res = [];
if (state === ATTR_VALUE_W) state = ATTR;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (state === TEXT && c === '<') {
if (reg.length) res.push([TEXT, reg]);
reg = '';
state = OPEN;
} else if (c === '>' && !quot(state) && state !== COMMENT) {
if (state === OPEN && reg.length) {
res.push([OPEN,reg]);
} else if (state === ATTR_KEY) {
res.push([ATTR_KEY,reg]);
} else if (state === ATTR_VALUE && reg.length) {
res.push([ATTR_VALUE,reg]);
}
res.push([CLOSE]);
reg = '';
state = TEXT;
} else if (state === COMMENT && /-$/.test(reg) && c === '-') {
if (opts.comments) {
res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)]);
}
reg = '';
state = TEXT;
} else if (state === OPEN && /^!--$/.test(reg)) {
if (opts.comments) {
res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ]);
}
reg = c;
state = COMMENT;
} else if (state === TEXT || state === COMMENT) {
reg += c;
} else if (state === OPEN && c === '/' && reg.length) ; else if (state === OPEN && /\s/.test(c)) {
if (reg.length) {
res.push([OPEN, reg]);
}
reg = '';
state = ATTR;
} else if (state === OPEN) {
reg += c;
} else if (state === ATTR && /[^\s"'=/]/.test(c)) {
state = ATTR_KEY;
reg = c;
} else if (state === ATTR && /\s/.test(c)) {
if (reg.length) res.push([ATTR_KEY,reg]);
res.push([ATTR_BREAK]);
} else if (state === ATTR_KEY && /\s/.test(c)) {
res.push([ATTR_KEY,reg]);
reg = '';
state = ATTR_KEY_W;
} else if (state === ATTR_KEY && c === '=') {
res.push([ATTR_KEY,reg],[ATTR_EQ]);
reg = '';
state = ATTR_VALUE_W;
} else if (state === ATTR_KEY) {
reg += c;
} else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') {
res.push([ATTR_EQ]);
state = ATTR_VALUE_W;
} else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) {
res.push([ATTR_BREAK]);
if (/[\w-]/.test(c)) {
reg += c;
state = ATTR_KEY;
} else state = ATTR;
} else if (state === ATTR_VALUE_W && c === '"') {
state = ATTR_VALUE_DQ;
} else if (state === ATTR_VALUE_W && c === "'") {
state = ATTR_VALUE_SQ;
} else if (state === ATTR_VALUE_DQ && c === '"') {
res.push([ATTR_VALUE,reg],[ATTR_BREAK]);
reg = '';
state = ATTR;
} else if (state === ATTR_VALUE_SQ && c === "'") {
res.push([ATTR_VALUE,reg],[ATTR_BREAK]);
reg = '';
state = ATTR;
} else if (state === ATTR_VALUE_W && !/\s/.test(c)) {
state = ATTR_VALUE;
i--;
} else if (state === ATTR_VALUE && /\s/.test(c)) {
res.push([ATTR_VALUE,reg],[ATTR_BREAK]);
reg = '';
state = ATTR;
} else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ
|| state === ATTR_VALUE_DQ) {
reg += c;
}
}
if (state === TEXT && reg.length) {
res.push([TEXT,reg]);
reg = '';
} else if (state === ATTR_VALUE && reg.length) {
res.push([ATTR_VALUE,reg]);
reg = '';
} else if (state === ATTR_VALUE_DQ && reg.length) {
res.push([ATTR_VALUE,reg]);
reg = '';
} else if (state === ATTR_VALUE_SQ && reg.length) {
res.push([ATTR_VALUE,reg]);
reg = '';
} else if (state === ATTR_KEY) {
res.push([ATTR_KEY,reg]);
reg = '';
}
return res
}
}
function strfn (x) {
if (typeof x === 'function') return x
else if (typeof x === 'string') return x
else if (x && typeof x === 'object') return x
else if (x === null || x === undefined) return x
else return concat('', x)
}
};
function quot (state) {
return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ
}
var closeRE = RegExp('^(' + [
'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed',
'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param',
'source', 'track', 'wbr', '!--',
// SVG TAGS
'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse',
'feBlend', 'feColorMatrix', 'feComposite',
'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR',
'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology',
'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri',
'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath',
'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view',
'vkern'
].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$');
function selfClosing (tag) { return closeRE.test(tag) }
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof commonjsGlobal !== "undefined") {
win = commonjsGlobal;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
var window_1 = win;
/* global MutationObserver */
var watch = Object.create(null);
var KEY_ID = 'onloadid' + (new Date() % 9e6).toString(36);
var KEY_ATTR = 'data-' + KEY_ID;
var INDEX = 0;
if (window_1 && window_1.MutationObserver) {
var observer = new MutationObserver(function (mutations) {
if (Object.keys(watch).length < 1) return
for (var i = 0; i < mutations.length; i++) {
if (mutations[i].attributeName === KEY_ATTR) {
eachAttr(mutations[i], turnon, turnoff);
continue
}
eachMutation(mutations[i].removedNodes, turnoff);
eachMutation(mutations[i].addedNodes, turnon);
}
});
if (document_1.body) {
beginObserve(observer);
} else {
document_1.addEventListener('DOMContentLoaded', function (event) {
beginObserve(observer);
});
}
}
function beginObserve (observer) {
observer.observe(document_1.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: true,
attributeFilter: [KEY_ATTR]
});
}
var onLoad = function onload (el, on, off, caller) {
assert(document_1.body, 'on-load: will not work prior to DOMContentLoaded');
on = on || function () {};
off = off || function () {};
el.setAttribute(KEY_ATTR, 'o' + INDEX);
watch['o' + INDEX] = [on, off, 0, caller || onload.caller];
INDEX += 1;
return el
};
var KEY_ATTR_1 = KEY_ATTR;
var KEY_ID_1 = KEY_ID;
function turnon (index, el) {
if (watch[index][0] && watch[index][2] === 0) {
watch[index][0](el);
watch[index][2] = 1;
}
}
function turnoff (index, el) {
if (watch[index][1] && watch[index][2] === 1) {
watch[index][1](el);
watch[index][2] = 0;
}
}
function eachAttr (mutation, on, off) {
var newValue = mutation.target.getAttribute(KEY_ATTR);
if (sameOrigin(mutation.oldValue, newValue)) {
watch[newValue] = watch[mutation.oldValue];
return
}
if (watch[mutation.oldValue]) {
off(mutation.oldValue, mutation.target);
}
if (watch[newValue]) {
on(newValue, mutation.target);
}
}
function sameOrigin (oldValue, newValue) {
if (!oldValue || !newValue) return false
return watch[oldValue][3] === watch[newValue][3]
}
function eachMutation (nodes, fn) {
var keys = Object.keys(watch);
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute(KEY_ATTR)) {
var onloadid = nodes[i].getAttribute(KEY_ATTR);
keys.forEach(function (k) {
if (onloadid === k) {
fn(k, nodes[i]);
}
});
}
if (nodes[i].childNodes.length > 0) {
eachMutation(nodes[i].childNodes, fn);
}
}
}
onLoad.KEY_ATTR = KEY_ATTR_1;
onLoad.KEY_ID = KEY_ID_1;
var server = createCommonjsModule(function (module) {
if (isElectron()) {
module.exports = onLoad; // explicite relative import to avoid browser field
} else {
module.exports = function () {};
}
function isElectron () {
return window_1 && window_1.process && window_1.process.type === 'renderer'
}
});
var bel = createCommonjsModule(function (module) {
var SVGNS = 'http://www.w3.org/2000/svg';
var XLINKNS = 'http://www.w3.org/1999/xlink';
var BOOL_PROPS = {
autofocus: 1,
checked: 1,
defaultchecked: 1,
disabled: 1,
formnovalidate: 1,
indeterminate: 1,
readonly: 1,
required: 1,
selected: 1,
willvalidate: 1
};
var COMMENT_TAG = '!--';
var SVG_TAGS = [
'svg',
'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor',
'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile',
'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix',
'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting',
'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB',
'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode',
'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting',
'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'font', 'font-face',
'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri',
'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image', 'line',
'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph', 'mpath',
'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect',
'set', 'stop', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref',
'tspan', 'use', 'view', 'vkern'
];
function belCreateElement (tag, props, children) {
var el;
// If an svg tag, it needs a namespace
if (SVG_TAGS.indexOf(tag) !== -1) {
props.namespace = SVGNS;
}
// If we are using a namespace
var ns = false;
if (props.namespace) {
ns = props.namespace;
delete props.namespace;
}
// Create the element
if (ns) {
el = document_1.createElementNS(ns, tag);
} else if (tag === COMMENT_TAG) {
return document_1.createComment(props.comment)
} else {
el = document_1.createElement(tag);
}
// If adding onload events
if (props.onload || props.onunload) {
var load = props.onload || function () {};
var unload = props.onunload || function () {};
server(el, function belOnload () {
load(el);
}, function belOnunload () {
unload(el);
},
// We have to use non-standard `caller` to find who invokes `belCreateElement`
belCreateElement.caller.caller.caller);
delete props.onload;
delete props.onunload;
}
// Create the properties
for (var p in props) {
if (props.hasOwnProperty(p)) {
var key = p.toLowerCase();
var val = props[p];
// Normalize className
if (key === 'classname') {
key = 'class';
p = 'class';
}
// The for attribute gets transformed to htmlFor, but we just set as for
if (p === 'htmlFor') {
p = 'for';
}
// If a property is boolean, set itself to the key
if (BOOL_PROPS[key]) {
if (val === 'true') val = key;
else if (val === 'false') continue
}
// If a property prefers being set directly vs setAttribute
if (key.slice(0, 2) === 'on') {
el[p] = val;
} else {
if (ns) {
if (p === 'xlink:href') {
el.setAttributeNS(XLINKNS, p, val);
} else if (/^xmlns($|:)/i.test(p)) ; else {
el.setAttributeNS(null, p, val);
}
} else {
el.setAttribute(p, val);
}
}
}
}
function appendChild (childs) {
if (!Array.isArray(childs)) return
for (var i = 0; i < childs.length; i++) {
var node = childs[i];
if (Array.isArray(node)) {
appendChild(node);
continue
}
if (typeof node === 'number' ||
typeof node === 'boolean' ||
typeof node === 'function' ||
node instanceof Date ||
node instanceof RegExp) {
node = node.toString();
}
if (typeof node === 'string') {
if (el.lastChild && el.lastChild.nodeName === '#text') {
el.lastChild.nodeValue += node;
continue
}
node = document_1.createTextNode(node);
}
if (node && node.nodeType) {
el.appendChild(node);
}
}
}
appendChild(children);
return el
}
module.exports = hyperx(belCreateElement, {comments: true});
module.exports.default = module.exports;
module.exports.createElement = belCreateElement;
});
var bel_1 = bel.createElement;
function morphAttrs(fromNode, toNode) {
var attrs = toNode.attributes;
var i;
var attr;
var attrName;
var attrNamespaceURI;
var attrValue;
var fromValue;
// update attributes on original DOM element
for (i = attrs.length - 1; i >= 0; --i) {
attr = attrs[i];
attrName = attr.name;
attrNamespaceURI = attr.namespaceURI;
attrValue = attr.value;
if (attrNamespaceURI) {
attrName = attr.localName || attrName;
fromValue = fromNode.getAttributeNS(attrNamespaceURI, attrName);
if (fromValue !== attrValue) {
fromNode.setAttributeNS(attrNamespaceURI, attrName, attrValue);
}
} else {
fromValue = fromNode.getAttribute(attrName);
if (fromValue !== attrValue) {
fromNode.setAttribute(attrName, attrValue);
}
}
}
// Remove any extra attributes found on the original DOM element that
// weren't found on the target element.
attrs = fromNode.attributes;
for (i = attrs.length - 1; i >= 0; --i) {
attr = attrs[i];
if (attr.specified !== false) {
attrName = attr.name;
attrNamespaceURI = attr.namespaceURI;
if (attrNamespaceURI) {
attrName = attr.localName || attrName;
if (!toNode.hasAttributeNS(attrNamespaceURI, attrName)) {
fromNode.removeAttributeNS(attrNamespaceURI, attrName);
}
} else {
if (!toNode.hasAttribute(attrName)) {
fromNode.removeAttribute(attrName);
}
}
}
}
}
var range; // Create a range object for efficently rendering strings to elements.
var NS_XHTML = 'http://www.w3.org/1999/xhtml';
var doc = typeof document === 'undefined' ? undefined : document;
/**
* This is about the same
* var html = new DOMParser().parseFromString(str, 'text/html');
* return html.body.firstChild;
*
* @method toElement
* @param {String} str
*/
function toElement(str) {
if (!range && doc.createRange) {
range = doc.createRange();
range.selectNode(doc.body);
}
var fragment;
if (range && range.createContextualFragment) {
fragment = range.createContextualFragment(str);
} else {
fragment = doc.createElement('body');
fragment.innerHTML = str;
}
return fragment.childNodes[0];
}
/**
* Returns true if two node's names are the same.
*
* NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same
* nodeName and different namespace URIs.
*
* @param {Element} a
* @param {Element} b The target element
* @return {boolean}
*/
function compareNodeNames(fromEl, toEl) {
var fromNodeName = fromEl.nodeName;
var toNodeName = toEl.nodeName;
if (fromNodeName === toNodeName) {
return true;
}
if (toEl.actualize &&
fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */
toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) {
// If the target element is a virtual DOM node then we may need to normalize the tag name
// before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml"
// are converted to upper case
return fromNodeName === toNodeName.toUpperCase();
} else {
return false;
}
}
/**
* Create an element, optionally with a known namespace URI.
*
* @param {string} name the element name, e.g. 'div' or 'svg'
* @param {string} [namespaceURI] the element's namespace URI, i.e. the value of
* its `xmlns` attribute or its inferred namespace.
*
* @return {Element}
*/
function createElementNS(name, namespaceURI) {
return !namespaceURI || namespaceURI === NS_XHTML ?
doc.createElement(name) :
doc.createElementNS(namespaceURI, name);
}
/**
* Copies the children of one DOM element to another DOM element
*/
function moveChildren(fromEl, toEl) {
var curChild = fromEl.firstChild;
while (curChild) {
var nextChild = curChild.nextSibling;
toEl.appendChild(curChild);
curChild = nextChild;
}
return toEl;
}
function syncBooleanAttrProp(fromEl, toEl, name) {
if (fromEl[name] !== toEl[name]) {
fromEl[name] = toEl[name];
if (fromEl[name]) {
fromEl.setAttribute(name, '');
} else {
fromEl.removeAttribute(name);
}
}
}
var specialElHandlers = {
OPTION: function(fromEl, toEl) {
var parentNode = fromEl.parentNode;
if (parentNode) {
var parentName = parentNode.nodeName.toUpperCase();
if (parentName === 'OPTGROUP') {
parentNode = parentNode.parentNode;
parentName = parentNode && parentNode.nodeName.toUpperCase();
}
if (parentName === 'SELECT' && !parentNode.hasAttribute('multiple')) {
if (fromEl.hasAttribute('selected') && !toEl.selected) {
// Workaround for MS Edge bug where the 'selected' attribute can only be
// removed if set to a non-empty value:
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12087679/
fromEl.setAttribute('selected', 'selected');
fromEl.removeAttribute('selected');
}
// We have to reset select element's selectedIndex to -1, otherwise setting
// fromEl.selected using the syncBooleanAttrProp below has no effect.
// The correct selectedIndex will be set in the SELECT special handler below.
parentNode.selectedIndex = -1;
}
}
syncBooleanAttrProp(fromEl, toEl, 'selected');
},
/**
* The "value" attribute is special for the <input> element since it sets
* the initial value. Changing the "value" attribute without changing the
* "value" property will have no effect since it is only used to the set the
* initial value. Similar for the "checked" attribute, and "disabled".
*/
INPUT: function(fromEl, toEl) {
syncBooleanAttrProp(fromEl, toEl, 'checked');
syncBooleanAttrProp(fromEl, toEl, 'disabled');
if (fromEl.value !== toEl.value) {
fromEl.value = toEl.value;
}
if (!toEl.hasAttribute('value')) {
fromEl.removeAttribute('value');
}
},
TEXTAREA: function(fromEl, toEl) {
var newValue = toEl.value;
if (fromEl.value !== newValue) {
fromEl.value = newValue;
}
var firstChild = fromEl.firstChild;
if (firstChild) {
// Needed for IE. Apparently IE sets the placeholder as the
// node value and vise versa. This ignores an empty update.
var oldValue = firstChild.nodeValue;
if (oldValue == newValue || (!newValue && oldValue == fromEl.placeholder)) {
return;
}
firstChild.nodeValue = newValue;
}
},
SELECT: function(fromEl, toEl) {
if (!toEl.hasAttribute('multiple')) {
var selectedIndex = -1;
var i = 0;
// We have to loop through children of fromEl, not toEl since nodes can be moved
// from toEl to fromEl directly when morphing.
// At the time this special handler is invoked, all children have already been morphed
// and appended to / removed from fromEl, so using fromEl here is safe and correct.
var curChild = fromEl.firstChild;
var optgroup;
var nodeName;
while(curChild) {
nodeName = curChild.nodeName && curChild.nodeName.toUpperCase();
if (nodeName === 'OPTGROUP') {
optgroup = curChild;
curChild = optgroup.firstChild;
} else {
if (nodeName === 'OPTION') {
if (curChild.hasAttribute('selected')) {
selectedIndex = i;
break;
}
i++;
}
curChild = curChild.nextSibling;
if (!curChild && optgroup) {
curChild = optgroup.nextSibling;
optgroup = null;
}
}
}
fromEl.selectedIndex = selectedIndex;
}
}
};
var ELEMENT_NODE = 1;
var DOCUMENT_FRAGMENT_NODE = 11;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
function noop() {}
function defaultGetNodeKey(node) {
return node.id;
}
function morphdomFactory(morphAttrs) {
return function morphdom(fromNode, toNode, options) {
if (!options) {
options = {};
}
if (typeof toNode === 'string') {
if (fromNode.nodeName === '#document' || fromNode.nodeName === 'HTML') {
var toNodeHtml = toNode;
toNode = doc.createElement('html');
toNode.innerHTML = toNodeHtml;
} else {
toNode = toElement(toNode);
}
}
var getNodeKey = options.getNodeKey || defaultGetNodeKey;
var onBeforeNodeAdded = options.onBeforeNodeAdded || noop;
var onNodeAdded = options.onNodeAdded || noop;
var onBeforeElUpdated = options.onBeforeElUpdated || noop;
var onElUpdated = options.onElUpdated || noop;
var onBeforeNodeDiscarded = options.onBeforeNodeDiscarded || noop;
var onNodeDiscarded = options.onNodeDiscarded || noop;
var onBeforeElChildrenUpdated = options.onBeforeElChildrenUpdated || noop;
var childrenOnly = options.childrenOnly === true;
// This object is used as a lookup to quickly find all keyed elements in the original DOM tree.
var fromNodesLookup = {};
var keyedRemovalList;
function addKeyedRemoval(key) {
if (keyedRemovalList) {
keyedRemovalList.push(key);
} else {
keyedRemovalList = [key];
}
}
function walkDiscardedChildNodes(node, skipKeyedNodes) {
if (node.nodeType === ELEMENT_NODE) {
var curChild = node.firstChild;
while (curChild) {
var key = undefined;
if (skipKeyedNodes && (key = getNodeKey(curChild))) {
// If we are skipping keyed nodes then we add the key
// to a list so that it can be handled at the very end.
addKeyedRemoval(key);
} else {
// Only report the node as discarded if it is not keyed. We do this because
// at the end we loop through all keyed elements that were unmatched
// and then discard them in one final pass.
onNodeDiscarded(curChild);
if (curChild.firstChild) {
walkDiscardedChildNodes(curChild, skipKeyedNodes);
}
}
curChild = curChild.nextSibling;
}
}
}
/**
* Removes a DOM node out of the original DOM
*
* @param {Node} node The node to remove
* @param {Node} parentNode The nodes parent
* @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded.
* @return {undefined}
*/
function removeNode(node, parentNode, skipKeyedNodes) {
if (onBeforeNodeDiscarded(node) === false) {
return;
}
if (parentNode) {
parentNode.removeChild(node);
}
onNodeDiscarded(node);
walkDiscardedChildNodes(node, skipKeyedNodes);
}
// // TreeWalker implementation is no faster, but keeping this around in case this changes in the future
// function indexTree(root) {
// var treeWalker = document.createTreeWalker(
// root,
// NodeFilter.SHOW_ELEMENT);
//
// var el;
// while((el = treeWalker.nextNode())) {
// var key = getNodeKey(el);
// if (key) {
// fromNodesLookup[key] = el;
// }
// }
// }
// // NodeIterator implementation is no faster, but keeping this around in case this changes in the future
//
// function indexTree(node) {
// var nodeIterator = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT);
// var el;
// while((el = nodeIterator.nextNode())) {
// var key = getNodeKey(el);
// if (key) {
// fromNodesLookup[key] = el;
// }
// }
// }
function indexTree(node) {
if (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE) {
var curChild = node.firstChild;
while (curChild) {
var key = getNodeKey(curChild);
if (key) {
fromNodesLookup[key] = curChild;
}
// Walk recursively
indexTree(curChild);
curChild = curChild.nextSibling;
}
}
}
indexTree(fromNode);
function handleNodeAdded(el) {
onNodeAdded(el);
var curChild = el.firstChild;
while (curChild) {
var nextSibling = curChild.nextSibling;
var key = getNodeKey(curChild);
if (key) {
var unmatchedFromEl = fromNodesLookup[key];
if (unmatchedFromEl && compareNodeNames(curChild, unmatchedFromEl)) {
curChild.parentNode.replaceChild(unmatchedFromEl, curChild);
morphEl(unmatchedFromEl, curChild);
}
}
handleNodeAdded(curChild);
curChild = nextSibling;
}
}
function cleanupFromEl(fromEl, curFromNodeChild, curFromNodeKey) {
// We have processed all of the "to nodes". If curFromNodeChild is
// non-null then we still have some from nodes left over that need
// to be removed
while (curFromNodeChild) {
var fromNextSibling = curFromNodeChild.nextSibling;
if ((curFromNodeKey = getNodeKey(curFromNodeChild))) {
// Since the node is keyed it might be matched up later so we defer
// the actual removal to later
addKeyedRemoval(curFromNodeKey);
} else {
// NOTE: we skip nested keyed nodes from being removed since there is
// still a chance they will be matched up later
removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */);
}
curFromNodeChild = fromNextSibling;
}
}
function morphEl(fromEl, toEl, childrenOnly) {
var toElKey = getNodeKey(toEl);
if (toElKey) {
// If an element with an ID is being morphed then it will be in the final
// DOM so clear it out of the saved elements collection
delete fromNodesLookup[toElKey];
}
if (toNode.isSameNode && toNode.isSameNode(fromNode)) {
return;
}
if (!childrenOnly) {
// optional
if (onBeforeElUpdated(fromEl, toEl) === false) {
return;
}
// update attributes on original DOM element first
morphAttrs(fromEl, toEl);
// optional
onElUpdated(fromEl);
if (onBeforeElChildrenUpdated(fromEl, toEl) === false) {
return;
}
}
if (fromEl.nodeName !== 'TEXTAREA') {
morphChildren(fromEl, toEl);
} else {
specialElHandlers.TEXTAREA(fromEl, toEl);
}
}
function morphChildren(fromEl, toEl) {
var curToNodeChild = toEl.firstChild;
var curFromNodeChild = fromEl.firstChild;
var curToNodeKey;
var curFromNodeKey;
var fromNextSibling;
var toNextSibling;
var matchingFromEl;
// walk the children
outer: while (curToNodeChild) {
toNextSibling = curToNodeChild.nextSibling;
curToNodeKey = getNodeKey(curToNodeChild);
// walk the fromNode children all the way through
while (curFromNodeChild) {
fromNextSibling = curFromNodeChild.nextSibling;
if (curToNodeChild.isSameNode && curToNodeChild.isSameNode(curFromNodeChild)) {
curToNodeChild = toNextSibling;
curFromNodeChild = fromNextSibling;
continue outer;
}
curFromNodeKey = getNodeKey(curFromNodeChild);
var curFromNodeType = curFromNodeChild.nodeType;
// this means if the curFromNodeChild doesnt have a match with the curToNodeChild
var isCompatible = undefined;
if (curFromNodeType === curToNodeChild.nodeType) {
if (curFromNodeType === ELEMENT_NODE) {
// Both nodes being compared are Element nodes
if (curToNodeKey) {
// The target node has a key so we want to match it up with the correct element
// in the original DOM tree
if (curToNodeKey !== curFromNodeKey) {
// The current element in the original DOM tree does not have a matching key so
// let's check our lookup to see if there is a matching element in the original
// DOM tree
if ((matchingFromEl = fromNodesLookup[curToNodeKey])) {
if (fromNextSibling === matchingFromEl) {
// Special case for single element removals. To avoid removing the original
// DOM node out of the tree (since that can break CSS transitions, etc.),
// we will instead discard the current node and wait until the next
// iteration to properly match up the keyed target element with its matching
// element in the original tree
isCompatible = false;
} else {
// We found a matching keyed element somewhere in the original DOM tree.
// Let's move the original DOM node into the current position and morph
// it.
// NOTE: We use insertBefore instead of replaceChild because we want to go through
// the `removeNode()` function for the node that is being discarded so that
// all lifecycle hooks are correctly invoked
fromEl.insertBefore(matchingFromEl, curFromNodeChild);
// fromNextSibling = curFromNodeChild.nextSibling;
if (curFromNodeKey) {
// Since the node is keyed it might be matched up later so we defer
// the actual removal to later
addKeyedRemoval(curFromNodeKey);
} else {
// NOTE: we skip nested keyed nodes from being removed since there is
// still a chance they will be matched up later
removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */);
}
curFromNodeChild = matchingFromEl;
}
} else {
// The nodes are not compatible since the "to" node has a key and there
// is no matching keyed node in the source tree
isCompatible = false;
}
}
} else if (curFromNodeKey) {
// The original has a key
isCompatible = false;
}
isCompatible = isCompatible !== false && compareNodeNames(curFromNodeChild, curToNodeChild);
if (isCompatible) {
// We found compatible DOM elements so transform
// the current "from" node to match the current
// target DOM node.
// MORPH
morphEl(curFromNodeChild, curToNodeChild);
}
} else if (curFromNodeType === TEXT_NODE || curFromNodeType == COMMENT_NODE) {
// Both nodes being compared are Text or Comment nodes
isCompatible = true;
// Simply update nodeValue on the original node to
// change the text value
if (curFromNodeChild.nodeValue !== curToNodeChild.nodeValue) {
curFromNodeChild.nodeValue = curToNodeChild.nodeValue;
}
}
}
if (isCompatible) {
// Advance both the "to" child and the "from" child since we found a match
// Nothing else to do as we already recursively called morphChildren above
curToNodeChild = toNextSibling;
curFromNodeChild = fromNextSibling;
continue outer;
}
// No compatible match so remove the old node from the DOM and continue trying to find a
// match in the original DOM. However, we only do this if the from node is not keyed
// since it is possible that a keyed node might match up with a node somewhere else in the
// target tree and we don't want to discard it just yet since it still might find a
// home in the final DOM tree. After everything is done we will remove any keyed nodes
// that didn't find a home
if (curFromNodeKey) {
// Since the node is keyed it might be matched up later so we defer
// the actual removal to later
addKeyedRemoval(curFromNodeKey);
} else {
// NOTE: we skip nested keyed nodes from being removed since there is
// still a chance they will be matched up later
removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */);
}
curFromNodeChild = fromNextSibling;
} // END: while(curFromNodeChild) {}
// If we got this far then we did not find a candidate match for
// our "to node" and we exhausted all of the children "from"
// nodes. Therefore, we will just append the current "to" node
// to the end
if (curToNodeKey && (matchingFromEl = fromNodesLookup[curToNodeKey]) && compareNodeNames(matchingFromEl, curToNodeChild)) {
fromEl.appendChild(matchingFromEl);
// MORPH
morphEl(matchingFromEl, curToNodeChild);
} else {
var onBeforeNodeAddedResult = onBeforeNodeAdded(curToNodeChild);
if (onBeforeNodeAddedResult !== false) {
if (onBeforeNodeAddedResult) {
curToNodeChild = onBeforeNodeAddedResult;
}
if (curToNodeChild.actualize) {
curToNodeChild = curToNodeChild.actualize(fromEl.ownerDocument || doc);
}
fromEl.appendChild(curToNodeChild);
handleNodeAdded(curToNodeChild);
}
}
curToNodeChild = toNextSibling;
curFromNodeChild = fromNextSibling;
}
cleanupFromEl(fromEl, curFromNodeChild, curFromNodeKey);
var specialElHandler = specialElHandlers[fromEl.nodeName];
if (specialElHandler) {
specialElHandler(fromEl, toEl);
}
} // END: morphChildren(...)
var morphedNode = fromNode;
var morphedNodeType = morphedNode.nodeType;
var toNodeType = toNode.nodeType;
if (!childrenOnly) {
// Handle the case where we are given two DOM nodes that are not
// compatible (e.g. <div> --> <span> or <div> --> TEXT)
if (morphedNodeType === ELEMENT_NODE) {
if (toNodeType === ELEMENT_NODE) {
if (!compareNodeNames(fromNode, toNode)) {
onNodeDiscarded(fromNode);
morphedNode = moveChildren(fromNode, createElementNS(toNode.nodeName, toNode.namespaceURI));
}
} else {
// Going from an element node to a text node
morphedNode = toNode;
}
} else if (morphedNodeType === TEXT_NODE || morphedNodeType === COMMENT_NODE) { // Text or comment node
if (toNodeType === morphedNodeType) {
if (morphedNode.nodeValue !== toNode.nodeValue) {
morphedNode.nodeValue = toNode.nodeValue;
}
return morphedNode;
} else {
// Text node to something else
morphedNode = toNode;
}
}
}
if (morphedNode === toNode) {
// The "to node" was not compatible with the "from node" so we had to
// toss out the "from node" and use the "to node"
onNodeDiscarded(fromNode);
} else {
morphEl(morphedNode, toNode, childrenOnly);
// We now need to loop over any keyed nodes that might need to be
// removed. We only do the removal if we know that the keyed node
// never found a match. When a keyed node is matched up we remove
// it out of fromNodesLookup and we use fromNodesLookup to determine
// if a keyed node has been matched up or not
if (keyedRemovalList) {
for (var i=0, len=keyedRemovalList.length; i<len; i++) {
var elToRemove = fromNodesLookup[keyedRemovalList[i]];
if (elToRemove) {
removeNode(elToRemove, elToRemove.parentNode, false);
}
}
}
}
if (!childrenOnly && morphedNode !== fromNode && fromNode.parentNode) {
if (morphedNode.actualize) {
morphedNode = morphedNode.actualize(fromNode.ownerDocument || doc);
}
// If we had to swap out the from node with a new node because the old
// node was not compatible with the target node then we need to
// replace the old DOM node in the original DOM tree. This is only
// possible if the original DOM node was part of a DOM tree which
// we know is the case if it has a parent node.
fromNode.parentNode.replaceChild(morphedNode, fromNode);
}
return morphedNode;
};
}
var morphdom = morphdomFactory(morphAttrs);
var updateEvents = [
// attribute events (can be set with attributes)
'onclick',
'ondblclick',
'onmousedown',
'onmouseup',
'onmouseover',
'onmousemove',
'onmouseout',
'ondragstart',
'ondrag',
'ondragenter',
'ondragleave',
'ondragover',
'ondrop',
'ondragend',
'onkeydown',
'onkeypress',
'onkeyup',
'onunload',
'onabort',
'onerror',
'onresize',
'onscroll',
'onselect',
'onchange',
'onsubmit',
'onreset',
'onfocus',
'onblur',
'oninput',
// other common events
'oncontextmenu',
'onfocusin',
'onfocusout'
];
// turns template tag into DOM elements
// efficiently diffs + morphs two DOM elements
// default events to be copied when dom elements update
var yoYo = bel;
// TODO move this + defaultEvents to a new module once we receive more feedback
var update = function (fromNode, toNode, opts) {
if (!opts) opts = {};
if (opts.events !== false) {
if (!opts.onBeforeElUpdated) opts.onBeforeElUpdated = copier;
}
return morphdom(fromNode, toNode, opts)
// morphdom only copies attributes. we decided we also wanted to copy events
// that can be set via attributes
function copier (f, t) {
// copy events:
var events = opts.events || updateEvents;
for (var i = 0; i < events.length; i++) {
var ev = events[i];
if (t[ev]) { // if new element has a whitelisted attribute
f[ev] = t[ev]; // update existing element
} else if (f[ev]) { // if existing element has it and new one doesnt
f[ev] = undefined; // remove it from existing element
}
}
var oldValue = f.value;
var newValue = t.value;
// copy values for form elements
if ((f.nodeName === 'INPUT' && f.type !== 'file') || f.nodeName === 'SELECT') {
if (!newValue && !t.hasAttribute('value')) {
t.value = f.value;
} else if (newValue !== oldValue) {
f.value = newValue;
}
} else if (f.nodeName === 'TEXTAREA') {
if (t.getAttribute('value') === null) f.value = t.value;
}
}
};
yoYo.update = update;
var nanoraf_1 = nanoraf;
// Only call RAF when needed
// (fn, fn?) -> fn
function nanoraf (render, raf) {
assert.equal(typeof render, 'function', 'nanoraf: render should be a function');
assert.ok(typeof raf === 'function' || typeof raf === 'undefined', 'nanoraf: raf should be a function or undefined');
raf = raf || window_1.requestAnimationFrame;
var inRenderingTransaction = false;
var redrawScheduled = false;
var currentState = null;
// pass new state to be rendered
// (obj, obj?) -> null
return function frame (state, prev) {
assert.equal(typeof state, 'object', 'nanoraf: state should be an object');
assert.equal(typeof prev, 'object', 'nanoraf: prev should be an object');
assert.equal(inRenderingTransaction, false, 'nanoraf: new frame was created before previous frame finished');
// request a redraw for next frame
if (currentState === null && !redrawScheduled) {
redrawScheduled = true;
raf(function redraw () {
redrawScheduled = false;
if (!currentState) return
inRenderingTransaction = true;
render(currentState, prev);
inRenderingTransaction = false;
currentState = null;
});
}
// update data for redraw
currentState = state;
}
}
var containers = []; // will store container HTMLElement references
var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement}
function insertCss(css, options) {
options = options || {};
var position = options.prepend === true ? 'prepend' : 'append';
var container = options.container !== undefined ? options.container : document.querySelector('head');
var containerId = containers.indexOf(container);
// first time we see this container, create the necessary entries
if (containerId === -1) {
containerId = containers.push(container) - 1;
styleElements[containerId] = {};
}
// try to get the correponding container + position styleElement, create it otherwise
var styleElement;
if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) {
styleElement = styleElements[containerId][position];
} else {
styleElement = styleElements[containerId][position] = createStyleElement();
if (position === 'prepend') {
container.insertBefore(styleElement, container.childNodes[0]);
} else {
container.appendChild(styleElement);
}
}
// strip potential UTF-8 BOM if css was read from a file
if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); }
// actually add the stylesheet
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText += css;
} else {
styleElement.textContent += css;
}
return styleElement;
}
function createStyleElement() {
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
return styleElement;
}
var insertCss_1 = insertCss;
var insertCss_2 = insertCss;
insertCss_1.insertCss = insertCss_2;
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return root.Date.now();
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var lodash_debounce = debounce;
function _templateObject5() {
var data = _taggedTemplateLiteral(["<div style='position:relative;", "'>", "</div>"]);
_templateObject5 = function _templateObject5() {
return data;
};
return data;
}
function _templateObject4() {
var data = _taggedTemplateLiteral(["<div class=\"dom-minimap-scroll dom-minimap-scroll-bottom\" style=\"top:", "\"></div>"]);
_templateObject4 = function _templateObject4() {
return data;
};
return data;
}
function _templateObject3() {
var data = _taggedTemplateLiteral(["<div class=\"dom-minimap-scroll dom-minimap-scroll-top\" style=\"bottom:", "\"></div>"]);
_templateObject3 = function _templateObject3() {
return data;
};
return data;
}
function _templateObject2() {
var data = _taggedTemplateLiteral(["\n <div class=\"dom-minimap-section unselectable\"\n title=", " onclick=", "\n style=\"top:", ";bottom:", ";", "\">\n ", "\n </div>\n "]);
_templateObject2 = function _templateObject2() {
return data;
};
return data;
}
function _templateObject() {
var data = _taggedTemplateLiteral(["<div style=\"margin-top:20px;text-align:center\">loading</div>"]);
_templateObject = function _templateObject() {
return data;
};
return data;
}
insertCss_1("\n .dom-minimap-section {\n position: absolute;\n background-color: lightgrey;\n overflow: hidden;\n color: grey;\n font-size: 11px;\n padding-left: 2px;\n border-radius: 2px;\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -khtml-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n cursor: pointer;\n left: 5px; right: 5px;\n }\n\n .dom-minimap-section:hover {\n background-color: #e6e6e6;\n }\n\n .dom-minimap-scroll {\n pointer-events: none;\n position: absolute;\n background-color: rgba(0,0,0,0.15);\n top: 0; left: 0; right: 0; bottom: 0;\n }\n");
var domMinimap = minimap;
function minimap(opts) {
opts = opts || {};
opts.sections = opts.sections || 'minimap-section';
if (typeof opts.sections !== 'function') {
var sectionName = opts.sections;
opts.sections = function (container) {
return Array.prototype.slice.call(container.getElementsByClassName(sectionName));
};
}
opts.title = opts.title || 'data-section-title';
if (typeof opts.title !== 'function') {
var titleName = opts.title;
opts.title = function (section) {
return section.getAttribute(titleName);
};
}
opts.tooltip = opts.tooltip || 'data-section-tooltip';
if (typeof opts.hover !== 'function') {
var tooltipName = opts.tooltip;
opts.tooltip = function (section) {
return section.getAttribute(tooltipName);
};
}
opts.content = opts.content || 'minimap-content';
opts.mapStyle = typeof opts.mapStyle !== 'undefined' ? opts.mapStyle : 'height: 100%;';
opts.sectionStyle = opts.sectionStyle || '';
opts.clickOffset = opts.clickOffset || 0;
var lastContainerHeight;
var container;
var element = document.createElement('div');
element.style.flex = '1';
var render = nanoraf_1(renderMap);
var state = {
opts: opts
};
server(element, function load() {
container = typeof opts.content === 'string' ? document.getElementById(opts.content) : opts.content;
lastContainerHeight = container.scrollHeight; // update on scroll event
container.addEventListener('scroll', scrollUpdate); // update on window resize event
window.addEventListener('resize', lodash_debounce(update), 100); // update on element loaded
update();
}, null, minimap);
element.addEventListener('wheel', function (event) {
if (container) container.scrollTop = container.scrollTop + event.deltaY;
});
function scrollUpdate() {
state.scroll = getScroll(container);
var top = element.querySelector('.dom-minimap-scroll-top');
var bottom = element.querySelector('.dom-minimap-scroll-bottom');
if (!top || !bottom) return;
top.style.bottom = state.scroll.topFromBottom;
bottom.style.top = state.scroll.bottomFromTop;
}
function update() {
var sections = getSections(container, element, opts);
if (!sections) return;
var newState = Object.assign({}, state, {
sections: sections,
scroll: getScroll(container)
});
render(newState, state);
state = newState;
}
return function () {
if (container) {
setTimeout(function () {
if (lastContainerHeight !== container.scrollHeight) {
update();
}
}, 1);
}
return element;
};
function scrollTo() {
var top = this.style.top.slice(0, -1);
if (top) container.scrollTop = Math.round(container.scrollHeight * top / 100) + opts.clickOffset;
}
function renderMap(state) {
var content = yoYo(_templateObject());
if (state.sections) {
content = state.sections.map(function (section) {
return yoYo(_templateObject2(), section.tooltip, scrollTo, section.top, section.bottom, typeof opts.sectionStyle === 'function' ? opts.sectionStyle(section) : opts.sectionStyle, section.title);
}).concat([yoYo(_templateObject3(), state.scroll.topFromBottom), yoYo(_templateObject4(), state.scroll.bottomFromTop)]);
}
yoYo.update(element, yoYo(_templateObject5(), opts.mapStyle, content));
}
}
function getScroll(container) {
var top = container.scrollTop;
var cHeight = container.clientHeight;
var height = container.scrollHeight;
return {
topFromBottom: (height - top) / height * 100 + '%',
bottomFromTop: (1 - (height - top - cHeight) / height) * 100 + '%'
};
}
function getSections(content, map, opts) {
if (!map.parentElement) return false;
var cHeight = content.scrollHeight;
var mHeight = map.parentElement.clientHeight;
var cBounds = content.getBoundingClientRect();
var scrollTop = content.scrollTop;
return opts.sections(content).map(function (section) {
var bounds = section.getBoundingClientRect();
var top = (bounds.top - cBounds.top + scrollTop) / cHeight;
var bottom = (bounds.bottom - cBounds.top + scrollTop) / cHeight;
return {
top: top * 100 + '%',
bottom: applyPadding((1 - bottom) * 100 + '%', opts.paddingBottom),
title: opts.title(section, mHeight * bottom - mHeight * top),
tooltip: opts.tooltip(section),
element: section
};
});
}
function applyPadding(value, padding) {
if (!padding) return value;
return "calc(".concat(value, " + ").concat(padding, ")");
}
return domMinimap;
}));