code
stringlengths
2
1.05M
/** * HTML tokenizer by Marijn Haverbeke * http://codemirror.net/ * @constructor * @memberOf __xmlParseDefine * @param {Function} require * @param {Underscore} _ */ emmet.define('xmlParser', function(require, _) { var Kludges = { autoSelfClosers : {}, implicitlyClosed : {}, contextGrabbers : {}, doNotIndent : {}, allowUnquoted : true, allowMissing : true }; // Return variables for tokenizers var tagName = null, type = null; function inText(stream, state) { function chain(parser) { state.tokenize = parser; return parser(stream, state); } var ch = stream.next(); if (ch == "<") { if (stream.eat("!")) { if (stream.eat("[")) { if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); else return null; } else if (stream.match("--")) return chain(inBlock("comment", "-->")); else if (stream.match("DOCTYPE", true, true)) { stream.eatWhile(/[\w\._\-]/); return chain(doctype(1)); } else return null; } else if (stream.eat("?")) { stream.eatWhile(/[\w\._\-]/); state.tokenize = inBlock("meta", "?>"); return "meta"; } else { type = stream.eat("/") ? "closeTag" : "openTag"; stream.eatSpace(); tagName = ""; var c; while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; state.tokenize = inTag; return "tag"; } } else if (ch == "&") { var ok; if (stream.eat("#")) { if (stream.eat("x")) { ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); } else { ok = stream.eatWhile(/[\d]/) && stream.eat(";"); } } else { ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); } return ok ? "atom" : "error"; } else { stream.eatWhile(/[^&<]/); return "text"; } } function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; return "tag"; } else if (ch == "=") { type = "equals"; return null; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); return state.tokenize(stream, state); } else { stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/); return "word"; } } function inAttribute(quote) { return function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; }; } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) !== null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } var curState = null, setStyle; function pass() { for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function pushContext(tagName, startOfLine) { var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); curState.context = { prev : curState.context, tagName : tagName, indent : curState.indented, startOfLine : startOfLine, noIndent : noIndent }; } function popContext() { if (curState.context) curState.context = curState.context.prev; } function element(type) { if (type == "openTag") { curState.tagName = tagName; return cont(attributes, endtag(curState.startOfLine)); } else if (type == "closeTag") { var err = false; if (curState.context) { if (curState.context.tagName != tagName) { if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { popContext(); } err = !curState.context || curState.context.tagName != tagName; } } else { err = true; } if (err) setStyle = "error"; return cont(endclosetag(err)); } return cont(); } function endtag(startOfLine) { return function(type) { if (type == "selfcloseTag" || (type == "endTag" && Kludges.autoSelfClosers .hasOwnProperty(curState.tagName .toLowerCase()))) { maybePopContext(curState.tagName.toLowerCase()); return cont(); } if (type == "endTag") { maybePopContext(curState.tagName.toLowerCase()); pushContext(curState.tagName, startOfLine); return cont(); } return cont(); }; } function endclosetag(err) { return function(type) { if (err) setStyle = "error"; if (type == "endTag") { popContext(); return cont(); } setStyle = "error"; return cont(arguments.callee); }; } function maybePopContext(nextTagName) { var parentTagName; while (true) { if (!curState.context) { return; } parentTagName = curState.context.tagName.toLowerCase(); if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { return; } popContext(); } } function attributes(type) { if (type == "word") { setStyle = "attribute"; return cont(attribute, attributes); } if (type == "endTag" || type == "selfcloseTag") return pass(); setStyle = "error"; return cont(attributes); } function attribute(type) { if (type == "equals") return cont(attvalue, attributes); if (!Kludges.allowMissing) setStyle = "error"; return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); } function attvalue(type) { if (type == "string") return cont(attvaluemaybe); if (type == "word" && Kludges.allowUnquoted) { setStyle = "string"; return cont(); } setStyle = "error"; return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); } function attvaluemaybe(type) { if (type == "string") return cont(attvaluemaybe); else return pass(); } function startState() { return { tokenize : inText, cc : [], indented : 0, startOfLine : true, tagName : null, context : null }; } function token(stream, state) { if (stream.sol()) { state.startOfLine = true; state.indented = 0; } if (stream.eatSpace()) return null; setStyle = type = tagName = null; var style = state.tokenize(stream, state); state.type = type; if ((style || type) && style != "comment") { curState = state; while (true) { var comb = state.cc.pop() || element; if (comb(type || style)) break; } } state.startOfLine = false; return setStyle || style; } return { /** * @memberOf emmet.xmlParser * @returns */ parse: function(data, offset) { offset = offset || 0; var state = startState(); var stream = require('stringStream').create(data); var tokens = []; while (!stream.eol()) { tokens.push({ type: token(stream, state), start: stream.start + offset, end: stream.pos + offset }); stream.start = stream.pos; } return tokens; } }; });
/** * @module zrender/tool/color */ var kCSSColorTable = { 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1], 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1], 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1], 'beige': [245,245,220,1], 'bisque': [255,228,196,1], 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1], 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1], 'brown': [165,42,42,1], 'burlywood': [222,184,135,1], 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1], 'chocolate': [210,105,30,1], 'coral': [255,127,80,1], 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1], 'crimson': [220,20,60,1], 'cyan': [0,255,255,1], 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1], 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1], 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1], 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1], 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1], 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1], 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1], 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1], 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1], 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1], 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1], 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1], 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1], 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1], 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1], 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1], 'gray': [128,128,128,1], 'green': [0,128,0,1], 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1], 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1], 'indianred': [205,92,92,1], 'indigo': [75,0,130,1], 'ivory': [255,255,240,1], 'khaki': [240,230,140,1], 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1], 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1], 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1], 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1], 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1], 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1], 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1], 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1], 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1], 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1], 'limegreen': [50,205,50,1], 'linen': [250,240,230,1], 'magenta': [255,0,255,1], 'maroon': [128,0,0,1], 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1], 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1], 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1], 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1], 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1], 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1], 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1], 'navy': [0,0,128,1], 'oldlace': [253,245,230,1], 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1], 'orange': [255,165,0,1], 'orangered': [255,69,0,1], 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1], 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1], 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1], 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1], 'pink': [255,192,203,1], 'plum': [221,160,221,1], 'powderblue': [176,224,230,1], 'purple': [128,0,128,1], 'red': [255,0,0,1], 'rosybrown': [188,143,143,1], 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1], 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1], 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1], 'sienna': [160,82,45,1], 'silver': [192,192,192,1], 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1], 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1], 'snow': [255,250,250,1], 'springgreen': [0,255,127,1], 'steelblue': [70,130,180,1], 'tan': [210,180,140,1], 'teal': [0,128,128,1], 'thistle': [216,191,216,1], 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1], 'violet': [238,130,238,1], 'wheat': [245,222,179,1], 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1], 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1] }; function clampCssByte(i) { // Clamp to integer 0 .. 255. i = Math.round(i); // Seems to be what Chrome does (vs truncation). return i < 0 ? 0 : i > 255 ? 255 : i; } function clampCssAngle(i) { // Clamp to integer 0 .. 360. i = Math.round(i); // Seems to be what Chrome does (vs truncation). return i < 0 ? 0 : i > 360 ? 360 : i; } function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0. return f < 0 ? 0 : f > 1 ? 1 : f; } function parseCssInt(str) { // int or percentage. if (str.length && str.charAt(str.length - 1) === '%') { return clampCssByte(parseFloat(str) / 100 * 255); } return clampCssByte(parseInt(str, 10)); } function parseCssFloat(str) { // float or percentage. if (str.length && str.charAt(str.length - 1) === '%') { return clampCssFloat(parseFloat(str) / 100); } return clampCssFloat(parseFloat(str)); } function cssHueToRgb(m1, m2, h) { if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } if (h * 2 < 1) { return m2; } if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } return m1; } function lerp(a, b, p) { return a + (b - a) * p; } /** * @param {string} colorStr * @return {Array.<number>} * @memberOf module:zrender/util/color */ function parse(colorStr) { if (!colorStr) { return; } // colorStr may be not string colorStr = colorStr + ''; // Remove all whitespace, not compliant, but should just be more accepting. var str = colorStr.replace(/ /g, '').toLowerCase(); // Color keywords (and transparent) lookup. if (str in kCSSColorTable) { return kCSSColorTable[str].slice(); // dup. } // #abc and #abc123 syntax. if (str.charAt(0) === '#') { if (str.length === 4) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xfff)) { return; // Covers NaN. } return [ ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), (iv & 0xf0) | ((iv & 0xf0) >> 4), (iv & 0xf) | ((iv & 0xf) << 4), 1 ]; } else if (str.length === 7) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xffffff)) { return; // Covers NaN. } return [ (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, 1 ]; } return; } var op = str.indexOf('('), ep = str.indexOf(')'); if (op !== -1 && ep + 1 === str.length) { var fname = str.substr(0, op); var params = str.substr(op + 1, ep - (op + 1)).split(','); var alpha = 1; // To allow case fallthrough. switch (fname) { case 'rgba': if (params.length !== 4) { return; } alpha = parseCssFloat(params.pop()); // jshint ignore:line // Fall through. case 'rgb': if (params.length !== 3) { return; } return [ parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha ]; case 'hsla': if (params.length !== 4) { return; } params[3] = parseCssFloat(params[3]); return hsla2rgba(params); case 'hsl': if (params.length !== 3) { return; } return hsla2rgba(params); default: return; } } return; } /** * @param {Array.<number>} hsla * @return {Array.<number>} rgba */ function hsla2rgba(hsla) { var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1 // NOTE(deanm): According to the CSS spec s/l should only be // percentages, but we don't bother and let float or percentage. var s = parseCssFloat(hsla[1]); var l = parseCssFloat(hsla[2]); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; var rgba = [ clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255) ]; if (hsla.length === 4) { rgba[3] = hsla[3]; } return rgba; } /** * @param {Array.<number>} rgba * @return {Array.<number>} hsla */ function rgba2hsla(rgba) { if (!rgba) { return; } // RGB from 0 to 255 var R = rgba[0] / 255; var G = rgba[1] / 255; var B = rgba[2] / 255; var vMin = Math.min(R, G, B); // Min. value of RGB var vMax = Math.max(R, G, B); // Max. value of RGB var delta = vMax - vMin; // Delta RGB value var L = (vMax + vMin) / 2; var H; var S; // HSL results from 0 to 1 if (delta === 0) { H = 0; S = 0; } else { if (L < 0.5) { S = delta / (vMax + vMin); } else { S = delta / (2 - vMax - vMin); } var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta; var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta; var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta; if (R === vMax) { H = deltaB - deltaG; } else if (G === vMax) { H = (1 / 3) + deltaR - deltaB; } else if (B === vMax) { H = (2 / 3) + deltaG - deltaR; } if (H < 0) { H += 1; } if (H > 1) { H -= 1; } } var hsla = [H * 360, S, L]; if (rgba[3] != null) { hsla.push(rgba[3]); } return hsla; } /** * @param {string} color * @param {number} level * @return {string} * @memberOf module:zrender/util/color */ function lift(color, level) { var colorArr = parse(color); if (colorArr) { for (var i = 0; i < 3; i++) { if (level < 0) { colorArr[i] = colorArr[i] * (1 - level) | 0; } else { colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0; } } return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb'); } } /** * @param {string} color * @return {string} * @memberOf module:zrender/util/color */ function toHex(color, level) { var colorArr = parse(color); if (colorArr) { return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1); } } /** * Map value to color. Faster than mapToColor methods because color is represented by rgba array * @param {number} normalizedValue A float between 0 and 1. * @param {Array.<Array.<number>>} colors List of rgba color array * @param {Array.<number>} [out] Mapped gba color array * @return {Array.<number>} */ function fastMapToColor(normalizedValue, colors, out) { if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1) ) { return; } out = out || [0, 0, 0, 0]; var value = normalizedValue * (colors.length - 1); var leftIndex = Math.floor(value); var rightIndex = Math.ceil(value); var leftColor = colors[leftIndex]; var rightColor = colors[rightIndex]; var dv = value - leftIndex; out[0] = clampCssByte(lerp(leftColor[0], rightColor[0], dv)); out[1] = clampCssByte(lerp(leftColor[1], rightColor[1], dv)); out[2] = clampCssByte(lerp(leftColor[2], rightColor[2], dv)); out[3] = clampCssByte(lerp(leftColor[3], rightColor[3], dv)); return out; } /** * @param {number} normalizedValue A float between 0 and 1. * @param {Array.<string>} colors Color list. * @param {boolean=} fullOutput Default false. * @return {(string|Object)} Result color. If fullOutput, * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...}, * @memberOf module:zrender/util/color */ function mapToColor(normalizedValue, colors, fullOutput) { if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1) ) { return; } var value = normalizedValue * (colors.length - 1); var leftIndex = Math.floor(value); var rightIndex = Math.ceil(value); var leftColor = parse(colors[leftIndex]); var rightColor = parse(colors[rightIndex]); var dv = value - leftIndex; var color = stringify( [ clampCssByte(lerp(leftColor[0], rightColor[0], dv)), clampCssByte(lerp(leftColor[1], rightColor[1], dv)), clampCssByte(lerp(leftColor[2], rightColor[2], dv)), clampCssFloat(lerp(leftColor[3], rightColor[3], dv)) ], 'rgba' ); return fullOutput ? { color: color, leftIndex: leftIndex, rightIndex: rightIndex, value: value } : color; } /** * @param {string} color * @param {number=} h 0 ~ 360, ignore when null. * @param {number=} s 0 ~ 1, ignore when null. * @param {number=} l 0 ~ 1, ignore when null. * @return {string} Color string in rgba format. * @memberOf module:zrender/util/color */ function modifyHSL(color, h, s, l) { color = parse(color); if (color) { color = rgba2hsla(color); h != null && (color[0] = clampCssAngle(h)); s != null && (color[1] = parseCssFloat(s)); l != null && (color[2] = parseCssFloat(l)); return stringify(hsla2rgba(color), 'rgba'); } } /** * @param {string} color * @param {number=} alpha 0 ~ 1 * @return {string} Color string in rgba format. * @memberOf module:zrender/util/color */ function modifyAlpha(color, alpha) { color = parse(color); if (color && alpha != null) { color[3] = clampCssFloat(alpha); return stringify(color, 'rgba'); } } /** * @param {Array.<string>} colors Color list. * @param {string} type 'rgba', 'hsva', ... * @return {string} Result color. */ function stringify(arrColor, type) { var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2]; if (type === 'rgba' || type === 'hsva' || type === 'hsla') { colorStr += ',' + arrColor[3]; } return type + '(' + colorStr + ')'; } module.exports = { parse: parse, lift: lift, toHex: toHex, fastMapToColor: fastMapToColor, mapToColor: mapToColor, modifyHSL: modifyHSL, modifyAlpha: modifyAlpha, stringify: stringify };
module.exports = function() { if (true) { if (true) { if (true) { return false } } } }
/*! hyperform.js.org */ 'use strict'; /* the following code is borrowed from the WebComponents project, licensed * under the BSD license. Source: * <https://github.com/webcomponents/webcomponentsjs/blob/5283db1459fa2323e5bfc8b9b5cc1753ed85e3d0/src/WebComponents/dom.js#L53-L78> */ // defaultPrevented is broken in IE. // https://connect.microsoft.com/IE/feedback/details/790389/event-defaultprevented-returns-false-after-preventdefault-was-called var workingDefaultPrevented = function () { var e = document.createEvent('Event'); e.initEvent('foo', true, true); e.preventDefault(); return e.defaultPrevented; }(); if (!workingDefaultPrevented) { (function () { var origPreventDefault = window.Event.prototype.preventDefault; window.Event.prototype.preventDefault = function () { if (!this.cancelable) { return; } origPreventDefault.call(this); Object.defineProperty(this, 'defaultPrevented', { get: function get() { return true; }, configurable: true }); }; })(); } /* end of borrowed code */ function create_event(name) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _ref$bubbles = _ref.bubbles; var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles; var _ref$cancelable = _ref.cancelable; var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable; var event = document.createEvent('Event'); event.initEvent(name, bubbles, cancelable); return event; } function trigger_event (element, event) { var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _ref2$bubbles = _ref2.bubbles; var bubbles = _ref2$bubbles === undefined ? true : _ref2$bubbles; var _ref2$cancelable = _ref2.cancelable; var cancelable = _ref2$cancelable === undefined ? false : _ref2$cancelable; var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (!(event instanceof window.Event)) { event = create_event(event, { bubbles: bubbles, cancelable: cancelable }); } for (var key in payload) { if (payload.hasOwnProperty(key)) { event[key] = payload[key]; } } element.dispatchEvent(event); return event; } /* shim layer for the Element.matches method */ var ep = window.Element.prototype; var native_matches = ep.matches || ep.matchesSelector || ep.msMatchesSelector || ep.webkitMatchesSelector; function matches (element, selector) { return native_matches.call(element, selector); } /** * mark an object with a '__hyperform=true' property * * We use this to distinguish our properties from the native ones. Usage: * js> mark(obj); * js> assert(obj.__hyperform === true) */ function mark (obj) { if (['object', 'function'].indexOf(typeof obj) > -1) { delete obj.__hyperform; Object.defineProperty(obj, '__hyperform', { configurable: true, enumerable: false, value: true }); } return obj; } /** * the internal storage for messages */ var store = new WeakMap(); /* jshint -W053 */ /* allow new String() */ /** * handle validation messages * * Falls back to browser-native errors, if any are available. The messages * are String objects so that we can mark() them. */ var message_store = { set: function set(element, message) { var is_custom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (element instanceof window.HTMLFieldSetElement) { var wrapped_form = get_wrapper(element); if (wrapped_form && !wrapped_form.settings.extendFieldset) { /* make this a no-op for <fieldset> in strict mode */ return message_store; } } if (typeof message === 'string') { message = new String(message); } if (is_custom) { message.is_custom = true; } mark(message); store.set(element, message); /* allow the :invalid selector to match */ if ('_original_setCustomValidity' in element) { element._original_setCustomValidity(message.toString()); } return message_store; }, get: function get(element) { var message = store.get(element); if (message === undefined && '_original_validationMessage' in element) { /* get the browser's validation message, if we have none. Maybe it * knows more than we. */ message = new String(element._original_validationMessage); } return message ? message : new String(''); }, delete: function _delete(element) { var is_custom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if ('_original_setCustomValidity' in element) { element._original_setCustomValidity(''); } var message = store.get(element); if (message && is_custom && !message.is_custom) { /* do not delete "native" messages, if asked */ return false; } return store.delete(element); } }; /** * counter that will be incremented with every call * * Will enforce uniqueness, as long as no more than 1 hyperform scripts * are loaded. (In that case we still have the "random" part below.) */ var uid = 0; /** * generate a random ID * * @see https://gist.github.com/gordonbrander/2230317 */ function generate_id () { var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'hf_'; return prefix + uid++ + Math.random().toString(36).substr(2); } /** * get all radio buttons (including `element`) that belong to element's * radio group */ function get_radiogroup(element) { if (element.form) { return Array.prototype.filter.call(element.form.elements, function (radio) { return radio.type === 'radio' && radio.name === element.name; }); } return [element]; } var warningsCache = new WeakMap(); var DefaultRenderer = { /** * called when a warning should become visible */ attachWarning: function attachWarning(warning, element) { /* should also work, if element is last, * http://stackoverflow.com/a/4793630/113195 */ element.parentNode.insertBefore(warning, element.nextSibling); }, /** * called when a warning should vanish */ detachWarning: function detachWarning(warning, element) { /* be conservative here, since an overwritten attachWarning() might not * actually have attached the warning. */ if (warning.parentNode) { warning.parentNode.removeChild(warning); } }, /** * called when feedback to an element's state should be handled * * i.e., showing and hiding warnings */ showWarning: function showWarning(element) { var whole_form_validated = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; /* don't render error messages on subsequent radio buttons of the * same group. This assumes, that element.validity.valueMissing is the only * possible validation failure for radio buttons. */ if (whole_form_validated && element.type === 'radio' && get_radiogroup(element)[0] !== element) { return; } var msg = message_store.get(element).toString(); var warning = warningsCache.get(element); if (msg) { if (!warning) { var wrapper = get_wrapper(element); warning = document.createElement('div'); warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning'; warning.id = generate_id(); warning.setAttribute('aria-live', 'polite'); warningsCache.set(element, warning); } element.setAttribute('aria-errormessage', warning.id); if (!element.hasAttribute('aria-describedby')) { element.setAttribute('aria-describedby', warning.id); } Renderer.setMessage(warning, msg, element); Renderer.attachWarning(warning, element); } else if (warning && warning.parentNode) { if (element.getAttribute('aria-describedby') === warning.id) { element.removeAttribute('aria-describedby'); } element.removeAttribute('aria-errormessage'); Renderer.detachWarning(warning, element); } }, /** * set the warning's content * * Overwrite this method, if you want, e.g., to allow HTML in warnings * or preprocess the content. */ setMessage: function setMessage(warning, message, element) { warning.textContent = message; } }; var Renderer = { attachWarning: DefaultRenderer.attachWarning, detachWarning: DefaultRenderer.detachWarning, showWarning: DefaultRenderer.showWarning, setMessage: DefaultRenderer.setMessage, set: function set(renderer, action) { if (renderer.indexOf('_') > -1) { /* global console */ // TODO delete before next non-patch version console.log('Renderer.set: please use camelCase names. ' + renderer + ' will be removed in the next non-patch release.'); renderer = renderer.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); }); } if (!action) { action = DefaultRenderer[renderer]; } Renderer[renderer] = action; }, getWarning: function getWarning(element) { return warningsCache.get(element); } }; var registry = Object.create(null); /** * run all actions registered for a hook * * Every action gets called with a state object as `this` argument and with the * hook's call arguments as call arguments. * * @return mixed the returned value of the action calls or undefined */ function call_hook(hook) { var result; var call_args = Array.prototype.slice.call(arguments, 1); if (hook in registry) { result = registry[hook].reduce(function (args) { return function (previousResult, currentAction) { var interimResult = currentAction.apply({ state: previousResult, hook: hook }, args); return interimResult !== undefined ? interimResult : previousResult; }; }(call_args), result); } return result; } /** * Filter a value through hooked functions * * Allows for additional parameters: * js> do_filter('foo', null, current_element) */ function do_filter(hook, initial_value) { var result = initial_value; var call_args = Array.prototype.slice.call(arguments, 1); if (hook in registry) { result = registry[hook].reduce(function (previousResult, currentAction) { call_args[0] = previousResult; var interimResult = currentAction.apply({ state: previousResult, hook: hook }, call_args); return interimResult !== undefined ? interimResult : previousResult; }, result); } return result; } /** * remove an action again */ function remove_hook(hook, action) { if (hook in registry) { for (var i = 0; i < registry[hook].length; i++) { if (registry[hook][i] === action) { registry[hook].splice(i, 1); break; } } } } /** * add an action to a hook */ function add_hook(hook, action, position) { if (!(hook in registry)) { registry[hook] = []; } if (position === undefined) { position = registry[hook].length; } registry[hook].splice(position, 0, action); } /* and datetime-local? Spec says “Nah!” */ var dates = ['datetime', 'date', 'month', 'week', 'time']; var plain_numbers = ['number', 'range']; /* everything that returns something meaningful for valueAsNumber and * can have the step attribute */ var numbers = dates.concat(plain_numbers, 'datetime-local'); /* the spec says to only check those for syntax in validity.typeMismatch. * ¯\_(ツ)_/¯ */ var type_checked = ['email', 'url']; /* check these for validity.badInput */ var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color']; var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked); /* input element types, that are candidates for the validation API. * Missing from this set are: button, hidden, menu (from <button>), reset and * the types for non-<input> elements. */ var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types); /* all known types of <input> */ var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates); /* apparently <select> and <textarea> have types of their own */ var non_inputs = ['select-one', 'select-multiple', 'textarea']; /** * get the element's type in a backwards-compatible way */ function get_type (element) { if (element instanceof window.HTMLTextAreaElement) { return 'textarea'; } else if (element instanceof window.HTMLSelectElement) { return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one'; } else if (element instanceof window.HTMLButtonElement) { return (element.getAttribute('type') || 'submit').toLowerCase(); } else if (element instanceof window.HTMLInputElement) { var attr = (element.getAttribute('type') || '').toLowerCase(); if (attr && inputs.indexOf(attr) > -1) { return attr; } else { /* perhaps the DOM has in-depth knowledge. Take that before returning * 'text'. */ return element.type || 'text'; } } return ''; } /** * check if an element should be ignored due to any of its parents * * Checks <fieldset disabled> and <datalist>. */ function is_in_disallowed_parent(element) { var p = element.parentNode; while (p && p.nodeType === 1) { if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) { /* quick return, if it's a child of a disabled fieldset */ return true; } else if (p.nodeName.toUpperCase() === 'DATALIST') { /* quick return, if it's a child of a datalist * Do not use HTMLDataListElement to support older browsers, * too. * @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation */ return true; } else if (p === element.form) { /* the outer boundary. We can stop looking for relevant elements. */ break; } p = p.parentNode; } return false; } /** * check if an element is a candidate for constraint validation * * @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation */ function is_validation_candidate (element) { /* allow a shortcut via filters, e.g. to validate type=hidden fields */ var filtered = do_filter('is_validation_candidate', null, element); if (filtered !== null) { return !!filtered; } /* it must be any of those elements */ if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) { var type = get_type(element); /* its type must be in the whitelist */ if (non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) { /* it mustn't be disabled or readonly */ if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) { var wrapped_form = get_wrapper(element); if ( /* the parent form doesn't allow non-standard "novalidate" attributes... */ wrapped_form && !wrapped_form.settings.novalidateOnElements || /* ...or it doesn't have such an attribute/property */ !element.hasAttribute('novalidate') && !element.noValidate) { /* it isn't part of a <fieldset disabled> */ if (!is_in_disallowed_parent(element)) { /* then it's a candidate */ return true; } } } } } /* this is no HTML5 validation candidate... */ return false; } function format_date (date) { var part = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; switch (part) { case 'date': return (date.toLocaleDateString || date.toDateString).call(date); case 'time': return (date.toLocaleTimeString || date.toTimeString).call(date); case 'month': return 'toLocaleDateString' in date ? date.toLocaleDateString(undefined, { year: 'numeric', month: '2-digit' }) : date.toDateString(); // case 'week': // TODO default: return (date.toLocaleString || date.toString).call(date); } } function sprintf (str) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var args_length = args.length; var global_index = 0; return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) { var local_index = global_index; if (position) { local_index = Number(position.replace(/\$$/, '')) - 1; } global_index += 1; var arg = ''; if (args_length > local_index) { arg = args[local_index]; } if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) { /* try getting a localized representation of dates and numbers, if the * browser supports this */ if (type === 'l') { arg = (arg.toLocaleString || arg.toString).call(arg); } else { arg = arg.toString(); } } return arg; }); } /* For a given date, get the ISO week number * * Source: http://stackoverflow.com/a/6117889/113195 * * Based on information at: * * http://www.merlyn.demon.co.uk/weekcalc.htm#WNR * * Algorithm is to find nearest thursday, it's year * is the year of the week number. Then get weeks * between that date and the first day of that year. * * Note that dates in one year can be weeks of previous * or next year, overlap is up to 3 days. * * e.g. 2014/12/29 is Monday in week 1 of 2015 * 2012/1/1 is Sunday in week 52 of 2011 */ function get_week_of_year (d) { /* Copy date so don't modify original */ d = new Date(+d); d.setUTCHours(0, 0, 0); /* Set to nearest Thursday: current date + 4 - current day number * Make Sunday's day number 7 */ d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); /* Get first day of year */ var yearStart = new Date(d.getUTCFullYear(), 0, 1); /* Calculate full weeks to nearest Thursday */ var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7); /* Return array of year and week number */ return [d.getUTCFullYear(), weekNo]; } function pad(num) { var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; var s = num + ''; while (s.length < size) { s = '0' + s; } return s; } /** * calculate a string from a date according to HTML5 */ function date_to_string(date, element_type) { if (!(date instanceof Date)) { return null; } switch (element_type) { case 'datetime': return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time'); case 'datetime-local': return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, ''); case 'date': return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate())); case 'month': return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1)); case 'week': var params = get_week_of_year(date); return sprintf.call(null, '%s-W%s', params[0], pad(params[1])); case 'time': return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, ''); } return null; } /** * return a new Date() representing the ISO date for a week number * * @see http://stackoverflow.com/a/16591175/113195 */ function get_date_from_week (week, year) { var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7)); if (date.getUTCDay() <= 4 /* thursday */) { date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1); } else { date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay()); } return date; } /** * calculate a date from a string according to HTML5 */ function string_to_date (string, element_type) { var date = void 0; switch (element_type) { case 'datetime': if (!/^([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) { return null; } date = new Date(string + 'z'); return isNaN(date.valueOf()) ? null : date; case 'date': if (!/^([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/.test(string)) { return null; } date = new Date(string); return isNaN(date.valueOf()) ? null : date; case 'month': if (!/^([0-9]{4})-(0[1-9]|1[012])$/.test(string)) { return null; } date = new Date(string); return isNaN(date.valueOf()) ? null : date; case 'week': if (!/^([0-9]{4})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) { return null; } return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1)); case 'time': if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) { return null; } date = new Date('1970-01-01T' + string + 'z'); return date; } return null; } /** * calculate a number from a string according to HTML5 */ function string_to_number (string, element_type) { var rval = string_to_date(string, element_type); if (rval !== null) { return +rval; } /* not parseFloat, because we want NaN for invalid values like "1.2xxy" */ return Number(string); } /** * the following validation messages are from Firefox source, * http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties * released under MPL license, http://mozilla.org/MPL/2.0/. */ var catalog = { en: { TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).', ValueMissing: 'Please fill out this field.', CheckboxMissing: 'Please check this box if you want to proceed.', RadioMissing: 'Please select one of these options.', FileMissing: 'Please select a file.', SelectMissing: 'Please select an item in the list.', InvalidEmail: 'Please enter an email address.', InvalidURL: 'Please enter a URL.', PatternMismatch: 'Please match the requested format.', PatternMismatchWithTitle: 'Please match the requested format: %l.', NumberRangeOverflow: 'Please select a value that is no more than %l.', DateRangeOverflow: 'Please select a value that is no later than %l.', TimeRangeOverflow: 'Please select a value that is no later than %l.', NumberRangeUnderflow: 'Please select a value that is no less than %l.', DateRangeUnderflow: 'Please select a value that is no earlier than %l.', TimeRangeUnderflow: 'Please select a value that is no earlier than %l.', StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.', StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.', BadInputNumber: 'Please enter a number.' } }; /** * the global language Hyperform will use */ var language = 'en'; /** * the base language according to BCP47, i.e., only the piece before the first hyphen */ var base_lang = 'en'; /** * set the language for Hyperform’s messages */ function set_language(newlang) { language = newlang; base_lang = newlang.replace(/[-_].*/, ''); } /** * add a lookup catalog "string: translation" for a language */ function add_translation(lang, new_catalog) { if (!(lang in catalog)) { catalog[lang] = {}; } for (var key in new_catalog) { if (new_catalog.hasOwnProperty(key)) { catalog[lang][key] = new_catalog[key]; } } } /** * return `s` translated into the current language * * Defaults to the base language and then English if the former has no * translation for `s`. */ function _ (s) { if (language in catalog && s in catalog[language]) { return catalog[language][s]; } else if (base_lang in catalog && s in catalog[base_lang]) { return catalog[base_lang][s]; } else if (s in catalog.en) { return catalog.en[s]; } return s; } var default_step = { 'datetime-local': 60, datetime: 60, time: 60 }; var step_scale_factor = { 'datetime-local': 1000, datetime: 1000, date: 86400000, week: 604800000, time: 1000 }; var default_step_base = { week: -259200000 }; var default_min = { range: 0 }; var default_max = { range: 100 }; /** * get previous and next valid values for a stepped input element */ function get_next_valid (element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var type = get_type(element); var aMin = element.getAttribute('min'); var min = default_min[type] || NaN; if (aMin) { var pMin = string_to_number(aMin, type); if (!isNaN(pMin)) { min = pMin; } } var aMax = element.getAttribute('max'); var max = default_max[type] || NaN; if (aMax) { var pMax = string_to_number(aMax, type); if (!isNaN(pMax)) { max = pMax; } } var aStep = element.getAttribute('step'); var step = default_step[type] || 1; if (aStep && aStep.toLowerCase() === 'any') { /* quick return: we cannot calculate prev and next */ return [_('any value'), _('any value')]; } else if (aStep) { var pStep = string_to_number(aStep, type); if (!isNaN(pStep)) { step = pStep; } } var default_value = string_to_number(element.getAttribute('value'), type); var value = string_to_number(element.value || element.getAttribute('value'), type); if (isNaN(value)) { /* quick return: we cannot calculate without a solid base */ return [_('any valid value'), _('any valid value')]; } var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0; var scale = step_scale_factor[type] || 1; var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n; var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n; if (prev < min) { prev = null; } else if (prev > max) { prev = max; } if (next > max) { next = null; } else if (next < min) { next = min; } /* convert to date objects, if appropriate */ if (dates.indexOf(type) > -1) { prev = date_to_string(new Date(prev), type); next = date_to_string(new Date(next), type); } return [prev, next]; } /** * patch String.length to account for non-BMP characters * * @see https://mathiasbynens.be/notes/javascript-unicode * We do not use the simple [...str].length, because it needs a ton of * polyfills in older browsers. */ function unicode_string_length (str) { return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length; } /** * internal storage for custom error messages */ var store$1 = new WeakMap(); /** * register custom error messages per element */ var custom_messages = { set: function set(element, validator, message) { var messages = store$1.get(element) || {}; messages[validator] = message; store$1.set(element, messages); return custom_messages; }, get: function get(element, validator) { var _default = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var messages = store$1.get(element); if (messages === undefined || !(validator in messages)) { var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase(); if (element.hasAttribute(data_id)) { /* if the element has a data-validator attribute, use this as fallback. * E.g., if validator == 'valueMissing', the element can specify a * custom validation message like this: * <input data-value-missing="Oh noes!"> */ return element.getAttribute(data_id); } return _default; } return messages[validator]; }, delete: function _delete(element) { var validator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!validator) { return store$1.delete(element); } var messages = store$1.get(element) || {}; if (validator in messages) { delete messages[validator]; store$1.set(element, messages); return true; } return false; } }; var internal_registry = new WeakMap(); /** * A registry for custom validators * * slim wrapper around a WeakMap to ensure the values are arrays * (hence allowing > 1 validators per element) */ var custom_validator_registry = { set: function set(element, validator) { var current = internal_registry.get(element) || []; current.push(validator); internal_registry.set(element, current); return custom_validator_registry; }, get: function get(element) { return internal_registry.get(element) || []; }, delete: function _delete(element) { return internal_registry.delete(element); } }; /** * test whether the element suffers from bad input */ function test_bad_input (element) { var type = get_type(element); if (input_checked.indexOf(type) === -1) { /* we're not interested, thanks! */ return true; } /* the browser hides some bad input from the DOM, e.g. malformed numbers, * email addresses with invalid punycode representation, ... We try to resort * to the original method here. The assumption is, that a browser hiding * bad input will hopefully also always support a proper * ValidityState.badInput */ if (!element.value) { if ('_original_validity' in element && !element._original_validity.__hyperform) { return !element._original_validity.badInput; } /* no value and no original badInput: Assume all's right. */ return true; } var result = true; switch (type) { case 'color': result = /^#[a-f0-9]{6}$/.test(element.value); break; case 'number': case 'range': result = !isNaN(Number(element.value)); break; case 'datetime': case 'date': case 'month': case 'week': case 'time': result = string_to_date(element.value, type) !== null; break; case 'datetime-local': result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value); break; case 'tel': /* spec says No! Phone numbers can have all kinds of formats, so this * is expected to be a free-text field. */ // TODO we could allow a setting 'phone_regex' to be evaluated here. break; case 'email': break; } return result; } /** * test the max attribute * * we use Number() instead of parseFloat(), because an invalid attribute * value like "123abc" should result in an error. */ function test_max (element) { var type = get_type(element); if (!element.value || !element.hasAttribute('max')) { /* we're not responsible here */ return true; } var value = void 0, max = void 0; if (dates.indexOf(type) > -1) { value = string_to_date(element.value, type); value = value === null ? NaN : +value; max = string_to_date(element.getAttribute('max'), type); max = max === null ? NaN : +max; } else { value = Number(element.value); max = Number(element.getAttribute('max')); } /* we cannot validate invalid values and trust on badInput, if isNaN(value) */ return isNaN(max) || isNaN(value) || value <= max; } /** * test the maxlength attribute */ function test_maxlength (element) { if (!element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength="" ) { return true; } var maxlength = parseInt(element.getAttribute('maxlength'), 10); /* check, if the maxlength value is usable at all. * We allow maxlength === 0 to basically disable input (Firefox does, too). */ if (isNaN(maxlength) || maxlength < 0) { return true; } return unicode_string_length(element.value) <= maxlength; } /** * test the min attribute * * we use Number() instead of parseFloat(), because an invalid attribute * value like "123abc" should result in an error. */ function test_min (element) { var type = get_type(element); if (!element.value || !element.hasAttribute('min')) { /* we're not responsible here */ return true; } var value = void 0, min = void 0; if (dates.indexOf(type) > -1) { value = string_to_date(element.value, type); value = value === null ? NaN : +value; min = string_to_date(element.getAttribute('min'), type); min = min === null ? NaN : +min; } else { value = Number(element.value); min = Number(element.getAttribute('min')); } /* we cannot validate invalid values and trust on badInput, if isNaN(value) */ return isNaN(min) || isNaN(value) || value >= min; } /** * test the minlength attribute */ function test_minlength (element) { if (!element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength="" ) { return true; } var minlength = parseInt(element.getAttribute('minlength'), 10); /* check, if the minlength value is usable at all. */ if (isNaN(minlength) || minlength < 0) { return true; } return unicode_string_length(element.value) >= minlength; } /** * test the pattern attribute */ function test_pattern (element) { return !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value); } function has_submittable_option(select) { /* Definition of the placeholder label option: * https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-select-required * Being required (the first constraint in the spec) is trivially true, since * this function is only called for such selects. */ var has_placeholder_option = !select.multiple && select.size <= 1 && select.options.length > 0 && select.options[0].parentNode == select && select.options[0].value === ''; return ( /* anything selected at all? That's redundant with the .some() call below, * but more performant in the most probable error case. */ select.selectedIndex > -1 && Array.prototype.some.call(select.options, function (option) { return ( /* it isn't the placeholder option */ (!has_placeholder_option || option.index !== 0) && /* it isn't disabled */ !option.disabled && /* and it is, in fact, selected */ option.selected ); }) ); } /** * test the required attribute */ function test_required (element) { if (element.type === 'radio') { /* the happy (and quick) path for radios: */ if (element.hasAttribute('required') && element.checked) { return true; } var radiogroup = get_radiogroup(element); /* if any radio in the group is required, we need any (not necessarily the * same) radio to be checked */ if (radiogroup.some(function (radio) { return radio.hasAttribute('required'); })) { return radiogroup.some(function (radio) { return radio.checked; }); } /* not required, validation passes */ return true; } if (!element.hasAttribute('required')) { /* nothing to do */ return true; } if (element instanceof window.HTMLSelectElement) { return has_submittable_option(element); } return element.type === 'checkbox' ? element.checked : !!element.value; } /** * test the step attribute */ function test_step (element) { var type = get_type(element); if (!element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') { /* we're not responsible here. Note: If no step attribute is given, we * need to validate against the default step as per spec. */ return true; } var step = element.getAttribute('step'); if (step) { step = string_to_number(step, type); } else { step = default_step[type] || 1; } if (step <= 0 || isNaN(step)) { /* error in specified "step". We cannot validate against it, so the value * is true. */ return true; } var scale = step_scale_factor[type] || 1; var value = string_to_number(element.value, type); var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type); if (isNaN(value)) { /* we cannot compare an invalid value and trust that the badInput validator * takes over from here */ return true; } if (isNaN(min)) { min = default_step_base[type] || 0; } if (type === 'month') { /* type=month has month-wide steps. See * https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29 */ min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth(); value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth(); } var result = Math.abs(min - value) % (step * scale); return result < 0.00000001 || /* crappy floating-point arithmetics! */ result > step * scale - 0.00000001; } var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; /** * trim a string of whitespace * * We don't use String.trim() to remove the need to polyfill it. */ function trim (str) { return str.replace(ws_on_start_or_end, ''); } /** * split a string on comma and trim the components * * As specified at * https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas * plus removing empty entries. */ function comma_split (str) { return str.split(',').map(function (item) { return trim(item); }).filter(function (b) { return b; }); } /* we use a dummy <a> where we set the href to test URL validity * The definition is out of the "global" scope so that JSDOM can be instantiated * after loading Hyperform for tests. */ var url_canary; /* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */ var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; /** * test the type-inherent syntax */ function test_type (element) { var type = get_type(element); if (type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) { /* we're not responsible for this element */ return true; } var is_valid = true; switch (type) { case 'url': if (!url_canary) { url_canary = document.createElement('a'); } var value = trim(element.value); url_canary.href = value; is_valid = url_canary.href === value || url_canary.href === value + '/'; break; case 'email': if (element.hasAttribute('multiple')) { is_valid = comma_split(element.value).every(function (value) { return email_pattern.test(value); }); } else { is_valid = email_pattern.test(trim(element.value)); } break; case 'file': if ('files' in element && element.files.length && element.hasAttribute('accept')) { var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) { if (/^(audio|video|image)\/\*$/.test(pattern)) { pattern = new RegExp('^' + RegExp.$1 + '/.+$'); } return pattern; }); if (!patterns.length) { break; } fileloop: for (var i = 0; i < element.files.length; i++) { /* we need to match a whitelist, so pre-set with false */ var file_valid = false; patternloop: for (var j = 0; j < patterns.length; j++) { var file = element.files[i]; var pattern = patterns[j]; var fileprop = file.type; if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') { if (file.name.search('.') === -1) { /* no match with any file ending */ continue patternloop; } fileprop = file.name.substr(file.name.lastIndexOf('.')); } if (fileprop.search(pattern) === 0) { /* we found one match and can quit looking */ file_valid = true; break patternloop; } } if (!file_valid) { is_valid = false; break fileloop; } } } } return is_valid; } /** * boilerplate function for all tests but customError */ function check$1(test, react) { return function (element) { var invalid = !test(element); if (invalid) { react(element); } return invalid; }; } /** * create a common function to set error messages */ function set_msg(element, msgtype, _default) { message_store.set(element, custom_messages.get(element, msgtype, _default)); } var badInput = check$1(test_bad_input, function (element) { return set_msg(element, 'badInput', _('Please match the requested type.')); }); function customError(element) { /* prevent infinite loops when the custom validators call setCustomValidity(), * which in turn calls this code again. We check, if there is an already set * custom validity message there. */ if (element.__hf_custom_validation_running) { var msg = message_store.get(element); return msg && msg.is_custom; } /* check, if there are custom validators in the registry, and call * them. */ var custom_validators = custom_validator_registry.get(element); var cvl = custom_validators.length; var valid = true; if (cvl) { element.__hf_custom_validation_running = true; for (var i = 0; i < cvl; i++) { var result = custom_validators[i](element); if (result !== undefined && !result) { valid = false; /* break on first invalid response */ break; } } delete element.__hf_custom_validation_running; } /* check, if there are other validity messages already */ if (valid) { var _msg = message_store.get(element); valid = !(_msg.toString() && 'is_custom' in _msg); } return !valid; } var patternMismatch = check$1(test_pattern, function (element) { set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch')); }); /** * TODO: when rangeOverflow and rangeUnderflow are both called directly and * successful, the inRange and outOfRange classes won't get removed, unless * element.validityState.valid is queried, too. */ var rangeOverflow = check$1(test_max, function (element) { var type = get_type(element); var wrapper = get_wrapper(element); var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var msg = void 0; switch (type) { case 'date': case 'datetime': case 'datetime-local': msg = sprintf(_('DateRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type)); break; case 'time': msg = sprintf(_('TimeRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type)); break; // case 'number': default: msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type)); break; } set_msg(element, 'rangeOverflow', msg); element.classList.add(outOfRangeClass); element.classList.remove(inRangeClass); }); var rangeUnderflow = check$1(test_min, function (element) { var type = get_type(element); var wrapper = get_wrapper(element); var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var msg = void 0; switch (type) { case 'date': case 'datetime': case 'datetime-local': msg = sprintf(_('DateRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type)); break; case 'time': msg = sprintf(_('TimeRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type)); break; // case 'number': default: msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type)); break; } set_msg(element, 'rangeUnderflow', msg); element.classList.add(outOfRangeClass); element.classList.remove(inRangeClass); }); var stepMismatch = check$1(test_step, function (element) { var list = get_next_valid(element); var min = list[0]; var max = list[1]; var sole = false; var msg = void 0; if (min === null) { sole = max; } else if (max === null) { sole = min; } if (sole !== false) { msg = sprintf(_('StepMismatchOneValue'), sole); } else { msg = sprintf(_('StepMismatch'), min, max); } set_msg(element, 'stepMismatch', msg); }); var tooLong = check$1(test_maxlength, function (element) { set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value))); }); var tooShort = check$1(test_minlength, function (element) { set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('minlength'), unicode_string_length(element.value))); }); var typeMismatch = check$1(test_type, function (element) { var msg = _('Please use the appropriate format.'); var type = get_type(element); if (type === 'email') { if (element.hasAttribute('multiple')) { msg = _('Please enter a comma separated list of email addresses.'); } else { msg = _('InvalidEmail'); } } else if (type === 'url') { msg = _('InvalidURL'); } else if (type === 'file') { msg = _('Please select a file of the correct type.'); } set_msg(element, 'typeMismatch', msg); }); var valueMissing = check$1(test_required, function (element) { var msg = _('ValueMissing'); var type = get_type(element); if (type === 'checkbox') { msg = _('CheckboxMissing'); } else if (type === 'radio') { msg = _('RadioMissing'); } else if (type === 'file') { if (element.hasAttribute('multiple')) { msg = _('Please select one or more files.'); } else { msg = _('FileMissing'); } } else if (element instanceof window.HTMLSelectElement) { msg = _('SelectMissing'); } set_msg(element, 'valueMissing', msg); }); /** * the "valid" property calls all other validity checkers and returns true, * if all those return false. * * This is the major access point for _all_ other API methods, namely * (check|report)Validity(). */ var valid = function valid(element) { var wrapper = get_wrapper(element); var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid'; var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid'; var userInvalidClass = wrapper && wrapper.settings.classes.userInvalid || 'hf-user-invalid'; var userValidClass = wrapper && wrapper.settings.classes.userValid || 'hf-user-valid'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated'; element.classList.add(validatedClass); var _arr = [badInput, customError, patternMismatch, rangeOverflow, rangeUnderflow, stepMismatch, tooLong, tooShort, typeMismatch, valueMissing]; for (var _i = 0; _i < _arr.length; _i++) { var checker = _arr[_i]; if (checker(element)) { element.classList.add(invalidClass); element.classList.remove(validClass); element.classList.remove(userValidClass); if ((element.type === 'checkbox' || element.type === 'radio') && element.checked !== element.defaultChecked || /* the following test is trivially false for checkboxes/radios */ element.value !== element.defaultValue) { element.classList.add(userInvalidClass); } else { element.classList.remove(userInvalidClass); } element.setAttribute('aria-invalid', 'true'); return false; } } message_store.delete(element); element.classList.remove(invalidClass); element.classList.remove(userInvalidClass); element.classList.remove(outOfRangeClass); element.classList.add(validClass); element.classList.add(inRangeClass); if (element.value !== element.defaultValue) { element.classList.add(userValidClass); } else { element.classList.remove(userValidClass); } element.setAttribute('aria-invalid', 'false'); return true; }; var validity_state_checkers = { badInput: badInput, customError: customError, patternMismatch: patternMismatch, rangeOverflow: rangeOverflow, rangeUnderflow: rangeUnderflow, stepMismatch: stepMismatch, tooLong: tooLong, tooShort: tooShort, typeMismatch: typeMismatch, valueMissing: valueMissing, valid: valid }; /** * the validity state constructor */ var ValidityState = function ValidityState(element) { if (!(element instanceof window.HTMLElement)) { throw new Error('cannot create a ValidityState for a non-element'); } var cached = ValidityState.cache.get(element); if (cached) { return cached; } if (!(this instanceof ValidityState)) { /* working around a forgotten `new` */ return new ValidityState(element); } this.element = element; ValidityState.cache.set(element, this); }; /** * the prototype for new validityState instances */ var ValidityStatePrototype = {}; ValidityState.prototype = ValidityStatePrototype; ValidityState.cache = new WeakMap(); /* small wrapper around the actual validator to check if the validator * should actually be called. `this` refers to the ValidityState object. */ var checker_getter = function checker_getter(func) { return function () { if (!is_validation_candidate(this.element)) { /* not being validated == valid by default */ return true; } return func(this.element); }; }; /** * copy functionality from the validity checkers to the ValidityState * prototype */ for (var prop in validity_state_checkers) { Object.defineProperty(ValidityStatePrototype, prop, { configurable: true, enumerable: true, get: checker_getter(validity_state_checkers[prop]), set: undefined }); } /** * mark the validity prototype, because that is what the client-facing * code deals with mostly, not the property descriptor thing */ mark(ValidityStatePrototype); /** * check element's validity and report an error back to the user */ function reportValidity(element) { /* if this is a <form>, report validity of all child inputs */ if (element instanceof window.HTMLFormElement) { element.__hf_form_validation = true; var form_valid = get_validated_elements(element).map(reportValidity).every(function (b) { return b; }); delete element.__hf_form_validation; return form_valid; } /* we copy checkValidity() here, b/c we have to check if the "invalid" * event was canceled. */ var valid = ValidityState(element).valid; var event; if (valid) { var wrapped_form = get_wrapper(element); if (wrapped_form && wrapped_form.settings.validEvent) { event = trigger_event(element, 'valid', { cancelable: true }); } } else { event = trigger_event(element, 'invalid', { cancelable: true }); } if (!event || !event.defaultPrevented) { Renderer.showWarning(element, !!element.form.__hf_form_validation); } return valid; } /** * submit a form, because `element` triggered it * * This method also dispatches a submit event on the form prior to the * submission. The event contains the trigger element as `submittedVia`. * * If the element is a button with a name, the name=value pair will be added * to the submitted data. */ function submit_form_via(element) { /* apparently, the submit event is not triggered in most browsers on * the submit() method, so we do it manually here to model a natural * submit as closely as possible. * Now to the fun fact: If you trigger a submit event from a form, what * do you think should happen? * 1) the form will be automagically submitted by the browser, or * 2) nothing. * And as you already suspected, the correct answer is: both! Firefox * opts for 1), Chrome for 2). Yay! */ var event_got_cancelled; var submit_event = create_event('submit', { cancelable: true }); /* force Firefox to not submit the form, then fake preventDefault() */ submit_event.preventDefault(); Object.defineProperty(submit_event, 'defaultPrevented', { value: false, writable: true }); Object.defineProperty(submit_event, 'preventDefault', { value: function value() { return submit_event.defaultPrevented = event_got_cancelled = true; }, writable: true }); trigger_event(element.form, submit_event, {}, { submittedVia: element }); if (!event_got_cancelled) { add_submit_field(element); window.HTMLFormElement.prototype.submit.call(element.form); window.setTimeout(function () { return remove_submit_field(element); }); } } /** * if a submit button was clicked, add its name=value by means of a type=hidden * input field */ function add_submit_field(button) { if (['image', 'submit'].indexOf(button.type) > -1 && button.name) { var wrapper = get_wrapper(button.form) || {}; var submit_helper = wrapper.submit_helper; if (submit_helper) { if (submit_helper.parentNode) { submit_helper.parentNode.removeChild(submit_helper); } } else { submit_helper = document.createElement('input'); submit_helper.type = 'hidden'; wrapper.submit_helper = submit_helper; } submit_helper.name = button.name; submit_helper.value = button.value; button.form.appendChild(submit_helper); } } /** * remove a possible helper input, that was added by `add_submit_field` */ function remove_submit_field(button) { if (['image', 'submit'].indexOf(button.type) > -1 && button.name) { var wrapper = get_wrapper(button.form) || {}; var submit_helper = wrapper.submit_helper; if (submit_helper && submit_helper.parentNode) { submit_helper.parentNode.removeChild(submit_helper); } } } /** * check a form's validity and submit it * * The method triggers a cancellable `validate` event on the form. If the * event is cancelled, form submission will be aborted, too. * * If the form is found to contain invalid fields, focus the first field. */ function check(button) { /* trigger a "validate" event on the form to be submitted */ var val_event = trigger_event(button.form, 'validate', { cancelable: true }); if (val_event.defaultPrevented) { /* skip the whole submit thing, if the validation is canceled. A user * can still call form.submit() afterwards. */ return; } var valid = true; var first_invalid; button.form.__hf_form_validation = true; get_validated_elements(button.form).map(function (element) { if (!reportValidity(element)) { valid = false; if (!first_invalid && 'focus' in element) { first_invalid = element; } } }); delete button.form.__hf_form_validation; if (valid) { submit_form_via(button); } else if (first_invalid) { /* focus the first invalid element, if validation went south */ first_invalid.focus(); /* tell the tale, if anyone wants to react to it */ trigger_event(button.form, 'forminvalid'); } } /** * test if node is a submit button */ function is_submit_button(node) { return ( /* must be an input or button element... */ (node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && ( /* ...and have a submitting type */ node.type === 'image' || node.type === 'submit') ); } /** * test, if the click event would trigger a submit */ function is_submitting_click(event, button) { return ( /* prevented default: won't trigger a submit */ !event.defaultPrevented && ( /* left button or middle button (submits in Chrome) */ !('button' in event) || event.button < 2) && /* must be a submit button... */ is_submit_button(button) && /* the button needs a form, that's going to be submitted */ button.form && /* again, if the form should not be validated, we're out of the game */ !button.form.hasAttribute('novalidate') ); } /** * test, if the keypress event would trigger a submit */ function is_submitting_keypress(event) { return ( /* prevented default: won't trigger a submit */ !event.defaultPrevented && ( /* ...and <Enter> was pressed... */ event.keyCode === 13 && /* ...on an <input> that is... */ event.target.nodeName === 'INPUT' && /* ...a standard text input field (not checkbox, ...) */ text_types.indexOf(event.target.type) > -1 || /* or <Enter> or <Space> was pressed... */ (event.keyCode === 13 || event.keyCode === 32) && /* ...on a submit button */ is_submit_button(event.target)) && /* there's a form... */ event.target.form && /* ...and the form allows validation */ !event.target.form.hasAttribute('novalidate') ); } /** * catch clicks to children of <button>s */ function get_clicked_button(element) { if (is_submit_button(element)) { return element; } else if (matches(element, 'button:not([type]) *, button[type="submit"] *')) { return get_clicked_button(element.parentNode); } else { return null; } } /** * return event handler to catch explicit submission by click on a button */ function get_click_handler() { var ignore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; return function (event) { var button = get_clicked_button(event.target); if (button && is_submitting_click(event, button)) { event.preventDefault(); if (ignore || button.hasAttribute('formnovalidate')) { /* if validation should be ignored, we're not interested in any checks */ submit_form_via(button); } else { check(button); } } }; } var click_handler = get_click_handler(); var ignored_click_handler = get_click_handler(true); /** * catch implicit submission by pressing <Enter> in some situations */ function get_keypress_handler(ignore) { return function keypress_handler(event) { if (is_submitting_keypress(event)) { event.preventDefault(); var wrapper = get_wrapper(event.target.form) || { settings: {} }; if (wrapper.settings.preventImplicitSubmit) { /* user doesn't want an implicit submit. Cancel here. */ return; } /* check, that there is no submit button in the form. Otherwise * that should be clicked. */ var el = event.target.form.elements.length; var submit; for (var i = 0; i < el; i++) { if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) { submit = event.target.form.elements[i]; break; } } /* trigger a "validate" event on the form to be submitted */ var implicit_event = trigger_event(event.target.form, 'implicit_submit', { cancelable: true }); implicit_event.trigger = event.target; implicit_event.submittedVia = submit || event.target; if (implicit_event.defaultPrevented) { /* skip the submit, if implicit submit is canceled */ return; } if (submit) { submit.click(); } else if (ignore) { submit_form_via(event.target); } else { check(event.target); } } }; } var keypress_handler = get_keypress_handler(); var ignored_keypress_handler = get_keypress_handler(true); /** * catch all relevant events _prior_ to a form being submitted * * @param bool ignore bypass validation, when an attempt to submit the * form is detected. True, when the wrapper's revalidate * setting is 'never'. */ function catch_submit(listening_node) { var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (ignore) { listening_node.addEventListener('click', ignored_click_handler); listening_node.addEventListener('keypress', ignored_keypress_handler); } else { listening_node.addEventListener('click', click_handler); listening_node.addEventListener('keypress', keypress_handler); } } /** * decommission the event listeners from catch_submit() again */ function uncatch_submit(listening_node) { listening_node.removeEventListener('click', ignored_click_handler); listening_node.removeEventListener('keypress', ignored_keypress_handler); listening_node.removeEventListener('click', click_handler); listening_node.removeEventListener('keypress', keypress_handler); } /** * remove `property` from element and restore _original_property, if present */ function uninstall_property (element, property) { try { delete element[property]; } catch (e) { /* Safari <= 9 and PhantomJS will end up here :-( Nothing to do except * warning */ var wrapper = get_wrapper(element); if (wrapper && wrapper.settings.debug) { /* global console */ console.log('[hyperform] cannot uninstall custom property ' + property); } return false; } var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property); if (original_descriptor) { Object.defineProperty(element, property, original_descriptor); } } /** * add `property` to an element * * ATTENTION! This function will search for an equally named property on the * *prototype* of an element, if element is a concrete DOM node. Do not use * it as general-purpose property installer. * * js> installer(element, 'foo', { value: 'bar' }); * js> assert(element.foo === 'bar'); */ function install_property (element, property, descriptor) { descriptor.configurable = true; descriptor.enumerable = true; if ('value' in descriptor) { descriptor.writable = true; } /* on concrete instances, i.e., <input> elements, the naive lookup * yields undefined. We have to look on its prototype then. On elements * like the actual HTMLInputElement object the first line works. */ var original_descriptor = Object.getOwnPropertyDescriptor(element, property); if (original_descriptor === undefined) { original_descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), property); } if (original_descriptor) { if (original_descriptor.configurable === false) { /* Safari <= 9 and PhantomJS will end up here :-( Nothing to do except * warning */ var wrapper = get_wrapper(element); if (wrapper && wrapper.settings.debug) { /* global console */ console.log('[hyperform] cannot install custom property ' + property); } return false; } /* we already installed that property... */ if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) { return; } /* publish existing property under new name, if it's not from us */ Object.defineProperty(element, '_original_' + property, original_descriptor); } delete element[property]; Object.defineProperty(element, property, descriptor); return true; } function is_field (element) { return element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement || element === window.HTMLButtonElement.prototype || element === window.HTMLInputElement.prototype || element === window.HTMLSelectElement.prototype || element === window.HTMLTextAreaElement.prototype || element === window.HTMLFieldSetElement.prototype; } /** * set a custom validity message or delete it with an empty string */ function setCustomValidity(element, msg) { if (!msg) { message_store.delete(element, true); } else { message_store.set(element, msg, true); } /* live-update the warning */ var warning = Renderer.getWarning(element); if (warning) { Renderer.setMessage(warning, msg, element); } /* update any classes if the validity state changes */ validity_state_checkers.valid(element); } /** * implement the valueAsDate functionality * * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate */ function valueAsDate(element) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; var type = get_type(element); if (dates.indexOf(type) > -1) { if (value !== undefined) { /* setter: value must be null or a Date() */ if (value === null) { element.value = ''; } else if (value instanceof Date) { if (isNaN(value.getTime())) { element.value = ''; } else { element.value = date_to_string(value, type); } } else { throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError'); } return; } var value_date = string_to_date(element.value, type); return value_date instanceof Date ? value_date : null; } else if (value !== undefined) { /* trying to set a date on a not-date input fails */ throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError'); } return null; } /** * implement the valueAsNumber functionality * * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber */ function valueAsNumber(element) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; var type = get_type(element); if (numbers.indexOf(type) > -1) { if (type === 'range' && element.hasAttribute('multiple')) { /* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */ return NaN; } if (value !== undefined) { /* setter: value must be NaN or a finite number */ if (isNaN(value)) { element.value = ''; } else if (typeof value === 'number' && window.isFinite(value)) { try { /* try setting as a date, but... */ valueAsDate(element, new Date(value)); } catch (e) { /* ... when valueAsDate is not responsible, ... */ if (!(e instanceof window.DOMException)) { throw e; } /* ... set it via Number.toString(). */ element.value = value.toString(); } } else { throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError'); } return; } return string_to_number(element.value, type); } else if (value !== undefined) { /* trying to set a number on a not-number input fails */ throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError'); } return NaN; } /** * */ function stepDown(element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (numbers.indexOf(get_type(element)) === -1) { throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError'); } if ((element.getAttribute('step') || '').toLowerCase() === 'any') { throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError'); } var prev = get_next_valid(element, n)[0]; if (prev !== null) { valueAsNumber(element, prev); } } /** * */ function stepUp(element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (numbers.indexOf(get_type(element)) === -1) { throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError'); } if ((element.getAttribute('step') || '').toLowerCase() === 'any') { throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError'); } var next = get_next_valid(element, n)[1]; if (next !== null) { valueAsNumber(element, next); } } /** * get the validation message for an element, empty string, if the element * satisfies all constraints. */ function validationMessage(element) { var msg = message_store.get(element); if (!msg) { return ''; } /* make it a primitive again, since message_store returns String(). */ return msg.toString(); } /** * check, if an element will be subject to HTML5 validation at all */ function willValidate(element) { return is_validation_candidate(element); } var gA = function gA(prop) { return function () { return do_filter('attr_get_' + prop, this.getAttribute(prop), this); }; }; var sA = function sA(prop) { return function (value) { this.setAttribute(prop, do_filter('attr_set_' + prop, value, this)); }; }; var gAb = function gAb(prop) { return function () { return do_filter('attr_get_' + prop, this.hasAttribute(prop), this); }; }; var sAb = function sAb(prop) { return function (value) { if (do_filter('attr_set_' + prop, value, this)) { this.setAttribute(prop, prop); } else { this.removeAttribute(prop); } }; }; var gAn = function gAn(prop) { return function () { return do_filter('attr_get_' + prop, Math.max(0, Number(this.getAttribute(prop))), this); }; }; var sAn = function sAn(prop) { return function (value) { value = do_filter('attr_set_' + prop, value, this); if (/^[0-9]+$/.test(value)) { this.setAttribute(prop, value); } }; }; function install_properties(element) { var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step']; for (var _i = 0; _i < _arr.length; _i++) { var prop = _arr[_i]; install_property(element, prop, { get: gA(prop), set: sA(prop) }); } var _arr2 = ['multiple', 'required', 'readOnly']; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var _prop = _arr2[_i2]; install_property(element, _prop, { get: gAb(_prop.toLowerCase()), set: sAb(_prop.toLowerCase()) }); } var _arr3 = ['minLength', 'maxLength']; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var _prop2 = _arr3[_i3]; install_property(element, _prop2, { get: gAn(_prop2.toLowerCase()), set: sAn(_prop2.toLowerCase()) }); } } function uninstall_properties(element) { var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength']; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var prop = _arr4[_i4]; uninstall_property(element, prop); } } var polyfills = { checkValidity: { value: mark(function () { return checkValidity(this); }) }, reportValidity: { value: mark(function () { return reportValidity(this); }) }, setCustomValidity: { value: mark(function (msg) { return setCustomValidity(this, msg); }) }, stepDown: { value: mark(function () { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; return stepDown(this, n); }) }, stepUp: { value: mark(function () { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; return stepUp(this, n); }) }, validationMessage: { get: mark(function () { return validationMessage(this); }) }, validity: { get: mark(function () { return ValidityState(this); }) }, valueAsDate: { get: mark(function () { return valueAsDate(this); }), set: mark(function (value) { valueAsDate(this, value); }) }, valueAsNumber: { get: mark(function () { return valueAsNumber(this); }), set: mark(function (value) { valueAsNumber(this, value); }) }, willValidate: { get: mark(function () { return willValidate(this); }) } }; function polyfill (element) { if (is_field(element)) { for (var prop in polyfills) { install_property(element, prop, polyfills[prop]); } install_properties(element); } else if (element instanceof window.HTMLFormElement || element === window.HTMLFormElement.prototype) { install_property(element, 'checkValidity', polyfills.checkValidity); install_property(element, 'reportValidity', polyfills.reportValidity); } } function polyunfill (element) { if (is_field(element)) { uninstall_property(element, 'checkValidity'); uninstall_property(element, 'reportValidity'); uninstall_property(element, 'setCustomValidity'); uninstall_property(element, 'stepDown'); uninstall_property(element, 'stepUp'); uninstall_property(element, 'validationMessage'); uninstall_property(element, 'validity'); uninstall_property(element, 'valueAsDate'); uninstall_property(element, 'valueAsNumber'); uninstall_property(element, 'willValidate'); uninstall_properties(element); } else if (element instanceof window.HTMLFormElement) { uninstall_property(element, 'checkValidity'); uninstall_property(element, 'reportValidity'); } } var instances = new WeakMap(); /** * wrap <form>s, window or document, that get treated with the global * hyperform() */ function Wrapper(form, settings) { /* do not allow more than one instance per form. Otherwise we'd end * up with double event handlers, polyfills re-applied, ... */ var existing = instances.get(form); if (existing) { existing.settings = settings; return existing; } this.form = form; this.settings = settings; this.revalidator = this.revalidate.bind(this); instances.set(form, this); catch_submit(form, settings.revalidate === 'never'); if (form === window || form.nodeType === 9) { /* install on the prototypes, when called for the whole document */ this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]); polyfill(window.HTMLFormElement); } else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) { this.install(form.elements); if (form instanceof window.HTMLFormElement) { polyfill(form); } } if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') { /* in a perfect world we'd just bind to "input", but support here is * abysmal: http://caniuse.com/#feat=input-event */ form.addEventListener('keyup', this.revalidator); form.addEventListener('change', this.revalidator); } if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') { /* useCapture=true, because `blur` doesn't bubble. See * https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation * for a discussion */ form.addEventListener('blur', this.revalidator, true); } } Wrapper.prototype = { destroy: function destroy() { uncatch_submit(this.form); instances.delete(this.form); this.form.removeEventListener('keyup', this.revalidator); this.form.removeEventListener('change', this.revalidator); this.form.removeEventListener('blur', this.revalidator, true); if (this.form === window || this.form.nodeType === 9) { this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]); polyunfill(window.HTMLFormElement); } else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) { this.uninstall(this.form.elements); if (this.form instanceof window.HTMLFormElement) { polyunfill(this.form); } } }, /** * revalidate an input element */ revalidate: function revalidate(event) { if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) { if (this.settings.revalidate === 'hybrid') { /* "hybrid" somewhat simulates what browsers do. See for example * Firefox's :-moz-ui-invalid pseudo-class: * https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */ if (event.type === 'blur' && event.target.value !== event.target.defaultValue || ValidityState(event.target).valid) { /* on blur, update the report when the value has changed from the * default or when the element is valid (possibly removing a still * standing invalidity report). */ reportValidity(event.target); } else if (event.type === 'keyup' && event.keyCode !== 9 || event.type === 'change') { if (ValidityState(event.target).valid) { // report instantly, when an element becomes valid, // postpone report to blur event, when an element is invalid reportValidity(event.target); } } } else if (event.type !== 'keyup' || event.keyCode !== 9) { /* do _not_ validate, when the user "tabbed" into the field initially, * i.e., a keyup event with keyCode 9 */ reportValidity(event.target); } } }, /** * install the polyfills on each given element * * If you add elements dynamically, you have to call install() on them * yourself: * * js> var form = hyperform(document.forms[0]); * js> document.forms[0].appendChild(input); * js> form.install(input); * * You can skip this, if you called hyperform on window or document. */ install: function install(els) { if (els instanceof window.Element) { els = [els]; } var els_length = els.length; for (var i = 0; i < els_length; i++) { polyfill(els[i]); } }, uninstall: function uninstall(els) { if (els instanceof window.Element) { els = [els]; } var els_length = els.length; for (var i = 0; i < els_length; i++) { polyunfill(els[i]); } } }; /** * try to get the appropriate wrapper for a specific element by looking up * its parent chain * * @return Wrapper | undefined */ function get_wrapper(element) { var wrapped; if (element.form) { /* try a shortcut with the element's <form> */ wrapped = instances.get(element.form); } /* walk up the parent nodes until document (including) */ while (!wrapped && element) { wrapped = instances.get(element); element = element.parentNode; } if (!wrapped) { /* try the global instance, if exists. This may also be undefined. */ wrapped = instances.get(window); } return wrapped; } /** * filter a form's elements for the ones needing validation prior to * a submit * * Returns an array of form elements. */ function get_validated_elements(form) { var wrapped_form = get_wrapper(form); return Array.prototype.filter.call(form.elements, function (element) { /* it must have a name (or validating nameless inputs is allowed) */ if (element.getAttribute('name') || wrapped_form && wrapped_form.settings.validateNameless) { return true; } return false; }); } /** * return either the data of a hook call or the result of action, if the * former is undefined * * @return function a function wrapper around action */ function return_hook_or (hook, action) { return function () { var data = call_hook(hook, Array.prototype.slice.call(arguments)); if (data !== undefined) { return data; } return action.apply(this, arguments); }; } /** * check an element's validity with respect to it's form */ var checkValidity = return_hook_or('checkValidity', function (element) { /* if this is a <form>, check validity of all child inputs */ if (element instanceof window.HTMLFormElement) { return get_validated_elements(element).map(checkValidity).every(function (b) { return b; }); } /* default is true, also for elements that are no validation candidates */ var valid = ValidityState(element).valid; if (valid) { var wrapped_form = get_wrapper(element); if (wrapped_form && wrapped_form.settings.validEvent) { trigger_event(element, 'valid'); } } else { trigger_event(element, 'invalid', { cancelable: true }); } return valid; }); var version = '0.10.0'; /* deprecate the old snake_case names * TODO: delme before next non-patch release */ function w(name) { var deprecated_message = 'Please use camelCase method names! The name "%s" is deprecated and will be removed in the next non-patch release.'; /* global console */ console.log(sprintf(deprecated_message, name)); } /** * public hyperform interface: */ function hyperform(form) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var classes = _ref.classes; var _ref$debug = _ref.debug; var debug = _ref$debug === undefined ? false : _ref$debug; var extend_fieldset = _ref.extend_fieldset; var extendFieldset = _ref.extendFieldset; var novalidate_on_elements = _ref.novalidate_on_elements; var novalidateOnElements = _ref.novalidateOnElements; var prevent_implicit_submit = _ref.prevent_implicit_submit; var preventImplicitSubmit = _ref.preventImplicitSubmit; var revalidate = _ref.revalidate; var _ref$strict = _ref.strict; var strict = _ref$strict === undefined ? false : _ref$strict; var valid_event = _ref.valid_event; var validEvent = _ref.validEvent; var _ref$validateNameless = _ref.validateNameless; var validateNameless = _ref$validateNameless === undefined ? false : _ref$validateNameless; if (!classes) { classes = {}; } // TODO: clean up before next non-patch release if (extendFieldset === undefined) { if (extend_fieldset === undefined) { extendFieldset = !strict; } else { w('extend_fieldset'); extendFieldset = extend_fieldset; } } if (novalidateOnElements === undefined) { if (novalidate_on_elements === undefined) { novalidateOnElements = !strict; } else { w('novalidate_on_elements'); novalidateOnElements = novalidate_on_elements; } } if (preventImplicitSubmit === undefined) { if (prevent_implicit_submit === undefined) { preventImplicitSubmit = false; } else { w('prevent_implicit_submit'); preventImplicitSubmit = prevent_implicit_submit; } } if (revalidate === undefined) { /* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */ revalidate = strict ? 'onsubmit' : 'hybrid'; } if (validEvent === undefined) { if (valid_event === undefined) { validEvent = !strict; } else { w('valid_event'); validEvent = valid_event; } } var settings = { debug: debug, strict: strict, preventImplicitSubmit: preventImplicitSubmit, revalidate: revalidate, validEvent: validEvent, extendFieldset: extendFieldset, classes: classes, novalidateOnElements: novalidateOnElements, validateNameless: validateNameless }; if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) { return Array.prototype.map.call(form, function (element) { return hyperform(element, settings); }); } return new Wrapper(form, settings); } hyperform.version = version; hyperform.checkValidity = checkValidity; hyperform.reportValidity = reportValidity; hyperform.setCustomValidity = setCustomValidity; hyperform.stepDown = stepDown; hyperform.stepUp = stepUp; hyperform.validationMessage = validationMessage; hyperform.ValidityState = ValidityState; hyperform.valueAsDate = valueAsDate; hyperform.valueAsNumber = valueAsNumber; hyperform.willValidate = willValidate; hyperform.setLanguage = function (lang) { set_language(lang);return hyperform; }; hyperform.addTranslation = function (lang, catalog) { add_translation(lang, catalog);return hyperform; }; hyperform.setRenderer = function (renderer, action) { Renderer.set(renderer, action);return hyperform; }; hyperform.addValidator = function (element, validator) { custom_validator_registry.set(element, validator);return hyperform; }; hyperform.setMessage = function (element, validator, message) { custom_messages.set(element, validator, message);return hyperform; }; hyperform.addHook = function (hook, action, position) { add_hook(hook, action, position);return hyperform; }; hyperform.removeHook = function (hook, action) { remove_hook(hook, action);return hyperform; }; // TODO: Remove in next non-patch version hyperform.set_language = function (lang) { w('set_language');set_language(lang);return hyperform; }; hyperform.add_translation = function (lang, catalog) { w('add_translation');add_translation(lang, catalog);return hyperform; }; hyperform.set_renderer = function (renderer, action) { w('set_renderer');Renderer.set(renderer, action);return hyperform; }; hyperform.add_validator = function (element, validator) { w('add_validator');custom_validator_registry.set(element, validator);return hyperform; }; hyperform.set_message = function (element, validator, message) { w('set_message');custom_messages.set(element, validator, message);return hyperform; }; hyperform.add_hook = function (hook, action, position) { w('add_hook');add_hook(hook, action, position);return hyperform; }; hyperform.remove_hook = function (hook, action) { w('remove_hook');remove_hook(hook, action);return hyperform; }; if (document.currentScript && document.currentScript.hasAttribute('data-hf-autoload')) { hyperform(window); } module.exports = hyperform;
/* Highcharts JS v5.0.7 (2017-01-17) (c) 2009-2016 Torstein Honsi License: www.highcharts.com/license */ (function(L,a){"object"===typeof module&&module.exports?module.exports=L.document?a(L):a:L.Highcharts=a(L)})("undefined"!==typeof window?window:this,function(L){L=function(){var a=window,B=a.document,A=a.navigator&&a.navigator.userAgent||"",H=B&&B.createElementNS&&!!B.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,G=/(edge|msie|trident)/i.test(A)&&!window.opera,r=!H,g=/Firefox/.test(A),f=g&&4>parseInt(A.split("Firefox/")[1],10);return a.Highcharts?a.Highcharts.error(16,!0):{product:"Highcharts", version:"5.0.7",deg2rad:2*Math.PI/360,doc:B,hasBidiBug:f,hasTouch:B&&void 0!==B.documentElement.ontouchstart,isMS:G,isWebKit:/AppleWebKit/.test(A),isFirefox:g,isTouchDevice:/(Mobile|Android|Windows Phone)/.test(A),SVG_NS:"http://www.w3.org/2000/svg",chartCount:0,seriesTypes:{},symbolSizes:{},svg:H,vml:r,win:a,charts:[],marginNames:["plotTop","marginRight","marginBottom","plotLeft"],noop:function(){}}}();(function(a){var B=[],A=a.charts,H=a.doc,G=a.win;a.error=function(r,g){r=a.isNumber(r)?"Highcharts error #"+ r+": www.highcharts.com/errors/"+r:r;if(g)throw Error(r);G.console&&console.log(r)};a.Fx=function(a,g,f){this.options=g;this.elem=a;this.prop=f};a.Fx.prototype={dSetter:function(){var a=this.paths[0],g=this.paths[1],f=[],u=this.now,l=a.length,q;if(1===u)f=this.toD;else if(l===g.length&&1>u)for(;l--;)q=parseFloat(a[l]),f[l]=isNaN(q)?a[l]:u*parseFloat(g[l]-q)+q;else f=g;this.elem.attr("d",f,null,!0)},update:function(){var a=this.elem,g=this.prop,f=this.now,u=this.options.step;if(this[g+"Setter"])this[g+ "Setter"]();else a.attr?a.element&&a.attr(g,f,null,!0):a.style[g]=f+this.unit;u&&u.call(a,f,this)},run:function(a,g,f){var r=this,l=function(a){return l.stopped?!1:r.step(a)},q;this.startTime=+new Date;this.start=a;this.end=g;this.unit=f;this.now=this.start;this.pos=0;l.elem=this.elem;l.prop=this.prop;l()&&1===B.push(l)&&(l.timerId=setInterval(function(){for(q=0;q<B.length;q++)B[q]()||B.splice(q--,1);B.length||clearInterval(l.timerId)},13))},step:function(a){var r=+new Date,f,u=this.options;f=this.elem; var l=u.complete,q=u.duration,d=u.curAnim,b;if(f.attr&&!f.element)f=!1;else if(a||r>=q+this.startTime){this.now=this.end;this.pos=1;this.update();a=d[this.prop]=!0;for(b in d)!0!==d[b]&&(a=!1);a&&l&&l.call(f);f=!1}else this.pos=u.easing((r-this.startTime)/q),this.now=this.start+(this.end-this.start)*this.pos,this.update(),f=!0;return f},initPath:function(r,g,f){function u(a){var e,b;for(n=a.length;n--;)e="M"===a[n]||"L"===a[n],b=/[a-zA-Z]/.test(a[n+3]),e&&b&&a.splice(n+1,0,a[n+1],a[n+2],a[n+1],a[n+ 2])}function l(a,e){for(;a.length<m;){a[0]=e[m-a.length];var b=a.slice(0,t);[].splice.apply(a,[0,0].concat(b));E&&(b=a.slice(a.length-t),[].splice.apply(a,[a.length,0].concat(b)),n--)}a[0]="M"}function q(a,e){for(var b=(m-a.length)/t;0<b&&b--;)c=a.slice().splice(a.length/z-t,t*z),c[0]=e[m-t-b*t],C&&(c[t-6]=c[t-2],c[t-5]=c[t-1]),[].splice.apply(a,[a.length/z,0].concat(c)),E&&b--}g=g||"";var d,b=r.startX,p=r.endX,C=-1<g.indexOf("C"),t=C?7:3,m,c,n;g=g.split(" ");f=f.slice();var E=r.isArea,z=E?2:1,e; C&&(u(g),u(f));if(b&&p){for(n=0;n<b.length;n++)if(b[n]===p[0]){d=n;break}else if(b[0]===p[p.length-b.length+n]){d=n;e=!0;break}void 0===d&&(g=[])}g.length&&a.isNumber(d)&&(m=f.length+d*z*t,e?(l(g,f),q(f,g)):(l(f,g),q(g,f)));return[g,f]}};a.extend=function(a,g){var f;a||(a={});for(f in g)a[f]=g[f];return a};a.merge=function(){var r,g=arguments,f,u={},l=function(q,d){var b,p;"object"!==typeof q&&(q={});for(p in d)d.hasOwnProperty(p)&&(b=d[p],a.isObject(b,!0)&&"renderTo"!==p&&"number"!==typeof b.nodeType? q[p]=l(q[p]||{},b):q[p]=d[p]);return q};!0===g[0]&&(u=g[1],g=Array.prototype.slice.call(g,2));f=g.length;for(r=0;r<f;r++)u=l(u,g[r]);return u};a.pInt=function(a,g){return parseInt(a,g||10)};a.isString=function(a){return"string"===typeof a};a.isArray=function(a){a=Object.prototype.toString.call(a);return"[object Array]"===a||"[object Array Iterator]"===a};a.isObject=function(r,g){return r&&"object"===typeof r&&(!g||!a.isArray(r))};a.isNumber=function(a){return"number"===typeof a&&!isNaN(a)};a.erase= function(a,g){for(var f=a.length;f--;)if(a[f]===g){a.splice(f,1);break}};a.defined=function(a){return void 0!==a&&null!==a};a.attr=function(r,g,f){var u,l;if(a.isString(g))a.defined(f)?r.setAttribute(g,f):r&&r.getAttribute&&(l=r.getAttribute(g));else if(a.defined(g)&&a.isObject(g))for(u in g)r.setAttribute(u,g[u]);return l};a.splat=function(r){return a.isArray(r)?r:[r]};a.syncTimeout=function(a,g,f){if(g)return setTimeout(a,g,f);a.call(0,f)};a.pick=function(){var a=arguments,g,f,u=a.length;for(g= 0;g<u;g++)if(f=a[g],void 0!==f&&null!==f)return f};a.css=function(r,g){a.isMS&&!a.svg&&g&&void 0!==g.opacity&&(g.filter="alpha(opacity\x3d"+100*g.opacity+")");a.extend(r.style,g)};a.createElement=function(r,g,f,u,l){r=H.createElement(r);var q=a.css;g&&a.extend(r,g);l&&q(r,{padding:0,border:"none",margin:0});f&&q(r,f);u&&u.appendChild(r);return r};a.extendClass=function(r,g){var f=function(){};f.prototype=new r;a.extend(f.prototype,g);return f};a.pad=function(a,g,f){return Array((g||2)+1-String(a).length).join(f|| 0)+a};a.relativeLength=function(a,g){return/%$/.test(a)?g*parseFloat(a)/100:parseFloat(a)};a.wrap=function(a,g,f){var r=a[g];a[g]=function(){var a=Array.prototype.slice.call(arguments),q=arguments,d=this;d.proceed=function(){r.apply(d,arguments.length?arguments:q)};a.unshift(r);a=f.apply(this,a);d.proceed=null;return a}};a.getTZOffset=function(r){var g=a.Date;return 6E4*(g.hcGetTimezoneOffset&&g.hcGetTimezoneOffset(r)||g.hcTimezoneOffset||0)};a.dateFormat=function(r,g,f){if(!a.defined(g)||isNaN(g))return a.defaultOptions.lang.invalidDate|| "";r=a.pick(r,"%Y-%m-%d %H:%M:%S");var u=a.Date,l=new u(g-a.getTZOffset(g)),q,d=l[u.hcGetHours](),b=l[u.hcGetDay](),p=l[u.hcGetDate](),C=l[u.hcGetMonth](),t=l[u.hcGetFullYear](),m=a.defaultOptions.lang,c=m.weekdays,n=m.shortWeekdays,E=a.pad,u=a.extend({a:n?n[b]:c[b].substr(0,3),A:c[b],d:E(p),e:E(p,2," "),w:b,b:m.shortMonths[C],B:m.months[C],m:E(C+1),y:t.toString().substr(2,2),Y:t,H:E(d),k:d,I:E(d%12||12),l:d%12||12,M:E(l[u.hcGetMinutes]()),p:12>d?"AM":"PM",P:12>d?"am":"pm",S:E(l.getSeconds()),L:E(Math.round(g% 1E3),3)},a.dateFormats);for(q in u)for(;-1!==r.indexOf("%"+q);)r=r.replace("%"+q,"function"===typeof u[q]?u[q](g):u[q]);return f?r.substr(0,1).toUpperCase()+r.substr(1):r};a.formatSingle=function(r,g){var f=/\.([0-9])/,u=a.defaultOptions.lang;/f$/.test(r)?(f=(f=r.match(f))?f[1]:-1,null!==g&&(g=a.numberFormat(g,f,u.decimalPoint,-1<r.indexOf(",")?u.thousandsSep:""))):g=a.dateFormat(r,g);return g};a.format=function(r,g){for(var f="{",u=!1,l,q,d,b,p=[],C;r;){f=r.indexOf(f);if(-1===f)break;l=r.slice(0, f);if(u){l=l.split(":");q=l.shift().split(".");b=q.length;C=g;for(d=0;d<b;d++)C=C[q[d]];l.length&&(C=a.formatSingle(l.join(":"),C));p.push(C)}else p.push(l);r=r.slice(f+1);f=(u=!u)?"}":"{"}p.push(r);return p.join("")};a.getMagnitude=function(a){return Math.pow(10,Math.floor(Math.log(a)/Math.LN10))};a.normalizeTickInterval=function(r,g,f,u,l){var q,d=r;f=a.pick(f,1);q=r/f;g||(g=l?[1,1.2,1.5,2,2.5,3,4,5,6,8,10]:[1,2,2.5,5,10],!1===u&&(1===f?g=a.grep(g,function(a){return 0===a%1}):.1>=f&&(g=[1/f]))); for(u=0;u<g.length&&!(d=g[u],l&&d*f>=r||!l&&q<=(g[u]+(g[u+1]||g[u]))/2);u++);return d=a.correctFloat(d*f,-Math.round(Math.log(.001)/Math.LN10))};a.stableSort=function(a,g){var f=a.length,r,l;for(l=0;l<f;l++)a[l].safeI=l;a.sort(function(a,d){r=g(a,d);return 0===r?a.safeI-d.safeI:r});for(l=0;l<f;l++)delete a[l].safeI};a.arrayMin=function(a){for(var g=a.length,f=a[0];g--;)a[g]<f&&(f=a[g]);return f};a.arrayMax=function(a){for(var g=a.length,f=a[0];g--;)a[g]>f&&(f=a[g]);return f};a.destroyObjectProperties= function(a,g){for(var f in a)a[f]&&a[f]!==g&&a[f].destroy&&a[f].destroy(),delete a[f]};a.discardElement=function(r){var g=a.garbageBin;g||(g=a.createElement("div"));r&&g.appendChild(r);g.innerHTML=""};a.correctFloat=function(a,g){return parseFloat(a.toPrecision(g||14))};a.setAnimation=function(r,g){g.renderer.globalAnimation=a.pick(r,g.options.chart.animation,!0)};a.animObject=function(r){return a.isObject(r)?a.merge(r):{duration:r?500:0}};a.timeUnits={millisecond:1,second:1E3,minute:6E4,hour:36E5, day:864E5,week:6048E5,month:24192E5,year:314496E5};a.numberFormat=function(r,g,f,u){r=+r||0;g=+g;var l=a.defaultOptions.lang,q=(r.toString().split(".")[1]||"").length,d,b;-1===g?g=Math.min(q,20):a.isNumber(g)||(g=2);b=(Math.abs(r)+Math.pow(10,-Math.max(g,q)-1)).toFixed(g);q=String(a.pInt(b));d=3<q.length?q.length%3:0;f=a.pick(f,l.decimalPoint);u=a.pick(u,l.thousandsSep);r=(0>r?"-":"")+(d?q.substr(0,d)+u:"");r+=q.substr(d).replace(/(\d{3})(?=\d)/g,"$1"+u);g&&(r+=f+b.slice(-g));return r};Math.easeInOutSine= function(a){return-.5*(Math.cos(Math.PI*a)-1)};a.getStyle=function(r,g){return"width"===g?Math.min(r.offsetWidth,r.scrollWidth)-a.getStyle(r,"padding-left")-a.getStyle(r,"padding-right"):"height"===g?Math.min(r.offsetHeight,r.scrollHeight)-a.getStyle(r,"padding-top")-a.getStyle(r,"padding-bottom"):(r=G.getComputedStyle(r,void 0))&&a.pInt(r.getPropertyValue(g))};a.inArray=function(a,g){return g.indexOf?g.indexOf(a):[].indexOf.call(g,a)};a.grep=function(a,g){return[].filter.call(a,g)};a.find=function(a, g){return[].find.call(a,g)};a.map=function(a,g){for(var f=[],u=0,l=a.length;u<l;u++)f[u]=g.call(a[u],a[u],u,a);return f};a.offset=function(a){var g=H.documentElement;a=a.getBoundingClientRect();return{top:a.top+(G.pageYOffset||g.scrollTop)-(g.clientTop||0),left:a.left+(G.pageXOffset||g.scrollLeft)-(g.clientLeft||0)}};a.stop=function(a,g){for(var f=B.length;f--;)B[f].elem!==a||g&&g!==B[f].prop||(B[f].stopped=!0)};a.each=function(a,g,f){return Array.prototype.forEach.call(a,g,f)};a.addEvent=function(r, g,f){function u(a){a.target=a.srcElement||G;f.call(r,a)}var l=r.hcEvents=r.hcEvents||{};r.addEventListener?r.addEventListener(g,f,!1):r.attachEvent&&(r.hcEventsIE||(r.hcEventsIE={}),r.hcEventsIE[f.toString()]=u,r.attachEvent("on"+g,u));l[g]||(l[g]=[]);l[g].push(f);return function(){a.removeEvent(r,g,f)}};a.removeEvent=function(r,g,f){function u(a,b){r.removeEventListener?r.removeEventListener(a,b,!1):r.attachEvent&&(b=r.hcEventsIE[b.toString()],r.detachEvent("on"+a,b))}function l(){var a,b;if(r.nodeName)for(b in g? (a={},a[g]=!0):a=d,a)if(d[b])for(a=d[b].length;a--;)u(b,d[b][a])}var q,d=r.hcEvents,b;d&&(g?(q=d[g]||[],f?(b=a.inArray(f,q),-1<b&&(q.splice(b,1),d[g]=q),u(g,f)):(l(),d[g]=[])):(l(),r.hcEvents={}))};a.fireEvent=function(r,g,f,u){var l;l=r.hcEvents;var q,d;f=f||{};if(H.createEvent&&(r.dispatchEvent||r.fireEvent))l=H.createEvent("Events"),l.initEvent(g,!0,!0),a.extend(l,f),r.dispatchEvent?r.dispatchEvent(l):r.fireEvent(g,l);else if(l)for(l=l[g]||[],q=l.length,f.target||a.extend(f,{preventDefault:function(){f.defaultPrevented= !0},target:r,type:g}),g=0;g<q;g++)(d=l[g])&&!1===d.call(r,f)&&f.preventDefault();u&&!f.defaultPrevented&&u(f)};a.animate=function(r,g,f){var u,l="",q,d,b;a.isObject(f)||(u=arguments,f={duration:u[2],easing:u[3],complete:u[4]});a.isNumber(f.duration)||(f.duration=400);f.easing="function"===typeof f.easing?f.easing:Math[f.easing]||Math.easeInOutSine;f.curAnim=a.merge(g);for(b in g)a.stop(r,b),d=new a.Fx(r,f,b),q=null,"d"===b?(d.paths=d.initPath(r,r.d,g.d),d.toD=g.d,u=0,q=1):r.attr?u=r.attr(b):(u=parseFloat(a.getStyle(r, b))||0,"opacity"!==b&&(l="px")),q||(q=g[b]),q.match&&q.match("px")&&(q=q.replace(/px/g,"")),d.run(u,q,l)};a.seriesType=function(r,g,f,u,l){var q=a.getOptions(),d=a.seriesTypes;q.plotOptions[r]=a.merge(q.plotOptions[g],f);d[r]=a.extendClass(d[g]||function(){},u);d[r].prototype.type=r;l&&(d[r].prototype.pointClass=a.extendClass(a.Point,l));return d[r]};a.uniqueKey=function(){var a=Math.random().toString(36).substring(2,9),g=0;return function(){return"highcharts-"+a+"-"+g++}}();G.jQuery&&(G.jQuery.fn.highcharts= function(){var r=[].slice.call(arguments);if(this[0])return r[0]?(new (a[a.isString(r[0])?r.shift():"Chart"])(this[0],r[0],r[1]),this):A[a.attr(this[0],"data-highcharts-chart")]});H&&!H.defaultView&&(a.getStyle=function(r,g){var f={width:"clientWidth",height:"clientHeight"}[g];if(r.style[g])return a.pInt(r.style[g]);"opacity"===g&&(g="filter");if(f)return r.style.zoom=1,Math.max(r[f]-2*a.getStyle(r,"padding"),0);r=r.currentStyle[g.replace(/\-(\w)/g,function(a,l){return l.toUpperCase()})];"filter"=== g&&(r=r.replace(/alpha\(opacity=([0-9]+)\)/,function(a,l){return l/100}));return""===r?1:a.pInt(r)});Array.prototype.forEach||(a.each=function(a,g,f){for(var u=0,l=a.length;u<l;u++)if(!1===g.call(f,a[u],u,a))return u});Array.prototype.indexOf||(a.inArray=function(a,g){var f,u=0;if(g)for(f=g.length;u<f;u++)if(g[u]===a)return u;return-1});Array.prototype.filter||(a.grep=function(a,g){for(var f=[],u=0,l=a.length;u<l;u++)g(a[u],u)&&f.push(a[u]);return f});Array.prototype.find||(a.find=function(a,g){var f, u=a.length;for(f=0;f<u;f++)if(g(a[f],f))return a[f]})})(L);(function(a){var B=a.each,A=a.isNumber,H=a.map,G=a.merge,r=a.pInt;a.Color=function(g){if(!(this instanceof a.Color))return new a.Color(g);this.init(g)};a.Color.prototype={parsers:[{regex:/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,parse:function(a){return[r(a[1]),r(a[2]),r(a[3]),parseFloat(a[4],10)]}},{regex:/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,parse:function(a){return[r(a[1], 16),r(a[2],16),r(a[3],16),1]}},{regex:/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,parse:function(a){return[r(a[1]),r(a[2]),r(a[3]),1]}}],names:{white:"#ffffff",black:"#000000"},init:function(g){var f,u,l,q;if((this.input=g=this.names[g]||g)&&g.stops)this.stops=H(g.stops,function(d){return new a.Color(d[1])});else for(l=this.parsers.length;l--&&!u;)q=this.parsers[l],(f=q.regex.exec(g))&&(u=q.parse(f));this.rgba=u||[]},get:function(a){var f=this.input,g=this.rgba,l;this.stops? (l=G(f),l.stops=[].concat(l.stops),B(this.stops,function(f,d){l.stops[d]=[l.stops[d][0],f.get(a)]})):l=g&&A(g[0])?"rgb"===a||!a&&1===g[3]?"rgb("+g[0]+","+g[1]+","+g[2]+")":"a"===a?g[3]:"rgba("+g.join(",")+")":f;return l},brighten:function(a){var f,g=this.rgba;if(this.stops)B(this.stops,function(l){l.brighten(a)});else if(A(a)&&0!==a)for(f=0;3>f;f++)g[f]+=r(255*a),0>g[f]&&(g[f]=0),255<g[f]&&(g[f]=255);return this},setOpacity:function(a){this.rgba[3]=a;return this}};a.color=function(g){return new a.Color(g)}})(L); (function(a){var B,A,H=a.addEvent,G=a.animate,r=a.attr,g=a.charts,f=a.color,u=a.css,l=a.createElement,q=a.defined,d=a.deg2rad,b=a.destroyObjectProperties,p=a.doc,C=a.each,t=a.extend,m=a.erase,c=a.grep,n=a.hasTouch,E=a.inArray,z=a.isArray,e=a.isFirefox,x=a.isMS,F=a.isObject,w=a.isString,h=a.isWebKit,y=a.merge,J=a.noop,K=a.pick,I=a.pInt,k=a.removeEvent,D=a.stop,P=a.svg,N=a.SVG_NS,S=a.symbolSizes,O=a.win;B=a.SVGElement=function(){return this};B.prototype={opacity:1,SVG_NS:N,textProps:"direction fontSize fontWeight fontFamily fontStyle color lineHeight width textDecoration textOverflow textOutline".split(" "), init:function(a,k){this.element="span"===k?l(k):p.createElementNS(this.SVG_NS,k);this.renderer=a},animate:function(v,k,e){k=a.animObject(K(k,this.renderer.globalAnimation,!0));0!==k.duration?(e&&(k.complete=e),G(this,v,k)):this.attr(v,null,e);return this},colorGradient:function(v,k,e){var b=this.renderer,h,D,c,x,M,m,n,d,F,t,p,w=[],l;v.linearGradient?D="linearGradient":v.radialGradient&&(D="radialGradient");if(D){c=v[D];M=b.gradients;n=v.stops;t=e.radialReference;z(c)&&(v[D]=c={x1:c[0],y1:c[1],x2:c[2], y2:c[3],gradientUnits:"userSpaceOnUse"});"radialGradient"===D&&t&&!q(c.gradientUnits)&&(x=c,c=y(c,b.getRadialAttr(t,x),{gradientUnits:"userSpaceOnUse"}));for(p in c)"id"!==p&&w.push(p,c[p]);for(p in n)w.push(n[p]);w=w.join(",");M[w]?t=M[w].attr("id"):(c.id=t=a.uniqueKey(),M[w]=m=b.createElement(D).attr(c).add(b.defs),m.radAttr=x,m.stops=[],C(n,function(v){0===v[1].indexOf("rgba")?(h=a.color(v[1]),d=h.get("rgb"),F=h.get("a")):(d=v[1],F=1);v=b.createElement("stop").attr({offset:v[0],"stop-color":d, "stop-opacity":F}).add(m);m.stops.push(v)}));l="url("+b.url+"#"+t+")";e.setAttribute(k,l);e.gradient=w;v.toString=function(){return l}}},applyTextOutline:function(a){var v=this.element,k,e,b,c;-1!==a.indexOf("contrast")&&(a=a.replace(/contrast/g,this.renderer.getContrast(v.style.fill)));this.fakeTS=!0;this.ySetter=this.xSetter;k=[].slice.call(v.getElementsByTagName("tspan"));a=a.split(" ");e=a[a.length-1];(b=a[0])&&"none"!==b&&(b=b.replace(/(^[\d\.]+)(.*?)$/g,function(a,v,k){return 2*v+k}),C(k,function(a){"highcharts-text-outline"=== a.getAttribute("class")&&m(k,v.removeChild(a))}),c=v.firstChild,C(k,function(a,k){0===k&&(a.setAttribute("x",v.getAttribute("x")),k=v.getAttribute("y"),a.setAttribute("y",k||0),null===k&&v.setAttribute("y",0));a=a.cloneNode(1);r(a,{"class":"highcharts-text-outline",fill:e,stroke:e,"stroke-width":b,"stroke-linejoin":"round"});v.insertBefore(a,c)}))},attr:function(a,k,e,b){var v,c=this.element,h,x=this,M;"string"===typeof a&&void 0!==k&&(v=a,a={},a[v]=k);if("string"===typeof a)x=(this[a+"Getter"]|| this._defaultGetter).call(this,a,c);else{for(v in a)k=a[v],M=!1,b||D(this,v),this.symbolName&&/^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(v)&&(h||(this.symbolAttr(a),h=!0),M=!0),!this.rotation||"x"!==v&&"y"!==v||(this.doTransform=!0),M||(M=this[v+"Setter"]||this._defaultSetter,M.call(this,k,v,c),this.shadows&&/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(v)&&this.updateShadows(v,k,M));this.doTransform&&(this.updateTransform(),this.doTransform=!1)}e&&e();return x},updateShadows:function(a, k,e){for(var v=this.shadows,b=v.length;b--;)e.call(v[b],"height"===a?Math.max(k-(v[b].cutHeight||0),0):"d"===a?this.d:k,a,v[b])},addClass:function(a,k){var v=this.attr("class")||"";-1===v.indexOf(a)&&(k||(a=(v+(v?" ":"")+a).replace(" "," ")),this.attr("class",a));return this},hasClass:function(a){return-1!==r(this.element,"class").indexOf(a)},removeClass:function(a){r(this.element,"class",(r(this.element,"class")||"").replace(a,""));return this},symbolAttr:function(a){var v=this;C("x y r start end width height innerR anchorX anchorY".split(" "), function(k){v[k]=K(a[k],v[k])});v.attr({d:v.renderer.symbols[v.symbolName](v.x,v.y,v.width,v.height,v)})},clip:function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":"none")},crisp:function(a,k){var v,e={},b;k=k||a.strokeWidth||0;b=Math.round(k)%2/2;a.x=Math.floor(a.x||this.x||0)+b;a.y=Math.floor(a.y||this.y||0)+b;a.width=Math.floor((a.width||this.width||0)-2*b);a.height=Math.floor((a.height||this.height||0)-2*b);q(a.strokeWidth)&&(a.strokeWidth=k);for(v in a)this[v]!==a[v]&& (this[v]=e[v]=a[v]);return e},css:function(a){var v=this.styles,k={},e=this.element,b,c,h="";b=!v;var D=["textOverflow","width"];a&&a.color&&(a.fill=a.color);if(v)for(c in a)a[c]!==v[c]&&(k[c]=a[c],b=!0);if(b){b=this.textWidth=a&&a.width&&"text"===e.nodeName.toLowerCase()&&I(a.width)||this.textWidth;v&&(a=t(v,k));this.styles=a;b&&!P&&this.renderer.forExport&&delete a.width;if(x&&!P)u(this.element,a);else{v=function(a,v){return"-"+v.toLowerCase()};for(c in a)-1===E(c,D)&&(h+=c.replace(/([A-Z])/g,v)+ ":"+a[c]+";");h&&r(e,"style",h)}this.added&&(b&&this.renderer.buildText(this),a&&a.textOutline&&this.applyTextOutline(a.textOutline))}return this},strokeWidth:function(){return this["stroke-width"]||0},on:function(a,k){var v=this,e=v.element;n&&"click"===a?(e.ontouchstart=function(a){v.touchEventFired=Date.now();a.preventDefault();k.call(e,a)},e.onclick=function(a){(-1===O.navigator.userAgent.indexOf("Android")||1100<Date.now()-(v.touchEventFired||0))&&k.call(e,a)}):e["on"+a]=k;return this},setRadialReference:function(a){var v= this.renderer.gradients[this.element.gradient];this.element.radialReference=a;v&&v.radAttr&&v.animate(this.renderer.getRadialAttr(a,v.radAttr));return this},translate:function(a,k){return this.attr({translateX:a,translateY:k})},invert:function(a){this.inverted=a;this.updateTransform();return this},updateTransform:function(){var a=this.translateX||0,k=this.translateY||0,e=this.scaleX,b=this.scaleY,c=this.inverted,h=this.rotation,D=this.element;c&&(a+=this.width,k+=this.height);a=["translate("+a+","+ k+")"];c?a.push("rotate(90) scale(-1,1)"):h&&a.push("rotate("+h+" "+(D.getAttribute("x")||0)+" "+(D.getAttribute("y")||0)+")");(q(e)||q(b))&&a.push("scale("+K(e,1)+" "+K(b,1)+")");a.length&&D.setAttribute("transform",a.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,k,e){var v,b,c,h,D={};b=this.renderer;c=b.alignedObjects;var x,y;if(a){if(this.alignOptions=a,this.alignByTranslate=k,!e||w(e))this.alignTo=v=e||"renderer",m(c,this),c.push(this), e=null}else a=this.alignOptions,k=this.alignByTranslate,v=this.alignTo;e=K(e,b[v],b);v=a.align;b=a.verticalAlign;c=(e.x||0)+(a.x||0);h=(e.y||0)+(a.y||0);"right"===v?x=1:"center"===v&&(x=2);x&&(c+=(e.width-(a.width||0))/x);D[k?"translateX":"x"]=Math.round(c);"bottom"===b?y=1:"middle"===b&&(y=2);y&&(h+=(e.height-(a.height||0))/y);D[k?"translateY":"y"]=Math.round(h);this[this.placed?"animate":"attr"](D);this.placed=!0;this.alignAttr=D;return this},getBBox:function(a,k){var v,e=this.renderer,b,c=this.element, h=this.styles,D,x=this.textStr,m,y=e.cache,n=e.cacheKeys,F;k=K(k,this.rotation);b=k*d;D=h&&h.fontSize;void 0!==x&&(F=x.toString(),-1===F.indexOf("\x3c")&&(F=F.replace(/[0-9]/g,"0")),F+=["",k||0,D,h&&h.width,h&&h.textOverflow].join());F&&!a&&(v=y[F]);if(!v){if(c.namespaceURI===this.SVG_NS||e.forExport){try{(m=this.fakeTS&&function(a){C(c.querySelectorAll(".highcharts-text-outline"),function(v){v.style.display=a})})&&m("none"),v=c.getBBox?t({},c.getBBox()):{width:c.offsetWidth,height:c.offsetHeight}, m&&m("")}catch(W){}if(!v||0>v.width)v={width:0,height:0}}else v=this.htmlGetBBox();e.isSVG&&(a=v.width,e=v.height,h&&"11px"===h.fontSize&&17===Math.round(e)&&(v.height=e=14),k&&(v.width=Math.abs(e*Math.sin(b))+Math.abs(a*Math.cos(b)),v.height=Math.abs(e*Math.cos(b))+Math.abs(a*Math.sin(b))));if(F&&0<v.height){for(;250<n.length;)delete y[n.shift()];y[F]||n.push(F);y[F]=v}}return v},show:function(a){return this.attr({visibility:a?"inherit":"visible"})},hide:function(){return this.attr({visibility:"hidden"})}, fadeOut:function(a){var v=this;v.animate({opacity:0},{duration:a||150,complete:function(){v.attr({y:-9999})}})},add:function(a){var v=this.renderer,k=this.element,e;a&&(this.parentGroup=a);this.parentInverted=a&&a.inverted;void 0!==this.textStr&&v.buildText(this);this.added=!0;if(!a||a.handleZ||this.zIndex)e=this.zIndexSetter();e||(a?a.element:v.box).appendChild(k);if(this.onAdd)this.onAdd();return this},safeRemoveChild:function(a){var v=a.parentNode;v&&v.removeChild(a)},destroy:function(){var a= this.element||{},k=this.renderer.isSVG&&"SPAN"===a.nodeName&&this.parentGroup,e,b;a.onclick=a.onmouseout=a.onmouseover=a.onmousemove=a.point=null;D(this);this.clipPath&&(this.clipPath=this.clipPath.destroy());if(this.stops){for(b=0;b<this.stops.length;b++)this.stops[b]=this.stops[b].destroy();this.stops=null}this.safeRemoveChild(a);for(this.destroyShadows();k&&k.div&&0===k.div.childNodes.length;)a=k.parentGroup,this.safeRemoveChild(k.div),delete k.div,k=a;this.alignTo&&m(this.renderer.alignedObjects, this);for(e in this)delete this[e];return null},shadow:function(a,k,e){var v=[],b,c,h=this.element,D,x,m,y;if(!a)this.destroyShadows();else if(!this.shadows){x=K(a.width,3);m=(a.opacity||.15)/x;y=this.parentInverted?"(-1,-1)":"("+K(a.offsetX,1)+", "+K(a.offsetY,1)+")";for(b=1;b<=x;b++)c=h.cloneNode(0),D=2*x+1-2*b,r(c,{isShadow:"true",stroke:a.color||"#000000","stroke-opacity":m*b,"stroke-width":D,transform:"translate"+y,fill:"none"}),e&&(r(c,"height",Math.max(r(c,"height")-D,0)),c.cutHeight=D),k? k.element.appendChild(c):h.parentNode.insertBefore(c,h),v.push(c);this.shadows=v}return this},destroyShadows:function(){C(this.shadows||[],function(a){this.safeRemoveChild(a)},this);this.shadows=void 0},xGetter:function(a){"circle"===this.element.nodeName&&("x"===a?a="cx":"y"===a&&(a="cy"));return this._defaultGetter(a)},_defaultGetter:function(a){a=K(this[a],this.element?this.element.getAttribute(a):null,0);/^[\-0-9\.]+$/.test(a)&&(a=parseFloat(a));return a},dSetter:function(a,k,e){a&&a.join&&(a= a.join(" "));/(NaN| {2}|^$)/.test(a)&&(a="M 0 0");e.setAttribute(k,a);this[k]=a},dashstyleSetter:function(a){var v,k=this["stroke-width"];"inherit"===k&&(k=1);if(a=a&&a.toLowerCase()){a=a.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");for(v=a.length;v--;)a[v]=I(a[v])*k;a=a.join(",").replace(/NaN/g,"none");this.element.setAttribute("stroke-dasharray", a)}},alignSetter:function(a){this.element.setAttribute("text-anchor",{left:"start",center:"middle",right:"end"}[a])},opacitySetter:function(a,k,e){this[k]=a;e.setAttribute(k,a)},titleSetter:function(a){var v=this.element.getElementsByTagName("title")[0];v||(v=p.createElementNS(this.SVG_NS,"title"),this.element.appendChild(v));v.firstChild&&v.removeChild(v.firstChild);v.appendChild(p.createTextNode(String(K(a),"").replace(/<[^>]*>/g,"")))},textSetter:function(a){a!==this.textStr&&(delete this.bBox, this.textStr=a,this.added&&this.renderer.buildText(this))},fillSetter:function(a,k,e){"string"===typeof a?e.setAttribute(k,a):a&&this.colorGradient(a,k,e)},visibilitySetter:function(a,k,e){"inherit"===a?e.removeAttribute(k):e.setAttribute(k,a)},zIndexSetter:function(a,k){var v=this.renderer,e=this.parentGroup,b=(e||v).element||v.box,c,h=this.element,D;c=this.added;var x;q(a)&&(h.zIndex=a,a=+a,this[k]===a&&(c=!1),this[k]=a);if(c){(a=this.zIndex)&&e&&(e.handleZ=!0);k=b.childNodes;for(x=0;x<k.length&& !D;x++)e=k[x],c=e.zIndex,e!==h&&(I(c)>a||!q(a)&&q(c)||0>a&&!q(c)&&b!==v.box)&&(b.insertBefore(h,e),D=!0);D||b.appendChild(h)}return D},_defaultSetter:function(a,k,e){e.setAttribute(k,a)}};B.prototype.yGetter=B.prototype.xGetter;B.prototype.translateXSetter=B.prototype.translateYSetter=B.prototype.rotationSetter=B.prototype.verticalAlignSetter=B.prototype.scaleXSetter=B.prototype.scaleYSetter=function(a,k){this[k]=a;this.doTransform=!0};B.prototype["stroke-widthSetter"]=B.prototype.strokeSetter=function(a, k,e){this[k]=a;this.stroke&&this["stroke-width"]?(B.prototype.fillSetter.call(this,this.stroke,"stroke",e),e.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0):"stroke-width"===k&&0===a&&this.hasStroke&&(e.removeAttribute("stroke"),this.hasStroke=!1)};A=a.SVGRenderer=function(){this.init.apply(this,arguments)};A.prototype={Element:B,SVG_NS:N,init:function(a,k,b,c,D,x){var v;c=this.createElement("svg").attr({version:"1.1","class":"highcharts-root"}).css(this.getStyle(c));v=c.element; a.appendChild(v);-1===a.innerHTML.indexOf("xmlns")&&r(v,"xmlns",this.SVG_NS);this.isSVG=!0;this.box=v;this.boxWrapper=c;this.alignedObjects=[];this.url=(e||h)&&p.getElementsByTagName("base").length?O.location.href.replace(/#.*?$/,"").replace(/<[^>]*>/g,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(p.createTextNode("Created with Highcharts 5.0.7"));this.defs=this.createElement("defs").add();this.allowHTML=x;this.forExport=D;this.gradients= {};this.cache={};this.cacheKeys=[];this.imgCount=0;this.setSize(k,b,!1);var m;e&&a.getBoundingClientRect&&(k=function(){u(a,{left:0,top:0});m=a.getBoundingClientRect();u(a,{left:Math.ceil(m.left)-m.left+"px",top:Math.ceil(m.top)-m.top+"px"})},k(),this.unSubPixelFix=H(O,"resize",k))},getStyle:function(a){return this.style=t({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},setStyle:function(a){this.boxWrapper.css(this.getStyle(a))},isHidden:function(){return!this.boxWrapper.getBBox().width}, destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();b(this.gradients||{});this.gradients=null;a&&(this.defs=a.destroy());this.unSubPixelFix&&this.unSubPixelFix();return this.alignedObjects=null},createElement:function(a){var k=new this.Element;k.init(this,a);return k},draw:J,getRadialAttr:function(a,k){return{cx:a[0]-a[2]/2+k.cx*a[2],cy:a[1]-a[2]/2+k.cy*a[2],r:k.r*a[2]}},buildText:function(a){var k=a.element,v=this,e=v.forExport,b=K(a.textStr,"").toString(), h=-1!==b.indexOf("\x3c"),D=k.childNodes,x,m,y,n,F=r(k,"x"),d=a.styles,t=a.textWidth,w=d&&d.lineHeight,l=d&&d.textOutline,z=d&&"ellipsis"===d.textOverflow,f=d&&"nowrap"===d.whiteSpace,E=d&&d.fontSize,q,g=D.length,d=t&&!a.added&&this.box,J=function(a){var e;e=/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize:E||v.style.fontSize||12;return w?I(w):v.fontMetrics(e,a.getAttribute("style")?a:k).h};q=[b,z,f,w,l,E,t].join();if(q!==a.textCache){for(a.textCache=q;g--;)k.removeChild(D[g]);h||l||z||t||-1!== b.indexOf(" ")?(x=/<.*class="([^"]+)".*>/,m=/<.*style="([^"]+)".*>/,y=/<.*href="(http[^"]+)".*>/,d&&d.appendChild(k),b=h?b.replace(/<(b|strong)>/g,'\x3cspan style\x3d"font-weight:bold"\x3e').replace(/<(i|em)>/g,'\x3cspan style\x3d"font-style:italic"\x3e').replace(/<a/g,"\x3cspan").replace(/<\/(b|strong|i|em|a)>/g,"\x3c/span\x3e").split(/<br.*?>/g):[b],b=c(b,function(a){return""!==a}),C(b,function(b,c){var h,D=0;b=b.replace(/^\s+|\s+$/g,"").replace(/<span/g,"|||\x3cspan").replace(/<\/span>/g,"\x3c/span\x3e|||"); h=b.split("|||");C(h,function(b){if(""!==b||1===h.length){var d={},w=p.createElementNS(v.SVG_NS,"tspan"),l,E;x.test(b)&&(l=b.match(x)[1],r(w,"class",l));m.test(b)&&(E=b.match(m)[1].replace(/(;| |^)color([ :])/,"$1fill$2"),r(w,"style",E));y.test(b)&&!e&&(r(w,"onclick",'location.href\x3d"'+b.match(y)[1]+'"'),u(w,{cursor:"pointer"}));b=(b.replace(/<(.|\n)*?>/g,"")||" ").replace(/&lt;/g,"\x3c").replace(/&gt;/g,"\x3e");if(" "!==b){w.appendChild(p.createTextNode(b));D?d.dx=0:c&&null!==F&&(d.x=F);r(w,d); k.appendChild(w);!D&&c&&(!P&&e&&u(w,{display:"block"}),r(w,"dy",J(w)));if(t){d=b.replace(/([^\^])-/g,"$1- ").split(" ");l=1<h.length||c||1<d.length&&!f;for(var q,g,M=[],C=J(w),K=a.rotation,I=b,Q=I.length;(l||z)&&(d.length||M.length);)a.rotation=0,q=a.getBBox(!0),g=q.width,!P&&v.forExport&&(g=v.measureSpanWidth(w.firstChild.data,a.styles)),q=g>t,void 0===n&&(n=q),z&&n?(Q/=2,""===I||!q&&.5>Q?d=[]:(I=b.substring(0,I.length+(q?-1:1)*Math.ceil(Q)),d=[I+(3<t?"\u2026":"")],w.removeChild(w.firstChild))): q&&1!==d.length?(w.removeChild(w.firstChild),M.unshift(d.pop())):(d=M,M=[],d.length&&!f&&(w=p.createElementNS(N,"tspan"),r(w,{dy:C,x:F}),E&&r(w,"style",E),k.appendChild(w)),g>t&&(t=g)),d.length&&w.appendChild(p.createTextNode(d.join(" ").replace(/- /g,"-")));a.rotation=K}D++}}})}),n&&a.attr("title",a.textStr),d&&d.removeChild(k),l&&a.applyTextOutline&&a.applyTextOutline(l)):k.appendChild(p.createTextNode(b.replace(/&lt;/g,"\x3c").replace(/&gt;/g,"\x3e")))}},getContrast:function(a){a=f(a).rgba;return 510< a[0]+a[1]+a[2]?"#000000":"#FFFFFF"},button:function(a,k,e,b,c,h,D,m,d){var v=this.label(a,k,e,d,null,null,null,null,"button"),n=0;v.attr(y({padding:8,r:2},c));var F,w,p,l;c=y({fill:"#f7f7f7",stroke:"#cccccc","stroke-width":1,style:{color:"#333333",cursor:"pointer",fontWeight:"normal"}},c);F=c.style;delete c.style;h=y(c,{fill:"#e6e6e6"},h);w=h.style;delete h.style;D=y(c,{fill:"#e6ebf5",style:{color:"#000000",fontWeight:"bold"}},D);p=D.style;delete D.style;m=y(c,{style:{color:"#cccccc"}},m);l=m.style; delete m.style;H(v.element,x?"mouseover":"mouseenter",function(){3!==n&&v.setState(1)});H(v.element,x?"mouseout":"mouseleave",function(){3!==n&&v.setState(n)});v.setState=function(a){1!==a&&(v.state=n=a);v.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/).addClass("highcharts-button-"+["normal","hover","pressed","disabled"][a||0]);v.attr([c,h,D,m][a||0]).css([F,w,p,l][a||0])};v.attr(c).css(t({cursor:"default"},F));return v.on("click",function(a){3!==n&&b.call(v,a)})},crispLine:function(a, k){a[1]===a[4]&&(a[1]=a[4]=Math.round(a[1])-k%2/2);a[2]===a[5]&&(a[2]=a[5]=Math.round(a[2])+k%2/2);return a},path:function(a){var k={fill:"none"};z(a)?k.d=a:F(a)&&t(k,a);return this.createElement("path").attr(k)},circle:function(a,k,e){a=F(a)?a:{x:a,y:k,r:e};k=this.createElement("circle");k.xSetter=k.ySetter=function(a,k,e){e.setAttribute("c"+k,a)};return k.attr(a)},arc:function(a,k,e,b,c,h){F(a)&&(k=a.y,e=a.r,b=a.innerR,c=a.start,h=a.end,a=a.x);a=this.symbol("arc",a||0,k||0,e||0,e||0,{innerR:b|| 0,start:c||0,end:h||0});a.r=e;return a},rect:function(a,k,e,b,c,h){c=F(a)?a.r:c;var v=this.createElement("rect");a=F(a)?a:void 0===a?{}:{x:a,y:k,width:Math.max(e,0),height:Math.max(b,0)};void 0!==h&&(a.strokeWidth=h,a=v.crisp(a));a.fill="none";c&&(a.r=c);v.rSetter=function(a,k,e){r(e,{rx:a,ry:a})};return v.attr(a)},setSize:function(a,k,e){var b=this.alignedObjects,v=b.length;this.width=a;this.height=k;for(this.boxWrapper.animate({width:a,height:k},{step:function(){this.attr({viewBox:"0 0 "+this.attr("width")+ " "+this.attr("height")})},duration:K(e,!0)?void 0:0});v--;)b[v].align()},g:function(a){var k=this.createElement("g");return a?k.attr({"class":"highcharts-"+a}):k},image:function(a,k,e,b,c){var v={preserveAspectRatio:"none"};1<arguments.length&&t(v,{x:k,y:e,width:b,height:c});v=this.createElement("image").attr(v);v.element.setAttributeNS?v.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a):v.element.setAttribute("hc-svg-href",a);return v},symbol:function(a,k,e,b,c,h){var v=this,D,x=this.symbols[a], m=q(k)&&x&&this.symbols[a](Math.round(k),Math.round(e),b,c,h),y=/^url\((.*?)\)$/,d,n;x?(D=this.path(m),D.attr("fill","none"),t(D,{symbolName:a,x:k,y:e,width:b,height:c}),h&&t(D,h)):y.test(a)&&(d=a.match(y)[1],D=this.image(d),D.imgwidth=K(S[d]&&S[d].width,h&&h.width),D.imgheight=K(S[d]&&S[d].height,h&&h.height),n=function(){D.attr({width:D.width,height:D.height})},C(["width","height"],function(a){D[a+"Setter"]=function(a,k){var e={},b=this["img"+k],v="width"===k?"translateX":"translateY";this[k]=a; q(b)&&(this.element&&this.element.setAttribute(k,b),this.alignByTranslate||(e[v]=((this[k]||0)-b)/2,this.attr(e)))}}),q(k)&&D.attr({x:k,y:e}),D.isImg=!0,q(D.imgwidth)&&q(D.imgheight)?n():(D.attr({width:0,height:0}),l("img",{onload:function(){var a=g[v.chartIndex];0===this.width&&(u(this,{position:"absolute",top:"-999em"}),p.body.appendChild(this));S[d]={width:this.width,height:this.height};D.imgwidth=this.width;D.imgheight=this.height;D.element&&n();this.parentNode&&this.parentNode.removeChild(this); v.imgCount--;if(!v.imgCount&&a&&a.onload)a.onload()},src:d}),this.imgCount++));return D},symbols:{circle:function(a,k,e,b){return this.arc(a+e/2,k+b/2,e/2,b/2,{start:0,end:2*Math.PI,open:!1})},square:function(a,k,e,b){return["M",a,k,"L",a+e,k,a+e,k+b,a,k+b,"Z"]},triangle:function(a,k,e,b){return["M",a+e/2,k,"L",a+e,k+b,a,k+b,"Z"]},"triangle-down":function(a,k,e,b){return["M",a,k,"L",a+e,k,a+e/2,k+b,"Z"]},diamond:function(a,k,e,b){return["M",a+e/2,k,"L",a+e,k+b/2,a+e/2,k+b,a,k+b/2,"Z"]},arc:function(a, k,e,b,c){var v=c.start,h=c.r||e,D=c.r||b||e,x=c.end-.001;e=c.innerR;b=c.open;var m=Math.cos(v),d=Math.sin(v),y=Math.cos(x),x=Math.sin(x);c=c.end-v<Math.PI?0:1;h=["M",a+h*m,k+D*d,"A",h,D,0,c,1,a+h*y,k+D*x];q(e)&&h.push(b?"M":"L",a+e*y,k+e*x,"A",e,e,0,c,0,a+e*m,k+e*d);h.push(b?"":"Z");return h},callout:function(a,k,e,b,c){var h=Math.min(c&&c.r||0,e,b),D=h+6,v=c&&c.anchorX;c=c&&c.anchorY;var x;x=["M",a+h,k,"L",a+e-h,k,"C",a+e,k,a+e,k,a+e,k+h,"L",a+e,k+b-h,"C",a+e,k+b,a+e,k+b,a+e-h,k+b,"L",a+h,k+b,"C", a,k+b,a,k+b,a,k+b-h,"L",a,k+h,"C",a,k,a,k,a+h,k];v&&v>e?c>k+D&&c<k+b-D?x.splice(13,3,"L",a+e,c-6,a+e+6,c,a+e,c+6,a+e,k+b-h):x.splice(13,3,"L",a+e,b/2,v,c,a+e,b/2,a+e,k+b-h):v&&0>v?c>k+D&&c<k+b-D?x.splice(33,3,"L",a,c+6,a-6,c,a,c-6,a,k+h):x.splice(33,3,"L",a,b/2,v,c,a,b/2,a,k+h):c&&c>b&&v>a+D&&v<a+e-D?x.splice(23,3,"L",v+6,k+b,v,k+b+6,v-6,k+b,a+h,k+b):c&&0>c&&v>a+D&&v<a+e-D&&x.splice(3,3,"L",v-6,k,v,k-6,v+6,k,e-h,k);return x}},clipRect:function(k,e,b,c){var h=a.uniqueKey(),D=this.createElement("clipPath").attr({id:h}).add(this.defs); k=this.rect(k,e,b,c,0).add(D);k.id=h;k.clipPath=D;k.count=0;return k},text:function(a,k,e,b){var c=!P&&this.forExport,h={};if(b&&(this.allowHTML||!this.forExport))return this.html(a,k,e);h.x=Math.round(k||0);e&&(h.y=Math.round(e));if(a||0===a)h.text=a;a=this.createElement("text").attr(h);c&&a.css({position:"absolute"});b||(a.xSetter=function(a,k,e){var b=e.getElementsByTagName("tspan"),c,h=e.getAttribute(k),D;for(D=0;D<b.length;D++)c=b[D],c.getAttribute(k)===h&&c.setAttribute(k,a);e.setAttribute(k, a)});return a},fontMetrics:function(a,k){a=a||k&&k.style&&k.style.fontSize||this.style&&this.style.fontSize;a=/px/.test(a)?I(a):/em/.test(a)?parseFloat(a)*(k?this.fontMetrics(null,k.parentNode).f:16):12;k=24>a?a+3:Math.round(1.2*a);return{h:k,b:Math.round(.8*k),f:a}},rotCorr:function(a,k,e){var b=a;k&&e&&(b=Math.max(b*Math.cos(k*d),4));return{x:-a/3*Math.sin(k*d),y:b}},label:function(a,e,b,c,h,D,x,m,d){var v=this,n=v.g("button"!==d&&"label"),F=n.text=v.text("",0,0,x).attr({zIndex:1}),w,p,l=0,z=3, E=0,f,g,J,K,P,N={},I,u,r=/^url\((.*?)\)$/.test(c),M=r,S,Q,R,O;d&&n.addClass("highcharts-"+d);M=r;S=function(){return(I||0)%2/2};Q=function(){var a=F.element.style,k={};p=(void 0===f||void 0===g||P)&&q(F.textStr)&&F.getBBox();n.width=(f||p.width||0)+2*z+E;n.height=(g||p.height||0)+2*z;u=z+v.fontMetrics(a&&a.fontSize,F).b;M&&(w||(n.box=w=v.symbols[c]||r?v.symbol(c):v.rect(),w.addClass(("button"===d?"":"highcharts-label-box")+(d?" highcharts-"+d+"-box":"")),w.add(n),a=S(),k.x=a,k.y=(m?-u:0)+a),k.width= Math.round(n.width),k.height=Math.round(n.height),w.attr(t(k,N)),N={})};R=function(){var a=E+z,k;k=m?0:u;q(f)&&p&&("center"===P||"right"===P)&&(a+={center:.5,right:1}[P]*(f-p.width));if(a!==F.x||k!==F.y)F.attr("x",a),void 0!==k&&F.attr("y",k);F.x=a;F.y=k};O=function(a,k){w?w.attr(a,k):N[a]=k};n.onAdd=function(){F.add(n);n.attr({text:a||0===a?a:"",x:e,y:b});w&&q(h)&&n.attr({anchorX:h,anchorY:D})};n.widthSetter=function(a){f=a};n.heightSetter=function(a){g=a};n["text-alignSetter"]=function(a){P=a}; n.paddingSetter=function(a){q(a)&&a!==z&&(z=n.padding=a,R())};n.paddingLeftSetter=function(a){q(a)&&a!==E&&(E=a,R())};n.alignSetter=function(a){a={left:0,center:.5,right:1}[a];a!==l&&(l=a,p&&n.attr({x:J}))};n.textSetter=function(a){void 0!==a&&F.textSetter(a);Q();R()};n["stroke-widthSetter"]=function(a,k){a&&(M=!0);I=this["stroke-width"]=a;O(k,a)};n.strokeSetter=n.fillSetter=n.rSetter=function(a,k){"fill"===k&&a&&(M=!0);O(k,a)};n.anchorXSetter=function(a,k){h=a;O(k,Math.round(a)-S()-J)};n.anchorYSetter= function(a,k){D=a;O(k,a-K)};n.xSetter=function(a){n.x=a;l&&(a-=l*((f||p.width)+2*z));J=Math.round(a);n.attr("translateX",J)};n.ySetter=function(a){K=n.y=Math.round(a);n.attr("translateY",K)};var V=n.css;return t(n,{css:function(a){if(a){var k={};a=y(a);C(n.textProps,function(e){void 0!==a[e]&&(k[e]=a[e],delete a[e])});F.css(k)}return V.call(n,a)},getBBox:function(){return{width:p.width+2*z,height:p.height+2*z,x:p.x-z,y:p.y-z}},shadow:function(a){a&&(Q(),w&&w.shadow(a));return n},destroy:function(){k(n.element, "mouseenter");k(n.element,"mouseleave");F&&(F=F.destroy());w&&(w=w.destroy());B.prototype.destroy.call(n);n=v=Q=R=O=null}})}};a.Renderer=A})(L);(function(a){var B=a.attr,A=a.createElement,H=a.css,G=a.defined,r=a.each,g=a.extend,f=a.isFirefox,u=a.isMS,l=a.isWebKit,q=a.pInt,d=a.SVGRenderer,b=a.win,p=a.wrap;g(a.SVGElement.prototype,{htmlCss:function(a){var b=this.element;if(b=a&&"SPAN"===b.tagName&&a.width)delete a.width,this.textWidth=b,this.updateTransform();a&&"ellipsis"===a.textOverflow&&(a.whiteSpace= "nowrap",a.overflow="hidden");this.styles=g(this.styles,a);H(this.element,a);return this},htmlGetBBox:function(){var a=this.element;"text"===a.nodeName&&(a.style.position="absolute");return{x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}},htmlUpdateTransform:function(){if(this.added){var a=this.renderer,b=this.element,m=this.translateX||0,c=this.translateY||0,n=this.x||0,d=this.y||0,p=this.textAlign||"left",e={left:0,center:.5,right:1}[p],x=this.styles;H(b,{marginLeft:m,marginTop:c}); this.shadows&&r(this.shadows,function(a){H(a,{marginLeft:m+1,marginTop:c+1})});this.inverted&&r(b.childNodes,function(e){a.invertChild(e,b)});if("SPAN"===b.tagName){var F=this.rotation,w=q(this.textWidth),h=x&&x.whiteSpace,y=[F,p,b.innerHTML,this.textWidth,this.textAlign].join();y!==this.cTT&&(x=a.fontMetrics(b.style.fontSize).b,G(F)&&this.setSpanRotation(F,e,x),H(b,{width:"",whiteSpace:h||"nowrap"}),b.offsetWidth>w&&/[ \-]/.test(b.textContent||b.innerText)&&H(b,{width:w+"px",display:"block",whiteSpace:h|| "normal"}),this.getSpanCorrection(b.offsetWidth,x,e,F,p));H(b,{left:n+(this.xCorr||0)+"px",top:d+(this.yCorr||0)+"px"});l&&(x=b.offsetHeight);this.cTT=y}}else this.alignOnAdd=!0},setSpanRotation:function(a,d,m){var c={},n=u?"-ms-transform":l?"-webkit-transform":f?"MozTransform":b.opera?"-o-transform":"";c[n]=c.transform="rotate("+a+"deg)";c[n+(f?"Origin":"-origin")]=c.transformOrigin=100*d+"% "+m+"px";H(this.element,c)},getSpanCorrection:function(a,b,m){this.xCorr=-a*m;this.yCorr=-b}});g(d.prototype, {html:function(a,b,m){var c=this.createElement("span"),n=c.element,d=c.renderer,l=d.isSVG,e=function(a,e){r(["opacity","visibility"],function(b){p(a,b+"Setter",function(a,b,c,x){a.call(this,b,c,x);e[c]=b})})};c.textSetter=function(a){a!==n.innerHTML&&delete this.bBox;n.innerHTML=this.textStr=a;c.htmlUpdateTransform()};l&&e(c,c.element.style);c.xSetter=c.ySetter=c.alignSetter=c.rotationSetter=function(a,e){"align"===e&&(e="textAlign");c[e]=a;c.htmlUpdateTransform()};c.attr({text:a,x:Math.round(b), y:Math.round(m)}).css({fontFamily:this.style.fontFamily,fontSize:this.style.fontSize,position:"absolute"});n.style.whiteSpace="nowrap";c.css=c.htmlCss;l&&(c.add=function(a){var b,x=d.box.parentNode,h=[];if(this.parentGroup=a){if(b=a.div,!b){for(;a;)h.push(a),a=a.parentGroup;r(h.reverse(),function(a){var n,m=B(a.element,"class");m&&(m={className:m});b=a.div=a.div||A("div",m,{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px",display:a.display,opacity:a.opacity,pointerEvents:a.styles&& a.styles.pointerEvents},b||x);n=b.style;g(a,{on:function(){c.on.apply({element:h[0].div},arguments);return a},translateXSetter:function(e,k){n.left=e+"px";a[k]=e;a.doTransform=!0},translateYSetter:function(e,k){n.top=e+"px";a[k]=e;a.doTransform=!0}});e(a,n)})}}else b=x;b.appendChild(n);c.added=!0;c.alignOnAdd&&c.htmlUpdateTransform();return c});return c}})})(L);(function(a){var B,A,H=a.createElement,G=a.css,r=a.defined,g=a.deg2rad,f=a.discardElement,u=a.doc,l=a.each,q=a.erase,d=a.extend;B=a.extendClass; var b=a.isArray,p=a.isNumber,C=a.isObject,t=a.merge;A=a.noop;var m=a.pick,c=a.pInt,n=a.SVGElement,E=a.SVGRenderer,z=a.win;a.svg||(A={docMode8:u&&8===u.documentMode,init:function(a,b){var e=["\x3c",b,' filled\x3d"f" stroked\x3d"f"'],c=["position: ","absolute",";"],h="div"===b;("shape"===b||h)&&c.push("left:0;top:0;width:1px;height:1px;");c.push("visibility: ",h?"hidden":"visible");e.push(' style\x3d"',c.join(""),'"/\x3e');b&&(e=h||"span"===b||"img"===b?e.join(""):a.prepVML(e),this.element=H(e));this.renderer= a},add:function(a){var e=this.renderer,b=this.element,c=e.box,h=a&&a.inverted,c=a?a.element||a:c;a&&(this.parentGroup=a);h&&e.invertChild(b,c);c.appendChild(b);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&&this.updateTransform();if(this.onAdd)this.onAdd();this.className&&this.attr("class",this.className);return this},updateTransform:n.prototype.htmlUpdateTransform,setSpanRotation:function(){var a=this.rotation,b=Math.cos(a*g),c=Math.sin(a*g);G(this.element,{filter:a?["progid:DXImageTransform.Microsoft.Matrix(M11\x3d", b,", M12\x3d",-c,", M21\x3d",c,", M22\x3d",b,", sizingMethod\x3d'auto expand')"].join(""):"none"})},getSpanCorrection:function(a,b,c,n,h){var e=n?Math.cos(n*g):1,x=n?Math.sin(n*g):0,d=m(this.elemHeight,this.element.offsetHeight),F;this.xCorr=0>e&&-a;this.yCorr=0>x&&-d;F=0>e*x;this.xCorr+=x*b*(F?1-c:c);this.yCorr-=e*b*(n?F?c:1-c:1);h&&"left"!==h&&(this.xCorr-=a*c*(0>e?-1:1),n&&(this.yCorr-=d*c*(0>x?-1:1)),G(this.element,{textAlign:h}))},pathToVML:function(a){for(var b=a.length,e=[];b--;)p(a[b])?e[b]= Math.round(10*a[b])-5:"Z"===a[b]?e[b]="x":(e[b]=a[b],!a.isArc||"wa"!==a[b]&&"at"!==a[b]||(e[b+5]===e[b+7]&&(e[b+7]+=a[b+7]>a[b+5]?1:-1),e[b+6]===e[b+8]&&(e[b+8]+=a[b+8]>a[b+6]?1:-1)));return e.join(" ")||"x"},clip:function(a){var b=this,e;a?(e=a.members,q(e,b),e.push(b),b.destroyClip=function(){q(e,b)},a=a.getCSS(b)):(b.destroyClip&&b.destroyClip(),a={clip:b.docMode8?"inherit":"rect(auto)"});return b.css(a)},css:n.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&f(a)},destroy:function(){this.destroyClip&& this.destroyClip();return n.prototype.destroy.apply(this)},on:function(a,b){this.element["on"+a]=function(){var a=z.event;a.target=a.srcElement;b(a)};return this},cutOffPath:function(a,b){var e;a=a.split(/[ ,]/);e=a.length;if(9===e||11===e)a[e-4]=a[e-2]=c(a[e-2])-10*b;return a.join(" ")},shadow:function(a,b,n){var e=[],h,d=this.element,x=this.renderer,p,F=d.style,k,D=d.path,l,t,z,f;D&&"string"!==typeof D.value&&(D="x");t=D;if(a){z=m(a.width,3);f=(a.opacity||.15)/z;for(h=1;3>=h;h++)l=2*z+1-2*h,n&& (t=this.cutOffPath(D.value,l+.5)),k=['\x3cshape isShadow\x3d"true" strokeweight\x3d"',l,'" filled\x3d"false" path\x3d"',t,'" coordsize\x3d"10 10" style\x3d"',d.style.cssText,'" /\x3e'],p=H(x.prepVML(k),null,{left:c(F.left)+m(a.offsetX,1),top:c(F.top)+m(a.offsetY,1)}),n&&(p.cutOff=l+1),k=['\x3cstroke color\x3d"',a.color||"#000000",'" opacity\x3d"',f*h,'"/\x3e'],H(x.prepVML(k),null,null,p),b?b.element.appendChild(p):d.parentNode.insertBefore(p,d),e.push(p);this.shadows=e}return this},updateShadows:A, setAttr:function(a,b){this.docMode8?this.element[a]=b:this.element.setAttribute(a,b)},classSetter:function(a){(this.added?this.element:this).className=a},dashstyleSetter:function(a,b,c){(c.getElementsByTagName("stroke")[0]||H(this.renderer.prepVML(["\x3cstroke/\x3e"]),null,null,c))[b]=a||"solid";this[b]=a},dSetter:function(a,b,c){var e=this.shadows;a=a||[];this.d=a.join&&a.join(" ");c.path=a=this.pathToVML(a);if(e)for(c=e.length;c--;)e[c].path=e[c].cutOff?this.cutOffPath(a,e[c].cutOff):a;this.setAttr(b, a)},fillSetter:function(a,b,c){var e=c.nodeName;"SPAN"===e?c.style.color=a:"IMG"!==e&&(c.filled="none"!==a,this.setAttr("fillcolor",this.renderer.color(a,c,b,this)))},"fill-opacitySetter":function(a,b,c){H(this.renderer.prepVML(["\x3c",b.split("-")[0],' opacity\x3d"',a,'"/\x3e']),null,null,c)},opacitySetter:A,rotationSetter:function(a,b,c){c=c.style;this[b]=c[b]=a;c.left=-Math.round(Math.sin(a*g)+1)+"px";c.top=Math.round(Math.cos(a*g))+"px"},strokeSetter:function(a,b,c){this.setAttr("strokecolor", this.renderer.color(a,c,b,this))},"stroke-widthSetter":function(a,b,c){c.stroked=!!a;this[b]=a;p(a)&&(a+="px");this.setAttr("strokeweight",a)},titleSetter:function(a,b){this.setAttr(b,a)},visibilitySetter:function(a,b,c){"inherit"===a&&(a="visible");this.shadows&&l(this.shadows,function(c){c.style[b]=a});"DIV"===c.nodeName&&(a="hidden"===a?"-999em":0,this.docMode8||(c.style[b]=a?"visible":"hidden"),b="top");c.style[b]=a},xSetter:function(a,b,c){this[b]=a;"x"===b?b="left":"y"===b&&(b="top");this.updateClipping? (this[b]=a,this.updateClipping()):c.style[b]=a},zIndexSetter:function(a,b,c){c.style[b]=a}},A["stroke-opacitySetter"]=A["fill-opacitySetter"],a.VMLElement=A=B(n,A),A.prototype.ySetter=A.prototype.widthSetter=A.prototype.heightSetter=A.prototype.xSetter,A={Element:A,isIE8:-1<z.navigator.userAgent.indexOf("MSIE 8.0"),init:function(a,b,c){var e,h;this.alignedObjects=[];e=this.createElement("div").css({position:"relative"});h=e.element;a.appendChild(e.element);this.isVML=!0;this.box=h;this.boxWrapper= e;this.gradients={};this.cache={};this.cacheKeys=[];this.imgCount=0;this.setSize(b,c,!1);if(!u.namespaces.hcv){u.namespaces.add("hcv","urn:schemas-microsoft-com:vml");try{u.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}catch(y){u.styleSheets[0].cssText+="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}}},isHidden:function(){return!this.box.offsetWidth}, clipRect:function(a,b,c,n){var e=this.createElement(),m=C(a);return d(e,{members:[],count:0,left:(m?a.x:a)+1,top:(m?a.y:b)+1,width:(m?a.width:c)-1,height:(m?a.height:n)-1,getCSS:function(a){var b=a.element,c=b.nodeName,k=a.inverted,e=this.top-("shape"===c?b.offsetTop:0),h=this.left,b=h+this.width,n=e+this.height,e={clip:"rect("+Math.round(k?h:e)+"px,"+Math.round(k?n:b)+"px,"+Math.round(k?b:n)+"px,"+Math.round(k?e:h)+"px)"};!k&&a.docMode8&&"DIV"===c&&d(e,{width:b+"px",height:n+"px"});return e},updateClipping:function(){l(e.members, function(a){a.element&&a.css(e.getCSS(a))})}})},color:function(b,c,n,m){var e=this,d,x=/^rgba/,p,t,k="none";b&&b.linearGradient?t="gradient":b&&b.radialGradient&&(t="pattern");if(t){var D,w,z=b.linearGradient||b.radialGradient,f,E,v,q,g,F="";b=b.stops;var C,u=[],r=function(){p=['\x3cfill colors\x3d"'+u.join(",")+'" opacity\x3d"',v,'" o:opacity2\x3d"',E,'" type\x3d"',t,'" ',F,'focus\x3d"100%" method\x3d"any" /\x3e'];H(e.prepVML(p),null,null,c)};f=b[0];C=b[b.length-1];0<f[0]&&b.unshift([0,f[1]]);1> C[0]&&b.push([1,C[1]]);l(b,function(k,b){x.test(k[1])?(d=a.color(k[1]),D=d.get("rgb"),w=d.get("a")):(D=k[1],w=1);u.push(100*k[0]+"% "+D);b?(v=w,q=D):(E=w,g=D)});if("fill"===n)if("gradient"===t)n=z.x1||z[0]||0,b=z.y1||z[1]||0,f=z.x2||z[2]||0,z=z.y2||z[3]||0,F='angle\x3d"'+(90-180*Math.atan((z-b)/(f-n))/Math.PI)+'"',r();else{var k=z.r,A=2*k,B=2*k,G=z.cx,U=z.cy,L=c.radialReference,T,k=function(){L&&(T=m.getBBox(),G+=(L[0]-T.x)/T.width-.5,U+=(L[1]-T.y)/T.height-.5,A*=L[2]/T.width,B*=L[2]/T.height);F= 'src\x3d"'+a.getOptions().global.VMLRadialGradientURL+'" size\x3d"'+A+","+B+'" origin\x3d"0.5,0.5" position\x3d"'+G+","+U+'" color2\x3d"'+g+'" ';r()};m.added?k():m.onAdd=k;k=q}else k=D}else x.test(b)&&"IMG"!==c.tagName?(d=a.color(b),m[n+"-opacitySetter"](d.get("a"),n,c),k=d.get("rgb")):(k=c.getElementsByTagName(n),k.length&&(k[0].opacity=1,k[0].type="solid"),k=b);return k},prepVML:function(a){var b=this.isIE8;a=a.join("");b?(a=a.replace("/\x3e",' xmlns\x3d"urn:schemas-microsoft-com:vml" /\x3e'),a= -1===a.indexOf('style\x3d"')?a.replace("/\x3e",' style\x3d"display:inline-block;behavior:url(#default#VML);" /\x3e'):a.replace('style\x3d"','style\x3d"display:inline-block;behavior:url(#default#VML);')):a=a.replace("\x3c","\x3chcv:");return a},text:E.prototype.html,path:function(a){var c={coordsize:"10 10"};b(a)?c.d=a:C(a)&&d(c,a);return this.createElement("shape").attr(c)},circle:function(a,b,c){var e=this.symbol("circle");C(a)&&(c=a.r,b=a.y,a=a.x);e.isCircle=!0;e.r=c;return e.attr({x:a,y:b})},g:function(a){var b; a&&(b={className:"highcharts-"+a,"class":"highcharts-"+a});return this.createElement("div").attr(b)},image:function(a,b,c,n,h){var e=this.createElement("img").attr({src:a});1<arguments.length&&e.attr({x:b,y:c,width:n,height:h});return e},createElement:function(a){return"rect"===a?this.symbol(a):E.prototype.createElement.call(this,a)},invertChild:function(a,b){var e=this;b=b.style;var n="IMG"===a.tagName&&a.style;G(a,{flip:"x",left:c(b.width)-(n?c(n.top):1),top:c(b.height)-(n?c(n.left):1),rotation:-90}); l(a.childNodes,function(b){e.invertChild(b,a)})},symbols:{arc:function(a,b,c,n,h){var e=h.start,m=h.end,d=h.r||c||n;c=h.innerR;n=Math.cos(e);var p=Math.sin(e),k=Math.cos(m),D=Math.sin(m);if(0===m-e)return["x"];e=["wa",a-d,b-d,a+d,b+d,a+d*n,b+d*p,a+d*k,b+d*D];h.open&&!c&&e.push("e","M",a,b);e.push("at",a-c,b-c,a+c,b+c,a+c*k,b+c*D,a+c*n,b+c*p,"x","e");e.isArc=!0;return e},circle:function(a,b,c,n,h){h&&r(h.r)&&(c=n=2*h.r);h&&h.isCircle&&(a-=c/2,b-=n/2);return["wa",a,b,a+c,b+n,a+c,b+n/2,a+c,b+n/2,"e"]}, rect:function(a,b,c,n,h){return E.prototype.symbols[r(h)&&h.r?"callout":"square"].call(0,a,b,c,n,h)}}},a.VMLRenderer=B=function(){this.init.apply(this,arguments)},B.prototype=t(E.prototype,A),a.Renderer=B);E.prototype.measureSpanWidth=function(a,b){var c=u.createElement("span");a=u.createTextNode(a);c.appendChild(a);G(c,b);this.box.appendChild(c);b=c.offsetWidth;f(c);return b}})(L);(function(a){function B(){var l=a.defaultOptions.global,f=u.moment;if(l.timezone){if(f)return function(a){return-f.tz(a, l.timezone).utcOffset()};a.error(25)}return l.useUTC&&l.getTimezoneOffset}function A(){var l=a.defaultOptions.global,q,d=l.useUTC,b=d?"getUTC":"get",p=d?"setUTC":"set";a.Date=q=l.Date||u.Date;q.hcTimezoneOffset=d&&l.timezoneOffset;q.hcGetTimezoneOffset=B();q.hcMakeTime=function(a,b,m,c,n,p){var l;d?(l=q.UTC.apply(0,arguments),l+=r(l)):l=(new q(a,b,f(m,1),f(c,0),f(n,0),f(p,0))).getTime();return l};G("Minutes Hours Day Date Month FullYear".split(" "),function(a){q["hcGet"+a]=b+a});G("Milliseconds Seconds Minutes Hours Date Month FullYear".split(" "), function(a){q["hcSet"+a]=p+a})}var H=a.color,G=a.each,r=a.getTZOffset,g=a.merge,f=a.pick,u=a.win;a.defaultOptions={colors:"#7cb5ec #434348 #90ed7d #f7a35c #8085e9 #f15c80 #e4d354 #2b908f #f45b5b #91e8e1".split(" "),symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January February March April May June July August September October November December".split(" "),shortMonths:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),weekdays:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), decimalPoint:".",numericSymbols:"kMGTPE".split(""),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:" "},global:{useUTC:!0,VMLRadialGradientURL:"http://code.highcharts.com/5.0.7/gfx/vml-radial-gradient.png"},chart:{borderRadius:0,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],resetZoomButton:{theme:{zIndex:20},position:{align:"right",x:-10,y:10}},width:null,height:null,borderColor:"#335cad",backgroundColor:"#ffffff",plotBorderColor:"#cccccc"},title:{text:"Chart title", align:"center",margin:15,widthAdjust:-44},subtitle:{text:"",align:"center",widthAdjust:-44},plotOptions:{},labels:{style:{position:"absolute",color:"#333333"}},legend:{enabled:!0,align:"center",layout:"horizontal",labelFormatter:function(){return this.name},borderColor:"#999999",borderRadius:0,navigation:{activeColor:"#003399",inactiveColor:"#cccccc"},itemStyle:{color:"#333333",fontSize:"12px",fontWeight:"bold"},itemHoverStyle:{color:"#000000"},itemHiddenStyle:{color:"#cccccc"},shadow:!1,itemCheckboxStyle:{position:"absolute", width:"13px",height:"13px"},squareSymbol:!0,symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"#ffffff",opacity:.5,textAlign:"center"}},tooltip:{enabled:!0,animation:a.svg,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y", month:"%B %Y",year:"%Y"},footerFormat:"",padding:8,snap:a.isTouchDevice?25:10,backgroundColor:H("#f7f7f7").setOpacity(.85).get(),borderWidth:1,headerFormat:'\x3cspan style\x3d"font-size: 10px"\x3e{point.key}\x3c/span\x3e\x3cbr/\x3e',pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e {series.name}: \x3cb\x3e{point.y}\x3c/b\x3e\x3cbr/\x3e',shadow:!0,style:{color:"#333333",cursor:"default",fontSize:"12px",pointerEvents:"none",whiteSpace:"nowrap"}},credits:{enabled:!0,href:"http://www.highcharts.com", position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#999999",fontSize:"9px"},text:"Highcharts.com"}};a.setOptions=function(l){a.defaultOptions=g(!0,a.defaultOptions,l);A();return a.defaultOptions};a.getOptions=function(){return a.defaultOptions};a.defaultPlotOptions=a.defaultOptions.plotOptions;A()})(L);(function(a){var B=a.arrayMax,A=a.arrayMin,H=a.defined,G=a.destroyObjectProperties,r=a.each,g=a.erase,f=a.merge,u=a.pick;a.PlotLineOrBand=function(a,f){this.axis= a;f&&(this.options=f,this.id=f.id)};a.PlotLineOrBand.prototype={render:function(){var a=this,q=a.axis,d=q.horiz,b=a.options,p=b.label,g=a.label,t=b.to,m=b.from,c=b.value,n=H(m)&&H(t),E=H(c),z=a.svgElem,e=!z,x=[],F,w=b.color,h=u(b.zIndex,0),y=b.events,x={"class":"highcharts-plot-"+(n?"band ":"line ")+(b.className||"")},J={},K=q.chart.renderer,I=n?"bands":"lines",k=q.log2lin;q.isLog&&(m=k(m),t=k(t),c=k(c));E?(x={stroke:w,"stroke-width":b.width},b.dashStyle&&(x.dashstyle=b.dashStyle)):n&&(w&&(x.fill= w),b.borderWidth&&(x.stroke=b.borderColor,x["stroke-width"]=b.borderWidth));J.zIndex=h;I+="-"+h;(w=q[I])||(q[I]=w=K.g("plot-"+I).attr(J).add());e&&(a.svgElem=z=K.path().attr(x).add(w));if(E)x=q.getPlotLinePath(c,z.strokeWidth());else if(n)x=q.getPlotBandPath(m,t,b);else return;if(e&&x&&x.length){if(z.attr({d:x}),y)for(F in b=function(b){z.on(b,function(k){y[b].apply(a,[k])})},y)b(F)}else z&&(x?(z.show(),z.animate({d:x})):(z.hide(),g&&(a.label=g=g.destroy())));p&&H(p.text)&&x&&x.length&&0<q.width&& 0<q.height&&!x.flat?(p=f({align:d&&n&&"center",x:d?!n&&4:10,verticalAlign:!d&&n&&"middle",y:d?n?16:10:n?6:-4,rotation:d&&!n&&90},p),this.renderLabel(p,x,n,h)):g&&g.hide();return a},renderLabel:function(a,f,d,b){var p=this.label,l=this.axis.chart.renderer;p||(p={align:a.textAlign||a.align,rotation:a.rotation,"class":"highcharts-plot-"+(d?"band":"line")+"-label "+(a.className||"")},p.zIndex=b,this.label=p=l.text(a.text,0,0,a.useHTML).attr(p).add(),p.css(a.style));b=[f[1],f[4],d?f[6]:f[1]];f=[f[2],f[5], d?f[7]:f[2]];d=A(b);l=A(f);p.align(a,!1,{x:d,y:l,width:B(b)-d,height:B(f)-l});p.show()},destroy:function(){g(this.axis.plotLinesAndBands,this);delete this.axis;G(this)}};a.AxisPlotLineOrBandExtension={getPlotBandPath:function(a,f){f=this.getPlotLinePath(f,null,null,!0);(a=this.getPlotLinePath(a,null,null,!0))&&f?(a.flat=a.toString()===f.toString(),a.push(f[4],f[5],f[1],f[2],"z")):a=null;return a},addPlotBand:function(a){return this.addPlotBandOrLine(a,"plotBands")},addPlotLine:function(a){return this.addPlotBandOrLine(a, "plotLines")},addPlotBandOrLine:function(f,g){var d=(new a.PlotLineOrBand(this,f)).render(),b=this.userOptions;d&&(g&&(b[g]=b[g]||[],b[g].push(f)),this.plotLinesAndBands.push(d));return d},removePlotBandOrLine:function(a){for(var f=this.plotLinesAndBands,d=this.options,b=this.userOptions,p=f.length;p--;)f[p].id===a&&f[p].destroy();r([d.plotLines||[],b.plotLines||[],d.plotBands||[],b.plotBands||[]],function(b){for(p=b.length;p--;)b[p].id===a&&g(b,b[p])})}}})(L);(function(a){var B=a.correctFloat,A= a.defined,H=a.destroyObjectProperties,G=a.isNumber,r=a.merge,g=a.pick,f=a.deg2rad;a.Tick=function(a,f,g,d){this.axis=a;this.pos=f;this.type=g||"";this.isNew=!0;g||d||this.addLabel()};a.Tick.prototype={addLabel:function(){var a=this.axis,f=a.options,q=a.chart,d=a.categories,b=a.names,p=this.pos,C=f.labels,t=a.tickPositions,m=p===t[0],c=p===t[t.length-1],b=d?g(d[p],b[p],p):p,d=this.label,t=t.info,n;a.isDatetimeAxis&&t&&(n=f.dateTimeLabelFormats[t.higherRanks[p]||t.unitName]);this.isFirst=m;this.isLast= c;f=a.labelFormatter.call({axis:a,chart:q,isFirst:m,isLast:c,dateTimeLabelFormat:n,value:a.isLog?B(a.lin2log(b)):b});A(d)?d&&d.attr({text:f}):(this.labelLength=(this.label=d=A(f)&&C.enabled?q.renderer.text(f,0,0,C.useHTML).css(r(C.style)).add(a.labelGroup):null)&&d.getBBox().width,this.rotation=0)},getLabelSize:function(){return this.label?this.label.getBBox()[this.axis.horiz?"height":"width"]:0},handleOverflow:function(a){var l=this.axis,q=a.x,d=l.chart.chartWidth,b=l.chart.spacing,p=g(l.labelLeft, Math.min(l.pos,b[3])),b=g(l.labelRight,Math.max(l.pos+l.len,d-b[1])),C=this.label,t=this.rotation,m={left:0,center:.5,right:1}[l.labelAlign],c=C.getBBox().width,n=l.getSlotWidth(),E=n,z=1,e,x={};if(t)0>t&&q-m*c<p?e=Math.round(q/Math.cos(t*f)-p):0<t&&q+m*c>b&&(e=Math.round((d-q)/Math.cos(t*f)));else if(d=q+(1-m)*c,q-m*c<p?E=a.x+E*(1-m)-p:d>b&&(E=b-a.x+E*m,z=-1),E=Math.min(n,E),E<n&&"center"===l.labelAlign&&(a.x+=z*(n-E-m*(n-Math.min(c,E)))),c>E||l.autoRotation&&(C.styles||{}).width)e=E;e&&(x.width= e,(l.options.labels.style||{}).textOverflow||(x.textOverflow="ellipsis"),C.css(x))},getPosition:function(a,f,g,d){var b=this.axis,p=b.chart,l=d&&p.oldChartHeight||p.chartHeight;return{x:a?b.translate(f+g,null,null,d)+b.transB:b.left+b.offset+(b.opposite?(d&&p.oldChartWidth||p.chartWidth)-b.right-b.left:0),y:a?l-b.bottom+b.offset-(b.opposite?b.height:0):l-b.translate(f+g,null,null,d)-b.transB}},getLabelPosition:function(a,g,q,d,b,p,C,t){var m=this.axis,c=m.transA,n=m.reversed,E=m.staggerLines,z=m.tickRotCorr|| {x:0,y:0},e=b.y;A(e)||(e=0===m.side?q.rotation?-8:-q.getBBox().height:2===m.side?z.y+8:Math.cos(q.rotation*f)*(z.y-q.getBBox(!1,0).height/2));a=a+b.x+z.x-(p&&d?p*c*(n?-1:1):0);g=g+e-(p&&!d?p*c*(n?1:-1):0);E&&(q=C/(t||1)%E,m.opposite&&(q=E-q-1),g+=m.labelOffset/E*q);return{x:a,y:Math.round(g)}},getMarkPath:function(a,f,g,d,b,p){return p.crispLine(["M",a,f,"L",a+(b?0:-g),f+(b?g:0)],d)},render:function(a,f,q){var d=this.axis,b=d.options,p=d.chart.renderer,l=d.horiz,t=this.type,m=this.label,c=this.pos, n=b.labels,E=this.gridLine,z=t?t+"Tick":"tick",e=d.tickSize(z),x=this.mark,F=!x,w=n.step,h={},y=!0,J=d.tickmarkOffset,K=this.getPosition(l,c,J,f),I=K.x,K=K.y,k=l&&I===d.pos+d.len||!l&&K===d.pos?-1:1,D=t?t+"Grid":"grid",P=b[D+"LineWidth"],N=b[D+"LineColor"],r=b[D+"LineDashStyle"],D=g(b[z+"Width"],!t&&d.isXAxis?1:0),z=b[z+"Color"];q=g(q,1);this.isActive=!0;E||(h.stroke=N,h["stroke-width"]=P,r&&(h.dashstyle=r),t||(h.zIndex=1),f&&(h.opacity=0),this.gridLine=E=p.path().attr(h).addClass("highcharts-"+(t? t+"-":"")+"grid-line").add(d.gridGroup));if(!f&&E&&(c=d.getPlotLinePath(c+J,E.strokeWidth()*k,f,!0)))E[this.isNew?"attr":"animate"]({d:c,opacity:q});e&&(d.opposite&&(e[0]=-e[0]),F&&(this.mark=x=p.path().addClass("highcharts-"+(t?t+"-":"")+"tick").add(d.axisGroup),x.attr({stroke:z,"stroke-width":D})),x[F?"attr":"animate"]({d:this.getMarkPath(I,K,e[0],x.strokeWidth()*k,l,p),opacity:q}));m&&G(I)&&(m.xy=K=this.getLabelPosition(I,K,m,l,n,J,a,w),this.isFirst&&!this.isLast&&!g(b.showFirstLabel,1)||this.isLast&& !this.isFirst&&!g(b.showLastLabel,1)?y=!1:!l||d.isRadial||n.step||n.rotation||f||0===q||this.handleOverflow(K),w&&a%w&&(y=!1),y&&G(K.y)?(K.opacity=q,m[this.isNew?"attr":"animate"](K)):m.attr("y",-9999),this.isNew=!1)},destroy:function(){H(this,this.axis)}}})(L);(function(a){var B=a.addEvent,A=a.animObject,H=a.arrayMax,G=a.arrayMin,r=a.AxisPlotLineOrBandExtension,g=a.color,f=a.correctFloat,u=a.defaultOptions,l=a.defined,q=a.deg2rad,d=a.destroyObjectProperties,b=a.each,p=a.extend,C=a.fireEvent,t=a.format, m=a.getMagnitude,c=a.grep,n=a.inArray,E=a.isArray,z=a.isNumber,e=a.isString,x=a.merge,F=a.normalizeTickInterval,w=a.pick,h=a.PlotLineOrBand,y=a.removeEvent,J=a.splat,K=a.syncTimeout,I=a.Tick;a.Axis=function(){this.init.apply(this,arguments)};a.Axis.prototype={defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,labels:{enabled:!0,style:{color:"#666666",cursor:"default",fontSize:"11px"}, x:0},minPadding:.01,maxPadding:.01,minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickLength:10,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",title:{align:"middle",style:{color:"#666666"}},type:"linear",minorGridLineColor:"#f2f2f2",minorGridLineWidth:1,minorTickColor:"#999999",lineColor:"#ccd6eb",lineWidth:1,gridLineColor:"#e6e6e6",tickColor:"#ccd6eb"},defaultYAxisOptions:{endOnTick:!0,tickPixelInterval:72,showLastLabel:!0,labels:{x:-8},maxPadding:.05, minPadding:.05,startOnTick:!0,title:{rotation:270,text:"Values"},stackLabels:{enabled:!1,formatter:function(){return a.numberFormat(this.total,-1)},style:{fontSize:"11px",fontWeight:"bold",color:"#000000",textOutline:"1px contrast"}},gridLineWidth:1,lineWidth:0},defaultLeftAxisOptions:{labels:{x:-15},title:{rotation:270}},defaultRightAxisOptions:{labels:{x:15},title:{rotation:90}},defaultBottomAxisOptions:{labels:{autoRotation:[-45],x:0},title:{rotation:0}},defaultTopAxisOptions:{labels:{autoRotation:[-45], x:0},title:{rotation:0}},init:function(a,b){var k=b.isX;this.chart=a;this.horiz=a.inverted?!k:k;this.isXAxis=k;this.coll=this.coll||(k?"xAxis":"yAxis");this.opposite=b.opposite;this.side=b.side||(this.horiz?this.opposite?0:2:this.opposite?1:3);this.setOptions(b);var c=this.options,e=c.type;this.labelFormatter=c.labels.formatter||this.defaultLabelFormatter;this.userOptions=b;this.minPixelPadding=0;this.reversed=c.reversed;this.visible=!1!==c.visible;this.zoomEnabled=!1!==c.zoomEnabled;this.hasNames= "category"===e||!0===c.categories;this.categories=c.categories||this.hasNames;this.names=this.names||[];this.isLog="logarithmic"===e;this.isDatetimeAxis="datetime"===e;this.isLinked=l(c.linkedTo);this.ticks={};this.labelEdge=[];this.minorTicks={};this.plotLinesAndBands=[];this.alternateBands={};this.len=0;this.minRange=this.userMinRange=c.minRange||c.maxZoom;this.range=c.range;this.offset=c.offset||0;this.stacks={};this.oldStacks={};this.stacksTouched=0;this.min=this.max=null;this.crosshair=w(c.crosshair, J(a.options.tooltip.crosshairs)[k?0:1],!1);var h;b=this.options.events;-1===n(this,a.axes)&&(k?a.axes.splice(a.xAxis.length,0,this):a.axes.push(this),a[this.coll].push(this));this.series=this.series||[];a.inverted&&k&&void 0===this.reversed&&(this.reversed=!0);this.removePlotLine=this.removePlotBand=this.removePlotBandOrLine;for(h in b)B(this,h,b[h]);this.isLog&&(this.val2lin=this.log2lin,this.lin2val=this.lin2log)},setOptions:function(a){this.options=x(this.defaultOptions,"yAxis"===this.coll&&this.defaultYAxisOptions, [this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],x(u[this.coll],a))},defaultLabelFormatter:function(){var b=this.axis,c=this.value,e=b.categories,h=this.dateTimeLabelFormat,n=u.lang,d=n.numericSymbols,n=n.numericSymbolMagnitude||1E3,v=d&&d.length,m,f=b.options.labels.format,b=b.isLog?c:b.tickInterval;if(f)m=t(f,this);else if(e)m=c;else if(h)m=a.dateFormat(h,c);else if(v&&1E3<=b)for(;v--&&void 0===m;)e=Math.pow(n,v+1),b>= e&&0===10*c%e&&null!==d[v]&&0!==c&&(m=a.numberFormat(c/e,-1)+d[v]);void 0===m&&(m=1E4<=Math.abs(c)?a.numberFormat(c,-1):a.numberFormat(c,-1,void 0,""));return m},getSeriesExtremes:function(){var a=this,e=a.chart;a.hasVisibleSeries=!1;a.dataMin=a.dataMax=a.threshold=null;a.softThreshold=!a.isXAxis;a.buildStacks&&a.buildStacks();b(a.series,function(b){if(b.visible||!e.options.chart.ignoreHiddenSeries){var k=b.options,h=k.threshold,D;a.hasVisibleSeries=!0;a.isLog&&0>=h&&(h=null);if(a.isXAxis)k=b.xData, k.length&&(b=G(k),z(b)||b instanceof Date||(k=c(k,function(a){return z(a)}),b=G(k)),a.dataMin=Math.min(w(a.dataMin,k[0]),b),a.dataMax=Math.max(w(a.dataMax,k[0]),H(k)));else if(b.getExtremes(),D=b.dataMax,b=b.dataMin,l(b)&&l(D)&&(a.dataMin=Math.min(w(a.dataMin,b),b),a.dataMax=Math.max(w(a.dataMax,D),D)),l(h)&&(a.threshold=h),!k.softThreshold||a.isLog)a.softThreshold=!1}})},translate:function(a,b,c,e,h,n){var k=this.linkedParent||this,D=1,m=0,d=e?k.oldTransA:k.transA;e=e?k.oldMin:k.min;var f=k.minPixelPadding; h=(k.isOrdinal||k.isBroken||k.isLog&&h)&&k.lin2val;d||(d=k.transA);c&&(D*=-1,m=k.len);k.reversed&&(D*=-1,m-=D*(k.sector||k.len));b?(a=(a*D+m-f)/d+e,h&&(a=k.lin2val(a))):(h&&(a=k.val2lin(a)),a=D*(a-e)*d+m+D*f+(z(n)?d*n:0));return a},toPixels:function(a,b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a-(b?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a,b,c,e,h){var k=this.chart,D=this.left,n=this.top,m,d,f=c&&k.oldChartHeight|| k.chartHeight,p=c&&k.oldChartWidth||k.chartWidth,y;m=this.transB;var t=function(a,b,k){if(a<b||a>k)e?a=Math.min(Math.max(b,a),k):y=!0;return a};h=w(h,this.translate(a,null,null,c));a=c=Math.round(h+m);m=d=Math.round(f-h-m);z(h)?this.horiz?(m=n,d=f-this.bottom,a=c=t(a,D,D+this.width)):(a=D,c=p-this.right,m=d=t(m,n,n+this.height)):y=!0;return y&&!e?null:k.renderer.crispLine(["M",a,m,"L",c,d],b||1)},getLinearTickPositions:function(a,b,c){var k,e=f(Math.floor(b/a)*a),h=f(Math.ceil(c/a)*a),D=[];if(b=== c&&z(b))return[b];for(b=e;b<=h;){D.push(b);b=f(b+a);if(b===k)break;k=b}return D},getMinorTickPositions:function(){var a=this.options,b=this.tickPositions,c=this.minorTickInterval,e=[],h,n=this.pointRangePadding||0;h=this.min-n;var n=this.max+n,m=n-h;if(m&&m/c<this.len/3)if(this.isLog)for(n=b.length,h=1;h<n;h++)e=e.concat(this.getLogTickPositions(c,b[h-1],b[h],!0));else if(this.isDatetimeAxis&&"auto"===a.minorTickInterval)e=e.concat(this.getTimeTicks(this.normalizeTimeTickInterval(c),h,n,a.startOfWeek)); else for(b=h+(b[0]-h)%c;b<=n&&b!==e[0];b+=c)e.push(b);0!==e.length&&this.trimTicks(e,a.startOnTick,a.endOnTick);return e},adjustForMinRange:function(){var a=this.options,c=this.min,e=this.max,h,n=this.dataMax-this.dataMin>=this.minRange,m,v,d,f,p,y;this.isXAxis&&void 0===this.minRange&&!this.isLog&&(l(a.min)||l(a.max)?this.minRange=null:(b(this.series,function(a){f=a.xData;for(v=p=a.xIncrement?1:f.length-1;0<v;v--)if(d=f[v]-f[v-1],void 0===m||d<m)m=d}),this.minRange=Math.min(5*m,this.dataMax-this.dataMin))); e-c<this.minRange&&(y=this.minRange,h=(y-e+c)/2,h=[c-h,w(a.min,c-h)],n&&(h[2]=this.isLog?this.log2lin(this.dataMin):this.dataMin),c=H(h),e=[c+y,w(a.max,c+y)],n&&(e[2]=this.isLog?this.log2lin(this.dataMax):this.dataMax),e=G(e),e-c<y&&(h[0]=e-y,h[1]=w(a.min,e-y),c=H(h)));this.min=c;this.max=e},getClosest:function(){var a;this.categories?a=1:b(this.series,function(b){var k=b.closestPointRange,c=b.visible||!b.chart.options.chart.ignoreHiddenSeries;!b.noSharedTooltip&&l(k)&&c&&(a=l(a)?Math.min(a,k):k)}); return a},nameToX:function(a){var b=E(this.categories),k=b?this.categories:this.names,c=a.options.x,e;a.series.requireSorting=!1;l(c)||(c=!1===this.options.uniqueNames?a.series.autoIncrement():n(a.name,k));-1===c?b||(e=k.length):e=c;this.names[e]=a.name;return e},updateNames:function(){var a=this;0<this.names.length&&(this.names.length=0,this.minRange=void 0,b(this.series||[],function(k){k.xIncrement=null;if(!k.points||k.isDirtyData)k.processData(),k.generatePoints();b(k.points,function(b,c){var e; b.options&&(e=a.nameToX(b),e!==b.x&&(b.x=e,k.xData[c]=e))})}))},setAxisTranslation:function(a){var k=this,c=k.max-k.min,h=k.axisPointRange||0,n,m=0,d=0,f=k.linkedParent,y=!!k.categories,p=k.transA,t=k.isXAxis;if(t||y||h)n=k.getClosest(),f?(m=f.minPointOffset,d=f.pointRangePadding):b(k.series,function(a){var b=y?1:t?w(a.options.pointRange,n,0):k.axisPointRange||0;a=a.options.pointPlacement;h=Math.max(h,b);k.single||(m=Math.max(m,e(a)?0:b/2),d=Math.max(d,"on"===a?0:b))}),f=k.ordinalSlope&&n?k.ordinalSlope/ n:1,k.minPointOffset=m*=f,k.pointRangePadding=d*=f,k.pointRange=Math.min(h,c),t&&(k.closestPointRange=n);a&&(k.oldTransA=p);k.translationSlope=k.transA=p=k.len/(c+d||1);k.transB=k.horiz?k.left:k.bottom;k.minPixelPadding=p*m},minFromRange:function(){return this.max-this.range},setTickInterval:function(k){var c=this,e=c.chart,h=c.options,n=c.isLog,d=c.log2lin,v=c.isDatetimeAxis,y=c.isXAxis,p=c.isLinked,t=h.maxPadding,x=h.minPadding,g=h.tickInterval,E=h.tickPixelInterval,q=c.categories,J=c.threshold, K=c.softThreshold,I,r,u,A;v||q||p||this.getTickAmount();u=w(c.userMin,h.min);A=w(c.userMax,h.max);p?(c.linkedParent=e[c.coll][h.linkedTo],e=c.linkedParent.getExtremes(),c.min=w(e.min,e.dataMin),c.max=w(e.max,e.dataMax),h.type!==c.linkedParent.options.type&&a.error(11,1)):(!K&&l(J)&&(c.dataMin>=J?(I=J,x=0):c.dataMax<=J&&(r=J,t=0)),c.min=w(u,I,c.dataMin),c.max=w(A,r,c.dataMax));n&&(!k&&0>=Math.min(c.min,w(c.dataMin,c.min))&&a.error(10,1),c.min=f(d(c.min),15),c.max=f(d(c.max),15));c.range&&l(c.max)&& (c.userMin=c.min=u=Math.max(c.min,c.minFromRange()),c.userMax=A=c.max,c.range=null);C(c,"foundExtremes");c.beforePadding&&c.beforePadding();c.adjustForMinRange();!(q||c.axisPointRange||c.usePercentage||p)&&l(c.min)&&l(c.max)&&(d=c.max-c.min)&&(!l(u)&&x&&(c.min-=d*x),!l(A)&&t&&(c.max+=d*t));z(h.floor)?c.min=Math.max(c.min,h.floor):z(h.softMin)&&(c.min=Math.min(c.min,h.softMin));z(h.ceiling)?c.max=Math.min(c.max,h.ceiling):z(h.softMax)&&(c.max=Math.max(c.max,h.softMax));K&&l(c.dataMin)&&(J=J||0,!l(u)&& c.min<J&&c.dataMin>=J?c.min=J:!l(A)&&c.max>J&&c.dataMax<=J&&(c.max=J));c.tickInterval=c.min===c.max||void 0===c.min||void 0===c.max?1:p&&!g&&E===c.linkedParent.options.tickPixelInterval?g=c.linkedParent.tickInterval:w(g,this.tickAmount?(c.max-c.min)/Math.max(this.tickAmount-1,1):void 0,q?1:(c.max-c.min)*E/Math.max(c.len,E));y&&!k&&b(c.series,function(a){a.processData(c.min!==c.oldMin||c.max!==c.oldMax)});c.setAxisTranslation(!0);c.beforeSetTickPositions&&c.beforeSetTickPositions();c.postProcessTickInterval&& (c.tickInterval=c.postProcessTickInterval(c.tickInterval));c.pointRange&&!g&&(c.tickInterval=Math.max(c.pointRange,c.tickInterval));k=w(h.minTickInterval,c.isDatetimeAxis&&c.closestPointRange);!g&&c.tickInterval<k&&(c.tickInterval=k);v||n||g||(c.tickInterval=F(c.tickInterval,null,m(c.tickInterval),w(h.allowDecimals,!(.5<c.tickInterval&&5>c.tickInterval&&1E3<c.max&&9999>c.max)),!!this.tickAmount));this.tickAmount||(c.tickInterval=c.unsquish());this.setTickPositions()},setTickPositions:function(){var a= this.options,b,c=a.tickPositions,e=a.tickPositioner,h=a.startOnTick,n=a.endOnTick,m;this.tickmarkOffset=this.categories&&"between"===a.tickmarkPlacement&&1===this.tickInterval?.5:0;this.minorTickInterval="auto"===a.minorTickInterval&&this.tickInterval?this.tickInterval/5:a.minorTickInterval;this.tickPositions=b=c&&c.slice();!b&&(b=this.isDatetimeAxis?this.getTimeTicks(this.normalizeTimeTickInterval(this.tickInterval,a.units),this.min,this.max,a.startOfWeek,this.ordinalPositions,this.closestPointRange, !0):this.isLog?this.getLogTickPositions(this.tickInterval,this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max),b.length>this.len&&(b=[b[0],b.pop()]),this.tickPositions=b,e&&(e=e.apply(this,[this.min,this.max])))&&(this.tickPositions=b=e);this.trimTicks(b,h,n);this.isLinked||(this.min===this.max&&l(this.min)&&!this.tickAmount&&(m=!0,this.min-=.5,this.max+=.5),this.single=m,c||e||this.adjustTickAmount())},trimTicks:function(a,b,c){var k=a[0],e=a[a.length-1],h=this.minPointOffset|| 0;if(!this.isLinked){if(b)this.min=k;else for(;this.min-h>a[0];)a.shift();if(c)this.max=e;else for(;this.max+h<a[a.length-1];)a.pop();0===a.length&&l(k)&&a.push((e+k)/2)}},alignToOthers:function(){var a={},c,e=this.options;!1===this.chart.options.chart.alignTicks||!1===e.alignTicks||this.isLog||b(this.chart[this.coll],function(b){var k=b.options,k=[b.horiz?k.left:k.top,k.width,k.height,k.pane].join();b.series.length&&(a[k]?c=!0:a[k]=1)});return c},getTickAmount:function(){var a=this.options,b=a.tickAmount, c=a.tickPixelInterval;!l(a.tickInterval)&&this.len<c&&!this.isRadial&&!this.isLog&&a.startOnTick&&a.endOnTick&&(b=2);!b&&this.alignToOthers()&&(b=Math.ceil(this.len/c)+1);4>b&&(this.finalTickAmt=b,b=5);this.tickAmount=b},adjustTickAmount:function(){var a=this.tickInterval,b=this.tickPositions,c=this.tickAmount,e=this.finalTickAmt,h=b&&b.length;if(h<c){for(;b.length<c;)b.push(f(b[b.length-1]+a));this.transA*=(h-1)/(c-1);this.max=b[b.length-1]}else h>c&&(this.tickInterval*=2,this.setTickPositions()); if(l(e)){for(a=c=b.length;a--;)(3===e&&1===a%2||2>=e&&0<a&&a<c-1)&&b.splice(a,1);this.finalTickAmt=void 0}},setScale:function(){var a,c;this.oldMin=this.min;this.oldMax=this.max;this.oldAxisLength=this.len;this.setAxisSize();c=this.len!==this.oldAxisLength;b(this.series,function(b){if(b.isDirtyData||b.isDirty||b.xAxis.isDirty)a=!0});c||a||this.isLinked||this.forceRedraw||this.userMin!==this.oldUserMin||this.userMax!==this.oldUserMax||this.alignToOthers()?(this.resetStacks&&this.resetStacks(),this.forceRedraw= !1,this.getSeriesExtremes(),this.setTickInterval(),this.oldUserMin=this.userMin,this.oldUserMax=this.userMax,this.isDirty||(this.isDirty=c||this.min!==this.oldMin||this.max!==this.oldMax)):this.cleanStacks&&this.cleanStacks()},setExtremes:function(a,c,e,h,n){var k=this,m=k.chart;e=w(e,!0);b(k.series,function(a){delete a.kdTree});n=p(n,{min:a,max:c});C(k,"setExtremes",n,function(){k.userMin=a;k.userMax=c;k.eventArgs=n;e&&m.redraw(h)})},zoom:function(a,b){var c=this.dataMin,k=this.dataMax,e=this.options, h=Math.min(c,w(e.min,c)),e=Math.max(k,w(e.max,k));if(a!==this.min||b!==this.max)this.allowZoomOutside||(l(c)&&(a<h&&(a=h),a>e&&(a=e)),l(k)&&(b<h&&(b=h),b>e&&(b=e))),this.displayBtn=void 0!==a||void 0!==b,this.setExtremes(a,b,!1,void 0,{trigger:"zoom"});return!0},setAxisSize:function(){var a=this.chart,b=this.options,c=b.offsets||[0,0,0,0],e=this.horiz,h=w(b.width,a.plotWidth-c[3]+c[1]),n=w(b.height,a.plotHeight-c[0]+c[2]),m=w(b.top,a.plotTop+c[0]),b=w(b.left,a.plotLeft+c[3]),c=/%$/;c.test(n)&&(n= Math.round(parseFloat(n)/100*a.plotHeight));c.test(m)&&(m=Math.round(parseFloat(m)/100*a.plotHeight+a.plotTop));this.left=b;this.top=m;this.width=h;this.height=n;this.bottom=a.chartHeight-n-m;this.right=a.chartWidth-h-b;this.len=Math.max(e?h:n,0);this.pos=e?b:m},getExtremes:function(){var a=this.isLog,b=this.lin2log;return{min:a?f(b(this.min)):this.min,max:a?f(b(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},getThreshold:function(a){var b= this.isLog,c=this.lin2log,k=b?c(this.min):this.min,b=b?c(this.max):this.max;null===a?a=k:k>a?a=k:b<a&&(a=b);return this.translate(a,0,1,0,1)},autoLabelAlign:function(a){a=(w(a,0)-90*this.side+720)%360;return 15<a&&165>a?"right":195<a&&345>a?"left":"center"},tickSize:function(a){var b=this.options,c=b[a+"Length"],k=w(b[a+"Width"],"tick"===a&&this.isXAxis?1:0);if(k&&c)return"inside"===b[a+"Position"]&&(c=-c),[c,k]},labelMetrics:function(){return this.chart.renderer.fontMetrics(this.options.labels.style&& this.options.labels.style.fontSize,this.ticks[0]&&this.ticks[0].label)},unsquish:function(){var a=this.options.labels,c=this.horiz,e=this.tickInterval,h=e,n=this.len/(((this.categories?1:0)+this.max-this.min)/e),m,d=a.rotation,f=this.labelMetrics(),p,y=Number.MAX_VALUE,t,x=function(a){a/=n||1;a=1<a?Math.ceil(a):1;return a*e};c?(t=!a.staggerLines&&!a.step&&(l(d)?[d]:n<w(a.autoRotationLimit,80)&&a.autoRotation))&&b(t,function(a){var b;if(a===d||a&&-90<=a&&90>=a)p=x(Math.abs(f.h/Math.sin(q*a))),b=p+ Math.abs(a/360),b<y&&(y=b,m=a,h=p)}):a.step||(h=x(f.h));this.autoRotation=t;this.labelRotation=w(m,d);return h},getSlotWidth:function(){var a=this.chart,b=this.horiz,c=this.options.labels,e=Math.max(this.tickPositions.length-(this.categories?0:1),1),h=a.margin[3];return b&&2>(c.step||0)&&!c.rotation&&(this.staggerLines||1)*this.len/e||!b&&(h&&h-a.spacing[3]||.33*a.chartWidth)},renderUnsquish:function(){var a=this.chart,c=a.renderer,h=this.tickPositions,n=this.ticks,m=this.options.labels,d=this.horiz, v=this.getSlotWidth(),f=Math.max(1,Math.round(v-2*(m.padding||5))),p={},y=this.labelMetrics(),t=m.style&&m.style.textOverflow,g,z=0,E,w;e(m.rotation)||(p.rotation=m.rotation||0);b(h,function(a){(a=n[a])&&a.labelLength>z&&(z=a.labelLength)});this.maxLabelLength=z;if(this.autoRotation)z>f&&z>y.h?p.rotation=this.labelRotation:this.labelRotation=0;else if(v&&(g={width:f+"px"},!t))for(g.textOverflow="clip",E=h.length;!d&&E--;)if(w=h[E],f=n[w].label)f.styles&&"ellipsis"===f.styles.textOverflow?f.css({textOverflow:"clip"}): n[w].labelLength>v&&f.css({width:v+"px"}),f.getBBox().height>this.len/h.length-(y.h-y.f)&&(f.specCss={textOverflow:"ellipsis"});p.rotation&&(g={width:(z>.5*a.chartHeight?.33*a.chartHeight:a.chartHeight)+"px"},t||(g.textOverflow="ellipsis"));if(this.labelAlign=m.align||this.autoLabelAlign(this.labelRotation))p.align=this.labelAlign;b(h,function(a){var b=(a=n[a])&&a.label;b&&(b.attr(p),g&&b.css(x(g,b.specCss)),delete b.specCss,a.rotation=p.rotation)});this.tickRotCorr=c.rotCorr(y.b,this.labelRotation|| 0,0!==this.side)},hasData:function(){return this.hasVisibleSeries||l(this.min)&&l(this.max)&&!!this.tickPositions},addTitle:function(a){var b=this.chart.renderer,c=this.horiz,k=this.opposite,e=this.options.title,h;this.axisTitle||((h=e.textAlign)||(h=(c?{low:"left",middle:"center",high:"right"}:{low:k?"right":"left",middle:"center",high:k?"left":"right"})[e.align]),this.axisTitle=b.text(e.text,0,0,e.useHTML).attr({zIndex:7,rotation:e.rotation||0,align:h}).addClass("highcharts-axis-title").css(e.style).add(this.axisGroup), this.axisTitle.isNew=!0);this.axisTitle[a?"show":"hide"](!0)},generateTick:function(a){var b=this.ticks;b[a]?b[a].addLabel():b[a]=new I(this,a)},getOffset:function(){var a=this,c=a.chart,e=c.renderer,h=a.options,n=a.tickPositions,m=a.ticks,d=a.horiz,f=a.side,p=c.inverted?[1,0,3,2][f]:f,y,t,x=0,g,z=0,E=h.title,q=h.labels,F=0,J=c.axisOffset,c=c.clipOffset,K=[-1,1,1,-1][f],C,I=h.className,r=a.axisParent,u=this.tickSize("tick");y=a.hasData();a.showAxis=t=y||w(h.showEmpty,!0);a.staggerLines=a.horiz&&q.staggerLines; a.axisGroup||(a.gridGroup=e.g("grid").attr({zIndex:h.gridZIndex||1}).addClass("highcharts-"+this.coll.toLowerCase()+"-grid "+(I||"")).add(r),a.axisGroup=e.g("axis").attr({zIndex:h.zIndex||2}).addClass("highcharts-"+this.coll.toLowerCase()+" "+(I||"")).add(r),a.labelGroup=e.g("axis-labels").attr({zIndex:q.zIndex||7}).addClass("highcharts-"+a.coll.toLowerCase()+"-labels "+(I||"")).add(r));if(y||a.isLinked)b(n,function(b,c){a.generateTick(b,c)}),a.renderUnsquish(),!1===q.reserveSpace||0!==f&&2!==f&& {1:"left",3:"right"}[f]!==a.labelAlign&&"center"!==a.labelAlign||b(n,function(a){F=Math.max(m[a].getLabelSize(),F)}),a.staggerLines&&(F*=a.staggerLines,a.labelOffset=F*(a.opposite?-1:1));else for(C in m)m[C].destroy(),delete m[C];E&&E.text&&!1!==E.enabled&&(a.addTitle(t),t&&(x=a.axisTitle.getBBox()[d?"height":"width"],g=E.offset,z=l(g)?0:w(E.margin,d?5:10)));a.renderLine();a.offset=K*w(h.offset,J[f]);a.tickRotCorr=a.tickRotCorr||{x:0,y:0};e=0===f?-a.labelMetrics().h:2===f?a.tickRotCorr.y:0;z=Math.abs(F)+ z;F&&(z=z-e+K*(d?w(q.y,a.tickRotCorr.y+8*K):q.x));a.axisTitleMargin=w(g,z);J[f]=Math.max(J[f],a.axisTitleMargin+x+K*a.offset,z,y&&n.length&&u?u[0]:0);h=h.offset?0:2*Math.floor(a.axisLine.strokeWidth()/2);c[p]=Math.max(c[p],h)},getLinePath:function(a){var b=this.chart,c=this.opposite,k=this.offset,e=this.horiz,h=this.left+(c?this.width:0)+k,k=b.chartHeight-this.bottom-(c?this.height:0)+k;c&&(a*=-1);return b.renderer.crispLine(["M",e?this.left:h,e?k:this.top,"L",e?b.chartWidth-this.right:h,e?k:b.chartHeight- this.bottom],a)},renderLine:function(){this.axisLine||(this.axisLine=this.chart.renderer.path().addClass("highcharts-axis-line").add(this.axisGroup),this.axisLine.attr({stroke:this.options.lineColor,"stroke-width":this.options.lineWidth,zIndex:7}))},getTitlePosition:function(){var a=this.horiz,b=this.left,c=this.top,e=this.len,h=this.options.title,n=a?b:c,m=this.opposite,d=this.offset,f=h.x||0,p=h.y||0,y=this.chart.renderer.fontMetrics(h.style&&h.style.fontSize,this.axisTitle).f,e={low:n+(a?0:e), middle:n+e/2,high:n+(a?e:0)}[h.align],b=(a?c+this.height:b)+(a?1:-1)*(m?-1:1)*this.axisTitleMargin+(2===this.side?y:0);return{x:a?e+f:b+(m?this.width:0)+d+f,y:a?b+p-(m?this.height:0)+d:e+p}},renderMinorTick:function(a){var b=this.chart.hasRendered&&z(this.oldMin),c=this.minorTicks;c[a]||(c[a]=new I(this,a,"minor"));b&&c[a].isNew&&c[a].render(null,!0);c[a].render(null,!1,1)},renderTick:function(a,b){var c=this.isLinked,e=this.ticks,k=this.chart.hasRendered&&z(this.oldMin);if(!c||a>=this.min&&a<=this.max)e[a]|| (e[a]=new I(this,a)),k&&e[a].isNew&&e[a].render(b,!0,.1),e[a].render(b)},render:function(){var a=this,c=a.chart,e=a.options,n=a.isLog,m=a.lin2log,d=a.isLinked,v=a.tickPositions,f=a.axisTitle,p=a.ticks,y=a.minorTicks,t=a.alternateBands,x=e.stackLabels,z=e.alternateGridColor,g=a.tickmarkOffset,E=a.axisLine,w=a.showAxis,l=A(c.renderer.globalAnimation),q,F;a.labelEdge.length=0;a.overlap=!1;b([p,y,t],function(a){for(var b in a)a[b].isActive=!1});if(a.hasData()||d)a.minorTickInterval&&!a.categories&&b(a.getMinorTickPositions(), function(b){a.renderMinorTick(b)}),v.length&&(b(v,function(b,c){a.renderTick(b,c)}),g&&(0===a.min||a.single)&&(p[-1]||(p[-1]=new I(a,-1,null,!0)),p[-1].render(-1))),z&&b(v,function(b,e){F=void 0!==v[e+1]?v[e+1]+g:a.max-g;0===e%2&&b<a.max&&F<=a.max+(c.polar?-g:g)&&(t[b]||(t[b]=new h(a)),q=b+g,t[b].options={from:n?m(q):q,to:n?m(F):F,color:z},t[b].render(),t[b].isActive=!0)}),a._addedPlotLB||(b((e.plotLines||[]).concat(e.plotBands||[]),function(b){a.addPlotBandOrLine(b)}),a._addedPlotLB=!0);b([p,y,t], function(a){var b,e,h=[],k=l.duration;for(b in a)a[b].isActive||(a[b].render(b,!1,0),a[b].isActive=!1,h.push(b));K(function(){for(e=h.length;e--;)a[h[e]]&&!a[h[e]].isActive&&(a[h[e]].destroy(),delete a[h[e]])},a!==t&&c.hasRendered&&k?k:0)});E&&(E[E.isPlaced?"animate":"attr"]({d:this.getLinePath(E.strokeWidth())}),E.isPlaced=!0,E[w?"show":"hide"](!0));f&&w&&(f[f.isNew?"attr":"animate"](a.getTitlePosition()),f.isNew=!1);x&&x.enabled&&a.renderStackTotals();a.isDirty=!1},redraw:function(){this.visible&& (this.render(),b(this.plotLinesAndBands,function(a){a.render()}));b(this.series,function(a){a.isDirty=!0})},keepProps:"extKey hcEvents names series userMax userMin".split(" "),destroy:function(a){var c=this,e=c.stacks,h,k=c.plotLinesAndBands,m;a||y(c);for(h in e)d(e[h]),e[h]=null;b([c.ticks,c.minorTicks,c.alternateBands],function(a){d(a)});if(k)for(a=k.length;a--;)k[a].destroy();b("stackTotalGroup axisLine axisTitle axisGroup gridGroup labelGroup cross".split(" "),function(a){c[a]&&(c[a]=c[a].destroy())}); for(m in c)c.hasOwnProperty(m)&&-1===n(m,c.keepProps)&&delete c[m]},drawCrosshair:function(a,b){var c,e=this.crosshair,h=w(e.snap,!0),k,n=this.cross;a||(a=this.cross&&this.cross.e);this.crosshair&&!1!==(l(b)||!h)?(h?l(b)&&(k=this.isXAxis?b.plotX:this.len-b.plotY):k=a&&(this.horiz?a.chartX-this.pos:this.len-a.chartY+this.pos),l(k)&&(c=this.getPlotLinePath(b&&(this.isXAxis?b.x:w(b.stackY,b.y)),null,null,null,k)||null),l(c)?(b=this.categories&&!this.isRadial,n||(this.cross=n=this.chart.renderer.path().addClass("highcharts-crosshair highcharts-crosshair-"+ (b?"category ":"thin ")+e.className).attr({zIndex:w(e.zIndex,2)}).add(),n.attr({stroke:e.color||(b?g("#ccd6eb").setOpacity(.25).get():"#cccccc"),"stroke-width":w(e.width,1)}),e.dashStyle&&n.attr({dashstyle:e.dashStyle})),n.show().attr({d:c}),b&&!e.width&&n.attr({"stroke-width":this.transA}),this.cross.e=a):this.hideCrosshair()):this.hideCrosshair()},hideCrosshair:function(){this.cross&&this.cross.hide()}};p(a.Axis.prototype,r)})(L);(function(a){var B=a.Axis,A=a.Date,H=a.dateFormat,G=a.defaultOptions, r=a.defined,g=a.each,f=a.extend,u=a.getMagnitude,l=a.getTZOffset,q=a.normalizeTickInterval,d=a.pick,b=a.timeUnits;B.prototype.getTimeTicks=function(a,q,t,m){var c=[],n={},p=G.global.useUTC,z,e=new A(q-l(q)),x=A.hcMakeTime,F=a.unitRange,w=a.count,h;if(r(q)){e[A.hcSetMilliseconds](F>=b.second?0:w*Math.floor(e.getMilliseconds()/w));if(F>=b.second)e[A.hcSetSeconds](F>=b.minute?0:w*Math.floor(e.getSeconds()/w));if(F>=b.minute)e[A.hcSetMinutes](F>=b.hour?0:w*Math.floor(e[A.hcGetMinutes]()/w));if(F>=b.hour)e[A.hcSetHours](F>= b.day?0:w*Math.floor(e[A.hcGetHours]()/w));if(F>=b.day)e[A.hcSetDate](F>=b.month?1:w*Math.floor(e[A.hcGetDate]()/w));F>=b.month&&(e[A.hcSetMonth](F>=b.year?0:w*Math.floor(e[A.hcGetMonth]()/w)),z=e[A.hcGetFullYear]());if(F>=b.year)e[A.hcSetFullYear](z-z%w);if(F===b.week)e[A.hcSetDate](e[A.hcGetDate]()-e[A.hcGetDay]()+d(m,1));z=e[A.hcGetFullYear]();m=e[A.hcGetMonth]();var y=e[A.hcGetDate](),J=e[A.hcGetHours]();if(A.hcTimezoneOffset||A.hcGetTimezoneOffset)h=(!p||!!A.hcGetTimezoneOffset)&&(t-q>4*b.month|| l(q)!==l(t)),e=e.getTime(),e=new A(e+l(e));p=e.getTime();for(q=1;p<t;)c.push(p),p=F===b.year?x(z+q*w,0):F===b.month?x(z,m+q*w):!h||F!==b.day&&F!==b.week?h&&F===b.hour?x(z,m,y,J+q*w):p+F*w:x(z,m,y+q*w*(F===b.day?1:7)),q++;c.push(p);F<=b.hour&&1E4>c.length&&g(c,function(a){0===a%18E5&&"000000000"===H("%H%M%S%L",a)&&(n[a]="day")})}c.info=f(a,{higherRanks:n,totalRange:F*w});return c};B.prototype.normalizeTimeTickInterval=function(a,d){var f=d||[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second", [1,2,5,10,15,30]],["minute",[1,2,5,10,15,30]],["hour",[1,2,3,4,6,8,12]],["day",[1,2]],["week",[1,2]],["month",[1,2,3,4,6]],["year",null]];d=f[f.length-1];var m=b[d[0]],c=d[1],n;for(n=0;n<f.length&&!(d=f[n],m=b[d[0]],c=d[1],f[n+1]&&a<=(m*c[c.length-1]+b[f[n+1][0]])/2);n++);m===b.year&&a<5*m&&(c=[1,2,5]);a=q(a/m,c,"year"===d[0]?Math.max(u(a/m),1):1);return{unitRange:m,count:a,unitName:d[0]}}})(L);(function(a){var B=a.Axis,A=a.getMagnitude,H=a.map,G=a.normalizeTickInterval,r=a.pick;B.prototype.getLogTickPositions= function(a,f,u,l){var g=this.options,d=this.len,b=this.lin2log,p=this.log2lin,C=[];l||(this._minorAutoInterval=null);if(.5<=a)a=Math.round(a),C=this.getLinearTickPositions(a,f,u);else if(.08<=a)for(var d=Math.floor(f),t,m,c,n,E,g=.3<a?[1,2,4]:.15<a?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];d<u+1&&!E;d++)for(m=g.length,t=0;t<m&&!E;t++)c=p(b(d)*g[t]),c>f&&(!l||n<=u)&&void 0!==n&&C.push(n),n>u&&(E=!0),n=c;else f=b(f),u=b(u),a=g[l?"minorTickInterval":"tickInterval"],a=r("auto"===a?null:a,this._minorAutoInterval, g.tickPixelInterval/(l?5:1)*(u-f)/((l?d/this.tickPositions.length:d)||1)),a=G(a,null,A(a)),C=H(this.getLinearTickPositions(a,f,u),p),l||(this._minorAutoInterval=a/5);l||(this.tickInterval=a);return C};B.prototype.log2lin=function(a){return Math.log(a)/Math.LN10};B.prototype.lin2log=function(a){return Math.pow(10,a)}})(L);(function(a){var B=a.dateFormat,A=a.each,H=a.extend,G=a.format,r=a.isNumber,g=a.map,f=a.merge,u=a.pick,l=a.splat,q=a.syncTimeout,d=a.timeUnits;a.Tooltip=function(){this.init.apply(this, arguments)};a.Tooltip.prototype={init:function(a,d){this.chart=a;this.options=d;this.crosshairs=[];this.now={x:0,y:0};this.isHidden=!0;this.split=d.split&&!a.inverted;this.shared=d.shared||this.split},cleanSplit:function(a){A(this.chart.series,function(b){var d=b&&b.tt;d&&(!d.isActive||a?b.tt=d.destroy():d.isActive=!1)})},getLabel:function(){var a=this.chart.renderer,d=this.options;this.label||(this.split?this.label=a.g("tooltip"):(this.label=a.label("",0,0,d.shape||"callout",null,null,d.useHTML, null,"tooltip").attr({padding:d.padding,r:d.borderRadius}),this.label.attr({fill:d.backgroundColor,"stroke-width":d.borderWidth}).css(d.style).shadow(d.shadow)),this.label.attr({zIndex:8}).add());return this.label},update:function(a){this.destroy();this.init(this.chart,f(!0,this.options,a))},destroy:function(){this.label&&(this.label=this.label.destroy());this.split&&this.tt&&(this.cleanSplit(this.chart,!0),this.tt=this.tt.destroy());clearTimeout(this.hideTimer);clearTimeout(this.tooltipTimeout)}, move:function(a,d,f,t){var b=this,c=b.now,n=!1!==b.options.animation&&!b.isHidden&&(1<Math.abs(a-c.x)||1<Math.abs(d-c.y)),p=b.followPointer||1<b.len;H(c,{x:n?(2*c.x+a)/3:a,y:n?(c.y+d)/2:d,anchorX:p?void 0:n?(2*c.anchorX+f)/3:f,anchorY:p?void 0:n?(c.anchorY+t)/2:t});b.getLabel().attr(c);n&&(clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){b&&b.move(a,d,f,t)},32))},hide:function(a){var b=this;clearTimeout(this.hideTimer);a=u(a,this.options.hideDelay,500);this.isHidden||(this.hideTimer= q(function(){b.getLabel()[a?"fadeOut":"hide"]();b.isHidden=!0},a))},getAnchor:function(a,d){var b,f=this.chart,m=f.inverted,c=f.plotTop,n=f.plotLeft,p=0,z=0,e,x;a=l(a);b=a[0].tooltipPos;this.followPointer&&d&&(void 0===d.chartX&&(d=f.pointer.normalize(d)),b=[d.chartX-f.plotLeft,d.chartY-c]);b||(A(a,function(a){e=a.series.yAxis;x=a.series.xAxis;p+=a.plotX+(!m&&x?x.left-n:0);z+=(a.plotLow?(a.plotLow+a.plotHigh)/2:a.plotY)+(!m&&e?e.top-c:0)}),p/=a.length,z/=a.length,b=[m?f.plotWidth-z:p,this.shared&& !m&&1<a.length&&d?d.chartY-c:m?f.plotHeight-p:z]);return g(b,Math.round)},getPosition:function(a,d,f){var b=this.chart,m=this.distance,c={},n=f.h||0,p,z=["y",b.chartHeight,d,f.plotY+b.plotTop,b.plotTop,b.plotTop+b.plotHeight],e=["x",b.chartWidth,a,f.plotX+b.plotLeft,b.plotLeft,b.plotLeft+b.plotWidth],x=!this.followPointer&&u(f.ttBelow,!b.inverted===!!f.negative),g=function(a,b,e,h,d,f){var k=e<h-m,y=h+m+e<b,p=h-m-e;h+=m;if(x&&y)c[a]=h;else if(!x&&k)c[a]=p;else if(k)c[a]=Math.min(f-e,0>p-n?p:p-n); else if(y)c[a]=Math.max(d,h+n+e>b?h:h+n);else return!1},w=function(a,b,e,h){var k;h<m||h>b-m?k=!1:c[a]=h<e/2?1:h>b-e/2?b-e-2:h-e/2;return k},h=function(a){var b=z;z=e;e=b;p=a},y=function(){!1!==g.apply(0,z)?!1!==w.apply(0,e)||p||(h(!0),y()):p?c.x=c.y=0:(h(!0),y())};(b.inverted||1<this.len)&&h();y();return c},defaultFormatter:function(a){var b=this.points||l(this),d;d=[a.tooltipFooterHeaderFormatter(b[0])];d=d.concat(a.bodyFormatter(b));d.push(a.tooltipFooterHeaderFormatter(b[0],!0));return d},refresh:function(a, d){var b=this.chart,f,m=this.options,c,n,p={},z=[];f=m.formatter||this.defaultFormatter;var p=b.hoverPoints,e=this.shared;clearTimeout(this.hideTimer);this.followPointer=l(a)[0].series.tooltipOptions.followPointer;n=this.getAnchor(a,d);d=n[0];c=n[1];!e||a.series&&a.series.noSharedTooltip?p=a.getLabelConfig():(b.hoverPoints=a,p&&A(p,function(a){a.setState()}),A(a,function(a){a.setState("hover");z.push(a.getLabelConfig())}),p={x:a[0].category,y:a[0].y},p.points=z,a=a[0]);this.len=z.length;p=f.call(p, this);e=a.series;this.distance=u(e.tooltipOptions.distance,16);!1===p?this.hide():(f=this.getLabel(),this.isHidden&&f.attr({opacity:1}).show(),this.split?this.renderSplit(p,b.hoverPoints):(f.attr({text:p&&p.join?p.join(""):p}),f.removeClass(/highcharts-color-[\d]+/g).addClass("highcharts-color-"+u(a.colorIndex,e.colorIndex)),f.attr({stroke:m.borderColor||a.color||e.color||"#666666"}),this.updatePosition({plotX:d,plotY:c,negative:a.negative,ttBelow:a.ttBelow,h:n[2]||0})),this.isHidden=!1)},renderSplit:function(b, d){var f=this,p=[],m=this.chart,c=m.renderer,n=!0,g=this.options,z,e=this.getLabel();A(b.slice(0,d.length+1),function(a,b){b=d[b-1]||{isHeader:!0,plotX:d[0].plotX};var x=b.series||f,h=x.tt,y=b.series||{},t="highcharts-color-"+u(b.colorIndex,y.colorIndex,"none");h||(x.tt=h=c.label(null,null,null,"callout").addClass("highcharts-tooltip-box "+t).attr({padding:g.padding,r:g.borderRadius,fill:g.backgroundColor,stroke:b.color||y.color||"#333333","stroke-width":g.borderWidth}).add(e));h.isActive=!0;h.attr({text:a}); h.css(g.style);a=h.getBBox();y=a.width+h.strokeWidth();b.isHeader?(z=a.height,y=Math.max(0,Math.min(b.plotX+m.plotLeft-y/2,m.chartWidth-y))):y=b.plotX+m.plotLeft-u(g.distance,16)-y;0>y&&(n=!1);a=(b.series&&b.series.yAxis&&b.series.yAxis.pos)+(b.plotY||0);a-=m.plotTop;p.push({target:b.isHeader?m.plotHeight+z:a,rank:b.isHeader?1:0,size:x.tt.getBBox().height+1,point:b,x:y,tt:h})});this.cleanSplit();a.distribute(p,m.plotHeight+z);A(p,function(a){var b=a.point,c=b.series;a.tt.attr({visibility:void 0=== a.pos?"hidden":"inherit",x:n||b.isHeader?a.x:b.plotX+m.plotLeft+u(g.distance,16),y:a.pos+m.plotTop,anchorX:b.isHeader?b.plotX+m.plotLeft:b.plotX+c.xAxis.pos,anchorY:b.isHeader?a.pos+m.plotTop-15:b.plotY+c.yAxis.pos})})},updatePosition:function(a){var b=this.chart,d=this.getLabel(),d=(this.options.positioner||this.getPosition).call(this,d.width,d.height,a);this.move(Math.round(d.x),Math.round(d.y||0),a.plotX+b.plotLeft,a.plotY+b.plotTop)},getDateFormat:function(a,f,g,t){var b=B("%m-%d %H:%M:%S.%L", f),c,n,p={millisecond:15,second:12,minute:9,hour:6,day:3},z="millisecond";for(n in d){if(a===d.week&&+B("%w",f)===g&&"00:00:00.000"===b.substr(6)){n="week";break}if(d[n]>a){n=z;break}if(p[n]&&b.substr(p[n])!=="01-01 00:00:00.000".substr(p[n]))break;"week"!==n&&(z=n)}n&&(c=t[n]);return c},getXDateFormat:function(a,d,f){d=d.dateTimeLabelFormats;var b=f&&f.closestPointRange;return(b?this.getDateFormat(b,a.x,f.options.startOfWeek,d):d.day)||d.year},tooltipFooterHeaderFormatter:function(a,d){var b=d?"footer": "header";d=a.series;var f=d.tooltipOptions,m=f.xDateFormat,c=d.xAxis,n=c&&"datetime"===c.options.type&&r(a.key),b=f[b+"Format"];n&&!m&&(m=this.getXDateFormat(a,f,c));n&&m&&(b=b.replace("{point.key}","{point.key:"+m+"}"));return G(b,{point:a,series:d})},bodyFormatter:function(a){return g(a,function(a){var b=a.series.tooltipOptions;return(b.pointFormatter||a.point.tooltipFormatter).call(a.point,b.pointFormat)})}}})(L);(function(a){var B=a.addEvent,A=a.attr,H=a.charts,G=a.color,r=a.css,g=a.defined,f= a.doc,u=a.each,l=a.extend,q=a.fireEvent,d=a.offset,b=a.pick,p=a.removeEvent,C=a.splat,t=a.Tooltip,m=a.win;a.Pointer=function(a,b){this.init(a,b)};a.Pointer.prototype={init:function(a,d){this.options=d;this.chart=a;this.runChartClick=d.chart.events&&!!d.chart.events.click;this.pinchDown=[];this.lastValidTouch={};t&&d.tooltip.enabled&&(a.tooltip=new t(a,d.tooltip),this.followTouchMove=b(d.tooltip.followTouchMove,!0));this.setDOMEvents()},zoomOption:function(a){var c=this.chart,d=c.options.chart,m=d.zoomType|| "",c=c.inverted;/touch/.test(a.type)&&(m=b(d.pinchType,m));this.zoomX=a=/x/.test(m);this.zoomY=m=/y/.test(m);this.zoomHor=a&&!c||m&&c;this.zoomVert=m&&!c||a&&c;this.hasZoom=a||m},normalize:function(a,b){var c,n;a=a||m.event;a.target||(a.target=a.srcElement);n=a.touches?a.touches.length?a.touches.item(0):a.changedTouches[0]:a;b||(this.chartPosition=b=d(this.chart.container));void 0===n.pageX?(c=Math.max(a.x,a.clientX-b.left),b=a.y):(c=n.pageX-b.left,b=n.pageY-b.top);return l(a,{chartX:Math.round(c), chartY:Math.round(b)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};u(this.chart.axes,function(c){b[c.isXAxis?"xAxis":"yAxis"].push({axis:c,value:c.toValue(a[c.horiz?"chartX":"chartY"])})});return b},runPointActions:function(c){var d=this.chart,m=d.series,p=d.tooltip,e=p?p.shared:!1,g=!0,t=d.hoverPoint,w=d.hoverSeries,h,y,l,q=[],r;if(!e&&!w)for(h=0;h<m.length;h++)if(m[h].directTouch||!m[h].options.stickyTracking)m=[];w&&(e?w.noSharedTooltip:w.directTouch)&&t?q=[t]:(e||!w||w.options.stickyTracking|| (m=[w]),u(m,function(a){y=a.noSharedTooltip&&e;l=!e&&a.directTouch;a.visible&&!y&&!l&&b(a.options.enableMouseTracking,!0)&&(r=a.searchPoint(c,!y&&1===a.kdDimensions))&&r.series&&q.push(r)}),q.sort(function(a,b){var c=a.distX-b.distX,h=a.dist-b.dist,k=(b.series.group&&b.series.group.zIndex)-(a.series.group&&a.series.group.zIndex);return 0!==c&&e?c:0!==h?h:0!==k?k:a.series.index>b.series.index?-1:1}));if(e)for(h=q.length;h--;)(q[h].x!==q[0].x||q[h].series.noSharedTooltip)&&q.splice(h,1);if(q[0]&&(q[0]!== this.prevKDPoint||p&&p.isHidden)){if(e&&!q[0].series.noSharedTooltip){for(h=0;h<q.length;h++)q[h].onMouseOver(c,q[h]!==(w&&w.directTouch&&t||q[0]));q.length&&p&&p.refresh(q.sort(function(a,b){return a.series.index-b.series.index}),c)}else if(p&&p.refresh(q[0],c),!w||!w.directTouch)q[0].onMouseOver(c);this.prevKDPoint=q[0];g=!1}g&&(m=w&&w.tooltipOptions.followPointer,p&&m&&!p.isHidden&&(m=p.getAnchor([{}],c),p.updatePosition({plotX:m[0],plotY:m[1]})));this.unDocMouseMove||(this.unDocMouseMove=B(f, "mousemove",function(b){if(H[a.hoverChartIndex])H[a.hoverChartIndex].pointer.onDocumentMouseMove(b)}));u(e?q:[b(t,q[0])],function(a){u(d.axes,function(b){(!a||a.series&&a.series[b.coll]===b)&&b.drawCrosshair(c,a)})})},reset:function(a,b){var c=this.chart,d=c.hoverSeries,e=c.hoverPoint,n=c.hoverPoints,m=c.tooltip,f=m&&m.shared?n:e;a&&f&&u(C(f),function(b){b.series.isCartesian&&void 0===b.plotX&&(a=!1)});if(a)m&&f&&(m.refresh(f),e&&(e.setState(e.state,!0),u(c.axes,function(a){a.crosshair&&a.drawCrosshair(null, e)})));else{if(e)e.onMouseOut();n&&u(n,function(a){a.setState()});if(d)d.onMouseOut();m&&m.hide(b);this.unDocMouseMove&&(this.unDocMouseMove=this.unDocMouseMove());u(c.axes,function(a){a.hideCrosshair()});this.hoverX=this.prevKDPoint=c.hoverPoints=c.hoverPoint=null}},scaleGroups:function(a,b){var c=this.chart,d;u(c.series,function(e){d=a||e.getPlotBox();e.xAxis&&e.xAxis.zoomEnabled&&e.group&&(e.group.attr(d),e.markerGroup&&(e.markerGroup.attr(d),e.markerGroup.clip(b?c.clipRect:null)),e.dataLabelsGroup&& e.dataLabelsGroup.attr(d))});c.clipRect.attr(b||c.clipBox)},dragStart:function(a){var b=this.chart;b.mouseIsDown=a.type;b.cancelClick=!1;b.mouseDownX=this.mouseDownX=a.chartX;b.mouseDownY=this.mouseDownY=a.chartY},drag:function(a){var b=this.chart,c=b.options.chart,d=a.chartX,e=a.chartY,m=this.zoomHor,f=this.zoomVert,p=b.plotLeft,h=b.plotTop,y=b.plotWidth,g=b.plotHeight,t,q=this.selectionMarker,k=this.mouseDownX,l=this.mouseDownY,r=c.panKey&&a[c.panKey+"Key"];q&&q.touch||(d<p?d=p:d>p+y&&(d=p+y),e< h?e=h:e>h+g&&(e=h+g),this.hasDragged=Math.sqrt(Math.pow(k-d,2)+Math.pow(l-e,2)),10<this.hasDragged&&(t=b.isInsidePlot(k-p,l-h),b.hasCartesianSeries&&(this.zoomX||this.zoomY)&&t&&!r&&!q&&(this.selectionMarker=q=b.renderer.rect(p,h,m?1:y,f?1:g,0).attr({fill:c.selectionMarkerFill||G("#335cad").setOpacity(.25).get(),"class":"highcharts-selection-marker",zIndex:7}).add()),q&&m&&(d-=k,q.attr({width:Math.abs(d),x:(0<d?0:d)+k})),q&&f&&(d=e-l,q.attr({height:Math.abs(d),y:(0<d?0:d)+l})),t&&!q&&c.panning&&b.pan(a, c.panning)))},drop:function(a){var b=this,c=this.chart,d=this.hasPinched;if(this.selectionMarker){var e={originalEvent:a,xAxis:[],yAxis:[]},m=this.selectionMarker,f=m.attr?m.attr("x"):m.x,p=m.attr?m.attr("y"):m.y,h=m.attr?m.attr("width"):m.width,y=m.attr?m.attr("height"):m.height,t;if(this.hasDragged||d)u(c.axes,function(c){if(c.zoomEnabled&&g(c.min)&&(d||b[{xAxis:"zoomX",yAxis:"zoomY"}[c.coll]])){var m=c.horiz,k="touchend"===a.type?c.minPixelPadding:0,n=c.toValue((m?f:p)+k),m=c.toValue((m?f+h:p+ y)-k);e[c.coll].push({axis:c,min:Math.min(n,m),max:Math.max(n,m)});t=!0}}),t&&q(c,"selection",e,function(a){c.zoom(l(a,d?{animation:!1}:null))});this.selectionMarker=this.selectionMarker.destroy();d&&this.scaleGroups()}c&&(r(c.container,{cursor:c._cursor}),c.cancelClick=10<this.hasDragged,c.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[])},onContainerMouseDown:function(a){a=this.normalize(a);this.zoomOption(a);a.preventDefault&&a.preventDefault();this.dragStart(a)},onDocumentMouseUp:function(b){H[a.hoverChartIndex]&& H[a.hoverChartIndex].pointer.drop(b)},onDocumentMouseMove:function(a){var b=this.chart,c=this.chartPosition;a=this.normalize(a,c);!c||this.inClass(a.target,"highcharts-tracker")||b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)||this.reset()},onContainerMouseLeave:function(b){var c=H[a.hoverChartIndex];c&&(b.relatedTarget||b.toElement)&&(c.pointer.reset(),c.pointer.chartPosition=null)},onContainerMouseMove:function(b){var c=this.chart;g(a.hoverChartIndex)&&H[a.hoverChartIndex]&&H[a.hoverChartIndex].mouseIsDown|| (a.hoverChartIndex=c.index);b=this.normalize(b);b.returnValue=!1;"mousedown"===c.mouseIsDown&&this.drag(b);!this.inClass(b.target,"highcharts-tracker")&&!c.isInsidePlot(b.chartX-c.plotLeft,b.chartY-c.plotTop)||c.openMenu||this.runPointActions(b)},inClass:function(a,b){for(var c;a;){if(c=A(a,"class")){if(-1!==c.indexOf(b))return!0;if(-1!==c.indexOf("highcharts-container"))return!1}a=a.parentNode}},onTrackerMouseOut:function(a){var b=this.chart.hoverSeries;a=a.relatedTarget||a.toElement;if(!(!b||!a|| b.options.stickyTracking||this.inClass(a,"highcharts-tooltip")||this.inClass(a,"highcharts-series-"+b.index)&&this.inClass(a,"highcharts-tracker")))b.onMouseOut()},onContainerClick:function(a){var b=this.chart,c=b.hoverPoint,d=b.plotLeft,e=b.plotTop;a=this.normalize(a);b.cancelClick||(c&&this.inClass(a.target,"highcharts-tracker")?(q(c.series,"click",l(a,{point:c})),b.hoverPoint&&c.firePointEvent("click",a)):(l(a,this.getCoordinates(a)),b.isInsidePlot(a.chartX-d,a.chartY-e)&&q(b,"click",a)))},setDOMEvents:function(){var b= this,d=b.chart.container;d.onmousedown=function(a){b.onContainerMouseDown(a)};d.onmousemove=function(a){b.onContainerMouseMove(a)};d.onclick=function(a){b.onContainerClick(a)};B(d,"mouseleave",b.onContainerMouseLeave);1===a.chartCount&&B(f,"mouseup",b.onDocumentMouseUp);a.hasTouch&&(d.ontouchstart=function(a){b.onContainerTouchStart(a)},d.ontouchmove=function(a){b.onContainerTouchMove(a)},1===a.chartCount&&B(f,"touchend",b.onDocumentTouchEnd))},destroy:function(){var b;p(this.chart.container,"mouseleave", this.onContainerMouseLeave);a.chartCount||(p(f,"mouseup",this.onDocumentMouseUp),p(f,"touchend",this.onDocumentTouchEnd));clearInterval(this.tooltipTimeout);for(b in this)this[b]=null}}})(L);(function(a){var B=a.charts,A=a.each,H=a.extend,G=a.map,r=a.noop,g=a.pick;H(a.Pointer.prototype,{pinchTranslate:function(a,g,l,q,d,b){this.zoomHor&&this.pinchTranslateDirection(!0,a,g,l,q,d,b);this.zoomVert&&this.pinchTranslateDirection(!1,a,g,l,q,d,b)},pinchTranslateDirection:function(a,g,l,q,d,b,p,r){var f= this.chart,m=a?"x":"y",c=a?"X":"Y",n="chart"+c,E=a?"width":"height",z=f["plot"+(a?"Left":"Top")],e,x,F=r||1,w=f.inverted,h=f.bounds[a?"h":"v"],y=1===g.length,J=g[0][n],u=l[0][n],I=!y&&g[1][n],k=!y&&l[1][n],D;l=function(){!y&&20<Math.abs(J-I)&&(F=r||Math.abs(u-k)/Math.abs(J-I));x=(z-u)/F+J;e=f["plot"+(a?"Width":"Height")]/F};l();g=x;g<h.min?(g=h.min,D=!0):g+e>h.max&&(g=h.max-e,D=!0);D?(u-=.8*(u-p[m][0]),y||(k-=.8*(k-p[m][1])),l()):p[m]=[u,k];w||(b[m]=x-z,b[E]=e);b=w?1/F:F;d[E]=e;d[m]=g;q[w?a?"scaleY": "scaleX":"scale"+c]=F;q["translate"+c]=b*z+(u-b*J)},pinch:function(a){var f=this,l=f.chart,q=f.pinchDown,d=a.touches,b=d.length,p=f.lastValidTouch,C=f.hasZoom,t=f.selectionMarker,m={},c=1===b&&(f.inClass(a.target,"highcharts-tracker")&&l.runTrackerClick||f.runChartClick),n={};1<b&&(f.initiated=!0);C&&f.initiated&&!c&&a.preventDefault();G(d,function(a){return f.normalize(a)});"touchstart"===a.type?(A(d,function(a,b){q[b]={chartX:a.chartX,chartY:a.chartY}}),p.x=[q[0].chartX,q[1]&&q[1].chartX],p.y=[q[0].chartY, q[1]&&q[1].chartY],A(l.axes,function(a){if(a.zoomEnabled){var b=l.bounds[a.horiz?"h":"v"],c=a.minPixelPadding,d=a.toPixels(g(a.options.min,a.dataMin)),m=a.toPixels(g(a.options.max,a.dataMax)),f=Math.max(d,m);b.min=Math.min(a.pos,Math.min(d,m)-c);b.max=Math.max(a.pos+a.len,f+c)}}),f.res=!0):f.followTouchMove&&1===b?this.runPointActions(f.normalize(a)):q.length&&(t||(f.selectionMarker=t=H({destroy:r,touch:!0},l.plotBox)),f.pinchTranslate(q,d,m,t,n,p),f.hasPinched=C,f.scaleGroups(m,n),f.res&&(f.res= !1,this.reset(!1,0)))},touch:function(f,r){var l=this.chart,q,d;if(l.index!==a.hoverChartIndex)this.onContainerMouseLeave({relatedTarget:!0});a.hoverChartIndex=l.index;1===f.touches.length?(f=this.normalize(f),(d=l.isInsidePlot(f.chartX-l.plotLeft,f.chartY-l.plotTop))&&!l.openMenu?(r&&this.runPointActions(f),"touchmove"===f.type&&(r=this.pinchDown,q=r[0]?4<=Math.sqrt(Math.pow(r[0].chartX-f.chartX,2)+Math.pow(r[0].chartY-f.chartY,2)):!1),g(q,!0)&&this.pinch(f)):r&&this.reset()):2===f.touches.length&& this.pinch(f)},onContainerTouchStart:function(a){this.zoomOption(a);this.touch(a,!0)},onContainerTouchMove:function(a){this.touch(a)},onDocumentTouchEnd:function(f){B[a.hoverChartIndex]&&B[a.hoverChartIndex].pointer.drop(f)}})})(L);(function(a){var B=a.addEvent,A=a.charts,H=a.css,G=a.doc,r=a.extend,g=a.noop,f=a.Pointer,u=a.removeEvent,l=a.win,q=a.wrap;if(l.PointerEvent||l.MSPointerEvent){var d={},b=!!l.PointerEvent,p=function(){var a,b=[];b.item=function(a){return this[a]};for(a in d)d.hasOwnProperty(a)&& b.push({pageX:d[a].pageX,pageY:d[a].pageY,target:d[a].target});return b},C=function(b,d,c,f){"touch"!==b.pointerType&&b.pointerType!==b.MSPOINTER_TYPE_TOUCH||!A[a.hoverChartIndex]||(f(b),f=A[a.hoverChartIndex].pointer,f[d]({type:c,target:b.currentTarget,preventDefault:g,touches:p()}))};r(f.prototype,{onContainerPointerDown:function(a){C(a,"onContainerTouchStart","touchstart",function(a){d[a.pointerId]={pageX:a.pageX,pageY:a.pageY,target:a.currentTarget}})},onContainerPointerMove:function(a){C(a,"onContainerTouchMove", "touchmove",function(a){d[a.pointerId]={pageX:a.pageX,pageY:a.pageY};d[a.pointerId].target||(d[a.pointerId].target=a.currentTarget)})},onDocumentPointerUp:function(a){C(a,"onDocumentTouchEnd","touchend",function(a){delete d[a.pointerId]})},batchMSEvents:function(a){a(this.chart.container,b?"pointerdown":"MSPointerDown",this.onContainerPointerDown);a(this.chart.container,b?"pointermove":"MSPointerMove",this.onContainerPointerMove);a(G,b?"pointerup":"MSPointerUp",this.onDocumentPointerUp)}});q(f.prototype, "init",function(a,b,c){a.call(this,b,c);this.hasZoom&&H(b.container,{"-ms-touch-action":"none","touch-action":"none"})});q(f.prototype,"setDOMEvents",function(a){a.apply(this);(this.hasZoom||this.followTouchMove)&&this.batchMSEvents(B)});q(f.prototype,"destroy",function(a){this.batchMSEvents(u);a.call(this)})}})(L);(function(a){var B,A=a.addEvent,H=a.css,G=a.discardElement,r=a.defined,g=a.each,f=a.extend,u=a.isFirefox,l=a.marginNames,q=a.merge,d=a.pick,b=a.setAnimation,p=a.stableSort,C=a.win,t=a.wrap; B=a.Legend=function(a,b){this.init(a,b)};B.prototype={init:function(a,b){this.chart=a;this.setOptions(b);b.enabled&&(this.render(),A(this.chart,"endResize",function(){this.legend.positionCheckboxes()}))},setOptions:function(a){var b=d(a.padding,8);this.options=a;this.itemStyle=a.itemStyle;this.itemHiddenStyle=q(this.itemStyle,a.itemHiddenStyle);this.itemMarginTop=a.itemMarginTop||0;this.initialItemX=this.padding=b;this.initialItemY=b-5;this.itemHeight=this.maxItemWidth=0;this.symbolWidth=d(a.symbolWidth, 16);this.pages=[]},update:function(a,b){var c=this.chart;this.setOptions(q(!0,this.options,a));this.destroy();c.isDirtyLegend=c.isDirtyBox=!0;d(b,!0)&&c.redraw()},colorizeItem:function(a,b){a.legendGroup[b?"removeClass":"addClass"]("highcharts-legend-item-hidden");var c=this.options,d=a.legendItem,m=a.legendLine,e=a.legendSymbol,f=this.itemHiddenStyle.color,c=b?c.itemStyle.color:f,p=b?a.color||f:f,g=a.options&&a.options.marker,h={fill:p},y;d&&d.css({fill:c,color:c});m&&m.attr({stroke:p});if(e){if(g&& e.isMarker&&(h=a.pointAttribs(),!b))for(y in h)h[y]=f;e.attr(h)}},positionItem:function(a){var b=this.options,d=b.symbolPadding,b=!b.rtl,m=a._legendItemPos,f=m[0],m=m[1],e=a.checkbox;(a=a.legendGroup)&&a.element&&a.translate(b?f:this.legendWidth-f-2*d-4,m);e&&(e.x=f,e.y=m)},destroyItem:function(a){var b=a.checkbox;g(["legendItem","legendLine","legendSymbol","legendGroup"],function(b){a[b]&&(a[b]=a[b].destroy())});b&&G(a.checkbox)},destroy:function(){function a(a){this[a]&&(this[a]=this[a].destroy())} g(this.getAllItems(),function(b){g(["legendItem","legendGroup"],a,b)});g(["box","title","group"],a,this);this.display=null},positionCheckboxes:function(a){var b=this.group&&this.group.alignAttr,d,m=this.clipHeight||this.legendHeight,f=this.titleHeight;b&&(d=b.translateY,g(this.allItems,function(c){var e=c.checkbox,n;e&&(n=d+f+e.y+(a||0)+3,H(e,{left:b.translateX+c.checkboxOffset+e.x-20+"px",top:n+"px",display:n>d-6&&n<d+m-6?"":"none"}))}))},renderTitle:function(){var a=this.padding,b=this.options.title, d=0;b.text&&(this.title||(this.title=this.chart.renderer.label(b.text,a-3,a-4,null,null,null,null,null,"legend-title").attr({zIndex:1}).css(b.style).add(this.group)),a=this.title.getBBox(),d=a.height,this.offsetWidth=a.width,this.contentGroup.attr({translateY:d}));this.titleHeight=d},setText:function(b){var c=this.options;b.legendItem.attr({text:c.labelFormat?a.format(c.labelFormat,b):c.labelFormatter.call(b)})},renderItem:function(a){var b=this.chart,f=b.renderer,m=this.options,p="horizontal"=== m.layout,e=this.symbolWidth,g=m.symbolPadding,l=this.itemStyle,t=this.itemHiddenStyle,h=this.padding,y=p?d(m.itemDistance,20):0,J=!m.rtl,r=m.width,I=m.itemMarginBottom||0,k=this.itemMarginTop,u=this.initialItemX,C=a.legendItem,N=!a.series,A=!N&&a.series.drawLegendSymbol?a.series:a,B=A.options,B=this.createCheckboxForItem&&B&&B.showCheckbox,v=m.useHTML;C||(a.legendGroup=f.g("legend-item").addClass("highcharts-"+A.type+"-series highcharts-color-"+a.colorIndex+(a.options.className?" "+a.options.className: "")+(N?" highcharts-series-"+a.index:"")).attr({zIndex:1}).add(this.scrollGroup),a.legendItem=C=f.text("",J?e+g:-g,this.baseline||0,v).css(q(a.visible?l:t)).attr({align:J?"left":"right",zIndex:2}).add(a.legendGroup),this.baseline||(l=l.fontSize,this.fontMetrics=f.fontMetrics(l,C),this.baseline=this.fontMetrics.f+3+k,C.attr("y",this.baseline)),this.symbolHeight=m.symbolHeight||this.fontMetrics.f,A.drawLegendSymbol(this,a),this.setItemEvents&&this.setItemEvents(a,C,v),B&&this.createCheckboxForItem(a)); this.colorizeItem(a,a.visible);this.setText(a);f=C.getBBox();e=a.checkboxOffset=m.itemWidth||a.legendItemWidth||e+g+f.width+y+(B?20:0);this.itemHeight=g=Math.round(a.legendItemHeight||f.height);p&&this.itemX-u+e>(r||b.chartWidth-2*h-u-m.x)&&(this.itemX=u,this.itemY+=k+this.lastLineHeight+I,this.lastLineHeight=0);this.maxItemWidth=Math.max(this.maxItemWidth,e);this.lastItemY=k+this.itemY+I;this.lastLineHeight=Math.max(g,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];p?this.itemX+=e: (this.itemY+=k+g+I,this.lastLineHeight=g);this.offsetWidth=r||Math.max((p?this.itemX-u-y:e)+h,this.offsetWidth)},getAllItems:function(){var a=[];g(this.chart.series,function(b){var c=b&&b.options;b&&d(c.showInLegend,r(c.linkedTo)?!1:void 0,!0)&&(a=a.concat(b.legendItems||("point"===c.legendType?b.data:b)))});return a},adjustMargins:function(a,b){var c=this.chart,f=this.options,m=f.align.charAt(0)+f.verticalAlign.charAt(0)+f.layout.charAt(0);f.floating||g([/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/, /(lbv|lm|ltv)/],function(e,n){e.test(m)&&!r(a[n])&&(c[l[n]]=Math.max(c[l[n]],c.legend[(n+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][n]*f[n%2?"x":"y"]+d(f.margin,12)+b[n]))})},render:function(){var a=this,b=a.chart,d=b.renderer,q=a.group,l,e,t,r,w=a.box,h=a.options,y=a.padding;a.itemX=a.initialItemX;a.itemY=a.initialItemY;a.offsetWidth=0;a.lastItemY=0;q||(a.group=q=d.g("legend").attr({zIndex:7}).add(),a.contentGroup=d.g().attr({zIndex:1}).add(q),a.scrollGroup=d.g().add(a.contentGroup));a.renderTitle(); l=a.getAllItems();p(l,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});h.reversed&&l.reverse();a.allItems=l;a.display=e=!!l.length;a.lastLineHeight=0;g(l,function(b){a.renderItem(b)});t=(h.width||a.offsetWidth)+y;r=a.lastItemY+a.lastLineHeight+a.titleHeight;r=a.handleOverflow(r);r+=y;w||(a.box=w=d.rect().addClass("highcharts-legend-box").attr({r:h.borderRadius}).add(q),w.isNew=!0);w.attr({stroke:h.borderColor,"stroke-width":h.borderWidth||0,fill:h.backgroundColor|| "none"}).shadow(h.shadow);0<t&&0<r&&(w[w.isNew?"attr":"animate"](w.crisp({x:0,y:0,width:t,height:r},w.strokeWidth())),w.isNew=!1);w[e?"show":"hide"]();a.legendWidth=t;a.legendHeight=r;g(l,function(b){a.positionItem(b)});e&&q.align(f({width:t,height:r},h),!0,"spacingBox");b.isResizing||this.positionCheckboxes()},handleOverflow:function(a){var b=this,f=this.chart,m=f.renderer,p=this.options,e=p.y,f=f.spacingBox.height+("top"===p.verticalAlign?-e:e)-this.padding,e=p.maxHeight,q,l=this.clipRect,t=p.navigation, h=d(t.animation,!0),y=t.arrowSize||12,r=this.nav,u=this.pages,I=this.padding,k,D=this.allItems,C=function(a){a?l.attr({height:a}):l&&(b.clipRect=l.destroy(),b.contentGroup.clip());b.contentGroup.div&&(b.contentGroup.div.style.clip=a?"rect("+I+"px,9999px,"+(I+a)+"px,0)":"auto")};"horizontal"!==p.layout||"middle"===p.verticalAlign||p.floating||(f/=2);e&&(f=Math.min(f,e));u.length=0;a>f&&!1!==t.enabled?(this.clipHeight=q=Math.max(f-20-this.titleHeight-I,0),this.currentPage=d(this.currentPage,1),this.fullHeight= a,g(D,function(a,b){var c=a._legendItemPos[1];a=Math.round(a.legendItem.getBBox().height);var e=u.length;if(!e||c-u[e-1]>q&&(k||c)!==u[e-1])u.push(k||c),e++;b===D.length-1&&c+a-u[e-1]>q&&u.push(c);c!==k&&(k=c)}),l||(l=b.clipRect=m.clipRect(0,I,9999,0),b.contentGroup.clip(l)),C(q),r||(this.nav=r=m.g().attr({zIndex:1}).add(this.group),this.up=m.symbol("triangle",0,0,y,y).on("click",function(){b.scroll(-1,h)}).add(r),this.pager=m.text("",15,10).addClass("highcharts-legend-navigation").css(t.style).add(r), this.down=m.symbol("triangle-down",0,0,y,y).on("click",function(){b.scroll(1,h)}).add(r)),b.scroll(0),a=f):r&&(C(),r.hide(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0);return a},scroll:function(a,c){var d=this.pages,f=d.length;a=this.currentPage+a;var m=this.clipHeight,e=this.options.navigation,p=this.pager,g=this.padding;a>f&&(a=f);0<a&&(void 0!==c&&b(c,this.chart),this.nav.attr({translateX:g,translateY:m+this.padding+7+this.titleHeight,visibility:"visible"}),this.up.attr({"class":1=== a?"highcharts-legend-nav-inactive":"highcharts-legend-nav-active"}),p.attr({text:a+"/"+f}),this.down.attr({x:18+this.pager.getBBox().width,"class":a===f?"highcharts-legend-nav-inactive":"highcharts-legend-nav-active"}),this.up.attr({fill:1===a?e.inactiveColor:e.activeColor}).css({cursor:1===a?"default":"pointer"}),this.down.attr({fill:a===f?e.inactiveColor:e.activeColor}).css({cursor:a===f?"default":"pointer"}),c=-d[a-1]+this.initialItemY,this.scrollGroup.animate({translateY:c}),this.currentPage= a,this.positionCheckboxes(c))}};a.LegendSymbolMixin={drawRectangle:function(a,b){var c=a.symbolHeight,f=a.options.squareSymbol;b.legendSymbol=this.chart.renderer.rect(f?(a.symbolWidth-c)/2:0,a.baseline-c+1,f?c:a.symbolWidth,c,d(a.options.symbolRadius,c/2)).addClass("highcharts-point").attr({zIndex:3}).add(b.legendGroup)},drawLineMarker:function(a){var b=this.options,f=b.marker,m=a.symbolWidth,p=a.symbolHeight,e=p/2,g=this.chart.renderer,l=this.legendGroup;a=a.baseline-Math.round(.3*a.fontMetrics.b); var t;t={"stroke-width":b.lineWidth||0};b.dashStyle&&(t.dashstyle=b.dashStyle);this.legendLine=g.path(["M",0,a,"L",m,a]).addClass("highcharts-graph").attr(t).add(l);f&&!1!==f.enabled&&(b=Math.min(d(f.radius,e),e),0===this.symbol.indexOf("url")&&(f=q(f,{width:p,height:p}),b=0),this.legendSymbol=f=g.symbol(this.symbol,m/2-b,a-b,2*b,2*b,f).addClass("highcharts-point").add(l),f.isMarker=!0)}};(/Trident\/7\.0/.test(C.navigator.userAgent)||u)&&t(B.prototype,"positionItem",function(a,b){var c=this,d=function(){b._legendItemPos&& a.call(c,b)};d();setTimeout(d)})})(L);(function(a){var B=a.addEvent,A=a.animate,H=a.animObject,G=a.attr,r=a.doc,g=a.Axis,f=a.createElement,u=a.defaultOptions,l=a.discardElement,q=a.charts,d=a.css,b=a.defined,p=a.each,C=a.extend,t=a.find,m=a.fireEvent,c=a.getStyle,n=a.grep,E=a.isNumber,z=a.isObject,e=a.isString,x=a.Legend,F=a.marginNames,w=a.merge,h=a.Pointer,y=a.pick,J=a.pInt,K=a.removeEvent,I=a.seriesTypes,k=a.splat,D=a.svg,P=a.syncTimeout,N=a.win,S=a.Renderer,O=a.Chart=function(){this.getArgs.apply(this, arguments)};a.chart=function(a,b,c){return new O(a,b,c)};O.prototype={callbacks:[],getArgs:function(){var a=[].slice.call(arguments);if(e(a[0])||a[0].nodeName)this.renderTo=a.shift();this.init(a[0],a[1])},init:function(b,c){var e,h=b.series;b.series=null;e=w(u,b);e.series=b.series=h;this.userOptions=b;this.respRules=[];b=e.chart;h=b.events;this.margin=[];this.spacing=[];this.bounds={h:{},v:{}};this.callback=c;this.isResizing=0;this.options=e;this.axes=[];this.series=[];this.hasCartesianSeries=b.showAxes; var d;this.index=q.length;q.push(this);a.chartCount++;if(h)for(d in h)B(this,d,h[d]);this.xAxis=[];this.yAxis=[];this.pointCount=this.colorCounter=this.symbolCounter=0;this.firstRender()},initSeries:function(b){var c=this.options.chart;(c=I[b.type||c.type||c.defaultSeriesType])||a.error(17,!0);c=new c;c.init(this,b);return c},orderSeries:function(a){var b=this.series;for(a=a||0;a<b.length;a++)b[a]&&(b[a].index=a,b[a].name=b[a].name||"Series "+(b[a].index+1))},isInsidePlot:function(a,b,c){var e=c? b:a;a=c?a:b;return 0<=e&&e<=this.plotWidth&&0<=a&&a<=this.plotHeight},redraw:function(b){var c=this.axes,e=this.series,h=this.pointer,d=this.legend,k=this.isDirtyLegend,f,n,y=this.hasCartesianSeries,g=this.isDirtyBox,v=e.length,l=v,q=this.renderer,t=q.isHidden(),w=[];this.setResponsive&&this.setResponsive(!1);a.setAnimation(b,this);t&&this.cloneRenderTo();for(this.layOutTitles();l--;)if(b=e[l],b.options.stacking&&(f=!0,b.isDirty)){n=!0;break}if(n)for(l=v;l--;)b=e[l],b.options.stacking&&(b.isDirty= !0);p(e,function(a){a.isDirty&&"point"===a.options.legendType&&(a.updateTotals&&a.updateTotals(),k=!0);a.isDirtyData&&m(a,"updatedData")});k&&d.options.enabled&&(d.render(),this.isDirtyLegend=!1);f&&this.getStacks();y&&p(c,function(a){a.updateNames();a.setScale()});this.getMargins();y&&(p(c,function(a){a.isDirty&&(g=!0)}),p(c,function(a){var b=a.min+","+a.max;a.extKey!==b&&(a.extKey=b,w.push(function(){m(a,"afterSetExtremes",C(a.eventArgs,a.getExtremes()));delete a.eventArgs}));(g||f)&&a.redraw()})); g&&this.drawChartBox();m(this,"predraw");p(e,function(a){(g||a.isDirty)&&a.visible&&a.redraw();a.isDirtyData=!1});h&&h.reset(!0);q.draw();m(this,"redraw");m(this,"render");t&&this.cloneRenderTo(!0);p(w,function(a){a.call()})},get:function(a){function b(b){return b.id===a||b.options&&b.options.id===a}var c,e=this.series,h;c=t(this.axes,b)||t(this.series,b);for(h=0;!c&&h<e.length;h++)c=t(e[h].points||[],b);return c},getAxes:function(){var a=this,b=this.options,c=b.xAxis=k(b.xAxis||{}),b=b.yAxis=k(b.yAxis|| {});p(c,function(a,b){a.index=b;a.isX=!0});p(b,function(a,b){a.index=b});c=c.concat(b);p(c,function(b){new g(a,b)})},getSelectedPoints:function(){var a=[];p(this.series,function(b){a=a.concat(n(b.points||[],function(a){return a.selected}))});return a},getSelectedSeries:function(){return n(this.series,function(a){return a.selected})},setTitle:function(a,b,c){var e=this,h=e.options,d;d=h.title=w({style:{color:"#333333",fontSize:h.isStock?"16px":"18px"}},h.title,a);h=h.subtitle=w({style:{color:"#666666"}}, h.subtitle,b);p([["title",a,d],["subtitle",b,h]],function(a,b){var c=a[0],h=e[c],d=a[1];a=a[2];h&&d&&(e[c]=h=h.destroy());a&&a.text&&!h&&(e[c]=e.renderer.text(a.text,0,0,a.useHTML).attr({align:a.align,"class":"highcharts-"+c,zIndex:a.zIndex||4}).add(),e[c].update=function(a){e.setTitle(!b&&a,b&&a)},e[c].css(a.style))});e.layOutTitles(c)},layOutTitles:function(a){var b=0,c,e=this.renderer,h=this.spacingBox;p(["title","subtitle"],function(a){var c=this[a],d=this.options[a],k;c&&(k=d.style.fontSize, k=e.fontMetrics(k,c).b,c.css({width:(d.width||h.width+d.widthAdjust)+"px"}).align(C({y:b+k+("title"===a?-3:2)},d),!1,"spacingBox"),d.floating||d.verticalAlign||(b=Math.ceil(b+c.getBBox().height)))},this);c=this.titleOffset!==b;this.titleOffset=b;!this.isDirtyBox&&c&&(this.isDirtyBox=c,this.hasRendered&&y(a,!0)&&this.isDirtyBox&&this.redraw())},getChartSize:function(){var a=this.options.chart,e=a.width,a=a.height,h=this.renderToClone||this.renderTo;b(e)||(this.containerWidth=c(h,"width"));b(a)||(this.containerHeight= c(h,"height"));this.chartWidth=Math.max(0,e||this.containerWidth||600);this.chartHeight=Math.max(0,a||this.containerHeight||400)},cloneRenderTo:function(a){var b=this.renderToClone,c=this.container;if(a){if(b){for(;b.childNodes.length;)this.renderTo.appendChild(b.firstChild);l(b);delete this.renderToClone}}else c&&c.parentNode===this.renderTo&&this.renderTo.removeChild(c),this.renderToClone=b=this.renderTo.cloneNode(0),d(b,{position:"absolute",top:"-9999px",display:"block"}),b.style.setProperty&& b.style.setProperty("display","block","important"),r.body.appendChild(b),c&&b.appendChild(c)},setClassName:function(a){this.container.className="highcharts-container "+(a||"")},getContainer:function(){var b,c=this.options,h=c.chart,d,k;b=this.renderTo;var m=a.uniqueKey(),n;b||(this.renderTo=b=h.renderTo);e(b)&&(this.renderTo=b=r.getElementById(b));b||a.error(13,!0);d=J(G(b,"data-highcharts-chart"));E(d)&&q[d]&&q[d].hasRendered&&q[d].destroy();G(b,"data-highcharts-chart",this.index);b.innerHTML=""; h.skipClone||b.offsetWidth||this.cloneRenderTo();this.getChartSize();d=this.chartWidth;k=this.chartHeight;n=C({position:"relative",overflow:"hidden",width:d+"px",height:k+"px",textAlign:"left",lineHeight:"normal",zIndex:0,"-webkit-tap-highlight-color":"rgba(0,0,0,0)"},h.style);this.container=b=f("div",{id:m},n,this.renderToClone||b);this._cursor=b.style.cursor;this.renderer=new (a[h.renderer]||S)(b,d,k,null,h.forExport,c.exporting&&c.exporting.allowHTML);this.setClassName(h.className);this.renderer.setStyle(h.style); this.renderer.chartIndex=this.index},getMargins:function(a){var c=this.spacing,e=this.margin,h=this.titleOffset;this.resetMargins();h&&!b(e[0])&&(this.plotTop=Math.max(this.plotTop,h+this.options.title.margin+c[0]));this.legend.display&&this.legend.adjustMargins(e,c);this.extraMargin&&(this[this.extraMargin.type]=(this[this.extraMargin.type]||0)+this.extraMargin.value);this.extraTopMargin&&(this.plotTop+=this.extraTopMargin);a||this.getAxisMargins()},getAxisMargins:function(){var a=this,c=a.axisOffset= [0,0,0,0],e=a.margin;a.hasCartesianSeries&&p(a.axes,function(a){a.visible&&a.getOffset()});p(F,function(h,d){b(e[d])||(a[h]+=c[d])});a.setChartSize()},reflow:function(a){var e=this,h=e.options.chart,d=e.renderTo,k=b(h.width),f=h.width||c(d,"width"),h=h.height||c(d,"height"),d=a?a.target:N;if(!k&&!e.isPrinting&&f&&h&&(d===N||d===r)){if(f!==e.containerWidth||h!==e.containerHeight)clearTimeout(e.reflowTimeout),e.reflowTimeout=P(function(){e.container&&e.setSize(void 0,void 0,!1)},a?100:0);e.containerWidth= f;e.containerHeight=h}},initReflow:function(){var a=this,b;b=B(N,"resize",function(b){a.reflow(b)});B(a,"destroy",b)},setSize:function(b,c,e){var h=this,k=h.renderer;h.isResizing+=1;a.setAnimation(e,h);h.oldChartHeight=h.chartHeight;h.oldChartWidth=h.chartWidth;void 0!==b&&(h.options.chart.width=b);void 0!==c&&(h.options.chart.height=c);h.getChartSize();b=k.globalAnimation;(b?A:d)(h.container,{width:h.chartWidth+"px",height:h.chartHeight+"px"},b);h.setChartSize(!0);k.setSize(h.chartWidth,h.chartHeight, e);p(h.axes,function(a){a.isDirty=!0;a.setScale()});h.isDirtyLegend=!0;h.isDirtyBox=!0;h.layOutTitles();h.getMargins();h.redraw(e);h.oldChartHeight=null;m(h,"resize");P(function(){h&&m(h,"endResize",null,function(){--h.isResizing})},H(b).duration)},setChartSize:function(a){var b=this.inverted,c=this.renderer,e=this.chartWidth,h=this.chartHeight,d=this.options.chart,k=this.spacing,f=this.clipOffset,m,n,y,g;this.plotLeft=m=Math.round(this.plotLeft);this.plotTop=n=Math.round(this.plotTop);this.plotWidth= y=Math.max(0,Math.round(e-m-this.marginRight));this.plotHeight=g=Math.max(0,Math.round(h-n-this.marginBottom));this.plotSizeX=b?g:y;this.plotSizeY=b?y:g;this.plotBorderWidth=d.plotBorderWidth||0;this.spacingBox=c.spacingBox={x:k[3],y:k[0],width:e-k[3]-k[1],height:h-k[0]-k[2]};this.plotBox=c.plotBox={x:m,y:n,width:y,height:g};e=2*Math.floor(this.plotBorderWidth/2);b=Math.ceil(Math.max(e,f[3])/2);c=Math.ceil(Math.max(e,f[0])/2);this.clipBox={x:b,y:c,width:Math.floor(this.plotSizeX-Math.max(e,f[1])/ 2-b),height:Math.max(0,Math.floor(this.plotSizeY-Math.max(e,f[2])/2-c))};a||p(this.axes,function(a){a.setAxisSize();a.setAxisTranslation()})},resetMargins:function(){var a=this,b=a.options.chart;p(["margin","spacing"],function(c){var e=b[c],h=z(e)?e:[e,e,e,e];p(["Top","Right","Bottom","Left"],function(e,d){a[c][d]=y(b[c+e],h[d])})});p(F,function(b,c){a[b]=y(a.margin[c],a.spacing[c])});a.axisOffset=[0,0,0,0];a.clipOffset=[0,0,0,0]},drawChartBox:function(){var a=this.options.chart,b=this.renderer,c= this.chartWidth,e=this.chartHeight,h=this.chartBackground,d=this.plotBackground,k=this.plotBorder,f,m=this.plotBGImage,n=a.backgroundColor,p=a.plotBackgroundColor,y=a.plotBackgroundImage,g,l=this.plotLeft,q=this.plotTop,t=this.plotWidth,w=this.plotHeight,x=this.plotBox,r=this.clipRect,z=this.clipBox,J="animate";h||(this.chartBackground=h=b.rect().addClass("highcharts-background").add(),J="attr");f=a.borderWidth||0;g=f+(a.shadow?8:0);n={fill:n||"none"};if(f||h["stroke-width"])n.stroke=a.borderColor, n["stroke-width"]=f;h.attr(n).shadow(a.shadow);h[J]({x:g/2,y:g/2,width:c-g-f%2,height:e-g-f%2,r:a.borderRadius});J="animate";d||(J="attr",this.plotBackground=d=b.rect().addClass("highcharts-plot-background").add());d[J](x);d.attr({fill:p||"none"}).shadow(a.plotShadow);y&&(m?m.animate(x):this.plotBGImage=b.image(y,l,q,t,w).add());r?r.animate({width:z.width,height:z.height}):this.clipRect=b.clipRect(z);J="animate";k||(J="attr",this.plotBorder=k=b.rect().addClass("highcharts-plot-border").attr({zIndex:1}).add()); k.attr({stroke:a.plotBorderColor,"stroke-width":a.plotBorderWidth||0,fill:"none"});k[J](k.crisp({x:l,y:q,width:t,height:w},-k.strokeWidth()));this.isDirtyBox=!1},propFromSeries:function(){var a=this,b=a.options.chart,c,e=a.options.series,h,d;p(["inverted","angular","polar"],function(k){c=I[b.type||b.defaultSeriesType];d=b[k]||c&&c.prototype[k];for(h=e&&e.length;!d&&h--;)(c=I[e[h].type])&&c.prototype[k]&&(d=!0);a[k]=d})},linkSeries:function(){var a=this,b=a.series;p(b,function(a){a.linkedSeries.length= 0});p(b,function(b){var c=b.options.linkedTo;e(c)&&(c=":previous"===c?a.series[b.index-1]:a.get(c))&&c.linkedParent!==b&&(c.linkedSeries.push(b),b.linkedParent=c,b.visible=y(b.options.visible,c.options.visible,b.visible))})},renderSeries:function(){p(this.series,function(a){a.translate();a.render()})},renderLabels:function(){var a=this,b=a.options.labels;b.items&&p(b.items,function(c){var e=C(b.style,c.style),h=J(e.left)+a.plotLeft,d=J(e.top)+a.plotTop+12;delete e.left;delete e.top;a.renderer.text(c.html, h,d).attr({zIndex:2}).css(e).add()})},render:function(){var a=this.axes,b=this.renderer,c=this.options,e,h,d;this.setTitle();this.legend=new x(this,c.legend);this.getStacks&&this.getStacks();this.getMargins(!0);this.setChartSize();c=this.plotWidth;e=this.plotHeight-=21;p(a,function(a){a.setScale()});this.getAxisMargins();h=1.1<c/this.plotWidth;d=1.05<e/this.plotHeight;if(h||d)p(a,function(a){(a.horiz&&h||!a.horiz&&d)&&a.setTickInterval(!0)}),this.getMargins();this.drawChartBox();this.hasCartesianSeries&& p(a,function(a){a.visible&&a.render()});this.seriesGroup||(this.seriesGroup=b.g("series-group").attr({zIndex:3}).add());this.renderSeries();this.renderLabels();this.addCredits();this.setResponsive&&this.setResponsive();this.hasRendered=!0},addCredits:function(a){var b=this;a=w(!0,this.options.credits,a);a.enabled&&!this.credits&&(this.credits=this.renderer.text(a.text+(this.mapCredits||""),0,0).addClass("highcharts-credits").on("click",function(){a.href&&(N.location.href=a.href)}).attr({align:a.position.align, zIndex:8}).css(a.style).add().align(a.position),this.credits.update=function(a){b.credits=b.credits.destroy();b.addCredits(a)})},destroy:function(){var b=this,c=b.axes,e=b.series,h=b.container,d,k=h&&h.parentNode;m(b,"destroy");q[b.index]=void 0;a.chartCount--;b.renderTo.removeAttribute("data-highcharts-chart");K(b);for(d=c.length;d--;)c[d]=c[d].destroy();this.scroller&&this.scroller.destroy&&this.scroller.destroy();for(d=e.length;d--;)e[d]=e[d].destroy();p("title subtitle chartBackground plotBackground plotBGImage plotBorder seriesGroup clipRect credits pointer rangeSelector legend resetZoomButton tooltip renderer".split(" "), function(a){var c=b[a];c&&c.destroy&&(b[a]=c.destroy())});h&&(h.innerHTML="",K(h),k&&l(h));for(d in b)delete b[d]},isReadyToRender:function(){var a=this;return D||N!=N.top||"complete"===r.readyState?!0:(r.attachEvent("onreadystatechange",function(){r.detachEvent("onreadystatechange",a.firstRender);"complete"===r.readyState&&a.firstRender()}),!1)},firstRender:function(){var a=this,b=a.options;if(a.isReadyToRender()){a.getContainer();m(a,"init");a.resetMargins();a.setChartSize();a.propFromSeries(); a.getAxes();p(b.series||[],function(b){a.initSeries(b)});a.linkSeries();m(a,"beforeRender");h&&(a.pointer=new h(a,b));a.render();if(!a.renderer.imgCount&&a.onload)a.onload();a.cloneRenderTo(!0)}},onload:function(){p([this.callback].concat(this.callbacks),function(a){a&&void 0!==this.index&&a.apply(this,[this])},this);m(this,"load");m(this,"render");b(this.index)&&!1!==this.options.chart.reflow&&this.initReflow();this.onload=null}}})(L);(function(a){var B,A=a.each,H=a.extend,G=a.erase,r=a.fireEvent, g=a.format,f=a.isArray,u=a.isNumber,l=a.pick,q=a.removeEvent;B=a.Point=function(){};B.prototype={init:function(a,b,f){this.series=a;this.color=a.color;this.applyOptions(b,f);a.options.colorByPoint?(b=a.options.colors||a.chart.options.colors,this.color=this.color||b[a.colorCounter],b=b.length,f=a.colorCounter,a.colorCounter++,a.colorCounter===b&&(a.colorCounter=0)):f=a.colorIndex;this.colorIndex=l(this.colorIndex,f);a.chart.pointCount++;return this},applyOptions:function(a,b){var d=this.series,f=d.options.pointValKey|| d.pointValKey;a=B.prototype.optionsToObject.call(this,a);H(this,a);this.options=this.options?H(this.options,a):a;a.group&&delete this.group;f&&(this.y=this[f]);this.isNull=l(this.isValid&&!this.isValid(),null===this.x||!u(this.y,!0));this.selected&&(this.state="select");"name"in this&&void 0===b&&d.xAxis&&d.xAxis.hasNames&&(this.x=d.xAxis.nameToX(this));void 0===this.x&&d&&(this.x=void 0===b?d.autoIncrement(this):b);return this},optionsToObject:function(a){var b={},d=this.series,g=d.options.keys, l=g||d.pointArrayMap||["y"],m=l.length,c=0,n=0;if(u(a)||null===a)b[l[0]]=a;else if(f(a))for(!g&&a.length>m&&(d=typeof a[0],"string"===d?b.name=a[0]:"number"===d&&(b.x=a[0]),c++);n<m;)g&&void 0===a[c]||(b[l[n]]=a[c]),c++,n++;else"object"===typeof a&&(b=a,a.dataLabels&&(d._hasPointLabels=!0),a.marker&&(d._hasPointMarkers=!0));return b},getClassName:function(){return"highcharts-point"+(this.selected?" highcharts-point-select":"")+(this.negative?" highcharts-negative":"")+(this.isNull?" highcharts-null-point": "")+(void 0!==this.colorIndex?" highcharts-color-"+this.colorIndex:"")+(this.options.className?" "+this.options.className:"")+(this.zone&&this.zone.className?" "+this.zone.className.replace("highcharts-negative",""):"")},getZone:function(){var a=this.series,b=a.zones,a=a.zoneAxis||"y",f=0,g;for(g=b[f];this[a]>=g.value;)g=b[++f];g&&g.color&&!this.options.color&&(this.color=g.color);return g},destroy:function(){var a=this.series.chart,b=a.hoverPoints,f;a.pointCount--;b&&(this.setState(),G(b,this),b.length|| (a.hoverPoints=null));if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)q(this),this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(f in this)this[f]=null},destroyElements:function(){for(var a=["graphic","dataLabel","dataLabelUpper","connector","shadowGroup"],b,f=6;f--;)b=a[f],this[b]&&(this[b]=this[b].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,color:this.color,colorIndex:this.colorIndex,key:this.name||this.category,series:this.series, point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(a){var b=this.series,d=b.tooltipOptions,f=l(d.valueDecimals,""),q=d.valuePrefix||"",m=d.valueSuffix||"";A(b.pointArrayMap||["y"],function(b){b="{point."+b;if(q||m)a=a.replace(b+"}",q+b+"}"+m);a=a.replace(b+"}",b+":,."+f+"f}")});return g(a,{point:this,series:this.series})},firePointEvent:function(a,b,f){var d=this,g=this.series.options;(g.point.events[a]||d.options&&d.options.events&&d.options.events[a])&& this.importEvents();"click"===a&&g.allowPointSelect&&(f=function(a){d.select&&d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});r(this,a,b,f)},visible:!0}})(L);(function(a){var B=a.addEvent,A=a.animObject,H=a.arrayMax,G=a.arrayMin,r=a.correctFloat,g=a.Date,f=a.defaultOptions,u=a.defaultPlotOptions,l=a.defined,q=a.each,d=a.erase,b=a.extend,p=a.fireEvent,C=a.grep,t=a.isArray,m=a.isNumber,c=a.isString,n=a.merge,E=a.pick,z=a.removeEvent,e=a.splat,x=a.SVGElement,F=a.syncTimeout,w=a.win;a.Series=a.seriesType("line", null,{lineWidth:2,allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},marker:{lineWidth:0,lineColor:"#ffffff",radius:4,states:{hover:{animation:{duration:50},enabled:!0,radiusPlus:2,lineWidthPlus:1},select:{fillColor:"#cccccc",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:{align:"center",formatter:function(){return null===this.y?"":a.numberFormat(this.y,-1)},style:{fontSize:"11px",fontWeight:"bold",color:"contrast",textOutline:"1px contrast"},verticalAlign:"bottom", x:0,y:0,padding:5},cropThreshold:300,pointRange:0,softThreshold:!0,states:{hover:{lineWidthPlus:1,marker:{},halo:{size:10,opacity:.25}},select:{marker:{}}},stickyTracking:!0,turboThreshold:1E3},{isCartesian:!0,pointClass:a.Point,sorted:!0,requireSorting:!0,directTouch:!1,axisTypes:["xAxis","yAxis"],colorCounter:0,parallelArrays:["x","y"],coll:"series",init:function(a,c){var e=this,h,d,k=a.series,f;e.chart=a;e.options=c=e.setOptions(c);e.linkedSeries=[];e.bindAxes();b(e,{name:c.name,state:"",visible:!1!== c.visible,selected:!0===c.selected});d=c.events;for(h in d)B(e,h,d[h]);if(d&&d.click||c.point&&c.point.events&&c.point.events.click||c.allowPointSelect)a.runTrackerClick=!0;e.getColor();e.getSymbol();q(e.parallelArrays,function(a){e[a+"Data"]=[]});e.setData(c.data,!1);e.isCartesian&&(a.hasCartesianSeries=!0);k.length&&(f=k[k.length-1]);e._i=E(f&&f._i,-1)+1;a.orderSeries(this.insert(k))},insert:function(a){var b=this.options.index,c;if(m(b)){for(c=a.length;c--;)if(b>=E(a[c].options.index,a[c]._i)){a.splice(c+ 1,0,this);break}-1===c&&a.unshift(this);c+=1}else a.push(this);return E(c,a.length-1)},bindAxes:function(){var b=this,c=b.options,e=b.chart,d;q(b.axisTypes||[],function(h){q(e[h],function(a){d=a.options;if(c[h]===d.index||void 0!==c[h]&&c[h]===d.id||void 0===c[h]&&0===d.index)b.insert(a.series),b[h]=a,a.isDirty=!0});b[h]||b.optionalAxis===h||a.error(18,!0)})},updateParallelArrays:function(a,b){var c=a.series,e=arguments,h=m(b)?function(e){var h="y"===e&&c.toYData?c.toYData(a):a[e];c[e+"Data"][b]= h}:function(a){Array.prototype[b].apply(c[a+"Data"],Array.prototype.slice.call(e,2))};q(c.parallelArrays,h)},autoIncrement:function(){var a=this.options,b=this.xIncrement,c,e=a.pointIntervalUnit,b=E(b,a.pointStart,0);this.pointInterval=c=E(this.pointInterval,a.pointInterval,1);e&&(a=new g(b),"day"===e?a=+a[g.hcSetDate](a[g.hcGetDate]()+c):"month"===e?a=+a[g.hcSetMonth](a[g.hcGetMonth]()+c):"year"===e&&(a=+a[g.hcSetFullYear](a[g.hcGetFullYear]()+c)),c=a-b);this.xIncrement=b+c;return b},setOptions:function(a){var b= this.chart,c=b.options.plotOptions,b=b.userOptions||{},e=b.plotOptions||{},h=c[this.type];this.userOptions=a;c=n(h,c.series,a);this.tooltipOptions=n(f.tooltip,f.plotOptions[this.type].tooltip,b.tooltip,e.series&&e.series.tooltip,e[this.type]&&e[this.type].tooltip,a.tooltip);null===h.marker&&delete c.marker;this.zoneAxis=c.zoneAxis;a=this.zones=(c.zones||[]).slice();!c.negativeColor&&!c.negativeFillColor||c.zones||a.push({value:c[this.zoneAxis+"Threshold"]||c.threshold||0,className:"highcharts-negative", color:c.negativeColor,fillColor:c.negativeFillColor});a.length&&l(a[a.length-1].value)&&a.push({color:this.color,fillColor:this.fillColor});return c},getCyclic:function(a,b,c){var e,h=this.chart,d=this.userOptions,f=a+"Index",n=a+"Counter",m=c?c.length:E(h.options.chart[a+"Count"],h[a+"Count"]);b||(e=E(d[f],d["_"+f]),l(e)||(h.series.length||(h[n]=0),d["_"+f]=e=h[n]%m,h[n]+=1),c&&(b=c[e]));void 0!==e&&(this[f]=e);this[a]=b},getColor:function(){this.options.colorByPoint?this.options.color=null:this.getCyclic("color", this.options.color||u[this.type].color,this.chart.options.colors)},getSymbol:function(){this.getCyclic("symbol",this.options.marker.symbol,this.chart.options.symbols)},drawLegendSymbol:a.LegendSymbolMixin.drawLineMarker,setData:function(b,e,d,f){var h=this,k=h.points,n=k&&k.length||0,g,p=h.options,y=h.chart,l=null,w=h.xAxis,x=p.turboThreshold,r=this.xData,z=this.yData,F=(g=h.pointArrayMap)&&g.length;b=b||[];g=b.length;e=E(e,!0);if(!1!==f&&g&&n===g&&!h.cropped&&!h.hasGroupedData&&h.visible)q(b,function(a, b){k[b].update&&a!==p.data[b]&&k[b].update(a,!1,null,!1)});else{h.xIncrement=null;h.colorCounter=0;q(this.parallelArrays,function(a){h[a+"Data"].length=0});if(x&&g>x){for(d=0;null===l&&d<g;)l=b[d],d++;if(m(l))for(d=0;d<g;d++)r[d]=this.autoIncrement(),z[d]=b[d];else if(t(l))if(F)for(d=0;d<g;d++)l=b[d],r[d]=l[0],z[d]=l.slice(1,F+1);else for(d=0;d<g;d++)l=b[d],r[d]=l[0],z[d]=l[1];else a.error(12)}else for(d=0;d<g;d++)void 0!==b[d]&&(l={series:h},h.pointClass.prototype.applyOptions.apply(l,[b[d]]),h.updateParallelArrays(l, d));c(z[0])&&a.error(14,!0);h.data=[];h.options.data=h.userOptions.data=b;for(d=n;d--;)k[d]&&k[d].destroy&&k[d].destroy();w&&(w.minRange=w.userMinRange);h.isDirty=y.isDirtyBox=!0;h.isDirtyData=!!k;d=!1}"point"===p.legendType&&(this.processData(),this.generatePoints());e&&y.redraw(d)},processData:function(b){var c=this.xData,e=this.yData,h=c.length,d;d=0;var k,f,n=this.xAxis,m,g=this.options;m=g.cropThreshold;var p=this.getExtremesFromAll||g.getExtremesFromAll,l=this.isCartesian,g=n&&n.val2lin,q=n&& n.isLog,t,w;if(l&&!this.isDirty&&!n.isDirty&&!this.yAxis.isDirty&&!b)return!1;n&&(b=n.getExtremes(),t=b.min,w=b.max);if(l&&this.sorted&&!p&&(!m||h>m||this.forceCrop))if(c[h-1]<t||c[0]>w)c=[],e=[];else if(c[0]<t||c[h-1]>w)d=this.cropData(this.xData,this.yData,t,w),c=d.xData,e=d.yData,d=d.start,k=!0;for(m=c.length||1;--m;)h=q?g(c[m])-g(c[m-1]):c[m]-c[m-1],0<h&&(void 0===f||h<f)?f=h:0>h&&this.requireSorting&&a.error(15);this.cropped=k;this.cropStart=d;this.processedXData=c;this.processedYData=e;this.closestPointRange= f},cropData:function(a,b,c,e){var h=a.length,d=0,f=h,n=E(this.cropShoulder,1),m;for(m=0;m<h;m++)if(a[m]>=c){d=Math.max(0,m-n);break}for(c=m;c<h;c++)if(a[c]>e){f=c+n;break}return{xData:a.slice(d,f),yData:b.slice(d,f),start:d,end:f}},generatePoints:function(){var a=this.options.data,b=this.data,c,d=this.processedXData,f=this.processedYData,k=this.pointClass,n=d.length,m=this.cropStart||0,g,p=this.hasGroupedData,l,q=[],t;b||p||(b=[],b.length=a.length,b=this.data=b);for(t=0;t<n;t++)g=m+t,p?(l=(new k).init(this, [d[t]].concat(e(f[t]))),l.dataGroup=this.groupMap[t]):(l=b[g])||void 0===a[g]||(b[g]=l=(new k).init(this,a[g],d[t])),l.index=g,q[t]=l;if(b&&(n!==(c=b.length)||p))for(t=0;t<c;t++)t!==m||p||(t+=n),b[t]&&(b[t].destroyElements(),b[t].plotX=void 0);this.data=b;this.points=q},getExtremes:function(a){var b=this.yAxis,c=this.processedXData,e,h=[],d=0;e=this.xAxis.getExtremes();var f=e.min,n=e.max,g,p,l,q;a=a||this.stackedYData||this.processedYData||[];e=a.length;for(q=0;q<e;q++)if(p=c[q],l=a[q],g=(m(l,!0)|| t(l))&&(!b.isLog||l.length||0<l),p=this.getExtremesFromAll||this.options.getExtremesFromAll||this.cropped||(c[q+1]||p)>=f&&(c[q-1]||p)<=n,g&&p)if(g=l.length)for(;g--;)null!==l[g]&&(h[d++]=l[g]);else h[d++]=l;this.dataMin=G(h);this.dataMax=H(h)},translate:function(){this.processedXData||this.processData();this.generatePoints();var a=this.options,b=a.stacking,c=this.xAxis,e=c.categories,d=this.yAxis,k=this.points,f=k.length,n=!!this.modifyValue,g=a.pointPlacement,p="between"===g||m(g),q=a.threshold, t=a.startFromThreshold?q:0,w,x,z,F,u=Number.MAX_VALUE;"between"===g&&(g=.5);m(g)&&(g*=E(a.pointRange||c.pointRange));for(a=0;a<f;a++){var C=k[a],A=C.x,B=C.y;x=C.low;var H=b&&d.stacks[(this.negStacks&&B<(t?0:q)?"-":"")+this.stackKey],G;d.isLog&&null!==B&&0>=B&&(C.isNull=!0);C.plotX=w=r(Math.min(Math.max(-1E5,c.translate(A,0,0,0,1,g,"flags"===this.type)),1E5));b&&this.visible&&!C.isNull&&H&&H[A]&&(F=this.getStackIndicator(F,A,this.index),G=H[A],B=G.points[F.key],x=B[0],B=B[1],x===t&&F.key===H[A].base&& (x=E(q,d.min)),d.isLog&&0>=x&&(x=null),C.total=C.stackTotal=G.total,C.percentage=G.total&&C.y/G.total*100,C.stackY=B,G.setOffset(this.pointXOffset||0,this.barW||0));C.yBottom=l(x)?d.translate(x,0,1,0,1):null;n&&(B=this.modifyValue(B,C));C.plotY=x="number"===typeof B&&Infinity!==B?Math.min(Math.max(-1E5,d.translate(B,0,1,0,1)),1E5):void 0;C.isInside=void 0!==x&&0<=x&&x<=d.len&&0<=w&&w<=c.len;C.clientX=p?r(c.translate(A,0,0,0,1,g)):w;C.negative=C.y<(q||0);C.category=e&&void 0!==e[C.x]?e[C.x]:C.x;C.isNull|| (void 0!==z&&(u=Math.min(u,Math.abs(w-z))),z=w);C.zone=this.zones.length&&C.getZone()}this.closestPointRangePx=u},getValidPoints:function(a,b){var c=this.chart;return C(a||this.points||[],function(a){return b&&!c.isInsidePlot(a.plotX,a.plotY,c.inverted)?!1:!a.isNull})},setClip:function(a){var b=this.chart,c=this.options,e=b.renderer,d=b.inverted,h=this.clipBox,f=h||b.clipBox,n=this.sharedClipKey||["_sharedClip",a&&a.duration,a&&a.easing,f.height,c.xAxis,c.yAxis].join(),m=b[n],g=b[n+"m"];m||(a&&(f.width= 0,b[n+"m"]=g=e.clipRect(-99,d?-b.plotLeft:-b.plotTop,99,d?b.chartWidth:b.chartHeight)),b[n]=m=e.clipRect(f),m.count={length:0});a&&!m.count[this.index]&&(m.count[this.index]=!0,m.count.length+=1);!1!==c.clip&&(this.group.clip(a||h?m:b.clipRect),this.markerGroup.clip(g),this.sharedClipKey=n);a||(m.count[this.index]&&(delete m.count[this.index],--m.count.length),0===m.count.length&&n&&b[n]&&(h||(b[n]=b[n].destroy()),b[n+"m"]&&(this.markerGroup.clip(),b[n+"m"]=b[n+"m"].destroy())))},animate:function(a){var b= this.chart,c=A(this.options.animation),e;a?this.setClip(c):(e=this.sharedClipKey,(a=b[e])&&a.animate({width:b.plotSizeX},c),b[e+"m"]&&b[e+"m"].animate({width:b.plotSizeX+99},c),this.animate=null)},afterAnimate:function(){this.setClip();p(this,"afterAnimate")},drawPoints:function(){var a=this.points,b=this.chart,c,e,d,k,f=this.options.marker,n,g,p,l,q=this.markerGroup,t=E(f.enabled,this.xAxis.isRadial?!0:null,this.closestPointRangePx>2*f.radius);if(!1!==f.enabled||this._hasPointMarkers)for(e=0;e<a.length;e++)d= a[e],c=d.plotY,k=d.graphic,n=d.marker||{},g=!!d.marker,p=t&&void 0===n.enabled||n.enabled,l=d.isInside,p&&m(c)&&null!==d.y?(c=E(n.symbol,this.symbol),d.hasImage=0===c.indexOf("url"),p=this.markerAttribs(d,d.selected&&"select"),k?k[l?"show":"hide"](!0).animate(p):l&&(0<p.width||d.hasImage)&&(d.graphic=k=b.renderer.symbol(c,p.x,p.y,p.width,p.height,g?n:f).add(q)),k&&k.attr(this.pointAttribs(d,d.selected&&"select")),k&&k.addClass(d.getClassName(),!0)):k&&(d.graphic=k.destroy())},markerAttribs:function(a, b){var c=this.options.marker,e=a.marker||{},d=E(e.radius,c.radius);b&&(c=c.states[b],b=e.states&&e.states[b],d=E(b&&b.radius,c&&c.radius,d+(c&&c.radiusPlus||0)));a.hasImage&&(d=0);a={x:Math.floor(a.plotX)-d,y:a.plotY-d};d&&(a.width=a.height=2*d);return a},pointAttribs:function(a,b){var c=this.options.marker,e=a&&a.options,d=e&&e.marker||{},h=this.color,f=e&&e.color,n=a&&a.color,e=E(d.lineWidth,c.lineWidth);a=a&&a.zone&&a.zone.color;h=f||a||n||h;a=d.fillColor||c.fillColor||h;h=d.lineColor||c.lineColor|| h;b&&(c=c.states[b],b=d.states&&d.states[b]||{},e=E(b.lineWidth,c.lineWidth,e+E(b.lineWidthPlus,c.lineWidthPlus,0)),a=b.fillColor||c.fillColor||a,h=b.lineColor||c.lineColor||h);return{stroke:h,"stroke-width":e,fill:a}},destroy:function(){var a=this,b=a.chart,c=/AppleWebKit\/533/.test(w.navigator.userAgent),e,f=a.data||[],k,n,m;p(a,"destroy");z(a);q(a.axisTypes||[],function(b){(m=a[b])&&m.series&&(d(m.series,a),m.isDirty=m.forceRedraw=!0)});a.legendItem&&a.chart.legend.destroyItem(a);for(e=f.length;e--;)(k= f[e])&&k.destroy&&k.destroy();a.points=null;clearTimeout(a.animationTimeout);for(n in a)a[n]instanceof x&&!a[n].survive&&(e=c&&"group"===n?"hide":"destroy",a[n][e]());b.hoverSeries===a&&(b.hoverSeries=null);d(b.series,a);b.orderSeries();for(n in a)delete a[n]},getGraphPath:function(a,b,c){var e=this,d=e.options,h=d.step,f,n=[],m=[],g;a=a||e.points;(f=a.reversed)&&a.reverse();(h={right:1,center:2}[h]||h&&3)&&f&&(h=4-h);!d.connectNulls||b||c||(a=this.getValidPoints(a));q(a,function(f,k){var p=f.plotX, q=f.plotY,t=a[k-1];(f.leftCliff||t&&t.rightCliff)&&!c&&(g=!0);f.isNull&&!l(b)&&0<k?g=!d.connectNulls:f.isNull&&!b?g=!0:(0===k||g?k=["M",f.plotX,f.plotY]:e.getPointSpline?k=e.getPointSpline(a,f,k):h?(k=1===h?["L",t.plotX,q]:2===h?["L",(t.plotX+p)/2,t.plotY,"L",(t.plotX+p)/2,q]:["L",p,t.plotY],k.push("L",p,q)):k=["L",p,q],m.push(f.x),h&&m.push(f.x),n.push.apply(n,k),g=!1)});n.xMap=m;return e.graphPath=n},drawGraph:function(){var a=this,b=this.options,c=(this.gappedPath||this.getGraphPath).call(this), e=[["graph","highcharts-graph",b.lineColor||this.color,b.dashStyle]];q(this.zones,function(c,d){e.push(["zone-graph-"+d,"highcharts-graph highcharts-zone-graph-"+d+" "+(c.className||""),c.color||a.color,c.dashStyle||b.dashStyle])});q(e,function(e,d){var h=e[0],f=a[h];f?(f.endX=c.xMap,f.animate({d:c})):c.length&&(a[h]=a.chart.renderer.path(c).addClass(e[1]).attr({zIndex:1}).add(a.group),f={stroke:e[2],"stroke-width":b.lineWidth,fill:a.fillGraph&&a.color||"none"},e[3]?f.dashstyle=e[3]:"square"!==b.linecap&& (f["stroke-linecap"]=f["stroke-linejoin"]="round"),f=a[h].attr(f).shadow(2>d&&b.shadow));f&&(f.startX=c.xMap,f.isArea=c.isArea)})},applyZones:function(){var a=this,b=this.chart,c=b.renderer,e=this.zones,d,f,n=this.clips||[],m,g=this.graph,p=this.area,l=Math.max(b.chartWidth,b.chartHeight),t=this[(this.zoneAxis||"y")+"Axis"],w,x,r=b.inverted,z,F,u,C,A=!1;e.length&&(g||p)&&t&&void 0!==t.min&&(x=t.reversed,z=t.horiz,g&&g.hide(),p&&p.hide(),w=t.getExtremes(),q(e,function(e,h){d=x?z?b.plotWidth:0:z?0: t.toPixels(w.min);d=Math.min(Math.max(E(f,d),0),l);f=Math.min(Math.max(Math.round(t.toPixels(E(e.value,w.max),!0)),0),l);A&&(d=f=t.toPixels(w.max));F=Math.abs(d-f);u=Math.min(d,f);C=Math.max(d,f);t.isXAxis?(m={x:r?C:u,y:0,width:F,height:l},z||(m.x=b.plotHeight-m.x)):(m={x:0,y:r?C:u,width:l,height:F},z&&(m.y=b.plotWidth-m.y));r&&c.isVML&&(m=t.isXAxis?{x:0,y:x?u:C,height:m.width,width:b.chartWidth}:{x:m.y-b.plotLeft-b.spacingBox.x,y:0,width:m.height,height:b.chartHeight});n[h]?n[h].animate(m):(n[h]= c.clipRect(m),g&&a["zone-graph-"+h].clip(n[h]),p&&a["zone-area-"+h].clip(n[h]));A=e.value>w.max}),this.clips=n)},invertGroups:function(a){function b(){q(["group","markerGroup"],function(b){c[b]&&(c[b].width=c.yAxis.len,c[b].height=c.xAxis.len,c[b].invert(a))})}var c=this,e;c.xAxis&&(e=B(c.chart,"resize",b),B(c,"destroy",e),b(a),c.invertGroups=b)},plotGroup:function(a,b,c,e,d){var h=this[a],f=!h;f&&(this[a]=h=this.chart.renderer.g(b).attr({zIndex:e||.1}).add(d),h.addClass("highcharts-series-"+this.index+ " highcharts-"+this.type+"-series highcharts-color-"+this.colorIndex+" "+(this.options.className||"")));h.attr({visibility:c})[f?"attr":"animate"](this.getPlotBox());return h},getPlotBox:function(){var a=this.chart,b=this.xAxis,c=this.yAxis;a.inverted&&(b=c,c=this.xAxis);return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:a.plotTop,scaleX:1,scaleY:1}},render:function(){var a=this,b=a.chart,c,e=a.options,d=!!a.animate&&b.renderer.isSVG&&A(e.animation).duration,f=a.visible?"inherit":"hidden",n= e.zIndex,m=a.hasRendered,g=b.seriesGroup,p=b.inverted;c=a.plotGroup("group","series",f,n,g);a.markerGroup=a.plotGroup("markerGroup","markers",f,n,g);d&&a.animate(!0);c.inverted=a.isCartesian?p:!1;a.drawGraph&&(a.drawGraph(),a.applyZones());a.drawDataLabels&&a.drawDataLabels();a.visible&&a.drawPoints();a.drawTracker&&!1!==a.options.enableMouseTracking&&a.drawTracker();a.invertGroups(p);!1===e.clip||a.sharedClipKey||m||c.clip(b.clipRect);d&&a.animate();m||(a.animationTimeout=F(function(){a.afterAnimate()}, d));a.isDirty=!1;a.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirty||this.isDirtyData,c=this.group,e=this.xAxis,d=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:E(e&&e.left,a.plotLeft),translateY:E(d&&d.top,a.plotTop)}));this.translate();this.render();b&&delete this.kdTree},kdDimensions:1,kdAxisArray:["clientX","plotY"],searchPoint:function(a,b){var c=this.xAxis,e=this.yAxis,d=this.chart.inverted;return this.searchKDTree({clientX:d? c.len-a.chartY+c.pos:a.chartX-c.pos,plotY:d?e.len-a.chartX+e.pos:a.chartY-e.pos},b)},buildKDTree:function(){function a(c,e,d){var h,f;if(f=c&&c.length)return h=b.kdAxisArray[e%d],c.sort(function(a,b){return a[h]-b[h]}),f=Math.floor(f/2),{point:c[f],left:a(c.slice(0,f),e+1,d),right:a(c.slice(f+1),e+1,d)}}this.buildingKdTree=!0;var b=this,c=b.kdDimensions;delete b.kdTree;F(function(){b.kdTree=a(b.getValidPoints(null,!b.directTouch),c,c);b.buildingKdTree=!1},b.options.kdNow?0:1)},searchKDTree:function(a, b){function c(a,b,k,n){var m=b.point,g=e.kdAxisArray[k%n],p,t,q=m;t=l(a[d])&&l(m[d])?Math.pow(a[d]-m[d],2):null;p=l(a[h])&&l(m[h])?Math.pow(a[h]-m[h],2):null;p=(t||0)+(p||0);m.dist=l(p)?Math.sqrt(p):Number.MAX_VALUE;m.distX=l(t)?Math.sqrt(t):Number.MAX_VALUE;g=a[g]-m[g];p=0>g?"left":"right";t=0>g?"right":"left";b[p]&&(p=c(a,b[p],k+1,n),q=p[f]<q[f]?p:m);b[t]&&Math.sqrt(g*g)<q[f]&&(a=c(a,b[t],k+1,n),q=a[f]<q[f]?a:q);return q}var e=this,d=this.kdAxisArray[0],h=this.kdAxisArray[1],f=b?"distX":"dist"; this.kdTree||this.buildingKdTree||this.buildKDTree();if(this.kdTree)return c(a,this.kdTree,this.kdDimensions,this.kdDimensions)}})})(L);(function(a){function B(a,d,b,f,g){var p=a.chart.inverted;this.axis=a;this.isNegative=b;this.options=d;this.x=f;this.total=null;this.points={};this.stack=g;this.rightCliff=this.leftCliff=0;this.alignOptions={align:d.align||(p?b?"left":"right":"center"),verticalAlign:d.verticalAlign||(p?"middle":b?"bottom":"top"),y:l(d.y,p?4:b?14:-6),x:l(d.x,p?b?-6:6:0)};this.textAlign= d.textAlign||(p?b?"right":"left":"center")}var A=a.Axis,H=a.Chart,G=a.correctFloat,r=a.defined,g=a.destroyObjectProperties,f=a.each,u=a.format,l=a.pick;a=a.Series;B.prototype={destroy:function(){g(this,this.axis)},render:function(a){var d=this.options,b=d.format,b=b?u(b,this):d.formatter.call(this);this.label?this.label.attr({text:b,visibility:"hidden"}):this.label=this.axis.chart.renderer.text(b,null,null,d.useHTML).css(d.style).attr({align:this.textAlign,rotation:d.rotation,visibility:"hidden"}).add(a)}, setOffset:function(a,d){var b=this.axis,f=b.chart,g=f.inverted,l=b.reversed,l=this.isNegative&&!l||!this.isNegative&&l,m=b.translate(b.usePercentage?100:this.total,0,0,0,1),b=b.translate(0),b=Math.abs(m-b);a=f.xAxis[0].translate(this.x)+a;var c=f.plotHeight,g={x:g?l?m:m-b:a,y:g?c-a-d:l?c-m-b:c-m,width:g?b:d,height:g?d:b};if(d=this.label)d.align(this.alignOptions,null,g),g=d.alignAttr,d[!1===this.options.crop||f.isInsidePlot(g.x,g.y)?"show":"hide"](!0)}};H.prototype.getStacks=function(){var a=this; f(a.yAxis,function(a){a.stacks&&a.hasVisibleSeries&&(a.oldStacks=a.stacks)});f(a.series,function(d){!d.options.stacking||!0!==d.visible&&!1!==a.options.chart.ignoreHiddenSeries||(d.stackKey=d.type+l(d.options.stack,""))})};A.prototype.buildStacks=function(){var a=this.series,d,b=l(this.options.reversedStacks,!0),f=a.length,g;if(!this.isXAxis){this.usePercentage=!1;for(g=f;g--;)a[b?g:f-g-1].setStackedPoints();for(g=f;g--;)d=a[b?g:f-g-1],d.setStackCliffs&&d.setStackCliffs();if(this.usePercentage)for(g= 0;g<f;g++)a[g].setPercentStacks()}};A.prototype.renderStackTotals=function(){var a=this.chart,d=a.renderer,b=this.stacks,f,g,l=this.stackTotalGroup;l||(this.stackTotalGroup=l=d.g("stack-labels").attr({visibility:"visible",zIndex:6}).add());l.translate(a.plotLeft,a.plotTop);for(f in b)for(g in a=b[f],a)a[g].render(l)};A.prototype.resetStacks=function(){var a=this.stacks,d,b;if(!this.isXAxis)for(d in a)for(b in a[d])a[d][b].touched<this.stacksTouched?(a[d][b].destroy(),delete a[d][b]):(a[d][b].total= null,a[d][b].cum=null)};A.prototype.cleanStacks=function(){var a,d,b;if(!this.isXAxis)for(d in this.oldStacks&&(a=this.stacks=this.oldStacks),a)for(b in a[d])a[d][b].cum=a[d][b].total};a.prototype.setStackedPoints=function(){if(this.options.stacking&&(!0===this.visible||!1===this.chart.options.chart.ignoreHiddenSeries)){var a=this.processedXData,d=this.processedYData,b=[],f=d.length,g=this.options,t=g.threshold,m=g.startFromThreshold?t:0,c=g.stack,g=g.stacking,n=this.stackKey,u="-"+n,z=this.negStacks, e=this.yAxis,x=e.stacks,F=e.oldStacks,w,h,y,A,K,I,k;e.stacksTouched+=1;for(K=0;K<f;K++)I=a[K],k=d[K],w=this.getStackIndicator(w,I,this.index),A=w.key,y=(h=z&&k<(m?0:t))?u:n,x[y]||(x[y]={}),x[y][I]||(F[y]&&F[y][I]?(x[y][I]=F[y][I],x[y][I].total=null):x[y][I]=new B(e,e.options.stackLabels,h,I,c)),y=x[y][I],null!==k&&(y.points[A]=y.points[this.index]=[l(y.cum,m)],r(y.cum)||(y.base=A),y.touched=e.stacksTouched,0<w.index&&!1===this.singleStacks&&(y.points[A][0]=y.points[this.index+","+I+",0"][0])),"percent"=== g?(h=h?n:u,z&&x[h]&&x[h][I]?(h=x[h][I],y.total=h.total=Math.max(h.total,y.total)+Math.abs(k)||0):y.total=G(y.total+(Math.abs(k)||0))):y.total=G(y.total+(k||0)),y.cum=l(y.cum,m)+(k||0),null!==k&&(y.points[A].push(y.cum),b[K]=y.cum);"percent"===g&&(e.usePercentage=!0);this.stackedYData=b;e.oldStacks={}}};a.prototype.setPercentStacks=function(){var a=this,d=a.stackKey,b=a.yAxis.stacks,g=a.processedXData,l;f([d,"-"+d],function(d){for(var f=g.length,c,n;f--;)if(c=g[f],l=a.getStackIndicator(l,c,a.index, d),c=(n=b[d]&&b[d][c])&&n.points[l.key])n=n.total?100/n.total:0,c[0]=G(c[0]*n),c[1]=G(c[1]*n),a.stackedYData[f]=c[1]})};a.prototype.getStackIndicator=function(a,d,b,f){!r(a)||a.x!==d||f&&a.key!==f?a={x:d,index:0,key:f}:a.index++;a.key=[b,d,a.index].join();return a}})(L);(function(a){var B=a.addEvent,A=a.animate,H=a.Axis,G=a.createElement,r=a.css,g=a.defined,f=a.each,u=a.erase,l=a.extend,q=a.fireEvent,d=a.inArray,b=a.isNumber,p=a.isObject,C=a.merge,t=a.pick,m=a.Point,c=a.Series,n=a.seriesTypes,E=a.setAnimation, z=a.splat;l(a.Chart.prototype,{addSeries:function(a,b,c){var e,d=this;a&&(b=t(b,!0),q(d,"addSeries",{options:a},function(){e=d.initSeries(a);d.isDirtyLegend=!0;d.linkSeries();b&&d.redraw(c)}));return e},addAxis:function(a,b,c,d){var e=b?"xAxis":"yAxis",f=this.options;a=C(a,{index:this[e].length,isX:b});new H(this,a);f[e]=z(f[e]||{});f[e].push(a);t(c,!0)&&this.redraw(d)},showLoading:function(a){var b=this,c=b.options,e=b.loadingDiv,d=c.loading,f=function(){e&&r(e,{left:b.plotLeft+"px",top:b.plotTop+ "px",width:b.plotWidth+"px",height:b.plotHeight+"px"})};e||(b.loadingDiv=e=G("div",{className:"highcharts-loading highcharts-loading-hidden"},null,b.container),b.loadingSpan=G("span",{className:"highcharts-loading-inner"},null,e),B(b,"redraw",f));e.className="highcharts-loading";b.loadingSpan.innerHTML=a||c.lang.loading;r(e,l(d.style,{zIndex:10}));r(b.loadingSpan,d.labelStyle);b.loadingShown||(r(e,{opacity:0,display:""}),A(e,{opacity:d.style.opacity||.5},{duration:d.showDuration||0}));b.loadingShown= !0;f()},hideLoading:function(){var a=this.options,b=this.loadingDiv;b&&(b.className="highcharts-loading highcharts-loading-hidden",A(b,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){r(b,{display:"none"})}}));this.loadingShown=!1},propsRequireDirtyBox:"backgroundColor borderColor borderWidth margin marginTop marginRight marginBottom marginLeft spacing spacingTop spacingRight spacingBottom spacingLeft borderRadius plotBackgroundColor plotBackgroundImage plotBorderColor plotBorderWidth plotShadow shadow".split(" "), propsRequireUpdateSeries:"chart.inverted chart.polar chart.ignoreHiddenSeries chart.type colors plotOptions".split(" "),update:function(a,c){var e,n={credits:"addCredits",title:"setTitle",subtitle:"setSubtitle"},h=a.chart,m,p;if(h){C(!0,this.options.chart,h);"className"in h&&this.setClassName(h.className);if("inverted"in h||"polar"in h)this.propFromSeries(),m=!0;for(e in h)h.hasOwnProperty(e)&&(-1!==d("chart."+e,this.propsRequireUpdateSeries)&&(p=!0),-1!==d(e,this.propsRequireDirtyBox)&&(this.isDirtyBox= !0));"style"in h&&this.renderer.setStyle(h.style)}for(e in a){if(this[e]&&"function"===typeof this[e].update)this[e].update(a[e],!1);else if("function"===typeof this[n[e]])this[n[e]](a[e]);"chart"!==e&&-1!==d(e,this.propsRequireUpdateSeries)&&(p=!0)}a.colors&&(this.options.colors=a.colors);a.plotOptions&&C(!0,this.options.plotOptions,a.plotOptions);f(["xAxis","yAxis","series"],function(b){a[b]&&f(z(a[b]),function(a,c){(c=g(a.id)&&this.get(a.id)||this[b][c])&&c.coll===b&&c.update(a,!1)},this)},this); m&&f(this.axes,function(a){a.update({},!1)});p&&f(this.series,function(a){a.update({},!1)});a.loading&&C(!0,this.options.loading,a.loading);e=h&&h.width;h=h&&h.height;b(e)&&e!==this.chartWidth||b(h)&&h!==this.chartHeight?this.setSize(e,h):t(c,!0)&&this.redraw()},setSubtitle:function(a){this.setTitle(void 0,a)}});l(m.prototype,{update:function(a,b,c,d){function e(){f.applyOptions(a);null===f.y&&n&&(f.graphic=n.destroy());p(a,!0)&&(n&&n.element&&a&&a.marker&&a.marker.symbol&&(f.graphic=n.destroy()), a&&a.dataLabels&&f.dataLabel&&(f.dataLabel=f.dataLabel.destroy()));m=f.index;g.updateParallelArrays(f,m);l.data[m]=p(l.data[m],!0)?f.options:a;g.isDirty=g.isDirtyData=!0;!g.fixedBox&&g.hasCartesianSeries&&(k.isDirtyBox=!0);"point"===l.legendType&&(k.isDirtyLegend=!0);b&&k.redraw(c)}var f=this,g=f.series,n=f.graphic,m,k=g.chart,l=g.options;b=t(b,!0);!1===d?e():f.firePointEvent("update",{options:a},e)},remove:function(a,b){this.series.removePoint(d(this,this.series.data),a,b)}});l(c.prototype,{addPoint:function(a, b,c,d){var e=this.options,f=this.data,g=this.chart,n=this.xAxis,n=n&&n.hasNames&&n.names,m=e.data,k,p,l=this.xData,q,w;b=t(b,!0);k={series:this};this.pointClass.prototype.applyOptions.apply(k,[a]);w=k.x;q=l.length;if(this.requireSorting&&w<l[q-1])for(p=!0;q&&l[q-1]>w;)q--;this.updateParallelArrays(k,"splice",q,0,0);this.updateParallelArrays(k,q);n&&k.name&&(n[w]=k.name);m.splice(q,0,a);p&&(this.data.splice(q,0,null),this.processData());"point"===e.legendType&&this.generatePoints();c&&(f[0]&&f[0].remove? f[0].remove(!1):(f.shift(),this.updateParallelArrays(k,"shift"),m.shift()));this.isDirtyData=this.isDirty=!0;b&&g.redraw(d)},removePoint:function(a,b,c){var e=this,d=e.data,f=d[a],g=e.points,n=e.chart,m=function(){g&&g.length===d.length&&g.splice(a,1);d.splice(a,1);e.options.data.splice(a,1);e.updateParallelArrays(f||{series:e},"splice",a,1);f&&f.destroy();e.isDirty=!0;e.isDirtyData=!0;b&&n.redraw()};E(c,n);b=t(b,!0);f?f.firePointEvent("remove",null,m):m()},remove:function(a,b,c){function e(){d.destroy(); f.isDirtyLegend=f.isDirtyBox=!0;f.linkSeries();t(a,!0)&&f.redraw(b)}var d=this,f=d.chart;!1!==c?q(d,"remove",null,e):e()},update:function(a,b){var c=this,e=this.chart,d=this.userOptions,g=this.type,m=a.type||d.type||e.options.chart.type,p=n[g].prototype,q=["group","markerGroup","dataLabelsGroup"],k;if(m&&m!==g||void 0!==a.zIndex)q.length=0;f(q,function(a){q[a]=c[a];delete c[a]});a=C(d,{animation:!1,index:this.index,pointStart:this.xData[0]},{data:this.options.data},a);this.remove(!1,null,!1);for(k in p)this[k]= void 0;l(this,n[m||g].prototype);f(q,function(a){c[a]=q[a]});this.init(e,a);e.linkSeries();t(b,!0)&&e.redraw(!1)}});l(H.prototype,{update:function(a,b){var c=this.chart;a=c.options[this.coll][this.options.index]=C(this.userOptions,a);this.destroy(!0);this.init(c,l(a,{events:void 0}));c.isDirtyBox=!0;t(b,!0)&&c.redraw()},remove:function(a){for(var b=this.chart,c=this.coll,e=this.series,d=e.length;d--;)e[d]&&e[d].remove(!1);u(b.axes,this);u(b[c],this);b.options[c].splice(this.options.index,1);f(b[c], function(a,b){a.options.index=b});this.destroy();b.isDirtyBox=!0;t(a,!0)&&b.redraw()},setTitle:function(a,b){this.update({title:a},b)},setCategories:function(a,b){this.update({categories:a},b)}})})(L);(function(a){var B=a.color,A=a.each,H=a.map,G=a.pick,r=a.Series,g=a.seriesType;g("area","line",{softThreshold:!1,threshold:0},{singleStacks:!1,getStackPoints:function(){var a=[],g=[],l=this.xAxis,q=this.yAxis,d=q.stacks[this.stackKey],b={},p=this.points,r=this.index,t=q.series,m=t.length,c,n=G(q.options.reversedStacks, !0)?1:-1,E,z;if(this.options.stacking){for(E=0;E<p.length;E++)b[p[E].x]=p[E];for(z in d)null!==d[z].total&&g.push(z);g.sort(function(a,b){return a-b});c=H(t,function(){return this.visible});A(g,function(e,f){var p=0,t,h;if(b[e]&&!b[e].isNull)a.push(b[e]),A([-1,1],function(a){var p=1===a?"rightNull":"leftNull",l=0,q=d[g[f+a]];if(q)for(E=r;0<=E&&E<m;)t=q.points[E],t||(E===r?b[e][p]=!0:c[E]&&(h=d[e].points[E])&&(l-=h[1]-h[0])),E+=n;b[e][1===a?"rightCliff":"leftCliff"]=l});else{for(E=r;0<=E&&E<m;){if(t= d[e].points[E]){p=t[1];break}E+=n}p=q.toPixels(p,!0);a.push({isNull:!0,plotX:l.toPixels(e,!0),plotY:p,yBottom:p})}})}return a},getGraphPath:function(a){var f=r.prototype.getGraphPath,g=this.options,q=g.stacking,d=this.yAxis,b,p,C=[],t=[],m=this.index,c,n=d.stacks[this.stackKey],E=g.threshold,z=d.getThreshold(g.threshold),e,g=g.connectNulls||"percent"===q,x=function(b,e,f){var h=a[b];b=q&&n[h.x].points[m];var g=h[f+"Null"]||0;f=h[f+"Cliff"]||0;var p,l,h=!0;f||g?(p=(g?b[0]:b[1])+f,l=b[0]+f,h=!!g):!q&& a[e]&&a[e].isNull&&(p=l=E);void 0!==p&&(t.push({plotX:c,plotY:null===p?z:d.getThreshold(p),isNull:h}),C.push({plotX:c,plotY:null===l?z:d.getThreshold(l),doCurve:!1}))};a=a||this.points;q&&(a=this.getStackPoints());for(b=0;b<a.length;b++)if(p=a[b].isNull,c=G(a[b].rectPlotX,a[b].plotX),e=G(a[b].yBottom,z),!p||g)g||x(b,b-1,"left"),p&&!q&&g||(t.push(a[b]),C.push({x:b,plotX:c,plotY:e})),g||x(b,b+1,"right");b=f.call(this,t,!0,!0);C.reversed=!0;p=f.call(this,C,!0,!0);p.length&&(p[0]="L");p=b.concat(p);f= f.call(this,t,!1,g);p.xMap=b.xMap;this.areaPath=p;return f},drawGraph:function(){this.areaPath=[];r.prototype.drawGraph.apply(this);var a=this,g=this.areaPath,l=this.options,q=[["area","highcharts-area",this.color,l.fillColor]];A(this.zones,function(d,b){q.push(["zone-area-"+b,"highcharts-area highcharts-zone-area-"+b+" "+d.className,d.color||a.color,d.fillColor||l.fillColor])});A(q,function(d){var b=d[0],f=a[b];f?(f.endX=g.xMap,f.animate({d:g})):(f=a[b]=a.chart.renderer.path(g).addClass(d[1]).attr({fill:G(d[3], B(d[2]).setOpacity(G(l.fillOpacity,.75)).get()),zIndex:0}).add(a.group),f.isArea=!0);f.startX=g.xMap;f.shiftUnit=l.step?2:1})},drawLegendSymbol:a.LegendSymbolMixin.drawRectangle})})(L);(function(a){var B=a.pick;a=a.seriesType;a("spline","line",{},{getPointSpline:function(a,H,G){var r=H.plotX,g=H.plotY,f=a[G-1];G=a[G+1];var u,l,q,d;if(f&&!f.isNull&&!1!==f.doCurve&&G&&!G.isNull&&!1!==G.doCurve){a=f.plotY;q=G.plotX;G=G.plotY;var b=0;u=(1.5*r+f.plotX)/2.5;l=(1.5*g+a)/2.5;q=(1.5*r+q)/2.5;d=(1.5*g+G)/2.5; q!==u&&(b=(d-l)*(q-r)/(q-u)+g-d);l+=b;d+=b;l>a&&l>g?(l=Math.max(a,g),d=2*g-l):l<a&&l<g&&(l=Math.min(a,g),d=2*g-l);d>G&&d>g?(d=Math.max(G,g),l=2*g-d):d<G&&d<g&&(d=Math.min(G,g),l=2*g-d);H.rightContX=q;H.rightContY=d}H=["C",B(f.rightContX,f.plotX),B(f.rightContY,f.plotY),B(u,r),B(l,g),r,g];f.rightContX=f.rightContY=null;return H}})})(L);(function(a){var B=a.seriesTypes.area.prototype,A=a.seriesType;A("areaspline","spline",a.defaultPlotOptions.area,{getStackPoints:B.getStackPoints,getGraphPath:B.getGraphPath, setStackCliffs:B.setStackCliffs,drawGraph:B.drawGraph,drawLegendSymbol:a.LegendSymbolMixin.drawRectangle})})(L);(function(a){var B=a.animObject,A=a.color,H=a.each,G=a.extend,r=a.isNumber,g=a.merge,f=a.pick,u=a.Series,l=a.seriesType,q=a.svg;l("column","line",{borderRadius:0,groupPadding:.2,marker:null,pointPadding:.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{halo:!1,brightness:.1,shadow:!1},select:{color:"#cccccc",borderColor:"#000000",shadow:!1}},dataLabels:{align:null,verticalAlign:null, y:null},softThreshold:!1,startFromThreshold:!0,stickyTracking:!1,tooltip:{distance:6},threshold:0,borderColor:"#ffffff"},{cropShoulder:0,directTouch:!0,trackerGroups:["group","dataLabelsGroup"],negStacks:!0,init:function(){u.prototype.init.apply(this,arguments);var a=this,b=a.chart;b.hasRendered&&H(b.series,function(b){b.type===a.type&&(b.isDirty=!0)})},getColumnMetrics:function(){var a=this,b=a.options,g=a.xAxis,l=a.yAxis,t=g.reversed,m,c={},n=0;!1===b.grouping?n=1:H(a.chart.series,function(b){var e= b.options,d=b.yAxis,f;b.type===a.type&&b.visible&&l.len===d.len&&l.pos===d.pos&&(e.stacking?(m=b.stackKey,void 0===c[m]&&(c[m]=n++),f=c[m]):!1!==e.grouping&&(f=n++),b.columnIndex=f)});var q=Math.min(Math.abs(g.transA)*(g.ordinalSlope||b.pointRange||g.closestPointRange||g.tickInterval||1),g.len),r=q*b.groupPadding,e=(q-2*r)/(n||1),b=Math.min(b.maxPointWidth||g.len,f(b.pointWidth,e*(1-2*b.pointPadding)));a.columnMetrics={width:b,offset:(e-b)/2+(r+((a.columnIndex||0)+(t?1:0))*e-q/2)*(t?-1:1)};return a.columnMetrics}, crispCol:function(a,b,f,g){var d=this.chart,m=this.borderWidth,c=-(m%2?.5:0),m=m%2?.5:1;d.inverted&&d.renderer.isVML&&(m+=1);f=Math.round(a+f)+c;a=Math.round(a)+c;g=Math.round(b+g)+m;c=.5>=Math.abs(b)&&.5<g;b=Math.round(b)+m;g-=b;c&&g&&(--b,g+=1);return{x:a,y:b,width:f-a,height:g}},translate:function(){var a=this,b=a.chart,g=a.options,l=a.dense=2>a.closestPointRange*a.xAxis.transA,l=a.borderWidth=f(g.borderWidth,l?0:1),t=a.yAxis,m=a.translatedThreshold=t.getThreshold(g.threshold),c=f(g.minPointLength, 5),n=a.getColumnMetrics(),q=n.width,r=a.barW=Math.max(q,1+2*l),e=a.pointXOffset=n.offset;b.inverted&&(m-=.5);g.pointPadding&&(r=Math.ceil(r));u.prototype.translate.apply(a);H(a.points,function(d){var g=f(d.yBottom,m),n=999+Math.abs(g),n=Math.min(Math.max(-n,d.plotY),t.len+n),h=d.plotX+e,l=r,p=Math.min(n,g),z,x=Math.max(n,g)-p;Math.abs(x)<c&&c&&(x=c,z=!t.reversed&&!d.negative||t.reversed&&d.negative,p=Math.abs(p-m)>c?g-c:m-(z?c:0));d.barX=h;d.pointWidth=q;d.tooltipPos=b.inverted?[t.len+t.pos-b.plotLeft- n,a.xAxis.len-h-l/2,x]:[h+l/2,n+t.pos-b.plotTop,x];d.shapeType="rect";d.shapeArgs=a.crispCol.apply(a,d.isNull?[d.plotX,t.len/2,0,0]:[h,p,l,x])})},getSymbol:a.noop,drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,drawGraph:function(){this.group[this.dense?"addClass":"removeClass"]("highcharts-dense-data")},pointAttribs:function(a,b){var d=this.options,f,g=this.pointAttrToOptions||{};f=g.stroke||"borderColor";var m=g["stroke-width"]||"borderWidth",c=a&&a.color||this.color,n=a[f]||d[f]||this.color|| c,l=a[m]||d[m]||this[m]||0,g=d.dashStyle;a&&this.zones.length&&(c=(c=a.getZone())&&c.color||a.options.color||this.color);b&&(a=d.states[b],b=a.brightness,c=a.color||void 0!==b&&A(c).brighten(a.brightness).get()||c,n=a[f]||n,l=a[m]||l,g=a.dashStyle||g);f={fill:c,stroke:n,"stroke-width":l};d.borderRadius&&(f.r=d.borderRadius);g&&(f.dashstyle=g);return f},drawPoints:function(){var a=this,b=this.chart,f=a.options,l=b.renderer,t=f.animationLimit||250,m;H(a.points,function(c){var d=c.graphic;if(r(c.plotY)&& null!==c.y){m=c.shapeArgs;if(d)d[b.pointCount<t?"animate":"attr"](g(m));else c.graphic=d=l[c.shapeType](m).attr({"class":c.getClassName()}).add(c.group||a.group);d.attr(a.pointAttribs(c,c.selected&&"select")).shadow(f.shadow,null,f.stacking&&!f.borderRadius)}else d&&(c.graphic=d.destroy())})},animate:function(a){var b=this,d=this.yAxis,f=b.options,g=this.chart.inverted,m={};q&&(a?(m.scaleY=.001,a=Math.min(d.pos+d.len,Math.max(d.pos,d.toPixels(f.threshold))),g?m.translateX=a-d.len:m.translateY=a,b.group.attr(m)): (m[g?"translateX":"translateY"]=d.pos,b.group.animate(m,G(B(b.options.animation),{step:function(a,d){b.group.attr({scaleY:Math.max(.001,d.pos)})}})),b.animate=null))},remove:function(){var a=this,b=a.chart;b.hasRendered&&H(b.series,function(b){b.type===a.type&&(b.isDirty=!0)});u.prototype.remove.apply(a,arguments)}})})(L);(function(a){a=a.seriesType;a("bar","column",null,{inverted:!0})})(L);(function(a){var B=a.Series;a=a.seriesType;a("scatter","line",{lineWidth:0,marker:{enabled:!0},tooltip:{headerFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e \x3cspan style\x3d"font-size: 0.85em"\x3e {series.name}\x3c/span\x3e\x3cbr/\x3e', pointFormat:"x: \x3cb\x3e{point.x}\x3c/b\x3e\x3cbr/\x3ey: \x3cb\x3e{point.y}\x3c/b\x3e\x3cbr/\x3e"}},{sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group","markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1,kdDimensions:2,drawGraph:function(){this.options.lineWidth&&B.prototype.drawGraph.call(this)}})})(L);(function(a){var B=a.pick,A=a.relativeLength;a.CenteredSeriesMixin={getCenter:function(){var a=this.options,G=this.chart,r=2*(a.slicedOffset||0),g=G.plotWidth-2*r,G=G.plotHeight- 2*r,f=a.center,f=[B(f[0],"50%"),B(f[1],"50%"),a.size||"100%",a.innerSize||0],u=Math.min(g,G),l,q;for(l=0;4>l;++l)q=f[l],a=2>l||2===l&&/%$/.test(q),f[l]=A(q,[g,G,u,f[2]][l])+(a?r:0);f[3]>f[2]&&(f[3]=f[2]);return f}}})(L);(function(a){var B=a.addEvent,A=a.defined,H=a.each,G=a.extend,r=a.inArray,g=a.noop,f=a.pick,u=a.Point,l=a.Series,q=a.seriesType,d=a.setAnimation;q("pie","line",{center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return null===this.y? void 0:this.point.name},x:0},ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,stickyTracking:!1,tooltip:{followPointer:!0},borderColor:"#ffffff",borderWidth:1,states:{hover:{brightness:.1,shadow:!1}}},{isCartesian:!1,requireSorting:!1,directTouch:!0,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttribs:a.seriesTypes.column.prototype.pointAttribs,animate:function(a){var b=this,d=b.points,f=b.startAngleRad;a||(H(d,function(a){var c= a.graphic,d=a.shapeArgs;c&&(c.attr({r:a.startR||b.center[3]/2,start:f,end:f}),c.animate({r:d.r,start:d.start,end:d.end},b.options.animation))}),b.animate=null)},updateTotals:function(){var a,d=0,f=this.points,g=f.length,m,c=this.options.ignoreHiddenPoint;for(a=0;a<g;a++)m=f[a],0>m.y&&(m.y=null),d+=c&&!m.visible?0:m.y;this.total=d;for(a=0;a<g;a++)m=f[a],m.percentage=0<d&&(m.visible||!c)?m.y/d*100:0,m.total=d},generatePoints:function(){l.prototype.generatePoints.call(this);this.updateTotals()},translate:function(a){this.generatePoints(); var b=0,d=this.options,g=d.slicedOffset,m=g+(d.borderWidth||0),c,n,l,q=d.startAngle||0,e=this.startAngleRad=Math.PI/180*(q-90),q=(this.endAngleRad=Math.PI/180*(f(d.endAngle,q+360)-90))-e,r=this.points,u=d.dataLabels.distance,d=d.ignoreHiddenPoint,w,h=r.length,y;a||(this.center=a=this.getCenter());this.getX=function(b,c){l=Math.asin(Math.min((b-a[1])/(a[2]/2+u),1));return a[0]+(c?-1:1)*Math.cos(l)*(a[2]/2+u)};for(w=0;w<h;w++){y=r[w];c=e+b*q;if(!d||y.visible)b+=y.percentage/100;n=e+b*q;y.shapeType= "arc";y.shapeArgs={x:a[0],y:a[1],r:a[2]/2,innerR:a[3]/2,start:Math.round(1E3*c)/1E3,end:Math.round(1E3*n)/1E3};l=(n+c)/2;l>1.5*Math.PI?l-=2*Math.PI:l<-Math.PI/2&&(l+=2*Math.PI);y.slicedTranslation={translateX:Math.round(Math.cos(l)*g),translateY:Math.round(Math.sin(l)*g)};c=Math.cos(l)*a[2]/2;n=Math.sin(l)*a[2]/2;y.tooltipPos=[a[0]+.7*c,a[1]+.7*n];y.half=l<-Math.PI/2||l>Math.PI/2?1:0;y.angle=l;m=Math.min(m,u/5);y.labelPos=[a[0]+c+Math.cos(l)*u,a[1]+n+Math.sin(l)*u,a[0]+c+Math.cos(l)*m,a[1]+n+Math.sin(l)* m,a[0]+c,a[1]+n,0>u?"center":y.half?"right":"left",l]}},drawGraph:null,drawPoints:function(){var a=this,d=a.chart.renderer,f,g,m,c,n=a.options.shadow;n&&!a.shadowGroup&&(a.shadowGroup=d.g("shadow").add(a.group));H(a.points,function(b){if(null!==b.y){g=b.graphic;c=b.shapeArgs;f=b.sliced?b.slicedTranslation:{};var l=b.shadowGroup;n&&!l&&(l=b.shadowGroup=d.g("shadow").add(a.shadowGroup));l&&l.attr(f);m=a.pointAttribs(b,b.selected&&"select");g?g.setRadialReference(a.center).attr(m).animate(G(c,f)):(b.graphic= g=d[b.shapeType](c).addClass(b.getClassName()).setRadialReference(a.center).attr(f).add(a.group),b.visible||g.attr({visibility:"hidden"}),g.attr(m).attr({"stroke-linejoin":"round"}).shadow(n,l))}})},searchPoint:g,sortByAngle:function(a,d){a.sort(function(a,b){return void 0!==a.angle&&(b.angle-a.angle)*d})},drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,getCenter:a.CenteredSeriesMixin.getCenter,getSymbol:g},{init:function(){u.prototype.init.apply(this,arguments);var a=this,d;a.name=f(a.name,"Slice"); d=function(b){a.slice("select"===b.type)};B(a,"select",d);B(a,"unselect",d);return a},setVisible:function(a,d){var b=this,g=b.series,m=g.chart,c=g.options.ignoreHiddenPoint;d=f(d,c);a!==b.visible&&(b.visible=b.options.visible=a=void 0===a?!b.visible:a,g.options.data[r(b,g.data)]=b.options,H(["graphic","dataLabel","connector","shadowGroup"],function(c){if(b[c])b[c][a?"show":"hide"](!0)}),b.legendItem&&m.legend.colorizeItem(b,a),a||"hover"!==b.state||b.setState(""),c&&(g.isDirty=!0),d&&m.redraw())}, slice:function(a,g,l){var b=this.series;d(l,b.chart);f(g,!0);this.sliced=this.options.sliced=a=A(a)?a:!this.sliced;b.options.data[r(this,b.data)]=this.options;a=a?this.slicedTranslation:{translateX:0,translateY:0};this.graphic.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)},haloPath:function(a){var b=this.shapeArgs;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(b.x,b.y,b.r+a,b.r+a,{innerR:this.shapeArgs.r,start:b.start,end:b.end})}})})(L);(function(a){var B= a.addEvent,A=a.arrayMax,H=a.defined,G=a.each,r=a.extend,g=a.format,f=a.map,u=a.merge,l=a.noop,q=a.pick,d=a.relativeLength,b=a.Series,p=a.seriesTypes,C=a.stableSort;a.distribute=function(a,b){function c(a,b){return a.target-b.target}var d,g=!0,m=a,e=[],l;l=0;for(d=a.length;d--;)l+=a[d].size;if(l>b){C(a,function(a,b){return(b.rank||0)-(a.rank||0)});for(l=d=0;l<=b;)l+=a[d].size,d++;e=a.splice(d-1,a.length)}C(a,c);for(a=f(a,function(a){return{size:a.size,targets:[a.target]}});g;){for(d=a.length;d--;)g= a[d],l=(Math.min.apply(0,g.targets)+Math.max.apply(0,g.targets))/2,g.pos=Math.min(Math.max(0,l-g.size/2),b-g.size);d=a.length;for(g=!1;d--;)0<d&&a[d-1].pos+a[d-1].size>a[d].pos&&(a[d-1].size+=a[d].size,a[d-1].targets=a[d-1].targets.concat(a[d].targets),a[d-1].pos+a[d-1].size>b&&(a[d-1].pos=b-a[d-1].size),a.splice(d,1),g=!0)}d=0;G(a,function(a){var b=0;G(a.targets,function(){m[d].pos=a.pos+b;b+=m[d].size;d++})});m.push.apply(m,e);C(m,c)};b.prototype.drawDataLabels=function(){var a=this,b=a.options, c=b.dataLabels,d=a.points,f,l,e=a.hasRendered||0,p,r,w=q(c.defer,!0),h=a.chart.renderer;if(c.enabled||a._hasPointLabels)a.dlProcessOptions&&a.dlProcessOptions(c),r=a.plotGroup("dataLabelsGroup","data-labels",w&&!e?"hidden":"visible",c.zIndex||6),w&&(r.attr({opacity:+e}),e||B(a,"afterAnimate",function(){a.visible&&r.show(!0);r[b.animation?"animate":"attr"]({opacity:1},{duration:200})})),l=c,G(d,function(e){var d,m=e.dataLabel,n,k,t,z=e.connector,w=!m,x;f=e.dlOptions||e.options&&e.options.dataLabels; if(d=q(f&&f.enabled,l.enabled)&&null!==e.y)for(k in c=u(l,f),n=e.getLabelConfig(),p=c.format?g(c.format,n):c.formatter.call(n,c),x=c.style,t=c.rotation,x.color=q(c.color,x.color,a.color,"#000000"),"contrast"===x.color&&(x.color=c.inside||0>c.distance||b.stacking?h.getContrast(e.color||a.color):"#000000"),b.cursor&&(x.cursor=b.cursor),n={fill:c.backgroundColor,stroke:c.borderColor,"stroke-width":c.borderWidth,r:c.borderRadius||0,rotation:t,padding:c.padding,zIndex:1},n)void 0===n[k]&&delete n[k];!m|| d&&H(p)?d&&H(p)&&(m?n.text=p:(m=e.dataLabel=h[t?"text":"label"](p,0,-9999,c.shape,null,null,c.useHTML,null,"data-label"),m.addClass("highcharts-data-label-color-"+e.colorIndex+" "+(c.className||"")+(c.useHTML?"highcharts-tracker":""))),m.attr(n),m.css(x).shadow(c.shadow),m.added||m.add(r),a.alignDataLabel(e,m,c,null,w)):(e.dataLabel=m.destroy(),z&&(e.connector=z.destroy()))})};b.prototype.alignDataLabel=function(a,b,c,d,f){var g=this.chart,e=g.inverted,m=q(a.plotX,-9999),n=q(a.plotY,-9999),l=b.getBBox(), h,p=c.rotation,t=c.align,u=this.visible&&(a.series.forceDL||g.isInsidePlot(m,Math.round(n),e)||d&&g.isInsidePlot(m,e?d.x+1:d.y+d.height-1,e)),E="justify"===q(c.overflow,"justify");u&&(h=c.style.fontSize,h=g.renderer.fontMetrics(h,b).b,d=r({x:e?g.plotWidth-n:m,y:Math.round(e?g.plotHeight-m:n),width:0,height:0},d),r(c,{width:l.width,height:l.height}),p?(E=!1,e=g.renderer.rotCorr(h,p),e={x:d.x+c.x+d.width/2+e.x,y:d.y+c.y+{top:0,middle:.5,bottom:1}[c.verticalAlign]*d.height},b[f?"attr":"animate"](e).attr({align:t}), m=(p+720)%360,m=180<m&&360>m,"left"===t?e.y-=m?l.height:0:"center"===t?(e.x-=l.width/2,e.y-=l.height/2):"right"===t&&(e.x-=l.width,e.y-=m?0:l.height)):(b.align(c,null,d),e=b.alignAttr),E?this.justifyDataLabel(b,c,e,l,d,f):q(c.crop,!0)&&(u=g.isInsidePlot(e.x,e.y)&&g.isInsidePlot(e.x+l.width,e.y+l.height)),c.shape&&!p&&b.attr({anchorX:a.plotX,anchorY:a.plotY}));u||(b.attr({y:-9999}),b.placed=!1)};b.prototype.justifyDataLabel=function(a,b,c,d,f,g){var e=this.chart,m=b.align,n=b.verticalAlign,l,h,p=a.box? 0:a.padding||0;l=c.x+p;0>l&&("right"===m?b.align="left":b.x=-l,h=!0);l=c.x+d.width-p;l>e.plotWidth&&("left"===m?b.align="right":b.x=e.plotWidth-l,h=!0);l=c.y+p;0>l&&("bottom"===n?b.verticalAlign="top":b.y=-l,h=!0);l=c.y+d.height-p;l>e.plotHeight&&("top"===n?b.verticalAlign="bottom":b.y=e.plotHeight-l,h=!0);h&&(a.placed=!g,a.align(b,null,f))};p.pie&&(p.pie.prototype.drawDataLabels=function(){var d=this,g=d.data,c,l=d.chart,p=d.options.dataLabels,r=q(p.connectorPadding,10),e=q(p.connectorWidth,1),u= l.plotWidth,F=l.plotHeight,w,h=p.distance,y=d.center,C=y[2]/2,B=y[1],H=0<h,k,D,L,N,S=[[],[]],O,v,M,Q,R=[0,0,0,0];d.visible&&(p.enabled||d._hasPointLabels)&&(b.prototype.drawDataLabels.apply(d),G(g,function(a){a.dataLabel&&a.visible&&(S[a.half].push(a),a.dataLabel._pos=null)}),G(S,function(b,e){var g,m,n=b.length,q,t,z;if(n)for(d.sortByAngle(b,e-.5),0<h&&(g=Math.max(0,B-C-h),m=Math.min(B+C+h,l.plotHeight),q=f(b,function(a){if(a.dataLabel)return z=a.dataLabel.getBBox().height||21,{target:a.labelPos[1]- g+z/2,size:z,rank:a.y}}),a.distribute(q,m+z-g)),Q=0;Q<n;Q++)c=b[Q],L=c.labelPos,k=c.dataLabel,M=!1===c.visible?"hidden":"inherit",t=L[1],q?void 0===q[Q].pos?M="hidden":(N=q[Q].size,v=g+q[Q].pos):v=t,O=p.justify?y[0]+(e?-1:1)*(C+h):d.getX(v<g+2||v>m-2?t:v,e),k._attr={visibility:M,align:L[6]},k._pos={x:O+p.x+({left:r,right:-r}[L[6]]||0),y:v+p.y-10},L.x=O,L.y=v,null===d.options.size&&(D=k.width,O-D<r?R[3]=Math.max(Math.round(D-O+r),R[3]):O+D>u-r&&(R[1]=Math.max(Math.round(O+D-u+r),R[1])),0>v-N/2?R[0]= Math.max(Math.round(-v+N/2),R[0]):v+N/2>F&&(R[2]=Math.max(Math.round(v+N/2-F),R[2])))}),0===A(R)||this.verifyDataLabelOverflow(R))&&(this.placeDataLabels(),H&&e&&G(this.points,function(a){var b;w=a.connector;if((k=a.dataLabel)&&k._pos&&a.visible){M=k._attr.visibility;if(b=!w)a.connector=w=l.renderer.path().addClass("highcharts-data-label-connector highcharts-color-"+a.colorIndex).add(d.dataLabelsGroup),w.attr({"stroke-width":e,stroke:p.connectorColor||a.color||"#666666"});w[b?"attr":"animate"]({d:d.connectorPath(a.labelPos)}); w.attr("visibility",M)}else w&&(a.connector=w.destroy())}))},p.pie.prototype.connectorPath=function(a){var b=a.x,c=a.y;return q(this.options.dataLabels.softConnector,!0)?["M",b+("left"===a[6]?5:-5),c,"C",b,c,2*a[2]-a[4],2*a[3]-a[5],a[2],a[3],"L",a[4],a[5]]:["M",b+("left"===a[6]?5:-5),c,"L",a[2],a[3],"L",a[4],a[5]]},p.pie.prototype.placeDataLabels=function(){G(this.points,function(a){var b=a.dataLabel;b&&a.visible&&((a=b._pos)?(b.attr(b._attr),b[b.moved?"animate":"attr"](a),b.moved=!0):b&&b.attr({y:-9999}))})}, p.pie.prototype.alignDataLabel=l,p.pie.prototype.verifyDataLabelOverflow=function(a){var b=this.center,c=this.options,f=c.center,g=c.minSize||80,l,e;null!==f[0]?l=Math.max(b[2]-Math.max(a[1],a[3]),g):(l=Math.max(b[2]-a[1]-a[3],g),b[0]+=(a[3]-a[1])/2);null!==f[1]?l=Math.max(Math.min(l,b[2]-Math.max(a[0],a[2])),g):(l=Math.max(Math.min(l,b[2]-a[0]-a[2]),g),b[1]+=(a[0]-a[2])/2);l<b[2]?(b[2]=l,b[3]=Math.min(d(c.innerSize||0,l),l),this.translate(b),this.drawDataLabels&&this.drawDataLabels()):e=!0;return e}); p.column&&(p.column.prototype.alignDataLabel=function(a,d,c,f,g){var l=this.chart.inverted,e=a.series,m=a.dlBox||a.shapeArgs,n=q(a.below,a.plotY>q(this.translatedThreshold,e.yAxis.len)),p=q(c.inside,!!this.options.stacking);m&&(f=u(m),0>f.y&&(f.height+=f.y,f.y=0),m=f.y+f.height-e.yAxis.len,0<m&&(f.height-=m),l&&(f={x:e.yAxis.len-f.y-f.height,y:e.xAxis.len-f.x-f.width,width:f.height,height:f.width}),p||(l?(f.x+=n?0:f.width,f.width=0):(f.y+=n?f.height:0,f.height=0)));c.align=q(c.align,!l||p?"center": n?"right":"left");c.verticalAlign=q(c.verticalAlign,l||p?"middle":n?"top":"bottom");b.prototype.alignDataLabel.call(this,a,d,c,f,g)})})(L);(function(a){var B=a.Chart,A=a.each,H=a.pick,G=a.addEvent;B.prototype.callbacks.push(function(a){function g(){var f=[];A(a.series,function(a){var g=a.options.dataLabels,q=a.dataLabelCollections||["dataLabel"];(g.enabled||a._hasPointLabels)&&!g.allowOverlap&&a.visible&&A(q,function(d){A(a.points,function(a){a[d]&&(a[d].labelrank=H(a.labelrank,a.shapeArgs&&a.shapeArgs.height), f.push(a[d]))})})});a.hideOverlappingLabels(f)}g();G(a,"redraw",g)});B.prototype.hideOverlappingLabels=function(a){var g=a.length,f,r,l,q,d,b,p,C,t,m=function(a,b,d,f,e,g,l,m){return!(e>a+d||e+l<a||g>b+f||g+m<b)};for(r=0;r<g;r++)if(f=a[r])f.oldOpacity=f.opacity,f.newOpacity=1;a.sort(function(a,b){return(b.labelrank||0)-(a.labelrank||0)});for(r=0;r<g;r++)for(l=a[r],f=r+1;f<g;++f)if(q=a[f],l&&q&&l.placed&&q.placed&&0!==l.newOpacity&&0!==q.newOpacity&&(d=l.alignAttr,b=q.alignAttr,p=l.parentGroup,C=q.parentGroup, t=2*(l.box?0:l.padding),d=m(d.x+p.translateX,d.y+p.translateY,l.width-t,l.height-t,b.x+C.translateX,b.y+C.translateY,q.width-t,q.height-t)))(l.labelrank<q.labelrank?l:q).newOpacity=0;A(a,function(a){var b,c;a&&(c=a.newOpacity,a.oldOpacity!==c&&a.placed&&(c?a.show(!0):b=function(){a.hide()},a.alignAttr.opacity=c,a[a.isOld?"animate":"attr"](a.alignAttr,null,b)),a.isOld=!0)})}})(L);(function(a){var B=a.addEvent,A=a.Chart,H=a.createElement,G=a.css,r=a.defaultOptions,g=a.defaultPlotOptions,f=a.each,u= a.extend,l=a.fireEvent,q=a.hasTouch,d=a.inArray,b=a.isObject,p=a.Legend,C=a.merge,t=a.pick,m=a.Point,c=a.Series,n=a.seriesTypes,E=a.svg;a=a.TrackerMixin={drawTrackerPoint:function(){var a=this,b=a.chart,c=b.pointer,d=function(a){for(var c=a.target,e;c&&!e;)e=c.point,c=c.parentNode;if(void 0!==e&&e!==b.hoverPoint)e.onMouseOver(a)};f(a.points,function(a){a.graphic&&(a.graphic.element.point=a);a.dataLabel&&(a.dataLabel.div?a.dataLabel.div.point=a:a.dataLabel.element.point=a)});a._hasTracking||(f(a.trackerGroups, function(b){if(a[b]){a[b].addClass("highcharts-tracker").on("mouseover",d).on("mouseout",function(a){c.onTrackerMouseOut(a)});if(q)a[b].on("touchstart",d);a.options.cursor&&a[b].css(G).css({cursor:a.options.cursor})}}),a._hasTracking=!0)},drawTrackerGraph:function(){var a=this,b=a.options,c=b.trackByArea,d=[].concat(c?a.areaPath:a.graphPath),g=d.length,h=a.chart,l=h.pointer,m=h.renderer,n=h.options.tooltip.snap,p=a.tracker,k,r=function(){if(h.hoverSeries!==a)a.onMouseOver()},t="rgba(192,192,192,"+ (E?.0001:.002)+")";if(g&&!c)for(k=g+1;k--;)"M"===d[k]&&d.splice(k+1,0,d[k+1]-n,d[k+2],"L"),(k&&"M"===d[k]||k===g)&&d.splice(k,0,"L",d[k-2]+n,d[k-1]);p?p.attr({d:d}):a.graph&&(a.tracker=m.path(d).attr({"stroke-linejoin":"round",visibility:a.visible?"visible":"hidden",stroke:t,fill:c?t:"none","stroke-width":a.graph.strokeWidth()+(c?0:2*n),zIndex:2}).add(a.group),f([a.tracker,a.markerGroup],function(a){a.addClass("highcharts-tracker").on("mouseover",r).on("mouseout",function(a){l.onTrackerMouseOut(a)}); b.cursor&&a.css({cursor:b.cursor});if(q)a.on("touchstart",r)}))}};n.column&&(n.column.prototype.drawTracker=a.drawTrackerPoint);n.pie&&(n.pie.prototype.drawTracker=a.drawTrackerPoint);n.scatter&&(n.scatter.prototype.drawTracker=a.drawTrackerPoint);u(p.prototype,{setItemEvents:function(a,b,c){var e=this,d=e.chart,f="highcharts-legend-"+(a.series?"point":"series")+"-active";(c?b:a.legendGroup).on("mouseover",function(){a.setState("hover");d.seriesGroup.addClass(f);b.css(e.options.itemHoverStyle)}).on("mouseout", function(){b.css(a.visible?e.itemStyle:e.itemHiddenStyle);d.seriesGroup.removeClass(f);a.setState()}).on("click",function(b){var c=function(){a.setVisible&&a.setVisible()};b={browserEvent:b};a.firePointEvent?a.firePointEvent("legendItemClick",b,c):l(a,"legendItemClick",b,c)})},createCheckboxForItem:function(a){a.checkbox=H("input",{type:"checkbox",checked:a.selected,defaultChecked:a.selected},this.options.itemCheckboxStyle,this.chart.container);B(a.checkbox,"click",function(b){l(a.series||a,"checkboxClick", {checked:b.target.checked,item:a},function(){a.select()})})}});r.legend.itemStyle.cursor="pointer";u(A.prototype,{showResetZoom:function(){var a=this,b=r.lang,c=a.options.chart.resetZoomButton,d=c.theme,f=d.states,g="chart"===c.relativeTo?null:"plotBox";this.resetZoomButton=a.renderer.button(b.resetZoom,null,null,function(){a.zoomOut()},d,f&&f.hover).attr({align:c.position.align,title:b.resetZoomTitle}).addClass("highcharts-reset-zoom").add().align(c.position,!1,g)},zoomOut:function(){var a=this; l(a,"selection",{resetSelection:!0},function(){a.zoom()})},zoom:function(a){var c,d=this.pointer,g=!1,l;!a||a.resetSelection?f(this.axes,function(a){c=a.zoom()}):f(a.xAxis.concat(a.yAxis),function(a){var b=a.axis;d[b.isXAxis?"zoomX":"zoomY"]&&(c=b.zoom(a.min,a.max),b.displayBtn&&(g=!0))});l=this.resetZoomButton;g&&!l?this.showResetZoom():!g&&b(l)&&(this.resetZoomButton=l.destroy());c&&this.redraw(t(this.options.chart.animation,a&&a.animation,100>this.pointCount))},pan:function(a,b){var c=this,d=c.hoverPoints, e;d&&f(d,function(a){a.setState()});f("xy"===b?[1,0]:[1],function(b){b=c[b?"xAxis":"yAxis"][0];var d=b.horiz,f=a[d?"chartX":"chartY"],d=d?"mouseDownX":"mouseDownY",g=c[d],h=(b.pointRange||0)/2,k=b.getExtremes(),l=b.toValue(g-f,!0)+h,h=b.toValue(g+b.len-f,!0)-h,m=h<l,g=m?h:l,l=m?l:h,h=Math.min(k.dataMin,k.min)-g,k=l-Math.max(k.dataMax,k.max);b.series.length&&0>h&&0>k&&(b.setExtremes(g,l,!1,!1,{trigger:"pan"}),e=!0);c[d]=f});e&&c.redraw(!1);G(c.container,{cursor:"move"})}});u(m.prototype,{select:function(a, b){var c=this,e=c.series,g=e.chart;a=t(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=c.options.selected=a;e.options.data[d(c,e.data)]=c.options;c.setState(a&&"select");b||f(g.getSelectedPoints(),function(a){a.selected&&a!==c&&(a.selected=a.options.selected=!1,e.options.data[d(a,e.data)]=a.options,a.setState(""),a.firePointEvent("unselect"))})})},onMouseOver:function(a,b){var c=this.series,d=c.chart,e=d.tooltip,f=d.hoverPoint;if(this.series){if(!b){if(f&& f!==this)f.onMouseOut();if(d.hoverSeries!==c)c.onMouseOver();d.hoverPoint=this}!e||e.shared&&!c.noSharedTooltip?e||this.setState("hover"):(this.setState("hover"),e.refresh(this,a));this.firePointEvent("mouseOver")}},onMouseOut:function(){var a=this.series.chart,b=a.hoverPoints;this.firePointEvent("mouseOut");b&&-1!==d(this,b)||(this.setState(),a.hoverPoint=null)},importEvents:function(){if(!this.hasImportedEvents){var a=C(this.series.options.point,this.options).events,b;this.events=a;for(b in a)B(this, b,a[b]);this.hasImportedEvents=!0}},setState:function(a,b){var c=Math.floor(this.plotX),d=this.plotY,e=this.series,f=e.options.states[a]||{},l=g[e.type].marker&&e.options.marker,m=l&&!1===l.enabled,n=l&&l.states&&l.states[a]||{},p=!1===n.enabled,k=e.stateMarkerGraphic,q=this.marker||{},r=e.chart,z=e.halo,C,A=l&&e.markerAttribs;a=a||"";if(!(a===this.state&&!b||this.selected&&"select"!==a||!1===f.enabled||a&&(p||m&&!1===n.enabled)||a&&q.states&&q.states[a]&&!1===q.states[a].enabled)){A&&(C=e.markerAttribs(this, a));if(this.graphic)this.state&&this.graphic.removeClass("highcharts-point-"+this.state),a&&this.graphic.addClass("highcharts-point-"+a),this.graphic.attr(e.pointAttribs(this,a)),C&&this.graphic.animate(C,t(r.options.chart.animation,n.animation,l.animation)),k&&k.hide();else{if(a&&n){l=q.symbol||e.symbol;k&&k.currentSymbol!==l&&(k=k.destroy());if(k)k[b?"animate":"attr"]({x:C.x,y:C.y});else l&&(e.stateMarkerGraphic=k=r.renderer.symbol(l,C.x,C.y,C.width,C.height).add(e.markerGroup),k.currentSymbol= l);k&&k.attr(e.pointAttribs(this,a))}k&&(k[a&&r.isInsidePlot(c,d,r.inverted)?"show":"hide"](),k.element.point=this)}(c=f.halo)&&c.size?(z||(e.halo=z=r.renderer.path().add(A?e.markerGroup:e.group)),z[b?"animate":"attr"]({d:this.haloPath(c.size)}),z.attr({"class":"highcharts-halo highcharts-color-"+t(this.colorIndex,e.colorIndex)}),z.point=this,z.attr(u({fill:this.color||e.color,"fill-opacity":c.opacity,zIndex:-1},c.attributes))):z&&z.point&&z.point.haloPath&&z.animate({d:z.point.haloPath(0)});this.state= a}},haloPath:function(a){return this.series.chart.renderer.symbols.circle(Math.floor(this.plotX)-a,this.plotY-a,2*a,2*a)}});u(c.prototype,{onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&&l(this,"mouseOver");this.setState("hover");a.hoverSeries=this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;b.hoverSeries=null;if(d)d.onMouseOut();this&&a.events.mouseOut&&l(this,"mouseOut");!c||a.stickyTracking|| c.shared&&!this.noSharedTooltip||c.hide();this.setState()},setState:function(a){var b=this,c=b.options,d=b.graph,g=c.states,h=c.lineWidth,c=0;a=a||"";if(b.state!==a&&(f([b.group,b.markerGroup],function(c){c&&(b.state&&c.removeClass("highcharts-series-"+b.state),a&&c.addClass("highcharts-series-"+a))}),b.state=a,!g[a]||!1!==g[a].enabled)&&(a&&(h=g[a].lineWidth||h+(g[a].lineWidthPlus||0)),d&&!d.dashstyle))for(g={"stroke-width":h},d.attr(g);b["zone-graph-"+c];)b["zone-graph-"+c].attr(g),c+=1},setVisible:function(a, b){var c=this,d=c.chart,e=c.legendItem,g,m=d.options.chart.ignoreHiddenSeries,n=c.visible;g=(c.visible=a=c.options.visible=c.userOptions.visible=void 0===a?!n:a)?"show":"hide";f(["group","dataLabelsGroup","markerGroup","tracker","tt"],function(a){if(c[a])c[a][g]()});if(d.hoverSeries===c||(d.hoverPoint&&d.hoverPoint.series)===c)c.onMouseOut();e&&d.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&f(d.series,function(a){a.options.stacking&&a.visible&&(a.isDirty=!0)});f(c.linkedSeries,function(b){b.setVisible(a, !1)});m&&(d.isDirtyBox=!0);!1!==b&&d.redraw();l(c,g)},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=void 0===a?!this.selected:a;this.checkbox&&(this.checkbox.checked=a);l(this,a?"select":"unselect")},drawTracker:a.drawTrackerGraph})})(L);(function(a){var B=a.Chart,A=a.each,H=a.inArray,G=a.isObject,r=a.pick,g=a.splat;B.prototype.setResponsive=function(a){var f=this.options.responsive;f&&f.rules&&A(f.rules,function(f){this.matchResponsiveRule(f, a)},this)};B.prototype.matchResponsiveRule=function(f,g){var l=this.respRules,q=f.condition,d;d=q.callback||function(){return this.chartWidth<=r(q.maxWidth,Number.MAX_VALUE)&&this.chartHeight<=r(q.maxHeight,Number.MAX_VALUE)&&this.chartWidth>=r(q.minWidth,0)&&this.chartHeight>=r(q.minHeight,0)};void 0===f._id&&(f._id=a.uniqueKey());d=d.call(this);!l[f._id]&&d?f.chartOptions&&(l[f._id]=this.currentOptions(f.chartOptions),this.update(f.chartOptions,g)):l[f._id]&&!d&&(this.update(l[f._id],g),delete l[f._id])}; B.prototype.currentOptions=function(a){function f(a,d,b,l){var p,q;for(p in a)if(!l&&-1<H(p,["series","xAxis","yAxis"]))for(a[p]=g(a[p]),b[p]=[],q=0;q<a[p].length;q++)b[p][q]={},f(a[p][q],d[p][q],b[p][q],l+1);else G(a[p])?(b[p]={},f(a[p],d[p]||{},b[p],l+1)):b[p]=d[p]||null}var l={};f(a,this.options,l,0);return l}})(L);return L});
//= require_tree ./application
var http = require('http'); var cicada = require('../'); var ci = cicada('/tmp/blarg'); ci.on('commit', function (commit) { commit.run('test').on('exit', function (code) { var status = code === 0 ? 'PASSED' : 'FAILED'; console.log(commit.hash + ' ' + status); }); }); var server = http.createServer(ci.handle); server.listen(5255);
/** * @author alteredq / http://alteredqualia.com/ */ THREE.EffectComposer = function ( renderer, renderTarget ) { this.renderer = renderer; if ( renderTarget === undefined ) { var width = window.innerWidth || 1; var height = window.innerHeight || 1; var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, stencilBuffer: false }; renderTarget = new THREE.WebGLRenderTarget( width, height, parameters ); } this.renderTarget1 = renderTarget; this.renderTarget2 = renderTarget.clone(); this.writeBuffer = this.renderTarget1; this.readBuffer = this.renderTarget2; this.passes = []; if ( THREE.CopyShader === undefined ) console.error( "THREE.EffectComposer relies on THREE.CopyShader" ); this.copyPass = new THREE.ShaderPass( THREE.CopyShader ); }; THREE.EffectComposer.prototype = { swapBuffers: function() { var tmp = this.readBuffer; this.readBuffer = this.writeBuffer; this.writeBuffer = tmp; }, addPass: function ( pass ) { this.passes.push( pass ); }, insertPass: function ( pass, index ) { this.passes.splice( index, 0, pass ); }, render: function ( delta ) { this.writeBuffer = this.renderTarget1; this.readBuffer = this.renderTarget2; var maskActive = false; var pass, i, il = this.passes.length; for ( i = 0; i < il; i ++ ) { pass = this.passes[ i ]; if ( !pass.enabled ) continue; pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive ); if ( pass.needsSwap ) { if ( maskActive ) { var context = this.renderer.context; context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff ); this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta ); context.stencilFunc( context.EQUAL, 1, 0xffffffff ); } this.swapBuffers(); } if ( pass instanceof THREE.MaskPass ) { maskActive = true; } else if ( pass instanceof THREE.ClearMaskPass ) { maskActive = false; } } }, reset: function ( renderTarget ) { if ( renderTarget === undefined ) { renderTarget = this.renderTarget1.clone(); renderTarget.width = window.innerWidth; renderTarget.height = window.innerHeight; } this.renderTarget1 = renderTarget; this.renderTarget2 = renderTarget.clone(); this.writeBuffer = this.renderTarget1; this.readBuffer = this.renderTarget2; }, setSize: function ( width, height ) { var renderTarget = this.renderTarget1.clone(); renderTarget.width = width; renderTarget.height = height; this.reset( renderTarget ); } };
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "primary", "label"]; import { createScopedElement } from "../../lib/jsxRuntime"; import Tappable from "../Tappable/Tappable"; import { getClassName } from "../../helpers/getClassName"; import { classNames } from "../../lib/classNames"; import { usePlatform } from "../../hooks/usePlatform"; import { isPrimitiveReactNode } from "../../lib/utils"; import { IOS, VKCOM, ANDROID } from "../../lib/platform"; import Text from "../Typography/Text/Text"; import Title from "../Typography/Title/Title"; var ButtonTypography = function ButtonTypography(_ref) { var primary = _ref.primary, children = _ref.children; var platform = usePlatform(); if (platform === IOS) { return createScopedElement(Title, { Component: "span", level: "3", weight: primary ? "semibold" : "regular" }, children); } return createScopedElement(Text, { weight: platform === VKCOM ? "regular" : "medium" }, children); }; export var PanelHeaderButton = function PanelHeaderButton(_ref2) { var children = _ref2.children, primary = _ref2.primary, label = _ref2.label, restProps = _objectWithoutProperties(_ref2, _excluded); var isPrimitive = isPrimitiveReactNode(children); var isPrimitiveLabel = isPrimitiveReactNode(label); var platform = usePlatform(); var hoverMode; var activeMode; switch (platform) { case ANDROID: hoverMode = "background"; activeMode = "background"; break; case IOS: hoverMode = "background"; activeMode = "opacity"; break; case VKCOM: hoverMode = "PanelHeaderButton--hover"; activeMode = "PanelHeaderButton--active"; } return createScopedElement(Tappable, _extends({}, restProps, { hoverMode: hoverMode, Component: restProps.href ? "a" : "button", activeEffectDelay: 200, activeMode: activeMode, vkuiClass: classNames(getClassName("PanelHeaderButton", platform), { "PanelHeaderButton--primary": primary, "PanelHeaderButton--primitive": isPrimitive, "PanelHeaderButton--notPrimitive": !isPrimitive && !isPrimitiveLabel }) }), isPrimitive ? createScopedElement(ButtonTypography, { primary: primary }, children) : children, isPrimitiveLabel ? createScopedElement(ButtonTypography, { primary: primary }, label) : label); }; PanelHeaderButton.defaultProps = { primary: false, "aria-label": "Закрыть" }; //# sourceMappingURL=PanelHeaderButton.js.map
this.primereact = this.primereact || {}; this.primereact.menubar = (function (exports, React, core) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MenubarSubComponent = /*#__PURE__*/function (_Component) { _inherits(MenubarSubComponent, _Component); var _super = _createSuper$1(MenubarSubComponent); function MenubarSubComponent(props) { var _this; _classCallCheck(this, MenubarSubComponent); _this = _super.call(this, props); _this.state = { activeItem: null }; _this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this)); _this.onChildItemKeyDown = _this.onChildItemKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(MenubarSubComponent, [{ key: "getElementRef", value: function getElementRef(el) { this.element = el; if (this.props.forwardRef) { return this.props.forwardRef(el); } return this.element; } }, { key: "onItemMouseEnter", value: function onItemMouseEnter(event, item) { if (item.disabled || this.props.mobileActive) { event.preventDefault(); return; } if (this.props.root) { if (this.state.activeItem || this.props.popup) { this.setState({ activeItem: item }); } } else { this.setState({ activeItem: item }); } } }, { key: "onItemClick", value: function onItemClick(event, item) { if (item.disabled) { event.preventDefault(); return; } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: item }); } if (item.items) { if (this.state.activeItem && item === this.state.activeItem) { this.setState({ activeItem: null }); } else { this.setState({ activeItem: item }); } } else { this.onLeafClick(); } } }, { key: "onItemKeyDown", value: function onItemKeyDown(event, item) { var listItem = event.currentTarget.parentElement; switch (event.which) { //down case 40: if (this.props.root) { if (item.items) { this.expandSubmenu(item, listItem); } } else { this.navigateToNextItem(listItem); } event.preventDefault(); break; //up case 38: if (!this.props.root) { this.navigateToPrevItem(listItem); } event.preventDefault(); break; //right case 39: if (this.props.root) { var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.children[0].focus(); } } else { if (item.items) { this.expandSubmenu(item, listItem); } } event.preventDefault(); break; //left case 37: if (this.props.root) { this.navigateToPrevItem(listItem); } event.preventDefault(); break; } if (this.props.onKeyDown) { this.props.onKeyDown(event, listItem); } } }, { key: "onChildItemKeyDown", value: function onChildItemKeyDown(event, childListItem) { if (this.props.root) { //up if (event.which === 38 && childListItem.previousElementSibling == null) { this.collapseMenu(childListItem); } } else { //left if (event.which === 37) { this.collapseMenu(childListItem); } } } }, { key: "expandSubmenu", value: function expandSubmenu(item, listItem) { this.setState({ activeItem: item }); setTimeout(function () { listItem.children[1].children[0].children[0].focus(); }, 50); } }, { key: "collapseMenu", value: function collapseMenu(listItem) { this.setState({ activeItem: null }); listItem.parentElement.previousElementSibling.focus(); } }, { key: "navigateToNextItem", value: function navigateToNextItem(listItem) { var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.children[0].focus(); } } }, { key: "navigateToPrevItem", value: function navigateToPrevItem(listItem) { var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.children[0].focus(); } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return core.DomHandler.hasClass(nextItem, 'p-disabled') || !core.DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return core.DomHandler.hasClass(prevItem, 'p-disabled') || !core.DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onLeafClick", value: function onLeafClick() { this.setState({ activeItem: null }); if (this.props.onLeafClick) { this.props.onLeafClick(); } } }, { key: "componentDidMount", value: function componentDidMount() { var _this2 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this2.element && !_this2.element.contains(event.target)) { _this2.setState({ activeItem: null }); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.parentActive && !this.props.parentActive) { this.setState({ activeItem: null }); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "renderSeparator", value: function renderSeparator(index) { return /*#__PURE__*/React__default['default'].createElement("li", { key: 'separator_' + index, className: "p-menu-separator", role: "separator" }); } }, { key: "renderSubmenu", value: function renderSubmenu(item) { if (item.items) { return /*#__PURE__*/React__default['default'].createElement(MenubarSub, { model: item.items, mobileActive: this.props.mobileActive, onLeafClick: this.onLeafClick, onKeyDown: this.onChildItemKeyDown, parentActive: item === this.state.activeItem }); } return null; } }, { key: "renderMenuitem", value: function renderMenuitem(item, index) { var _this3 = this; var className = core.classNames('p-menuitem', { 'p-menuitem-active': this.state.activeItem === item }, item.className); var linkClassName = core.classNames('p-menuitem-link', { 'p-disabled': item.disabled }); var iconClassName = core.classNames('p-menuitem-icon', item.icon); var submenuIconClassName = core.classNames('p-submenu-icon pi', { 'pi-angle-down': this.props.root, 'pi-angle-right': !this.props.root }); var icon = item.icon && /*#__PURE__*/React__default['default'].createElement("span", { className: iconClassName }); var label = item.label && /*#__PURE__*/React__default['default'].createElement("span", { className: "p-menuitem-text" }, item.label); var submenuIcon = item.items && /*#__PURE__*/React__default['default'].createElement("span", { className: submenuIconClassName }); var submenu = this.renderSubmenu(item); var content = /*#__PURE__*/React__default['default'].createElement("a", { href: item.url || '#', role: "menuitem", className: linkClassName, target: item.target, "aria-haspopup": item.items != null, onClick: function onClick(event) { return _this3.onItemClick(event, item); }, onKeyDown: function onKeyDown(event) { return _this3.onItemKeyDown(event, item); } }, icon, label, submenuIcon, /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); if (item.template) { var defaultContentOptions = { onClick: function onClick(event) { return _this3.onItemClick(event, item); }, onKeyDown: function onKeyDown(event) { return _this3.onItemKeyDown(event, item); }, className: linkClassName, labelClassName: 'p-menuitem-text', iconClassName: iconClassName, submenuIconClassName: submenuIconClassName, element: content, props: this.props }; content = core.ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React__default['default'].createElement("li", { key: item.label + '_' + index, role: "none", className: className, style: item.style, onMouseEnter: function onMouseEnter(event) { return _this3.onItemMouseEnter(event, item); } }, content, submenu); } }, { key: "renderItem", value: function renderItem(item, index) { if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index); } }, { key: "renderMenu", value: function renderMenu() { var _this4 = this; if (this.props.model) { return this.props.model.map(function (item, index) { return _this4.renderItem(item, index); }); } return null; } }, { key: "render", value: function render() { var _this5 = this; var className = core.classNames({ 'p-submenu-list': !this.props.root, 'p-menubar-root-list': this.props.root }); var submenu = this.renderMenu(); return /*#__PURE__*/React__default['default'].createElement("ul", { ref: function ref(el) { return _this5.getElementRef(el); }, className: className, role: this.props.root ? 'menubar' : 'menu' }, submenu); } }]); return MenubarSubComponent; }(React.Component); _defineProperty(MenubarSubComponent, "defaultProps", { model: null, root: false, className: null, popup: false, onLeafClick: null, onKeyDown: null, parentActive: false, mobileActive: false, forwardRef: null }); var MenubarSub = /*#__PURE__*/React__default['default'].forwardRef(function (props, ref) { return /*#__PURE__*/React__default['default'].createElement(MenubarSubComponent, _extends({ forwardRef: ref }, props)); }); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Menubar = /*#__PURE__*/function (_Component) { _inherits(Menubar, _Component); var _super = _createSuper(Menubar); function Menubar(props) { var _this; _classCallCheck(this, Menubar); _this = _super.call(this, props); _this.state = { mobileActive: false }; _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); _this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(Menubar, [{ key: "toggle", value: function toggle(event) { var _this2 = this; event.preventDefault(); this.setState(function (prevState) { return { mobileActive: !prevState.mobileActive }; }, function () { if (_this2.state.mobileActive) { core.ZIndexUtils.set('menu', _this2.rootmenu); _this2.bindDocumentClickListener(); } else { _this2.unbindDocumentClickListener(); core.ZIndexUtils.clear(_this2.rootmenu); } }); } }, { key: "bindDocumentClickListener", value: function bindDocumentClickListener() { var _this3 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this3.state.mobileActive && _this3.isOutsideClicked(event)) { _this3.setState({ mobileActive: false }, function () { _this3.unbindDocumentClickListener(); core.ZIndexUtils.clear(_this3.rootmenu); }); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "isOutsideClicked", value: function isOutsideClicked(event) { return this.rootmenu !== event.target && !this.rootmenu.contains(event.target) && this.menubutton !== event.target && !this.menubutton.contains(event.target); } }, { key: "unbindDocumentClickListener", value: function unbindDocumentClickListener() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "onLeafClick", value: function onLeafClick() { var _this4 = this; this.setState({ mobileActive: false }, function () { _this4.unbindDocumentClickListener(); core.ZIndexUtils.clear(_this4.rootmenu); }); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { core.ZIndexUtils.clear(this.rootmenu); } }, { key: "renderCustomContent", value: function renderCustomContent() { if (this.props.children) { return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-menubar-custom" }, this.props.children); } return null; } }, { key: "renderStartContent", value: function renderStartContent() { if (this.props.start) { var start = core.ObjectUtils.getJSXElement(this.props.start, this.props); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-menubar-start" }, start); } return null; } }, { key: "renderEndContent", value: function renderEndContent() { if (this.props.end) { var end = core.ObjectUtils.getJSXElement(this.props.end, this.props); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-menubar-end" }, end); } return null; } }, { key: "renderMenuButton", value: function renderMenuButton() { var _this5 = this; /* eslint-disable */ var button = /*#__PURE__*/React__default['default'].createElement("a", { ref: function ref(el) { return _this5.menubutton = el; }, href: '#', role: "button", tabIndex: 0, className: "p-menubar-button", onClick: this.toggle }, /*#__PURE__*/React__default['default'].createElement("i", { className: "pi pi-bars" })); /* eslint-enable */ return button; } }, { key: "render", value: function render() { var _this6 = this; var className = core.classNames('p-menubar p-component', { 'p-menubar-mobile-active': this.state.mobileActive }, this.props.className); var start = this.renderStartContent(); var end = this.renderEndContent(); var menuButton = this.renderMenuButton(); return /*#__PURE__*/React__default['default'].createElement("div", { id: this.props.id, className: className, style: this.props.style }, start, menuButton, /*#__PURE__*/React__default['default'].createElement(MenubarSub, { ref: function ref(el) { return _this6.rootmenu = el; }, model: this.props.model, root: true, mobileActive: this.state.mobileActive, onLeafClick: this.onLeafClick }), end); } }]); return Menubar; }(React.Component); _defineProperty(Menubar, "defaultProps", { id: null, model: null, style: null, className: null, start: null, end: null }); exports.Menubar = Menubar; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, React, primereact.core));
/** * Auto-update the 'latest activity' widget. * * @mixin * @namespace Bolt.activity * * @param {Object} bolt - The Bolt module. * @param {Object} $ - jQuery. */ (function (bolt, $) { /** * Bolt.activity mixin container. * * @private * @type {Object} */ var activity = {}; /** * Initializes the mixin. * * @static * @function init * @memberof Bolt.activity */ activity.init = function () { if ($('#latestactivity').is('*')) { setTimeout( function () { bolt.activity.update(); }, intervall ); } }; /** * Initializes the mixin. * * @static * @function update * @memberof Bolt.activity */ activity.update = function () { $.get( bolt.conf('paths.async') + 'latestactivity', function (data) { $('#latesttemp').html(data); bolt.moments.update(); $('#latestactivity').html($('#latesttemp').html()); } ); setTimeout( function () { bolt.activity.update(); }, intervall ); }; /** * Update intervall. * * @private * @constant {number} intervall * @memberof Bolt.activity */ var intervall = 30 * 1000; // 30 seconds // Apply mixin container bolt.activity = activity; })(Bolt || {}, jQuery);
/* Copyright (C) 2012 by Samuel Ronce Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ if (typeof exports != "undefined") { var CE = require("canvasengine").listen(), CanvasEngine = false, Class = CE.Class; } Class.create("Tiled", { el: null, url: "", tile_w: 0, tile_h: 0, tile_image_h:0, tile_image_w:0, tilesets: [], width: 0, height: 0, layers: [], objects: {}, scene: null, _ready: null, initialize: function() { }, /** @doc tiled/ @method ready Calls the function when the layers are drawn @param {Function} callback */ ready: function(callback) { this._ready = callback; }, /** @doc tiled/ @method load Load JSON file and draw layers in the element of the scene. View Tiled class description for more informations (http://canvasengine.net/doc/?p=editor.tiled) @param {CanvasEngine.Scene} scene @param {CanvasEngine.Element} el The element containing layers of Tiled @param {String} url Path to JSON file of Tiled Map Editor @example Example with Node.js : Server : var CE = require("canvasengine").listen(8333), Tiled = CE.Core.requireExtend("Tiled").Class, Class = CE.Class; CE.Model.init("Main", { initialize: function(socket) { var tiled = Class.New("Tiled"); tiled.ready(function(map) { socket.emit("Scene_Map.load", map); }); tiled.load("Map/map.json"); } }); Client : canvas.Scene.New({ name: "Scene_Map", events: ["load"], materials: { images: { tileset: "my_tileset.png" } }, load: function(data) { var tiled = canvas.Tiled.New(); tiled.ready(function() { var tile_w = this.getTileWidth(), tile_h = this.getTileHeight(), layer_object = this.getLayerObject(); }); tiled.load(this, this.getStage(), data); } }); */ load: function(scene, el, url) { var self = this; if (typeof scene == "string") { this.url = url = scene; } else { this.el = el; this.url = url; this.scene = scene; } function ready(data) { var clone_data = CE.Core.extend({}, data); self.tile_h = data.tileheight; self.tile_w = data.tilewidth; self.width = data.width; self.height = data.height; self.tilesets = data.tilesets; self.layers = data.layers; self.tilesetsIndexed = []; for (var i=0 ; i < self.tilesets.length ; i++) { var props = self.tilesets[i].tileproperties, new_props = {}; if (props) { for (var key in props) { new_props[+key+1] = props[key]; } self.tilesets[i].tileproperties = new_props; } self.tilesetsIndexed[self.tilesets[i].firstgid] = self.tilesets[i]; } // // Check to see if the tileset uses a different height/width to the layer // For example, pseudo-3d tiles such as PlanetCute are 101x171 sprites // on a Tiled layer grid of 101x80 // if (self.tilesets[0].tileheight && self.tilesets[0].tilewidth) { self.tile_image_h = self.tilesets[0].tileheight; self.tile_image_w = self.tilesets[0].tilewidth; } else { self.tile_image_h = self.tile_h; self.tile_image_w = self.tile_w; } var _id, length = self.tilesetsIndexed.length + (Math.round(self.tilesets[self.tilesets.length-1].imageheight / self.tile_h) * (Math.round(self.tilesets[self.tilesets.length-1].imagewidth / self.tile_w))); for (var m=0; m < length; m++) { _id = self.tilesetsIndexed[m] ? m : _id; self.tilesetsIndexed[m] = self.tilesetsIndexed[_id]; } if (typeof exports == "undefined") { self._draw(); } else { if (self._ready) self._ready.call(self, clone_data); } } if (typeof url === 'string') { (CanvasEngine || CE.Core).getJSON(this.url, ready); } else { ready(url); } }, _drawTile: function(_id, layer_name, data) { var _tile = this.scene.createElement(), tileset, tileoffset, nb_tile = {}; if (data.position != "absolute") { data.x *= this.tile_w; data.y *= this.tile_h; } var flippedHorizontally = false, flippedVertically = false, flippedAntiDiagonally = false; if (_id & Tiled.FlippedHorizontallyFlag) { flippedHorizontally = true; } if (_id & Tiled.FlippedVerticallyFlag) { flippedVertically = true; } if (_id & Tiled.FlippedAntiDiagonallyFlag) { flippedAntiDiagonally = true; } _id &= ~(Tiled.FlippedHorizontallyFlag | Tiled.FlippedVerticallyFlag | Tiled.FlippedAntiDiagonallyFlag); tileset = this.tilesetsIndexed[_id]; _id -= tileset.firstgid; nb_tile = { width: tileset.imagewidth / this.tile_image_w, height: tileset.imageheight / this.tile_image_h }; tileoffset = tileset.tileoffset || {x: 0, y: 0}; y = this.tile_image_h * Math.floor(_id / (nb_tile.width - (nb_tile.width / 2 * tileset.margin))); x = this.tile_w * (_id % Math.round((tileset.imagewidth - nb_tile.height / 2 * tileset.margin) / this.tile_w)); _tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_w + tileset.margin, y + tileset.spacing * y / this.tile_h + tileset.margin, this.tile_w, this.tile_h, data.x + tileoffset.x, data.y + tileoffset.y, this.tile_w, this.tile_h); this.el_layers[layer_name].append(_tile); var scaleX = (flippedHorizontally) ? -1 : 1, scaleY = (flippedVertically) ? -1 : 1, rotation = 0; if (flippedAntiDiagonally) { rotation = 90; scaleX *= -1; halfDiff = nb_tile.height/2 - nb_tile.width/2 y += halfDiff } _tile.drawImage(tileset.name, x + tileset.spacing * x / this.tile_image_w + tileset.margin, y + tileset.spacing * y / this.tile_image_h + tileset.margin, this.tile_image_w, this.tile_image_h, 0, 0, this.tile_image_w, this.tile_image_h); _tile.x = data.x + tileoffset.x _tile.y = data.y + tileoffset.y _tile.width = this.tile_w _tile.height = this.tile_h _tile.setOriginPoint("middle"); _tile.scaleX = scaleX _tile.scaleY = scaleY _tile.rotation = rotation if (data.visible === false) { _tile.hide(); } this.el_layers[layer_name].append(_tile); return _tile; }, _draw: function() { this.map = this.scene.createElement(); this.el_layers = {}; var x, y, tileset, layer, self = this; var id, _id, obj, layer_type, el_objs = {}; for (var i=0 ; i < this.layers.length ; i++) { id = 0; layer = this.layers[i]; this.el_layers[layer.name] = this.scene.createElement(); if (layer.type == "tilelayer") { for (var k=0 ; k < layer.height ; k++) { for (var j=0 ; j < layer.width ; j++) { _id = layer.data[id]; if (_id != 0) { this._drawTile(_id, layer.name, { x: j, y: k }); } id++; } } } else if (layer.type == "objectgroup") { for (var j=0 ; j < layer.objects.length ; j++) { obj = layer.objects[j]; if (!el_objs[obj.name]) el_objs[obj.name] = []; if (obj.gid) { el_objs[obj.name].push(this._drawTile(obj.gid, layer.name, CE.extend(obj, { y: obj.y - this.tile_h, position: "absolute" }))); } } this.objects[layer.name] = { layer: this.el_layers[layer.name], objects: el_objs }; } this.map.append(this.el_layers[layer.name]); } this.el.append(this.map); if (this._ready) this._ready.call(this); }, /** @doc tiled/ @method getLayerObject Retrieves the object layer. @param {Integer} name Returns the layer by name @return {CanvasEngine.Element} */ getLayerObject: function(name) { if (!name) { for (var id in this.objects) { name = id; break; } } if (!this.objects[name]) { return false; } return this.objects[name].layer; }, // TODO getObject: function(layer_name, obj_name, pos) { if (!pos) pos = 0; return this.objects[layer_name].objects[obj_name][pos]; }, /** @doc tiled/ @method getLayer Retrieves the layer by its identifier. @param {String} id Layer name in Tiled Map Editor @return {CanvasEngine.Element} */ getLayer: function(id) { return this.el_layers[id]; }, /** @doc tiled/ @method getMap Returns the element containing all the layers @return {CanvasEngine.Element} */ getMap: function() { return this.map; }, /** @doc tiled/ @method getTileWidth Returns the width of the map in tiles @return {Integer} */ getTileWidth: function() { return this.tile_w; }, /** @doc tiled/ @method getTileHeight Returns the height of the map in tiles @return {Integer} */ getTileHeight: function() { return this.tile_h; }, /** @doc tiled/ @method getWidthPixel Returns the width of the map in pixels @return {Integer} */ getWidthPixel: function() { return this.width * this.getTileWidth(); }, /** @doc tiled/ @method getHeightPixel Returns the height of the map in pixels @return {Integer} */ getHeightPixel: function() { return this.height * this.getTileHeight(); }, /** @doc tiled/ @method getDataLayers Returns the data for each map @return {Array} */ getDataLayers: function() { var layer = []; for (var i=0 ; i < this.layers.length ; i++) { if (this.layers[i].data) layer.push(this.layers[i].data); } return layer; }, /** @doc tiled/ @method getTileInMap Retrieves the position of a tile to the Tileset according positions X and Y @params {Integer} x Position X @params {Integer} y Position Y @return {Array} */ getTileInMap: function(x, y) { return this.width * y + x; }, /** @doc tiled/ @method getTileProperties Gets the properties of a tile depending on its identifier @params {Integer} tile Id of tile @params {String} (optional) layer Layer name @return {Object} */ /** @doc tiled/ @method getTileProperties Gets the properties of a tile depending on its positions @params {Integer} tile Id of tile. Put "null" @params {Integer} x Positon X @params {Integer} y Positon Y @return {Object} */ getTileProperties: function(tile, layerOrX, y) { var self = this; var tileset = this.tilesets[0]; function _getTileLayers(tile) { var _layers = []; for (var i=0 ; i < self.layers.length ; i++) { if (self.layers[i].data) _layers.push(tileset.tileproperties[self.layers[i].data[tile]]); } return _layers; } if (layerOrX === undefined) { return _getTileLayers(tile); } else if (y !== undefined) { var new_tile = this.getTileInMap(layerOrX, y); return _getTileLayers(new_tile); } return tileset.tileproperties[this.layers[layerOrX].data[tile]]; }, tileToProperty: function(prop_name) { var layers = this.getDataLayers(), val; var new_layers = []; for (var i=0 ; i < layers.length ; i++) { new_layers[i] = []; for (var j=0 ; j < layers[i].length ; j++) { val = this.tilesets[0].tileproperties[layers[i][j]]; // Hack Tiled Bug new_layers[i][j] = val ? +val[prop_name] : 0; } } return new_layers; } }); /** @doc tiled @class Tiled Tiled is a general purpose tile map editor. It's built to be easy to use, yet flexible enough to work with varying game engines, whether your game is an RPG, platformer or Breakout clone. Tiled is free software and written in C++, using the Qt application framework. http://www.mapeditor.org Consider adding inserting Tiled.js <script src="extends/Tiled.js"></script> <script> var canvas = CE.defines("canvas_id"). extend(Tiled). ready(function() { }); </script> @param {CanvasEngine.Scene} scene @param {CanvasEngine.Element} el The layers are displayed on this element @param {String} url Path to the JSON file of Tiled Map Editor @example var canvas = CE.defines("canvas_id"). extend(Tiled). ready(function() { canvas.Scene.call("MyScene"); }); canvas.Scene.new({ name: "MyScene", materials: { images: { mytileset: "path/to/tileset.png" } }, ready: function(stage) { var el = this.createElement(); var tiled = canvas.Tiled.new(); tiled.ready(function() { var tile_w = this.getTileWidth(), tile_h = this.getTileHeight(), layer_object = this.getLayerObject(); stage.append(el); }); tiled.load(this, el, "map/map.json"); } }); 1. `mytileset` in material object is the name of tileset in Tiled Map Editor 2. `getLayer()` retrieves a layer. The name is the same as in Tiled Map Editor ![](http://canvasengine.net/presentation/images/tiled2.png) */ var Tiled = { Tiled: { FlippedHorizontallyFlag: 0x80000000, FlippedVerticallyFlag: 0x40000000, FlippedAntiDiagonallyFlag: 0x20000000, New: function() { return this["new"].apply(this, arguments); }, "new": function(scene, el, url) { return Class["new"]("Tiled", [scene, el, url]); } } }; if (typeof exports != "undefined") { exports.Class = Tiled.Tiled; }
var name = "Supafly Flycatcher"; var collection_type = 0; var is_secret = 0; var desc = "Caught 501 perfectly perfect jars of Fireflies"; var status_text = "Yes! 501 perfect jars of Fireflies, making you a certifiably Supafly Flycatcher. Tell all your friends."; var last_published = 1348802871; var is_shareworthy = 1; var url = "supafly-flycatcher"; var category = "harvesting"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-09-10\/supafly_flycatcher_1315685974.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-09-10\/supafly_flycatcher_1315685974_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-09-10\/supafly_flycatcher_1315685974_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-09-10\/supafly_flycatcher_1315685974_40.png"; function on_apply(pc){ } var conditions = { 512 : { type : "counter", group : "firefly_jar", label : "full", value : "501" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(800 * multiplier), true); pc.stats_add_favor_points("mab", round_to_5(175 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 800, "favor" : { "giant" : "mab", "points" : 175 } }; // generated ok (NO DATE)
version https://git-lfs.github.com/spec/v1 oid sha256:574bbfb7c8314e96c3e7dfcb549768dc2e7fbd5859d9459c3331a3120b674923 size 5051
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The response model for the list dsc nodes operation. */ class DscNodeReportListResult extends Array { /** * Create a DscNodeReportListResult. * @member {string} [nextLink] Gets or sets the next link. */ constructor() { super(); } /** * Defines the metadata of DscNodeReportListResult * * @returns {object} metadata of DscNodeReportListResult * */ mapper() { return { required: false, serializedName: 'DscNodeReportListResult', type: { name: 'Composite', className: 'DscNodeReportListResult', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'DscNodeReportElementType', type: { name: 'Composite', className: 'DscNodeReport' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = DscNodeReportListResult;
class ExplorerNavCtrl { constructor() { 'ngInject'; } } let ExplorerNav = { controller: ExplorerNavCtrl, templateUrl: 'modules/explorer/layout/nav.html' }; export default ExplorerNav;
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- "use strict"; var crypto = require("crypto"); var AuthHandler = { getAuthorizationHeader: function (documentClient, verb, path, resourceId, resourceType, headers) { if (documentClient.masterKey) { return this.getAuthorizationTokenUsingMasterKey(verb, resourceId, resourceType, headers, documentClient.masterKey); } else if (documentClient.resourceTokens) { return this.getAuthorizationTokenUsingResourceTokens(documentClient.resourceTokens, path, resourceId); } }, getAuthorizationTokenUsingMasterKey: function (verb, resourceId, resourceType, headers, masterKey) { var key = new Buffer(masterKey, "base64"); var text = (verb || "").toLowerCase() + "\n" + (resourceType || "").toLowerCase() + "\n" + (resourceId || "") + "\n" + (headers["x-ms-date"] || "").toLowerCase() + "\n" + (headers["date"] || "").toLowerCase() + "\n"; var body = new Buffer(text, "utf8"); var signature = crypto.createHmac("sha256", key).update(body).digest("base64"); var MasterToken = "master"; var TokenVersion = "1.0"; return "type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature; }, getAuthorizationTokenUsingResourceTokens: function (resourceTokens, path, resourceId) { if (resourceTokens[resourceId]) { return resourceTokens[resourceId]; } else { var pathParts = path.split("/"); var resourceTypes = ["dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions", "attachments", "media", "conflicts", "offers"]; for (var i = pathParts.length - 1; i >= 0; i--) { if (resourceTypes.indexOf(pathParts[i]) === -1) { if (resourceTokens[pathParts[i]]) { return resourceTokens[pathParts[i]]; } } } } } }; if (typeof exports !== "undefined") { module.exports = AuthHandler; }
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'; export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'; export function increment() { return { type: INCREMENT_COUNTER }; } export function decrement() { return { type: DECREMENT_COUNTER }; } export function incrementIfOdd() { return (dispatch, getState) => { const { counter } = getState(); if (counter % 2 === 0) { return; } dispatch(increment()); }; } export function incrementAsync(delay = 1000) { return dispatch => { setTimeout(() => { dispatch(increment()); }, delay); }; }
import { isBlank, isPresent, CONST_EXPR, isString } from 'angular2/src/facade/lang'; import { PromiseWrapper } from 'angular2/src/facade/promise'; import { ObservableWrapper } from 'angular2/src/facade/async'; import { StringMapWrapper } from 'angular2/src/facade/collection'; import { OpaqueToken } from 'angular2/core'; /** * Providers for validators to be used for {@link Control}s in a form. * * Provide this using `multi: true` to add validators. * * ### Example * * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'} */ export const NG_VALIDATORS = CONST_EXPR(new OpaqueToken("NgValidators")); /** * Providers for asynchronous validators to be used for {@link Control}s * in a form. * * Provide this using `multi: true` to add validators. * * See {@link NG_VALIDATORS} for more details. */ export const NG_ASYNC_VALIDATORS = CONST_EXPR(new OpaqueToken("NgAsyncValidators")); /** * Provides a set of validators used by form controls. * * A validator is a function that processes a {@link Control} or collection of * controls and returns a map of errors. A null map means that validation has passed. * * ### Example * * ```typescript * var loginControl = new Control("", Validators.required) * ``` */ export class Validators { /** * Validator that requires controls to have a non-empty value. */ static required(control) { return isBlank(control.value) || (isString(control.value) && control.value == "") ? { "required": true } : null; } /** * Validator that requires controls to have a value of a minimum length. */ static minLength(minLength) { return (control) => { if (isPresent(Validators.required(control))) return null; var v = control.value; return v.length < minLength ? { "minlength": { "requiredLength": minLength, "actualLength": v.length } } : null; }; } /** * Validator that requires controls to have a value of a maximum length. */ static maxLength(maxLength) { return (control) => { if (isPresent(Validators.required(control))) return null; var v = control.value; return v.length > maxLength ? { "maxlength": { "requiredLength": maxLength, "actualLength": v.length } } : null; }; } /** * No-op validator. */ static nullValidator(c) { return null; } /** * Compose multiple validators into a single function that returns the union * of the individual error maps. */ static compose(validators) { if (isBlank(validators)) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function (control) { return _mergeErrors(_executeValidators(control, presentValidators)); }; } static composeAsync(validators) { if (isBlank(validators)) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function (control) { let promises = _executeValidators(control, presentValidators).map(_convertToPromise); return PromiseWrapper.all(promises).then(_mergeErrors); }; } } function _convertToPromise(obj) { return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); } function _executeValidators(control, validators) { return validators.map(v => v(control)); } function _mergeErrors(arrayOfErrors) { var res = arrayOfErrors.reduce((res, errors) => { return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res; }, {}); return StringMapWrapper.isEmpty(res) ? null : res; }
"use strict"; const idlUtils = require("../generated/utils"); const ElementImpl = require("./Element-impl").implementation; const MouseEvent = require("../generated/MouseEvent"); const GlobalEventHandlersImpl = require("./GlobalEventHandlers-impl").implementation; const focusing = require("../helpers/focusing.js"); const conversions = require("webidl-conversions"); const isDisabled = require("../helpers/form-controls").isDisabled; class HTMLElementImpl extends ElementImpl { constructor(args, privateData) { super(args, privateData); this._initGlobalEvents(); this._tabIndex = 0; this._settingCssText = false; this._clickInProgress = false; this._style = new this._core.CSSStyleDeclaration(newCssText => { if (!this._settingCssText) { this._settingCssText = true; this.setAttribute("style", newCssText); this._settingCssText = false; } }); } // Add default event behavior (click link to navigate, click button to submit // form, etc). We start by wrapping dispatchEvent so we can forward events to // the element's default functions (only events that did not incur // preventDefault). dispatchEvent(event) { if (event.type === "click") { callEventBehaviorHook(event, "_preClickActivationSteps", this); } const outcome = super.dispatchEvent(event); if (event.type === "click") { if (event.defaultPrevented) { callEventBehaviorHook(event, "_canceledActivationSteps"); } else { callEventBehaviorHook(event, "_activationBehavior"); } } return outcome; } focus() { if (!focusing.isFocusableAreaElement(this)) { return; } const previous = this._ownerDocument._lastFocusedElement; focusing.fireFocusEventWithTargetAdjustment("blur", previous, this); this._ownerDocument._lastFocusedElement = this; focusing.fireFocusEventWithTargetAdjustment("focus", this, previous); if (this._ownerDocument._defaultView._frameElement) { this._ownerDocument._defaultView._frameElement.focus(); } } blur() { if (this._ownerDocument._lastFocusedElement !== this || !focusing.isFocusableAreaElement(this)) { return; } focusing.fireFocusEventWithTargetAdjustment("blur", this, this._ownerDocument); this._ownerDocument._lastFocusedElement = null; focusing.fireFocusEventWithTargetAdjustment("focus", this._ownerDocument, this); } click() { // https://html.spec.whatwg.org/multipage/interaction.html#dom-click // https://html.spec.whatwg.org/multipage/interaction.html#run-synthetic-click-activation-steps // Not completely spec compliant due to e.g. incomplete implementations of disabled for form controls, or no // implementation at all of isTrusted. if (this._clickInProgress) { return; } this._clickInProgress = true; if (isDisabled(this)) { return; } const event = MouseEvent.createImpl(["click", { bubbles: true, cancelable: true }], {}); // Run synthetic click activation steps. According to the spec, // this should not be calling dispatchEvent, but it matches browser behavior. // See: https://www.w3.org/Bugs/Public/show_bug.cgi?id=12230 // See also: https://github.com/whatwg/html/issues/805 this.dispatchEvent(event); this._clickInProgress = false; } get dir() { let dirValue = this.getAttribute("dir"); if (dirValue !== null) { dirValue = dirValue.toLowerCase(); if (["ltr", "rtl", "auto"].includes(dirValue)) { return dirValue; } } return ""; } set dir(value) { this.setAttribute("dir", value); } get style() { return this._style; } set style(value) { this._style.cssText = value; } _attrModified(name, value, oldValue) { if (name === "style" && value !== oldValue && !this._settingCssText) { this._settingCssText = true; this._style.cssText = value; this._settingCssText = false; } else if (name.startsWith("on")) { this._globalEventChanged(name.substring(2)); } super._attrModified.apply(this, arguments); } // TODO this should be [Reflect]able if we added default value support to webidl2js's [Reflect] get tabIndex() { if (!this.hasAttribute("tabindex")) { return focusing.isFocusableAreaElement(this) ? 0 : -1; } return conversions.long(this.getAttribute("tabindex")); } set tabIndex(value) { this.setAttribute("tabIndex", String(value)); } get offsetParent() { return null; } get offsetTop() { return 0; } get offsetLeft() { return 0; } get offsetWidth() { return 0; } get offsetHeight() { return 0; } } function callEventBehaviorHook(event, name, targetOverride) { if (event) { const target = targetOverride || event.target; if (target && typeof target[name] === "function") { target[name](); } } } idlUtils.mixin(HTMLElementImpl.prototype, GlobalEventHandlersImpl.prototype); module.exports = { implementation: HTMLElementImpl };
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.ui.emoji.FastNonProgressiveEmojiPickerTest'); goog.setTestOnly('goog.ui.emoji.FastNonProgressiveEmojiPickerTest'); goog.require('goog.dom.classlist'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.style'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPicker'); goog.require('goog.ui.emoji.SpriteInfo'); goog.require('goog.userAgent'); var sprite = '../../demos/emoji/sprite.png'; var sprite2 = '../../demos/emoji/sprite2.png'; /** * Creates a SpriteInfo object with the specified properties. If the image is * sprited via CSS, then only the first parameter needs a value. If the image * is sprited via metadata, then the first parameter should be left null. * * @param {?string} cssClass CSS class to properly display the sprited image. * @param {string=} opt_url Url of the sprite image. * @param {number=} opt_width Width of the image being sprited. * @param {number=} opt_height Height of the image being sprited. * @param {number=} opt_xOffset Positive x offset of the image being sprited * within the sprite. * @param {number=} opt_yOffset Positive y offset of the image being sprited * within the sprite. * @param {boolean=} opt_animated Whether the sprite info is for an animated * emoji. */ function si(cssClass, opt_url, opt_width, opt_height, opt_xOffset, opt_yOffset, opt_animated) { return new goog.ui.emoji.SpriteInfo(cssClass, opt_url, opt_width, opt_height, opt_xOffset, opt_yOffset, opt_animated); } // This group contains a mix of sprited emoji via css, sprited emoji via // metadata, and non-sprited emoji. var spritedEmoji2 = [ 'Emoji 1', [ ['../../demos/emoji/200.gif', 'std.200', si('SPRITE_200')], ['../../demos/emoji/201.gif', 'std.201', si('SPRITE_201')], ['../../demos/emoji/202.gif', 'std.202', si('SPRITE_202')], ['../../demos/emoji/203.gif', 'std.203', si('SPRITE_203')], ['../../demos/emoji/204.gif', 'std.204', si('SPRITE_204')], ['../../demos/emoji/205.gif', 'std.205', si('SPRITE_205')], ['../../demos/emoji/206.gif', 'std.206', si('SPRITE_206')], ['../../demos/emoji/2BC.gif', 'std.2BC', si('SPRITE_2BC')], ['../../demos/emoji/2BD.gif', 'std.2BD', si('SPRITE_2BD')], ['../../demos/emoji/2BE.gif', 'std.2BE', si(null, sprite, 18, 18, 36, 54)], ['../../demos/emoji/2BF.gif', 'std.2BF', si(null, sprite, 18, 18, 0, 126)], ['../../demos/emoji/2C0.gif', 'std.2C0', si(null, sprite, 18, 18, 18, 305)], ['../../demos/emoji/2C1.gif', 'std.2C1', si(null, sprite, 18, 18, 0, 287)], ['../../demos/emoji/2C2.gif', 'std.2C2', si(null, sprite, 18, 18, 18, 126)], ['../../demos/emoji/2C3.gif', 'std.2C3', si(null, sprite, 18, 18, 36, 234)], ['../../demos/emoji/2C4.gif', 'std.2C4', si(null, sprite, 18, 18, 36, 72)], ['../../demos/emoji/2C5.gif', 'std.2C5', si(null, sprite, 18, 18, 54, 54)], ['../../demos/emoji/2C6.gif', 'std.2C6'], ['../../demos/emoji/2C7.gif', 'std.2C7'], ['../../demos/emoji/2C8.gif', 'std.2C8'], ['../../demos/emoji/2C9.gif', 'std.2C9'], ['../../demos/emoji/2CA.gif', 'std.2CA', si(null, sprite2, 18, 20, 36, 72, 1)], ['../../demos/emoji/2E3.gif', 'std.2E3', si(null, sprite2, 18, 18, 0, 0, 1)], ['../../demos/emoji/2EF.gif', 'std.2EF', si(null, sprite2, 18, 20, 0, 300, 1)], ['../../demos/emoji/2F1.gif', 'std.2F1', si(null, sprite2, 18, 18, 0, 320, 1)] ]]; /** * Returns true if the two paths end with the same file. * * E.g., ('../../cool.gif', 'file:///home/usr/somewhere/cool.gif') --> true * * @param {string} path1 First url * @param {string} path2 Second url */ function checkPathsEndWithSameFile(path1, path2) { var pieces1 = path1.split('/'); var file1 = pieces1[pieces1.length - 1]; var pieces2 = path2.split('/'); var file2 = pieces2[pieces2.length - 1]; return file1 == file2; } /** * Checks and verifies the structure of a non-progressive fast-loading picker * after the animated emoji have loaded. * * @param {goog.ui.emoji.EmojiPalette} palette Emoji palette to check. * @param {Array.<Array.<string>>} emoji Emoji that should be in the palette. * @param {Object} images Map of id -> Image for the images loaded in this * picker. */ function checkPostLoadStructureForFastLoadNonProgressivePicker(palette, emoji, images) { for (var i = 0; i < emoji[1].length; i++) { palette.setSelectedIndex(i); var emojiInfo = emoji[1][i]; var cell = palette.getSelectedItem(); var id = cell.getAttribute(goog.ui.emoji.Emoji.ATTRIBUTE); var inner = /** @type {Element} */ (cell.firstChild); // Check that the cell is a div wrapped around something else, and that the // outer div contains the goomoji attribute assertEquals('The palette item should be a div wrapped around something', cell.tagName, 'DIV'); assertNotNull('The outer div is not wrapped around another element', inner); assertEquals('The palette item should have the goomoji attribute', cell.getAttribute(goog.ui.emoji.Emoji.ATTRIBUTE), emojiInfo[1]); // Now check the contents of the cells var url = emojiInfo[0]; // url of the animated emoji var spriteInfo = emojiInfo[2]; if (spriteInfo) { assertEquals(inner.tagName, 'DIV'); if (spriteInfo.isAnimated()) { var img = images[id]; checkPathsEndWithSameFile( goog.style.getStyle(inner, 'background-image'), url); assertEquals(String(img.width), goog.style.getStyle(inner, 'width'). replace(/px/g, '').replace(/pt/g, '')); assertEquals(String(img.height), goog.style.getStyle(inner, 'height'). replace(/px/g, '').replace(/pt/g, '')); assertEquals('0 0', goog.style.getStyle(inner, 'background-position').replace(/px/g, ''). replace(/pt/g, '')); } else { var cssClass = spriteInfo.getCssClass(); if (cssClass) { assertTrue('Sprite should have its CSS class set', goog.dom.classlist.contains(inner, cssClass)); } else { checkPathsEndWithSameFile( goog.style.getStyle(inner, 'background-image'), spriteInfo.getUrl()); assertEquals(spriteInfo.getWidthCssValue(), goog.style.getStyle(inner, 'width')); assertEquals(spriteInfo.getHeightCssValue(), goog.style.getStyle(inner, 'height')); assertEquals((spriteInfo.getXOffsetCssValue() + ' ' + spriteInfo.getYOffsetCssValue()).replace(/px/g, ''). replace(/pt/g, ''), goog.style.getStyle(inner, 'background-position').replace(/px/g, ''). replace(/pt/g, '')); } } } else { // A non-sprited emoji is just an img assertEquals(inner.tagName, 'IMG'); checkPathsEndWithSameFile(inner.src, emojiInfo[0]); } } } var testCase = new goog.testing.AsyncTestCase(document.title); testCase.stepTimeout = 4 * 1000; testCase.setUpPage = function() { this.waitForAsync('setUpPage'); var defaultImg = '../../demos/emoji/none.gif'; this.picker = new goog.ui.emoji.EmojiPicker(defaultImg); this.picker.setDelayedLoad(false); this.picker.setManualLoadOfAnimatedEmoji(true); this.picker.setProgressiveRender(false); this.picker.addEmojiGroup(spritedEmoji2[0], spritedEmoji2[1]); this.picker.render(); this.palette = this.picker.getPage(0); var imageLoader = this.palette.getImageLoader(); this.images = {}; goog.events.listen(imageLoader, goog.net.EventType.COMPLETE, this.onImageLoaderComplete, false, this); goog.events.listen(imageLoader, goog.events.EventType.LOAD, this.onImageLoaded, false, this); // Now we load the animated emoji and check the structure again. The animated // emoji will be different. this.picker.manuallyLoadAnimatedEmoji(); }; testCase.onImageLoaded = function(e) { var image = e.target; this.log('Image loaded: ' + image.src); this.images[image.id] = image; }; testCase.onImageLoaderComplete = function(e) { this.log('Image loading complete'); this.continueTesting(); }; testCase.tearDownPage = function() { this.picker.dispose(); }; testCase.addNewTest('testStructure', function() { // Bug 2280968 if (goog.userAgent.IE && goog.userAgent.VERSION == '6.0') { this.log('Not testing emojipicker structure'); return; } this.log('Testing emojipicker structure'); checkPostLoadStructureForFastLoadNonProgressivePicker(this.palette, spritedEmoji2, this.images); }); // Standalone Closure Test Runner. G_testRunner.initialize(testCase);
KISSY.add(function (S, Node,Demo) { var $ = Node.all; describe('tb-video-player', function () { it('Instantiation of components',function(){ var demo = new Demo(); expect(S.isObject(demo)).toBe(true); }) }); },{requires:['node','gallery/tb-video-player/1.5/']});
{ // Map BGM addAudio:[ ["map-bgm",[audioserver+"tlol-cave.mp3",audioserver+"tlol-cave.ogg"],{channel:"bgmusic",loop:true}], ], // Map graphics addImage:[ ["tiles","resources/tlol/gfx-cave.png"], ], // Map Tileset addTiles:[ {id:"tiles",image:"tiles",tileh:30,tilew:30,tilerow:10,gapx:0,gapy:0}, ], setObject:[ // Dialogues on this map { object:"dialogues", property:"arrowstutorial", value:{ istutorial:true, font:"smalltut", skipkey:"a", esckey:"b", who: noface, scenes:[ { speed:1, who:"noone", audio:"beep", talk:["Use the B button to switch between","weapons. Now you can fire lighting","arrows! Try to hit the B button and","then fire with A!"]} ] } },{ object:"dialogues", property:"usebtutorial", value:{ istutorial:true, font:"smalltut", skipkey:"a", esckey:"b", who: noface, scenes:[ { speed:1, who:"noone", audio:"beep", talk:["Use the B button to interact","with objects, that means that you can","open doors, tresaure chests, talk","with villagers etc."]} ] } },{ object:"dialogues", property:"soul", value:{ endgame:true, font:"small", skipkey:"a", esckey:null, who: noface, scenes:[ { speed:1, who:"noone", audio:"beepbad", talk:["Your eyes... I know you, my little","guy..."]}, { speed:1, who:"noone", audio:"beepbad", talk:["I'm the guardian of all the souls","who died here, tricked by the evil","villagers of the Kariko village."]}, { speed:1, who:"noone", audio:"beepbad", talk:["I'll teach everything I know. A","day you'll be able to go out","and bring the rage of the tricked."]}, { speed:6, who:"noone", audio:"beepbad", talk:["You are the Hero of the Legend.","The Legend of Sadness."]}, ] } // Map data and actions },{ object:"tilemaps", property:"map", value:{ tileset:"tiles", map:[ [ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12], [ 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12], [ 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 0, 0, 13, 13, 13, 13, 13, 13, 13, 0, 0, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 14, 14, 14, 6, 6, 14, 0, 0, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 11, 11, 13, 13, 14, 14, 14, 14, 6, 6, 14, 13, 13, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 10, 10, 14, 14, 14, 14, 14, 14, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 3, 6, 6, 6, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 0, 0, 0, 6, 6, 6, 12, 12, 13, 13, 13, 13, 13, 13, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 0, 0, 0, 6, 6, 6, 12, 12, 14, 14, 14, 14, 14, 14, 6, 6, 14, 14, 14, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 14, 14, 14, 14, 14, 14, 6, 6, 14, 14, 14, 12], [ 12, 6, 1, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 14, 14, 14, 6, 6, 14, 0, 0, 12], [ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 14, 14, 14, 13, 13, 14, 0, 0, 12], [ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12] ], addObjects:function() { if (!tilemaps.queststatus["oldmanstory"]) gbox.playAudio("map-bgm"); if (tilemaps.queststatus["oldmanstory"]) // If you've heard the old man story... maingame.addNpc(555,180,[8,9],"soul"); // The soul of the tricked appears. if (!tilemaps.queststatus["floor2trapped"]) { maingame.setTileInMap(14,6,4,false); } if (!tilemaps.queststatus["floor2arrows"]) { maingame.addChest(19,6,null,false,"arrow",null,0); } if (tilemaps.queststatus["floor1eyeswitch"]&&!tilemaps.queststatus["bosskey"]) { maingame.addEnemy("fifth1","octo",3,4,true); maingame.addEnemy("fifth2","octo",5,4,true); maingame.addEnemy("fifth3","octo",6,4,true); maingame.addEnemy("fifth4","octo",7,4,true); tilemaps.queststatus["_tmpbosskey"]=false; } }, mapActions:function() { var pl=gbox.getObject("player","player"); var ontile=help.getTileInMap(pl.x+pl.colx+pl.colhw,pl.y+pl.coly+pl.colhh,tilemaps.map,tilemaps._defaultblock,"map"); if (!tilemaps.queststatus["floor2trapped"]&&!tilemaps.queststatus["floor2untrapped"]) // the trap on floor 2 if (ontile==4) { gbox.hitAudio("beep"); // Switch sound maingame.addDoor("sidedoor","doorv",10,4,true); maingame.addEnemy("third1","octo",13,2,true); maingame.addEnemy("third2","octo",21,2,true); maingame.addEnemy("third3","octo",13,10,true); maingame.addEnemy("third4","octo",21,10,true); tilemaps.queststatus["floor2trapped"]=true; // Trap on maingame.addQuestClear("TRAPPED!"); maingame.startDialogue("usebtutorial"); // Explain how to open the first tresaure chest. maingame.setTileInMap(14,6,3,true); } if (tilemaps.queststatus["floor2trapped"]&&!tilemaps.queststatus["floor2untrapped"]) { if (!gbox.getObject("foes","third1")&&!gbox.getObject("foes","third2")&&!gbox.getObject("foes","third3")&&!gbox.getObject("foes","third4")) { // check them. If beaten... gbox.getObject("walls","sidedoor").doOpen(); tilemaps.queststatus["floor2untrapped"]=true; // Set the quest as done... maingame.addQuestClear(); // Arcade-ish message "QUEST CLEAR"! } } if (tilemaps.queststatus["floor1eyeswitch"]&&!tilemaps.queststatus["bosskey"]&&!tilemaps.queststatus["_tmpbosskey"]) { if (!gbox.getObject("foes","fifth1")&&!gbox.getObject("foes","fifth2")&&!gbox.getObject("foes","fifth3")&&!gbox.getObject("foes","fifth4")) { // check them. If beaten... maingame.addQuestClear(); // Quest clear maingame.addChest(5,7,null,true,"BOSSKEY","bosskey",0); tilemaps.queststatus["_tmpbosskey"]=true; } } var pl=gbox.getObject("player","player"); var ontile=help.getTileInMap(pl.x+pl.colx+pl.colhw,pl.y+pl.coly+pl.colhh,tilemaps.map,tilemaps._defaultblock,"map"); if (ontile==1) maingame.gotoLevel({level:"floor1",x:60,y:530,label:"Floor 1 stairs"}); }, tileIsSolid:function(obj,t){ return (obj._bullet?(t!=13)&&(t!=14):true)&&(t>9) } // Bullets flies over the pits. } } ] }
'use strict'; describe('myApp.view5 module', function() { beforeEach(module('myApp.view5')); describe('view5 controller', function(){ it('should ....', inject(function($controller) { //spec body var view5Ctrl = $controller('View5Ctrl'); expect(view5Ctrl).toBeDefined(); })); }); });
/** * Created by alberto on 6/7/15. */ angular.module('routing').controller('TasksListController', TasksListController); function TasksListController($scope, $rootScope) { $scope.search = {}; $scope.taskslist = $rootScope.taskslist; }
var moment = require("../../index"); exports["America/Los_Angeles"] = { "1918" : function (t) { t.equal(moment("1918-03-31T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1918-03-31T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1918-03-31T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1918-03-31T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1918-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1918-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1918-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1918-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1918-03-31T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1918-03-31T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1918-03-31T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1918-03-31T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1918-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1918-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1918-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1918-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1919" : function (t) { t.equal(moment("1919-03-30T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1919-03-30T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1919-03-30T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1919-03-30T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1919-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1919-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1919-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1919-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1919-03-30T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1919-03-30T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1919-03-30T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1919-03-30T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1919-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1919-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1919-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1919-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1942" : function (t) { t.equal(moment("1942-02-09T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1942-02-09T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1942-02-09T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1942-02-09T10:00:00+00:00 should be 03:00:00 PWT"); t.equal(moment("1942-02-09T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1942-02-09T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1942-02-09T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1942-02-09T10:00:00+00:00 should be 420 minutes offset in PWT"); t.done(); }, "1945" : function (t) { t.equal(moment("1945-08-14T22:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "15:59:59", "1945-08-14T22:59:59+00:00 should be 15:59:59 PWT"); t.equal(moment("1945-08-14T23:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "16:00:00", "1945-08-14T23:00:00+00:00 should be 16:00:00 PPT"); t.equal(moment("1945-09-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1945-09-30T08:59:59+00:00 should be 01:59:59 PPT"); t.equal(moment("1945-09-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1945-09-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1945-08-14T22:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1945-08-14T22:59:59+00:00 should be 420 minutes offset in PWT"); t.equal(moment("1945-08-14T23:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1945-08-14T23:00:00+00:00 should be 420 minutes offset in PPT"); t.equal(moment("1945-09-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1945-09-30T08:59:59+00:00 should be 420 minutes offset in PPT"); t.equal(moment("1945-09-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1945-09-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1948" : function (t) { t.equal(moment("1948-03-14T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1948-03-14T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1948-03-14T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1948-03-14T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1948-03-14T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1948-03-14T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1948-03-14T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1948-03-14T10:00:00+00:00 should be 420 minutes offset in PDT"); t.done(); }, "1949" : function (t) { t.equal(moment("1949-01-01T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1949-01-01T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1949-01-01T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1949-01-01T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1949-01-01T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1949-01-01T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1949-01-01T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1949-01-01T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1950" : function (t) { t.equal(moment("1950-04-30T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1950-04-30T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1950-04-30T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1950-04-30T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1950-09-24T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1950-09-24T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1950-09-24T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1950-09-24T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1950-04-30T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1950-04-30T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1950-04-30T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1950-04-30T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1950-09-24T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1950-09-24T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1950-09-24T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1950-09-24T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1951" : function (t) { t.equal(moment("1951-04-29T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1951-04-29T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1951-04-29T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1951-04-29T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1951-09-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1951-09-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1951-09-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1951-09-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1951-04-29T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1951-04-29T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1951-04-29T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1951-04-29T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1951-09-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1951-09-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1951-09-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1951-09-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1952" : function (t) { t.equal(moment("1952-04-27T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1952-04-27T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1952-04-27T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1952-04-27T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1952-09-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1952-09-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1952-09-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1952-09-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1952-04-27T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1952-04-27T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1952-04-27T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1952-04-27T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1952-09-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1952-09-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1952-09-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1952-09-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1953" : function (t) { t.equal(moment("1953-04-26T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1953-04-26T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1953-04-26T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1953-04-26T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1953-09-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1953-09-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1953-09-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1953-09-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1953-04-26T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1953-04-26T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1953-04-26T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1953-04-26T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1953-09-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1953-09-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1953-09-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1953-09-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1954" : function (t) { t.equal(moment("1954-04-25T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1954-04-25T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1954-04-25T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1954-04-25T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1954-09-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1954-09-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1954-09-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1954-09-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1954-04-25T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1954-04-25T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1954-04-25T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1954-04-25T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1954-09-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1954-09-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1954-09-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1954-09-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1955" : function (t) { t.equal(moment("1955-04-24T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1955-04-24T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1955-04-24T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1955-04-24T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1955-09-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1955-09-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1955-09-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1955-09-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1955-04-24T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1955-04-24T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1955-04-24T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1955-04-24T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1955-09-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1955-09-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1955-09-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1955-09-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1956" : function (t) { t.equal(moment("1956-04-29T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1956-04-29T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1956-04-29T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1956-04-29T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1956-09-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1956-09-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1956-09-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1956-09-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1956-04-29T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1956-04-29T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1956-04-29T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1956-04-29T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1956-09-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1956-09-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1956-09-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1956-09-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1957" : function (t) { t.equal(moment("1957-04-28T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1957-04-28T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1957-04-28T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1957-04-28T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1957-09-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1957-09-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1957-09-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1957-09-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1957-04-28T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1957-04-28T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1957-04-28T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1957-04-28T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1957-09-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1957-09-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1957-09-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1957-09-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1958" : function (t) { t.equal(moment("1958-04-27T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1958-04-27T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1958-04-27T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1958-04-27T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1958-09-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1958-09-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1958-09-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1958-09-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1958-04-27T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1958-04-27T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1958-04-27T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1958-04-27T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1958-09-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1958-09-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1958-09-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1958-09-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1959" : function (t) { t.equal(moment("1959-04-26T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1959-04-26T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1959-04-26T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1959-04-26T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1959-09-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1959-09-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1959-09-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1959-09-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1959-04-26T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1959-04-26T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1959-04-26T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1959-04-26T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1959-09-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1959-09-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1959-09-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1959-09-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1960" : function (t) { t.equal(moment("1960-04-24T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1960-04-24T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1960-04-24T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1960-04-24T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1960-09-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1960-09-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1960-09-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1960-09-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1960-04-24T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1960-04-24T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1960-04-24T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1960-04-24T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1960-09-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1960-09-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1960-09-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1960-09-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1961" : function (t) { t.equal(moment("1961-04-30T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1961-04-30T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1961-04-30T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1961-04-30T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1961-09-24T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1961-09-24T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1961-09-24T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1961-09-24T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1961-04-30T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1961-04-30T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1961-04-30T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1961-04-30T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1961-09-24T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1961-09-24T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1961-09-24T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1961-09-24T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1962" : function (t) { t.equal(moment("1962-04-29T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1962-04-29T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1962-04-29T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1962-04-29T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1962-10-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1962-10-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1962-10-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1962-10-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1962-04-29T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1962-04-29T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1962-04-29T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1962-04-29T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1962-10-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1962-10-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1962-10-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1962-10-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1963" : function (t) { t.equal(moment("1963-04-28T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1963-04-28T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1963-04-28T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1963-04-28T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1963-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1963-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1963-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1963-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1963-04-28T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1963-04-28T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1963-04-28T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1963-04-28T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1963-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1963-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1963-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1963-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1964" : function (t) { t.equal(moment("1964-04-26T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1964-04-26T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1964-04-26T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1964-04-26T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1964-10-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1964-10-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1964-10-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1964-10-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1964-04-26T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1964-04-26T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1964-04-26T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1964-04-26T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1964-10-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1964-10-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1964-10-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1964-10-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1965" : function (t) { t.equal(moment("1965-04-25T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1965-04-25T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1965-04-25T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1965-04-25T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1965-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1965-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1965-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1965-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1965-04-25T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1965-04-25T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1965-04-25T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1965-04-25T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1965-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1965-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1965-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1965-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1966" : function (t) { t.equal(moment("1966-04-24T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1966-04-24T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1966-04-24T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1966-04-24T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1966-10-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1966-10-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1966-10-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1966-10-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1966-04-24T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1966-04-24T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1966-04-24T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1966-04-24T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1966-10-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1966-10-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1966-10-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1966-10-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1967" : function (t) { t.equal(moment("1967-04-30T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1967-04-30T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1967-04-30T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1967-04-30T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1967-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1967-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1967-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1967-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1967-04-30T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1967-04-30T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1967-04-30T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1967-04-30T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1967-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1967-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1967-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1967-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1968" : function (t) { t.equal(moment("1968-04-28T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1968-04-28T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1968-04-28T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1968-04-28T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1968-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1968-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1968-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1968-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1968-04-28T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1968-04-28T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1968-04-28T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1968-04-28T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1968-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1968-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1968-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1968-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1969" : function (t) { t.equal(moment("1969-04-27T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1969-04-27T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1969-04-27T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1969-04-27T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1969-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1969-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1969-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1969-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1969-04-27T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1969-04-27T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1969-04-27T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1969-04-27T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1969-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1969-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1969-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1969-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1970" : function (t) { t.equal(moment("1970-04-26T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1970-04-26T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1970-04-26T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1970-04-26T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1970-10-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1970-10-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1970-10-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1970-10-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1970-04-26T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1970-04-26T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1970-04-26T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1970-04-26T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1970-10-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1970-10-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1970-10-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1970-10-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1971" : function (t) { t.equal(moment("1971-04-25T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1971-04-25T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1971-04-25T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1971-04-25T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1971-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1971-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1971-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1971-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1971-04-25T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1971-04-25T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1971-04-25T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1971-04-25T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1971-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1971-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1971-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1971-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1972" : function (t) { t.equal(moment("1972-04-30T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1972-04-30T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1972-04-30T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1972-04-30T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1972-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1972-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1972-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1972-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1972-04-30T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1972-04-30T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1972-04-30T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1972-04-30T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1972-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1972-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1972-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1972-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1973" : function (t) { t.equal(moment("1973-04-29T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1973-04-29T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1973-04-29T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1973-04-29T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1973-10-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1973-10-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1973-10-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1973-10-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1973-04-29T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1973-04-29T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1973-04-29T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1973-04-29T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1973-10-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1973-10-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1973-10-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1973-10-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1974" : function (t) { t.equal(moment("1974-01-06T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1974-01-06T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1974-01-06T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1974-01-06T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1974-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1974-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1974-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1974-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1974-01-06T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1974-01-06T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1974-01-06T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1974-01-06T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1974-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1974-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1974-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1974-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1975" : function (t) { t.equal(moment("1975-02-23T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1975-02-23T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1975-02-23T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1975-02-23T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1975-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1975-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1975-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1975-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1975-02-23T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1975-02-23T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1975-02-23T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1975-02-23T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1975-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1975-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1975-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1975-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1976" : function (t) { t.equal(moment("1976-04-25T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1976-04-25T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1976-04-25T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1976-04-25T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1976-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1976-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1976-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1976-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1976-04-25T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1976-04-25T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1976-04-25T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1976-04-25T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1976-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1976-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1976-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1976-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1977" : function (t) { t.equal(moment("1977-04-24T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1977-04-24T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1977-04-24T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1977-04-24T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1977-10-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1977-10-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1977-10-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1977-10-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1977-04-24T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1977-04-24T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1977-04-24T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1977-04-24T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1977-10-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1977-10-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1977-10-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1977-10-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1978" : function (t) { t.equal(moment("1978-04-30T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1978-04-30T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1978-04-30T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1978-04-30T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1978-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1978-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1978-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1978-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1978-04-30T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1978-04-30T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1978-04-30T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1978-04-30T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1978-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1978-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1978-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1978-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1979" : function (t) { t.equal(moment("1979-04-29T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1979-04-29T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1979-04-29T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1979-04-29T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1979-10-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1979-10-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1979-10-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1979-10-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1979-04-29T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1979-04-29T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1979-04-29T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1979-04-29T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1979-10-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1979-10-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1979-10-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1979-10-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1980" : function (t) { t.equal(moment("1980-04-27T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1980-04-27T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1980-04-27T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1980-04-27T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1980-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1980-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1980-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1980-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1980-04-27T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1980-04-27T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1980-04-27T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1980-04-27T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1980-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1980-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1980-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1980-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1981" : function (t) { t.equal(moment("1981-04-26T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1981-04-26T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1981-04-26T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1981-04-26T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1981-10-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1981-10-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1981-10-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1981-10-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1981-04-26T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1981-04-26T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1981-04-26T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1981-04-26T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1981-10-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1981-10-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1981-10-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1981-10-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1982" : function (t) { t.equal(moment("1982-04-25T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1982-04-25T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1982-04-25T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1982-04-25T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1982-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1982-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1982-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1982-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1982-04-25T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1982-04-25T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1982-04-25T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1982-04-25T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1982-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1982-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1982-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1982-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1983" : function (t) { t.equal(moment("1983-04-24T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1983-04-24T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1983-04-24T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1983-04-24T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1983-10-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1983-10-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1983-10-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1983-10-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1983-04-24T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1983-04-24T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1983-04-24T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1983-04-24T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1983-10-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1983-10-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1983-10-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1983-10-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1984" : function (t) { t.equal(moment("1984-04-29T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1984-04-29T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1984-04-29T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1984-04-29T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1984-10-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1984-10-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1984-10-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1984-10-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1984-04-29T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1984-04-29T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1984-04-29T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1984-04-29T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1984-10-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1984-10-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1984-10-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1984-10-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1985" : function (t) { t.equal(moment("1985-04-28T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1985-04-28T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1985-04-28T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1985-04-28T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1985-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1985-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1985-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1985-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1985-04-28T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1985-04-28T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1985-04-28T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1985-04-28T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1985-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1985-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1985-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1985-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1986" : function (t) { t.equal(moment("1986-04-27T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1986-04-27T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1986-04-27T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1986-04-27T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1986-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1986-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1986-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1986-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1986-04-27T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1986-04-27T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1986-04-27T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1986-04-27T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1986-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1986-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1986-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1986-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1987" : function (t) { t.equal(moment("1987-04-05T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1987-04-05T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1987-04-05T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1987-04-05T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1987-10-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1987-10-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1987-10-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1987-10-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1987-04-05T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1987-04-05T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1987-04-05T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1987-04-05T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1987-10-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1987-10-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1987-10-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1987-10-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1988" : function (t) { t.equal(moment("1988-04-03T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1988-04-03T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1988-04-03T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1988-04-03T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1988-10-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1988-10-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1988-10-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1988-10-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1988-04-03T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1988-04-03T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1988-04-03T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1988-04-03T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1988-10-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1988-10-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1988-10-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1988-10-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1989" : function (t) { t.equal(moment("1989-04-02T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1989-04-02T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1989-04-02T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1989-04-02T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1989-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1989-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1989-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1989-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1989-04-02T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1989-04-02T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1989-04-02T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1989-04-02T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1989-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1989-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1989-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1989-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1990" : function (t) { t.equal(moment("1990-04-01T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1990-04-01T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1990-04-01T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1990-04-01T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1990-10-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1990-10-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1990-10-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1990-10-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1990-04-01T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1990-04-01T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1990-04-01T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1990-04-01T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1990-10-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1990-10-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1990-10-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1990-10-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1991" : function (t) { t.equal(moment("1991-04-07T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1991-04-07T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1991-04-07T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1991-04-07T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1991-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1991-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1991-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1991-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1991-04-07T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1991-04-07T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1991-04-07T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1991-04-07T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1991-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1991-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1991-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1991-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1992" : function (t) { t.equal(moment("1992-04-05T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1992-04-05T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1992-04-05T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1992-04-05T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1992-10-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1992-10-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1992-10-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1992-10-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1992-04-05T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1992-04-05T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1992-04-05T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1992-04-05T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1992-10-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1992-10-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1992-10-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1992-10-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1993" : function (t) { t.equal(moment("1993-04-04T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1993-04-04T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1993-04-04T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1993-04-04T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1993-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1993-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1993-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1993-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1993-04-04T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1993-04-04T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1993-04-04T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1993-04-04T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1993-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1993-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1993-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1993-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1994" : function (t) { t.equal(moment("1994-04-03T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1994-04-03T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1994-04-03T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1994-04-03T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1994-10-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1994-10-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1994-10-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1994-10-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1994-04-03T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1994-04-03T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1994-04-03T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1994-04-03T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1994-10-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1994-10-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1994-10-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1994-10-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1995" : function (t) { t.equal(moment("1995-04-02T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1995-04-02T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1995-04-02T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1995-04-02T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1995-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1995-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1995-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1995-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1995-04-02T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1995-04-02T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1995-04-02T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1995-04-02T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1995-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1995-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1995-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1995-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1996" : function (t) { t.equal(moment("1996-04-07T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1996-04-07T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1996-04-07T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1996-04-07T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1996-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1996-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1996-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1996-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1996-04-07T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1996-04-07T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1996-04-07T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1996-04-07T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1996-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1996-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1996-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1996-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1997" : function (t) { t.equal(moment("1997-04-06T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1997-04-06T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1997-04-06T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1997-04-06T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1997-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1997-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1997-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1997-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1997-04-06T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1997-04-06T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1997-04-06T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1997-04-06T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1997-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1997-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1997-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1997-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1998" : function (t) { t.equal(moment("1998-04-05T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1998-04-05T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1998-04-05T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1998-04-05T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1998-10-25T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1998-10-25T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1998-10-25T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1998-10-25T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1998-04-05T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1998-04-05T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1998-04-05T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1998-04-05T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1998-10-25T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1998-10-25T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1998-10-25T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1998-10-25T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "1999" : function (t) { t.equal(moment("1999-04-04T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1999-04-04T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("1999-04-04T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "1999-04-04T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("1999-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "1999-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("1999-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "1999-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("1999-04-04T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "1999-04-04T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("1999-04-04T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "1999-04-04T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1999-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "1999-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("1999-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "1999-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2000" : function (t) { t.equal(moment("2000-04-02T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2000-04-02T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2000-04-02T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2000-04-02T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2000-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2000-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2000-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2000-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2000-04-02T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2000-04-02T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2000-04-02T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2000-04-02T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2000-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2000-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2000-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2000-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2001" : function (t) { t.equal(moment("2001-04-01T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2001-04-01T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2001-04-01T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2001-04-01T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2001-10-28T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2001-10-28T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2001-10-28T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2001-10-28T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2001-04-01T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2001-04-01T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2001-04-01T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2001-04-01T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2001-10-28T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2001-10-28T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2001-10-28T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2001-10-28T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2002" : function (t) { t.equal(moment("2002-04-07T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2002-04-07T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2002-04-07T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2002-04-07T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2002-10-27T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2002-10-27T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2002-10-27T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2002-10-27T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2002-04-07T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2002-04-07T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2002-04-07T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2002-04-07T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2002-10-27T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2002-10-27T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2002-10-27T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2002-10-27T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2003" : function (t) { t.equal(moment("2003-04-06T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2003-04-06T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2003-04-06T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2003-04-06T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2003-10-26T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2003-10-26T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2003-10-26T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2003-10-26T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2003-04-06T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2003-04-06T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2003-04-06T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2003-04-06T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2003-10-26T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2003-10-26T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2003-10-26T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2003-10-26T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2004" : function (t) { t.equal(moment("2004-04-04T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2004-04-04T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2004-04-04T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2004-04-04T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2004-10-31T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2004-10-31T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2004-10-31T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2004-10-31T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2004-04-04T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2004-04-04T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2004-04-04T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2004-04-04T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2004-10-31T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2004-10-31T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2004-10-31T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2004-10-31T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2005" : function (t) { t.equal(moment("2005-04-03T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2005-04-03T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2005-04-03T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2005-04-03T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2005-10-30T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2005-10-30T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2005-10-30T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2005-10-30T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2005-04-03T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2005-04-03T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2005-04-03T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2005-04-03T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2005-10-30T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2005-10-30T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2005-10-30T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2005-10-30T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2006" : function (t) { t.equal(moment("2006-04-02T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2006-04-02T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2006-04-02T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2006-04-02T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2006-10-29T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2006-10-29T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2006-10-29T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2006-10-29T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2006-04-02T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2006-04-02T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2006-04-02T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2006-04-02T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2006-10-29T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2006-10-29T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2006-10-29T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2006-10-29T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2007" : function (t) { t.equal(moment("2007-03-11T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2007-03-11T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2007-03-11T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2007-03-11T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2007-11-04T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2007-11-04T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2007-11-04T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2007-11-04T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2007-03-11T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2007-03-11T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2007-03-11T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2007-03-11T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2007-11-04T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2007-11-04T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2007-11-04T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2007-11-04T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2008" : function (t) { t.equal(moment("2008-03-09T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2008-03-09T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2008-03-09T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2008-03-09T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2008-11-02T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2008-11-02T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2008-11-02T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2008-11-02T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2008-03-09T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2008-03-09T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2008-03-09T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2008-03-09T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2008-11-02T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2008-11-02T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2008-11-02T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2008-11-02T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2009" : function (t) { t.equal(moment("2009-03-08T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2009-03-08T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2009-03-08T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2009-03-08T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2009-11-01T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2009-11-01T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2009-11-01T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2009-11-01T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2009-03-08T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2009-03-08T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2009-03-08T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2009-03-08T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2009-11-01T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2009-11-01T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2009-11-01T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2009-11-01T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2010" : function (t) { t.equal(moment("2010-03-14T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2010-03-14T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2010-03-14T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2010-03-14T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2010-11-07T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2010-11-07T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2010-11-07T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2010-11-07T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2010-03-14T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2010-03-14T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2010-03-14T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2010-03-14T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2010-11-07T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2010-11-07T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2010-11-07T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2010-11-07T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2011" : function (t) { t.equal(moment("2011-03-13T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2011-03-13T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2011-03-13T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2011-03-13T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2011-11-06T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2011-11-06T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2011-11-06T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2011-11-06T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2011-03-13T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2011-03-13T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2011-03-13T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2011-03-13T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2011-11-06T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2011-11-06T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2011-11-06T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2011-11-06T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2012" : function (t) { t.equal(moment("2012-03-11T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2012-03-11T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2012-03-11T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2012-03-11T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2012-11-04T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2012-11-04T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2012-11-04T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2012-11-04T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2012-03-11T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2012-03-11T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2012-03-11T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2012-03-11T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2012-11-04T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2012-11-04T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2012-11-04T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2012-11-04T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2013" : function (t) { t.equal(moment("2013-03-10T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2013-03-10T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2013-03-10T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2013-03-10T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2013-11-03T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2013-11-03T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2013-11-03T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2013-11-03T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2013-03-10T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2013-03-10T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2013-03-10T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2013-03-10T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2013-11-03T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2013-11-03T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2013-11-03T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2013-11-03T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2014" : function (t) { t.equal(moment("2014-03-09T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2014-03-09T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2014-03-09T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2014-03-09T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2014-11-02T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2014-11-02T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2014-11-02T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2014-11-02T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2014-03-09T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2014-03-09T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2014-03-09T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2014-03-09T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2014-11-02T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2014-11-02T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2014-11-02T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2014-11-02T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2015" : function (t) { t.equal(moment("2015-03-08T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2015-03-08T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2015-03-08T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2015-03-08T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2015-11-01T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2015-11-01T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2015-11-01T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2015-11-01T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2015-03-08T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2015-03-08T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2015-03-08T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2015-03-08T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2015-11-01T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2015-11-01T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2015-11-01T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2015-11-01T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2016" : function (t) { t.equal(moment("2016-03-13T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2016-03-13T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2016-03-13T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2016-03-13T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2016-11-06T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2016-11-06T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2016-11-06T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2016-11-06T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2016-03-13T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2016-03-13T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2016-03-13T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2016-03-13T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2016-11-06T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2016-11-06T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2016-11-06T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2016-11-06T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2017" : function (t) { t.equal(moment("2017-03-12T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2017-03-12T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2017-03-12T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2017-03-12T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2017-11-05T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2017-11-05T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2017-11-05T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2017-11-05T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2017-03-12T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2017-03-12T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2017-03-12T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2017-03-12T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2017-11-05T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2017-11-05T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2017-11-05T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2017-11-05T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2018" : function (t) { t.equal(moment("2018-03-11T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2018-03-11T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2018-03-11T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2018-03-11T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2018-11-04T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2018-11-04T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2018-11-04T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2018-11-04T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2018-03-11T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2018-03-11T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2018-03-11T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2018-03-11T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2018-11-04T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2018-11-04T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2018-11-04T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2018-11-04T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2019" : function (t) { t.equal(moment("2019-03-10T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2019-03-10T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2019-03-10T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2019-03-10T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2019-11-03T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2019-11-03T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2019-11-03T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2019-11-03T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2019-03-10T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2019-03-10T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2019-03-10T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2019-03-10T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2019-11-03T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2019-11-03T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2019-11-03T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2019-11-03T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2020" : function (t) { t.equal(moment("2020-03-08T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2020-03-08T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2020-03-08T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2020-03-08T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2020-11-01T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2020-11-01T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2020-11-01T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2020-11-01T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2020-03-08T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2020-03-08T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2020-03-08T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2020-03-08T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2020-11-01T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2020-11-01T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2020-11-01T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2020-11-01T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2021" : function (t) { t.equal(moment("2021-03-14T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2021-03-14T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2021-03-14T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2021-03-14T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2021-11-07T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2021-11-07T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2021-11-07T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2021-11-07T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2021-03-14T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2021-03-14T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2021-03-14T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2021-03-14T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2021-11-07T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2021-11-07T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2021-11-07T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2021-11-07T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2022" : function (t) { t.equal(moment("2022-03-13T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2022-03-13T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2022-03-13T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2022-03-13T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2022-11-06T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2022-11-06T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2022-11-06T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2022-11-06T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2022-03-13T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2022-03-13T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2022-03-13T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2022-03-13T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2022-11-06T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2022-11-06T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2022-11-06T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2022-11-06T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2023" : function (t) { t.equal(moment("2023-03-12T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2023-03-12T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2023-03-12T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2023-03-12T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2023-11-05T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2023-11-05T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2023-11-05T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2023-11-05T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2023-03-12T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2023-03-12T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2023-03-12T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2023-03-12T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2023-11-05T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2023-11-05T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2023-11-05T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2023-11-05T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2024" : function (t) { t.equal(moment("2024-03-10T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2024-03-10T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2024-03-10T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2024-03-10T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2024-11-03T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2024-11-03T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2024-11-03T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2024-11-03T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2024-03-10T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2024-03-10T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2024-03-10T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2024-03-10T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2024-11-03T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2024-11-03T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2024-11-03T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2024-11-03T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2025" : function (t) { t.equal(moment("2025-03-09T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2025-03-09T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2025-03-09T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2025-03-09T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2025-11-02T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2025-11-02T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2025-11-02T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2025-11-02T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2025-03-09T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2025-03-09T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2025-03-09T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2025-03-09T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2025-11-02T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2025-11-02T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2025-11-02T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2025-11-02T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2026" : function (t) { t.equal(moment("2026-03-08T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2026-03-08T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2026-03-08T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2026-03-08T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2026-11-01T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2026-11-01T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2026-11-01T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2026-11-01T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2026-03-08T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2026-03-08T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2026-03-08T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2026-03-08T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2026-11-01T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2026-11-01T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2026-11-01T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2026-11-01T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2027" : function (t) { t.equal(moment("2027-03-14T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2027-03-14T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2027-03-14T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2027-03-14T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2027-11-07T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2027-11-07T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2027-11-07T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2027-11-07T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2027-03-14T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2027-03-14T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2027-03-14T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2027-03-14T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2027-11-07T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2027-11-07T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2027-11-07T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2027-11-07T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2028" : function (t) { t.equal(moment("2028-03-12T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2028-03-12T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2028-03-12T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2028-03-12T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2028-11-05T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2028-11-05T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2028-11-05T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2028-11-05T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2028-03-12T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2028-03-12T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2028-03-12T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2028-03-12T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2028-11-05T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2028-11-05T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2028-11-05T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2028-11-05T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2029" : function (t) { t.equal(moment("2029-03-11T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2029-03-11T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2029-03-11T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2029-03-11T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2029-11-04T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2029-11-04T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2029-11-04T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2029-11-04T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2029-03-11T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2029-03-11T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2029-03-11T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2029-03-11T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2029-11-04T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2029-11-04T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2029-11-04T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2029-11-04T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2030" : function (t) { t.equal(moment("2030-03-10T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2030-03-10T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2030-03-10T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2030-03-10T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2030-11-03T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2030-11-03T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2030-11-03T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2030-11-03T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2030-03-10T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2030-03-10T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2030-03-10T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2030-03-10T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2030-11-03T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2030-11-03T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2030-11-03T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2030-11-03T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2031" : function (t) { t.equal(moment("2031-03-09T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2031-03-09T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2031-03-09T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2031-03-09T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2031-11-02T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2031-11-02T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2031-11-02T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2031-11-02T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2031-03-09T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2031-03-09T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2031-03-09T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2031-03-09T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2031-11-02T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2031-11-02T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2031-11-02T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2031-11-02T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2032" : function (t) { t.equal(moment("2032-03-14T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2032-03-14T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2032-03-14T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2032-03-14T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2032-11-07T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2032-11-07T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2032-11-07T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2032-11-07T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2032-03-14T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2032-03-14T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2032-03-14T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2032-03-14T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2032-11-07T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2032-11-07T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2032-11-07T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2032-11-07T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2033" : function (t) { t.equal(moment("2033-03-13T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2033-03-13T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2033-03-13T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2033-03-13T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2033-11-06T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2033-11-06T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2033-11-06T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2033-11-06T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2033-03-13T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2033-03-13T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2033-03-13T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2033-03-13T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2033-11-06T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2033-11-06T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2033-11-06T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2033-11-06T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2034" : function (t) { t.equal(moment("2034-03-12T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2034-03-12T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2034-03-12T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2034-03-12T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2034-11-05T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2034-11-05T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2034-11-05T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2034-11-05T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2034-03-12T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2034-03-12T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2034-03-12T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2034-03-12T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2034-11-05T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2034-11-05T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2034-11-05T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2034-11-05T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2035" : function (t) { t.equal(moment("2035-03-11T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2035-03-11T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2035-03-11T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2035-03-11T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2035-11-04T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2035-11-04T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2035-11-04T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2035-11-04T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2035-03-11T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2035-03-11T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2035-03-11T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2035-03-11T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2035-11-04T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2035-11-04T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2035-11-04T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2035-11-04T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2036" : function (t) { t.equal(moment("2036-03-09T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2036-03-09T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2036-03-09T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2036-03-09T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2036-11-02T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2036-11-02T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2036-11-02T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2036-11-02T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2036-03-09T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2036-03-09T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2036-03-09T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2036-03-09T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2036-11-02T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2036-11-02T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2036-11-02T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2036-11-02T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); }, "2037" : function (t) { t.equal(moment("2037-03-08T09:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2037-03-08T09:59:59+00:00 should be 01:59:59 PST"); t.equal(moment("2037-03-08T10:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "03:00:00", "2037-03-08T10:00:00+00:00 should be 03:00:00 PDT"); t.equal(moment("2037-11-01T08:59:59+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:59:59", "2037-11-01T08:59:59+00:00 should be 01:59:59 PDT"); t.equal(moment("2037-11-01T09:00:00+00:00").tz("America/Los_Angeles").format("HH:mm:ss"), "01:00:00", "2037-11-01T09:00:00+00:00 should be 01:00:00 PST"); t.equal(moment("2037-03-08T09:59:59+00:00").tz("America/Los_Angeles").zone(), 480, "2037-03-08T09:59:59+00:00 should be 480 minutes offset in PST"); t.equal(moment("2037-03-08T10:00:00+00:00").tz("America/Los_Angeles").zone(), 420, "2037-03-08T10:00:00+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2037-11-01T08:59:59+00:00").tz("America/Los_Angeles").zone(), 420, "2037-11-01T08:59:59+00:00 should be 420 minutes offset in PDT"); t.equal(moment("2037-11-01T09:00:00+00:00").tz("America/Los_Angeles").zone(), 480, "2037-11-01T09:00:00+00:00 should be 480 minutes offset in PST"); t.done(); } };
/*globals console, angular*/ 'use strict'; var demoApp = angular.module('isis.ui.contextmenu.demo', ['isis.ui.contextmenu']); demoApp.controller('ContextmenuCustomTemplateController', function ($scope, contextmenuService) { $scope.parameter = {}; $scope.closeClick = function () { console.log('closing this manually'); contextmenuService.close(); }; $scope.isValid = function (num) { console.log('Who knows if is valid?', num); if (parseInt(num, 10) === 4) { $scope.parameter.invalid = false; } else { $scope.parameter.invalid = true; } }; }); demoApp.controller('ContextmenuDemoController', function ($scope) { var menuData = [{ id: 'top', items: [{ id: 'newProject', label: 'New project ...', iconClass: 'glyphicon glyphicon-plus', action: function () { console.log('New project clicked'); }, actionData: {} }, { id: 'importProject', label: 'Import project ...', iconClass: 'glyphicon glyphicon-import', action: function () { console.log('Import project clicked'); }, actionData: {} }] }, { id: 'projects', label: 'Recent projects', totalItems: 20, items: [], showAllItems: function () { console.log('Recent projects clicked'); } }, { id: 'preferences', label: 'preferences', items: [{ id: 'showPreferences', label: 'Show preferences', action: function () { console.log('Show preferences'); }, menu: [{ items: [{ id: 'preferences 1', label: 'Preferences 1' }, { id: 'preferences 2', label: 'Preferences 2' }, { id: 'preferences 3', label: 'Preferences 3', menu: [{ items: [{ id: 'sub_preferences 1', label: 'Sub preferences 1' }, { id: 'sub_preferences 2', label: 'Sub preferences 2' }] }] }] }] }] }]; $scope.menuConfig1 = { triggerEvent: 'click', position: 'right bottom' }; $scope.menuConfig2 = { triggerEvent: 'mouseover', position: 'left bottom', contentTemplateUrl: 'contextmenu-custom-content.html', doNotAutoClose: true, menuCssClass: 'green-shadow' }; $scope.menuData = menuData; $scope.preContextMenu = function (e) { console.log('In preContextMenu ', e); }; });
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import assets from './assets.json'; const server = global.server = express(); const port = process.env.PORT || 5000; server.set('port', port); // // Register Node.js middleware // ----------------------------------------------------------------------------- server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '', entry: assets.app.js }; const css = []; const context = { insertCss: styles => css.push(styles._getCss()), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
var a = { a: 1, b: 2, // <-- trailing comma };
var util = require("util"); var choreography = require("temboo/core/choreography"); /* GeoPoint Associates a Geo point with an existing object. */ var GeoPoint = function(session) { /* Create a new instance of the GeoPoint Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Parse/GeoPoints/GeoPoint" GeoPoint.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GeoPointResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GeoPointInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GeoPoint Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GeoPointInputSet = function() { GeoPointInputSet.super_.call(this); /* Set the value of the ApplicationID input for this Choreo. ((required, string) The Application ID provided by Parse.) */ this.set_ApplicationID = function(value) { this.setInput("ApplicationID", value); } /* Set the value of the ClassName input for this Choreo. ((required, string) The class name for the object being created.) */ this.set_ClassName = function(value) { this.setInput("ClassName", value); } /* Set the value of the Latitude input for this Choreo. ((required, decimal) The latitude coordinate of the Geo Point.) */ this.set_Latitude = function(value) { this.setInput("Latitude", value); } /* Set the value of the Longitude input for this Choreo. ((required, decimal) The longitude coordinate of the Geo Point.) */ this.set_Longitude = function(value) { this.setInput("Longitude", value); } /* Set the value of the RESTAPIKey input for this Choreo. ((required, string) The REST API Key provided by Parse.) */ this.set_RESTAPIKey = function(value) { this.setInput("RESTAPIKey", value); } } /* A ResultSet with methods tailored to the values returned by the GeoPoint Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GeoPointResultSet = function(resultStream) { GeoPointResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Parse.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GeoPoint, choreography.Choreography); util.inherits(GeoPointInputSet, choreography.InputSet); util.inherits(GeoPointResultSet, choreography.ResultSet); exports.GeoPoint = GeoPoint; /* Query Returns objects associated with Geo points near a specified set of coordinates. */ var Query = function(session) { /* Create a new instance of the Query Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Parse/GeoPoints/Query" Query.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new QueryResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new QueryInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the Query Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var QueryInputSet = function() { QueryInputSet.super_.call(this); /* Set the value of the ApplicationID input for this Choreo. ((required, string) The Application ID provided by Parse.) */ this.set_ApplicationID = function(value) { this.setInput("ApplicationID", value); } /* Set the value of the ClassName input for this Choreo. ((required, string) The class name for the object being created.) */ this.set_ClassName = function(value) { this.setInput("ClassName", value); } /* Set the value of the Count input for this Choreo. ((optional, boolean) A flag indicating to include a count of objects in the response. Set to 1 to include a count. Defaults to 0.) */ this.set_Count = function(value) { this.setInput("Count", value); } /* Set the value of the Include input for this Choreo. ((optional, string) Specify a field to return multiple types of related objects in this query. For example, enter: post.author, to retrieve posts and their authors related to this class.) */ this.set_Include = function(value) { this.setInput("Include", value); } /* Set the value of the Latitude input for this Choreo. ((required, decimal) The latitude coordinate of the Geo Point.) */ this.set_Latitude = function(value) { this.setInput("Latitude", value); } /* Set the value of the Limit input for this Choreo. ((optional, integer) The number of results to return.) */ this.set_Limit = function(value) { this.setInput("Limit", value); } /* Set the value of the Longitude input for this Choreo. ((required, decimal) The longitude coordinate of the Geo Point.) */ this.set_Longitude = function(value) { this.setInput("Longitude", value); } /* Set the value of the RESTAPIKey input for this Choreo. ((required, string) The REST API Key provided by Parse.) */ this.set_RESTAPIKey = function(value) { this.setInput("RESTAPIKey", value); } /* Set the value of the Skip input for this Choreo. ((optional, integer) Returns only records after this number. Used in combination with the Limit input to page through many results.) */ this.set_Skip = function(value) { this.setInput("Skip", value); } } /* A ResultSet with methods tailored to the values returned by the Query Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var QueryResultSet = function(resultStream) { QueryResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Parse.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(Query, choreography.Choreography); util.inherits(QueryInputSet, choreography.InputSet); util.inherits(QueryResultSet, choreography.ResultSet); exports.Query = Query;
/** * Dropdown module. * @module foundation.dropdown * @requires foundation.util.keyboard * @requires foundation.util.box */ !function($, Foundation){ 'use strict'; /** * Creates a new instance of a dropdown. * @class * @param {jQuery} element - jQuery object to make into an accordion menu. * @param {Object} options - Overrides to the default plugin settings. */ function Dropdown(element, options){ this.$element = element; this.options = $.extend({}, Dropdown.defaults, this.$element.data(), options); this._init(); Foundation.registerPlugin(this); Foundation.Keyboard.register('Dropdown', { 'ENTER': 'open', 'SPACE': 'open', 'ESCAPE': 'close', 'TAB': 'tab_forward', 'SHIFT_TAB': 'tab_backward' }); } Dropdown.defaults = { /** * Amount of time to delay opening a submenu on hover event. * @option * @example 250 */ hoverDelay: 250, /** * Allow submenus to open on hover events * @option * @example false */ hover: false, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @example 1 */ vOffset: 1, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @example 1 */ hOffset: 1, /** * Class applied to adjust open position. JS will test and fill this in. * @option * @example 'top' */ positionClass: '', /** * Allow the plugin to trap focus to the dropdown pane on open. * @option * @example false */ trapFocus: false }; /** * Initializes the plugin by setting/checking options and attributes, adding helper variables, and saving the anchor. * @function * @private */ Dropdown.prototype._init = function(){ var $id = this.$element.attr('id'); this.$anchor = $('[data-toggle="' + $id + '"]') || $('[data-open="' + $id + '"]'); this.$anchor.attr({ 'aria-controls': $id, 'data-is-focus': false, 'data-yeti-box': $id, 'aria-haspopup': true, 'aria-expanded': false // 'data-resize': $id }); this.options.positionClass = this.getPositionClass(); this.counter = 4; this.usedPositions = []; this.$element.attr({ 'aria-hidden': 'true', 'data-yeti-box': $id, 'data-resize': $id, 'aria-labelledby': this.$anchor[0].id || Foundation.GetYoDigits(6, 'dd-anchor') }); this._events(); }; /** * Helper function to determine current orientation of dropdown pane. * @function * @returns {String} position - string value of a position class. */ Dropdown.prototype.getPositionClass = function(){ var position = this.$element[0].className.match(/(top|left|right)/g); position = position ? position[0] : ''; return position; }; /** * Adjusts the dropdown panes orientation by adding/removing positioning classes. * @function * @private * @param {String} position - position class to remove. */ Dropdown.prototype._reposition = function(position){ this.usedPositions.push(position ? position : 'bottom'); //default, try switching to opposite side if(!position && (this.usedPositions.indexOf('top') < 0)){ this.$element.addClass('top'); }else if(position === 'top' && (this.usedPositions.indexOf('bottom') < 0)){ this.$element.removeClass(position); }else if(position === 'left' && (this.usedPositions.indexOf('right') < 0)){ this.$element.removeClass(position) .addClass('right'); }else if(position === 'right' && (this.usedPositions.indexOf('left') < 0)){ this.$element.removeClass(position) .addClass('left'); } //if default change didn't work, try bottom or left first else if(!position && (this.usedPositions.indexOf('top') > -1) && (this.usedPositions.indexOf('left') < 0)){ this.$element.addClass('left'); }else if(position === 'top' && (this.usedPositions.indexOf('bottom') > -1) && (this.usedPositions.indexOf('left') < 0)){ this.$element.removeClass(position) .addClass('left'); }else if(position === 'left' && (this.usedPositions.indexOf('right') > -1) && (this.usedPositions.indexOf('bottom') < 0)){ this.$element.removeClass(position); }else if(position === 'right' && (this.usedPositions.indexOf('left') > -1) && (this.usedPositions.indexOf('bottom') < 0)){ this.$element.removeClass(position); } //if nothing cleared, set to bottom else{ this.$element.removeClass(position); } this.classChanged = true; this.counter--; }; /** * Sets the position and orientation of the dropdown pane, checks for collisions. * Recursively calls itself if a collision is detected, with a new position class. * @function * @private */ Dropdown.prototype._setPosition = function(){ if(this.$anchor.attr('aria-expanded') === 'false'){ return false; } var position = this.getPositionClass(), $eleDims = Foundation.Box.GetDimensions(this.$element), $anchorDims = Foundation.Box.GetDimensions(this.$anchor), _this = this, direction = (position === 'left' ? 'left' : ((position === 'right') ? 'left' : 'top')), param = (direction === 'top') ? 'height' : 'width', offset = (param === 'height') ? this.options.vOffset : this.options.hOffset; if(($eleDims.width >= $eleDims.windowDims.width) || (!this.counter && !Foundation.Box.ImNotTouchingYou(this.$element))){ this.$element.offset(Foundation.Box.GetOffsets(this.$element, this.$anchor, 'center bottom', this.options.vOffset, this.options.hOffset, true)).css({ 'width': $eleDims.windowDims.width - (this.options.hOffset * 2), 'height': 'auto', }); this.classChanged = true; return false; } this.$element.offset(Foundation.Box.GetOffsets(this.$element, this.$anchor, position, this.options.vOffset, this.options.hOffset)); while(!Foundation.Box.ImNotTouchingYou(this.$element) && this.counter){ this._reposition(position); this._setPosition(); } }; /** * Adds event listeners to the element utilizing the triggers utility library. * @function * @private */ Dropdown.prototype._events = function(){ var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': this._setPosition.bind(this) }); if(this.options.hover){ clearTimeout(_this.timeout); this.$anchor.on('mouseenter.zf.dropdown mouseleave.zf.dropdown', function(){ _this.timeOut = setTimeout(function(){ _this.toggle(); }, _this.options.hoverDelay); }); } this.$anchor.add(this.$element).on('keydown.zf.dropdown', function(e) { var visibleFocusableElements = Foundation.Keyboard.findFocusable(_this.$element); Foundation.Keyboard.handleKey(e, _this, { tab_forward: function() { if (this.$element.find(':focus').is(visibleFocusableElements.eq(-1))) { // left modal downwards, setting focus to first element if (this.options.trapFocus) { // if focus shall be trapped visibleFocusableElements.eq(0).focus(); e.preventDefault(); } else { // if focus is not trapped, close dropdown on focus out this.close(); } } }, tab_backward: function() { if (this.$element.find(':focus').is(visibleFocusableElements.eq(0)) || this.$element.is(':focus')) { // left modal upwards, setting focus to last element if (this.options.trapFocus) { // if focus shall be trapped visibleFocusableElements.eq(-1).focus(); e.preventDefault(); } else { // if focus is not trapped, close dropdown on focus out this.close(); } } }, open: function() { _this.open(); _this.$element.attr('tabindex', -1).focus(); }, close: function() { _this.close(); _this.$anchor.focus(); } }); }); }; /** * Opens the dropdown pane, and fires a bubbling event to close other dropdowns. * @function * @fires Dropdown#closeme * @fires Dropdown#show */ Dropdown.prototype.open = function(){ // var _this = this; /** * Fires to close other open dropdowns * @event Dropdown#closeme */ this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id')); this.$anchor.addClass('hover') .attr({'aria-expanded': true}); // this.$element/*.show()*/; this._setPosition(); this.$element.addClass('is-open') .attr({'aria-hidden': false}); /** * Fires once the dropdown is visible. * @event Dropdown#show */ this.$element.trigger('show.zf.dropdown', [this.$element]); //why does this not work correctly for this plugin? // Foundation.reflow(this.$element, 'dropdown'); // Foundation._reflow(this.$element.attr('data-dropdown')); }; /** * Closes the open dropdown pane. * @function * @fires Dropdown#hide */ Dropdown.prototype.close = function(){ if(!this.$element.hasClass('is-open')){ return false; } this.$element.removeClass('is-open') .attr({'aria-hidden': true}); this.$anchor.removeClass('hover') .attr('aria-expanded', false); if(this.classChanged){ var curPositionClass = this.getPositionClass(); if(curPositionClass){ this.$element.removeClass(curPositionClass); } this.$element.addClass(this.options.positionClass) /*.hide()*/.css({height: '', width: ''}); this.classChanged = false; this.counter = 4; this.usedPositions.length = 0; } this.$element.trigger('hide.zf.dropdown', [this.$element]); // Foundation.reflow(this.$element, 'dropdown'); }; /** * Toggles the dropdown pane's visibility. * @function */ Dropdown.prototype.toggle = function(){ if(this.$element.hasClass('is-open')){ this.close(); }else{ this.open(); } }; /** * Destroys the dropdown. * @function */ Dropdown.prototype.destroy = function(){ this.$element.off('.zf.trigger').hide(); this.$anchor.off('.zf.dropdown'); Foundation.unregisterPlugin(this); }; Foundation.plugin(Dropdown); }(jQuery, window.Foundation);
/* global QUnit */ import { RawShaderMaterial } from '../../../../src/materials/RawShaderMaterial'; export default QUnit.module( 'Materials', () => { QUnit.module( 'RawShaderMaterial', () => { // INHERITANCE QUnit.todo( "Extending", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // INSTANCING QUnit.todo( "Instancing", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // PUBLIC STUFF QUnit.todo( "isRawShaderMaterial", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); } ); } );
'use strict' const assert = require('assert') const {closeWindow} = require('./window-helpers') const {remote} = require('electron') const {BrowserView, BrowserWindow} = remote describe('View module', function () { var w = null var view = null beforeEach(function () { w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }) }) afterEach(function () { if (view) { view.destroy() view = null } return closeWindow(w).then(function () { w = null }) }) describe('BrowserView.setBackgroundColor()', function () { it('does not throw for valid args', function () { view = new BrowserView() view.setBackgroundColor('#000') }) it('throws for invalid args', function () { view = new BrowserView() assert.throws(function () { view.setBackgroundColor(null) }, /conversion failure/) }) }) describe('BrowserView.setAutoResize()', function () { it('does not throw for valid args', function () { view = new BrowserView() view.setAutoResize({}) view.setAutoResize({ width: true, height: false }) }) it('throws for invalid args', function () { view = new BrowserView() assert.throws(function () { view.setAutoResize(null) }, /conversion failure/) }) }) describe('BrowserView.setBounds()', function () { it('does not throw for valid args', function () { view = new BrowserView() view.setBounds({ x: 0, y: 0, width: 1, height: 1 }) }) it('throws for invalid args', function () { view = new BrowserView() assert.throws(function () { view.setBounds(null) }, /conversion failure/) assert.throws(function () { view.setBounds({}) }, /conversion failure/) }) }) describe('BrowserWindow.setBrowserView()', function () { it('does not throw for valid args', function () { view = new BrowserView() w.setBrowserView(view) }) it('does not throw if called multiple times with same view', function () { view = new BrowserView() w.setBrowserView(view) w.setBrowserView(view) w.setBrowserView(view) }) }) })
/*! * IE10 viewport hack for Surface/desktop Windows 8 bug * Copyright 2014-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ // See the Getting Started docs for more information: // http://getbootstrap.com/getting-started/#support-ie10-width (function () { 'use strict'; if (navigator.userAgent.match(/IEMobile\/10\.0/)) { var msViewportStyle = document.createElement('style'); msViewportStyle.appendChild( document.createTextNode( '@-ms-viewport{width:auto!important}' ) ); document.querySelector('head').appendChild(msViewportStyle); } })();
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import InputBasedMixin from 'sl-ember-components/mixins/sl-input-based'; import TooltipEnabledMixin from 'sl-ember-components/mixins/sl-tooltip-enabled'; moduleForComponent( 'sl-textarea', 'Unit | Component | sl textarea', { unit: true }); test( 'Expected Mixins are present', function( assert ) { assert.ok( InputBasedMixin.detect( this.subject() ), 'InputBased Mixin is present' ); assert.ok( TooltipEnabledMixin.detect( this.subject() ), 'TooltipEnabled Mixin is present' ); }); test( 'Expected classes are only ones applied', function( assert ) { assert.equal( this.$().prop( 'class' ), [ 'ember-view form-group sl-textarea' ], 'Rendered component has expected classes' ); }); test( 'If "label" property is not populated, label element is not rendered', function( assert ) { assert.equal( Ember.typeOf( this.$( 'label' ).prop( 'for' ) ), 'undefined', 'Label element is not rendered' ); }); test( 'If "label" property is populated, label element is rendered', function( assert ) { const labelText = 'Test Label'; this.subject({ label: labelText }); const label = this.$( 'label[for="' + this.$( 'textarea' ).prop( 'id' ) + '"]' ); assert.equal( label.length, 1, 'Label is present' ); assert.equal( Ember.$.trim( label.text() ), labelText, 'Label text is expected value' ); }); test( 'If "label" property is populated, "for" attribute is expected value', function( assert ) { const labelText = 'Test Label'; this.subject({ label: labelText }); assert.equal( this.$( 'label' ).prop( 'for' ), this.$( 'textarea' ).prop( 'id' ), 'Label "for" property matches textarea\'s "id" property' ); }); test( 'If "label" property is not populated, "optional" and "required" elements are not rendered even if populated', function( assert ) { this.subject({ optional: true, required: true }); assert.strictEqual( this.$( 'label > .text-info' ).length, 0, "Label's text-info is not rendered" ); assert.strictEqual( this.$( 'label > .text-danger' ).length, 0, "Label's text-danger is not rendered" ); } ); test( '"optional" and "required" elements are rendered if populated along with "label" property', function( assert ) { this.subject({ label: 'Test Label', optional: true, required: true }); assert.equal( this.$( 'label > .text-info' ).prop( 'tagName' ), 'SMALL', "Label's text-info <small> is rendered" ); assert.equal( this.$( 'label > .text-danger' ).prop( 'tagName' ), 'SMALL', "Label's text-danger <small> is rendered" ); }); test( '"helpText" is rendered if populated', function( assert ) { const helpText = 'Help Text'; this.subject({ helpText }); assert.equal( this.$( '.help-block' ).prop( 'tagName' ), 'P', 'Help text block is rendered as a <p>' ); assert.equal( Ember.$.trim( this.$( '.help-block' ).text() ), helpText, 'Help text block text is expected value' ); }); test( '"autofocus" property is supported', function( assert ) { this.subject({ autofocus: true }); assert.equal( this.$( 'textarea' ).attr( 'autofocus' ), 'autofocus', `Textarea's "autofocus" attribute is present` ); }); test( '"cols" property is supported', function( assert ) { const cols = '8'; this.subject({ cols }); assert.equal( this.$( 'textarea' ).attr( 'cols' ), cols, `Textarea's "cols" attribute is expected value` ); }); test( '"disabled" property is supported', function( assert ) { this.subject({ disabled: true }); assert.ok( this.$( 'textarea' ).is( ':disabled' ), 'Textarea is disabled as expected' ); }); test( '"maxlength" property is supported', function( assert ) { const maxlength = '12'; this.subject({ maxlength }); assert.equal( this.$( 'textarea' ).attr( 'maxlength' ), maxlength, `Textarea's "maxlength" attribute is expected value` ); }); test( '"placeholder" property is supported', function( assert ) { const placeholder = 'Placeholder text'; this.subject({ placeholder }); assert.equal( this.$( 'textarea' ).attr( 'placeholder' ), placeholder, `Textarea's "placeholder" attribute is expected value` ); }); test( '"readonly" property is supported', function( assert ) { this.subject({ readonly: true }); assert.ok( this.$( 'textarea' ).prop( 'readonly' ), 'Textarea is readonly as expected' ); }); test( '"rows" property is supported', function( assert ) { const rows = '4'; this.subject({ rows }); assert.equal( this.$( 'textarea' ).attr( 'rows' ), rows, `Textarea's "rows" attribute is expected value` ); }); test( '"selectionDirection" is supported', function( assert ) { this.subject({ selectionDirection: 'backward' }); assert.equal( this.$( 'textarea' ).attr( 'selectionDirection' ), 'backward', `Textarea's "selectionDirection" attribute is expected value` ); }); test( '"selectionEnd" is supported', function( assert ) { const selectionEnd = '10'; this.subject({ selectionEnd }); assert.equal( this.$( 'textarea' ).attr( 'selectionEnd' ), selectionEnd, `Textarea's "selectionEnd" attribute is expected value` ); }); test( '"selectionStart" is supported', function( assert ) { const selectionStart = '10'; this.subject({ selectionStart }); assert.equal( this.$( 'textarea' ).attr( 'selectionStart' ), selectionStart, `Textarea's "selectionStart" attribute is expected value` ); }); test( '"spellcheck" property is supported', function( assert ) { const spellcheck = 'true'; this.subject({ spellcheck }); assert.equal( this.$( 'textarea' ).attr( 'spellcheck' ), spellcheck, `Textarea's "spellcheck" attribute is expected value` ); }); test( '"tabindex" property is supported', function( assert ) { const tabindex = '2'; this.subject({ tabindex }); assert.equal( this.$( 'textarea' ).attr( 'tabindex' ), tabindex, `Textarea's "tabindex" attribute is expected value` ); }); test( '"wrap" property is supported', function( assert ) { const wrap = 'hard'; this.subject({ wrap }); assert.equal( this.$( 'textarea' ).attr( 'wrap' ), wrap, `Textarea's "wrap" attribute is expected value` ); }); test( '"value" property is supported', function( assert ) { const value = 'Bound Value'; this.subject({ value }); assert.equal( this.$( 'textarea' ).val(), value, "Textarea's value is expected value" ); });
/** * MySql: https://github.com/felixge/node-mysql */ function MySql () { this.client = require('mysql'); this.connection = null; this.config = null; this.mysql = true; this.name = 'mysql'; } MySql.prototype.connect = function (options, done) { this.connection = this.client.createConnection(options); this.connection.connect(function (err) { if (err) return done(err); this.config = this.connection.config; this.config.schema = this.config.database; done(); }.bind(this)); this.connection.on('error', function (err) { if (err.code == 'PROTOCOL_CONNECTION_LOST') { this.handleDisconnect(options); } else throw err; }.bind(this)); } MySql.prototype.handleDisconnect = function (options) { setTimeout(function () { this.connect(options, function (err) { err && this.handleDisconnect(options); }.bind(this)); }.bind(this), 2000); } MySql.prototype.query = function (sql, done) { this.connection.query(sql, function (err, rows) { if (err) return done(err); done(null, rows); }); } MySql.prototype.getColumnsInfo = function (data) { var columns = {}; for (var key in data) { var column = data[key]; columns[column.Field] = { type: column.Type, allowNull: column.Null === 'YES' ? true : false, key: column.Key.toLowerCase(), defaultValue: column.Default // extra: column.Extra }; } return columns; } /** * PostgreSql: https://github.com/brianc/node-postgres * or: https://github.com/brianc/node-postgres-pure */ function PostgreSQL () { try {this.client = require('pg')} catch (err) { try {this.client = require('pg.js')} catch (err) { throw Error('Could not find `pg` or `pg.js` module'); } } this.connection = null; this.config = null; this.pg = true; this.name = 'pg'; } PostgreSQL.prototype.connect = function (options, done) { this.connection = new this.client.Client(options); this.connection.connect(function (err) { if (err) return done(err); this.config = this.connection.connectionParameters; this.config.schema = options.schema || 'public'; done(); }.bind(this)); } PostgreSQL.prototype.query = function (sql, done) { this.connection.query(sql, function (err, result) { if (err) return done(err); if (result.command == 'INSERT' && result.rows.length) { var obj = result.rows[0], key = Object.keys(obj)[0]; result.insertId = obj[key]; return done(null, result); } // select done(null, result.rows); }); } function getType (column) { switch (true) { case /^double precision$/.test(column.Type): return 'double'; case /^numeric$/.test(column.Type): return column.numeric_precision ? 'decimal('+column.numeric_precision+','+column.numeric_scale+')' : 'decimal' case /^time\s.*/.test(column.Type): return 'time'; case /^timestamp\s.*/.test(column.Type): return 'timestamp'; case /^bit$/.test(column.Type): return 'bit('+column.character_maximum_length+')'; case /^character$/.test(column.Type): return 'char('+column.character_maximum_length+')'; case /^character varying$/.test(column.Type): return 'varchar('+column.character_maximum_length+')'; case /^boolean$/.test(column.Type): return 'char'; default: return column.Type; } } PostgreSQL.prototype.getColumnsInfo = function (data) { var columns = {}; for (var key in data) { var column = data[key]; columns[column.Field] = { type: getType(column), allowNull: column.Null === 'YES' ? true : false, key: (column.Key && column.Key.slice(0,3).toLowerCase()) || '', defaultValue: column.Default && column.Default.indexOf('nextval')==0 ? null : column.Default // extra: column.Extra }; } return columns; } /** * Sqlite: https://github.com/mapbox/node-sqlite3 */ function SQLite () { try { this.client = require('sqlite3'); } catch (err) { throw new Error('Could not find `sqlite3` module'); } this.connection = null; this.config = null; this.sqlite = true; this.name = 'sqlite'; } SQLite.prototype.connect = function (options, done) { this.connection = new this.client.Database(options.database); this.config = {schema:''}; done(); } SQLite.prototype.query = function (sql, done) { if (/^(insert|update|delete)/i.test(sql)) { this.connection.run(sql, function (err) { if (err) return done(err); done(null, {insertId: this.lastID}); }); } else { this.connection.all(sql, function (err, rows) { if (err) return done(err); done(null, rows); }); } } SQLite.prototype.getColumnsInfo = function (data) { var columns = {}; for (var i=0; i < data.length; i++) { var column = data[i]; columns[column.name] = { type: column.type, allowNull: column.notnull === 1 ? false : true, key: column.pk === 1 ? 'pri' : '', defaultValue: column.dflt_value }; } return columns; } /** * Factory */ function Client (config) { if (config.mysql) return new MySql(); if (config.pg) return new PostgreSQL(); if (config.sqlite) return new SQLite(); else throw new Error('Not supported database type!'); } exports = module.exports = Client;
/** * @license Highmaps JS v6.1.2 (2018-08-31) * Highmaps as a plugin for Highcharts or Highstock. * * (c) 2011-2017 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { module.exports = factory; } else if (typeof define === 'function' && define.amd) { define(function () { return factory; }); } else { factory(Highcharts); } }(function (Highcharts) { (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var addEvent = H.addEvent, Axis = H.Axis, each = H.each, pick = H.pick; /** * Override to use the extreme coordinates from the SVG shape, not the * data values */ addEvent(Axis, 'getSeriesExtremes', function () { var xData = []; // Remove the xData array and cache it locally so that the proceed method // doesn't use it if (this.isXAxis) { each(this.series, function (series, i) { if (series.useMapGeometry) { xData[i] = series.xData; series.xData = []; } }); this.seriesXData = xData; } }); addEvent(Axis, 'afterGetSeriesExtremes', function () { var xData = this.seriesXData, dataMin, dataMax, useMapGeometry; // Run extremes logic for map and mapline if (this.isXAxis) { dataMin = pick(this.dataMin, Number.MAX_VALUE); dataMax = pick(this.dataMax, -Number.MAX_VALUE); each(this.series, function (series, i) { if (series.useMapGeometry) { dataMin = Math.min(dataMin, pick(series.minX, dataMin)); dataMax = Math.max(dataMax, pick(series.maxX, dataMax)); series.xData = xData[i]; // Reset xData array useMapGeometry = true; } }); if (useMapGeometry) { this.dataMin = dataMin; this.dataMax = dataMax; } delete this.seriesXData; } }); /** * Override axis translation to make sure the aspect ratio is always kept */ addEvent(Axis, 'afterSetAxisTranslation', function () { var chart = this.chart, mapRatio, plotRatio = chart.plotWidth / chart.plotHeight, adjustedAxisLength, xAxis = chart.xAxis[0], padAxis, fixTo, fixDiff, preserveAspectRatio; // Check for map-like series if (this.coll === 'yAxis' && xAxis.transA !== undefined) { each(this.series, function (series) { if (series.preserveAspectRatio) { preserveAspectRatio = true; } }); } // On Y axis, handle both if (preserveAspectRatio) { // Use the same translation for both axes this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA); mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min)); // What axis to pad to put the map in the middle padAxis = mapRatio < 1 ? this : xAxis; // Pad it adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA; padAxis.pixelPadding = padAxis.len - adjustedAxisLength; padAxis.minPixelPadding = padAxis.pixelPadding / 2; fixTo = padAxis.fixTo; if (fixTo) { fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true); fixDiff *= padAxis.transA; if ( Math.abs(fixDiff) > padAxis.minPixelPadding || ( padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax ) ) { // zooming out again, keep within restricted area fixDiff = 0; } padAxis.minPixelPadding -= fixDiff; } } }); /** * Override Axis.render in order to delete the fixTo prop */ addEvent(Axis, 'render', function () { this.fixTo = null; }); }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var addEvent = H.addEvent, Axis = H.Axis, Chart = H.Chart, color = H.color, ColorAxis, each = H.each, extend = H.extend, isNumber = H.isNumber, Legend = H.Legend, LegendSymbolMixin = H.LegendSymbolMixin, noop = H.noop, merge = H.merge, pick = H.pick; // If ColorAxis already exists, we may be loading the heatmap module on top of // Highmaps. if (!H.ColorAxis) { /** * The ColorAxis object for inclusion in gradient legends */ ColorAxis = H.ColorAxis = function () { this.init.apply(this, arguments); }; extend(ColorAxis.prototype, Axis.prototype); extend(ColorAxis.prototype, { /** * A color axis for choropleth maps and heat maps. Visually, the color * axis will appear as a gradient or as separate items inside the * legend, depending on whether the axis is scalar or based on data * classes. * * For supported color formats, see the * [docs article about colors](https://www.highcharts.com/docs/chart-design-and-style/colors). * * A scalar color axis is represented by a gradient. The colors either * range between the [minColor](#colorAxis.minColor) and the * [maxColor](#colorAxis.maxColor), or for more fine grained control the * colors can be defined in [stops](#colorAxis.stops). Often times, the * color axis needs to be adjusted to get the right color spread for the * data. In addition to stops, consider using a logarithmic * [axis type](#colorAxis.type), or setting [min](#colorAxis.min) and * [max](#colorAxis.max) to avoid the colors being determined by * outliers. * * When [dataClasses](#colorAxis.dataClasses) are used, the ranges are * subdivided into separate classes like categories based on their * values. This can be used for ranges between two values, but also for * a true category. However, when your data is categorized, it may be as * convenient to add each category to a separate series. * * See [the Axis object](/class-reference/Highcharts.Axis) for * programmatic access to the axis. * * @extends xAxis * @excluding allowDecimals,alternateGridColor,breaks,categories, * crosshair,dateTimeLabelFormats,lineWidth,linkedTo,maxZoom, * minRange,minTickInterval,offset,opposite,plotBands, * plotLines,showEmpty,title * @product highcharts highmaps * @optionparent colorAxis */ defaultColorAxisOptions: { /** * Whether to allow decimals on the color axis. * @type {Boolean} * @default true * @product highcharts highmaps * @apioption colorAxis.allowDecimals */ /** * Determines how to set each data class' color if no individual * color is set. The default value, `tween`, computes intermediate * colors between `minColor` and `maxColor`. The other possible * value, `category`, pulls colors from the global or chart specific * [colors](#colors) array. * * @validvalue ["tween", "category"] * @type {String} * @sample {highmaps} maps/coloraxis/dataclasscolor/ Category colors * @default tween * @product highcharts highmaps * @apioption colorAxis.dataClassColor */ /** * An array of data classes or ranges for the choropleth map. If * none given, the color axis is scalar and values are distributed * as a gradient between the minimum and maximum colors. * * @type {Array<Object>} * @sample {highmaps} maps/demo/data-class-ranges/ Multiple ranges * @sample {highmaps} maps/demo/data-class-two-ranges/ Two ranges * @product highcharts highmaps * @apioption colorAxis.dataClasses */ /** * The color of each data class. If not set, the color is pulled * from the global or chart-specific [colors](#colors) array. In * styled mode, this option is ignored. Instead, use colors defined * in CSS. * * @type {Color} * @sample {highmaps} maps/demo/data-class-two-ranges/ * Explicit colors * @product highcharts highmaps * @apioption colorAxis.dataClasses.color */ /** * The start of the value range that the data class represents, * relating to the point value. * * The range of each `dataClass` is closed in both ends, but can be * overridden by the next `dataClass`. * * @type {Number} * @product highcharts highmaps * @apioption colorAxis.dataClasses.from */ /** * The name of the data class as it appears in the legend. * If no name is given, it is automatically created based on the * `from` and `to` values. For full programmatic control, * [legend.labelFormatter](#legend.labelFormatter) can be used. * In the formatter, `this.from` and `this.to` can be accessed. * * @type {String} * @sample {highmaps} maps/coloraxis/dataclasses-name/ * Named data classes * @sample {highmaps} maps/coloraxis/dataclasses-labelformatter/ * Formatted data classes * @product highcharts highmaps * @apioption colorAxis.dataClasses.name */ /** * The end of the value range that the data class represents, * relating to the point value. * * The range of each `dataClass` is closed in both ends, but can be * overridden by the next `dataClass`. * * @type {Number} * @product highcharts highmaps * @apioption colorAxis.dataClasses.to */ /** * @ignore-option */ lineWidth: 0, /** * Padding of the min value relative to the length of the axis. A * padding of 0.05 will make a 100px axis 5px longer. * * @type {Number} * @product highcharts highmaps */ minPadding: 0, /** * The maximum value of the axis in terms of map point values. If * `null`, the max value is automatically calculated. If the * `endOnTick` option is true, the max value might be rounded up. * * @type {Number} * @sample {highmaps} maps/coloraxis/gridlines/ * Explicit min and max to reduce the effect of outliers * @product highcharts highmaps * @apioption colorAxis.max */ /** * The minimum value of the axis in terms of map point values. If * `null`, the min value is automatically calculated. If the * `startOnTick` option is true, the min value might be rounded * down. * * @type {Number} * @sample {highmaps} maps/coloraxis/gridlines/ * Explicit min and max to reduce the effect of outliers * @product highcharts highmaps * @apioption colorAxis.min */ /** * Padding of the max value relative to the length of the axis. A * padding of 0.05 will make a 100px axis 5px longer. * * @type {Number} * @product highcharts highmaps */ maxPadding: 0, /** * Color of the grid lines extending from the axis across the * gradient. * * @type {Color} * @sample {highmaps} maps/coloraxis/gridlines/ * Grid lines demonstrated * @default #e6e6e6 * @product highcharts highmaps * @apioption colorAxis.gridLineColor */ /** * The width of the grid lines extending from the axis across the * gradient of a scalar color axis. * * @type {Number} * @sample {highmaps} maps/coloraxis/gridlines/ * Grid lines demonstrated * @default 1 * @product highcharts highmaps */ gridLineWidth: 1, /** * The interval of the tick marks in axis units. When `null`, the * tick interval is computed to approximately follow the * `tickPixelInterval`. * * @type {Number} * @product highcharts highmaps * @apioption colorAxis.tickInterval */ /** * If [tickInterval](#colorAxis.tickInterval) is `null` this option * sets the approximate pixel interval of the tick marks. * * @type {Number} * @default 72 * @product highcharts highmaps */ tickPixelInterval: 72, /** * Whether to force the axis to start on a tick. Use this option * with the `maxPadding` option to control the axis start. * * @type {Boolean} * @default true * @product highcharts highmaps */ startOnTick: true, /** * Whether to force the axis to end on a tick. Use this option with * the [maxPadding](#colorAxis.maxPadding) option to control the * axis end. * * @type {Boolean} * @default true * @product highcharts highmaps */ endOnTick: true, /** @ignore */ offset: 0, /** * The triangular marker on a scalar color axis that points to the * value of the hovered area. To disable the marker, set * `marker: null`. * * @type {Object} * @sample {highmaps} maps/coloraxis/marker/ Black marker * @product highcharts highmaps */ marker: { /** * Animation for the marker as it moves between values. Set to * `false` to disable animation. Defaults to `{ duration: 50 }`. * * @type {AnimationOptions|Boolean} * @product highcharts highmaps */ animation: { duration: 50 }, /** * @ignore */ width: 0.01, /** * The color of the marker. * * @type {Color} * @default #999999 * @product highcharts highmaps */ color: '#999999' }, /** * The axis labels show the number for each tick. * * For more live examples on label options, see [xAxis.labels in the * Highcharts API.](/highcharts#xAxis.labels) * * @type {Object} * @extends xAxis.labels * @product highcharts highmaps */ labels: { /** * How to handle overflowing labels on horizontal color axis. * Can be undefined or "justify". If "justify", labels will not * render outside the legend area. If there is room to move it, * it will be aligned to the edge, else it will be removed. * * @validvalue [null, "justify"] * @type {String} * @default justify * @product highcharts highmaps */ overflow: 'justify', rotation: 0 }, /** * The color to represent the minimum of the color axis. Unless * [dataClasses](#colorAxis.dataClasses) or * [stops](#colorAxis.stops) are set, the gradient starts at this * value. * * If dataClasses are set, the color is based on minColor and * maxColor unless a color is set for each data class, or the * [dataClassColor](#colorAxis.dataClassColor) is set. * * @type {Color} * @sample {highmaps} maps/coloraxis/mincolor-maxcolor/ * Min and max colors on scalar (gradient) axis * @sample {highmaps} maps/coloraxis/mincolor-maxcolor-dataclasses/ * On data classes * @default #e6ebf5 * @product highcharts highmaps */ minColor: '#e6ebf5', /** * The color to represent the maximum of the color axis. Unless * [dataClasses](#colorAxis.dataClasses) or * [stops](#colorAxis.stops) are set, the gradient ends at this * value. * * If dataClasses are set, the color is based on minColor and * maxColor unless a color is set for each data class, or the * [dataClassColor](#colorAxis.dataClassColor) is set. * * @type {Color} * @sample {highmaps} maps/coloraxis/mincolor-maxcolor/ * Min and max colors on scalar (gradient) axis * @sample {highmaps} maps/coloraxis/mincolor-maxcolor-dataclasses/ * On data classes * @default #003399 * @product highcharts highmaps */ maxColor: '#003399', /** * Color stops for the gradient of a scalar color axis. Use this in * cases where a linear gradient between a `minColor` and `maxColor` * is not sufficient. The stops is an array of tuples, where the * first item is a float between 0 and 1 assigning the relative * position in the gradient, and the second item is the color. * * @type {Array<Array>} * @sample {highmaps} maps/demo/heatmap/ * Heatmap with three color stops * @product highcharts highmaps * @apioption colorAxis.stops */ /** * The pixel length of the main tick marks on the color axis. */ tickLength: 5, /** * The type of interpolation to use for the color axis. Can be * `linear` or `logarithmic`. * * @validvalue ["linear", "logarithmic"] * @type {String} * @default linear * @product highcharts highmaps * @apioption colorAxis.type */ /** * Whether to reverse the axis so that the highest number is closest * to the origin. Defaults to `false` in a horizontal legend and * `true` in a vertical legend, where the smallest value starts on * top. * * @type {Boolean} * @product highcharts highmaps * @apioption colorAxis.reversed */ /** * Fires when the legend item belonging to the colorAxis is clicked. * One parameter, `event`, is passed to the function. * * @type {Function} * @product highcharts highmaps * @apioption colorAxis.events.legendItemClick */ /** * Whether to display the colorAxis in the legend. * * @type {Boolean} * @see [heatmap.showInLegend](#series.heatmap.showInLegend) * @default true * @since 4.2.7 * @product highcharts highmaps */ showInLegend: true }, // Properties to preserve after destroy, for Axis.update (#5881, #6025) keepProps: [ 'legendGroup', 'legendItemHeight', 'legendItemWidth', 'legendItem', 'legendSymbol' ].concat(Axis.prototype.keepProps), /** * Initialize the color axis */ init: function (chart, userOptions) { var horiz = chart.options.legend.layout !== 'vertical', options; this.coll = 'colorAxis'; // Build the options options = merge(this.defaultColorAxisOptions, { side: horiz ? 2 : 1, reversed: !horiz }, userOptions, { opposite: !horiz, showEmpty: false, title: null, visible: chart.options.legend.enabled }); Axis.prototype.init.call(this, chart, options); // Base init() pushes it to the xAxis array, now pop it again // chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop(); // Prepare data classes if (userOptions.dataClasses) { this.initDataClasses(userOptions); } this.initStops(); // Override original axis properties this.horiz = horiz; this.zoomEnabled = false; // Add default values this.defaultLegendLength = 200; }, initDataClasses: function (userOptions) { var chart = this.chart, dataClasses, colorCounter = 0, colorCount = chart.options.chart.colorCount, options = this.options, len = userOptions.dataClasses.length; this.dataClasses = dataClasses = []; this.legendItems = []; each(userOptions.dataClasses, function (dataClass, i) { var colors; dataClass = merge(dataClass); dataClasses.push(dataClass); if (dataClass.color) { return; } if (options.dataClassColor === 'category') { colors = chart.options.colors; colorCount = colors.length; dataClass.color = colors[colorCounter]; dataClass.colorIndex = colorCounter; // increase and loop back to zero colorCounter++; if (colorCounter === colorCount) { colorCounter = 0; } } else { dataClass.color = color(options.minColor).tweenTo( color(options.maxColor), len < 2 ? 0.5 : i / (len - 1) // #3219 ); } }); }, /** * Override so that ticks are not added in data class axes (#6914) */ setTickPositions: function () { if (!this.dataClasses) { return Axis.prototype.setTickPositions.call(this); } }, initStops: function () { this.stops = this.options.stops || [ [0, this.options.minColor], [1, this.options.maxColor] ]; each(this.stops, function (stop) { stop.color = color(stop[1]); }); }, /** * Extend the setOptions method to process extreme colors and color * stops. */ setOptions: function (userOptions) { Axis.prototype.setOptions.call(this, userOptions); this.options.crosshair = this.options.marker; }, setAxisSize: function () { var symbol = this.legendSymbol, chart = this.chart, legendOptions = chart.options.legend || {}, x, y, width, height; if (symbol) { this.left = x = symbol.attr('x'); this.top = y = symbol.attr('y'); this.width = width = symbol.attr('width'); this.height = height = symbol.attr('height'); this.right = chart.chartWidth - x - width; this.bottom = chart.chartHeight - y - height; this.len = this.horiz ? width : height; this.pos = this.horiz ? x : y; } else { // Fake length for disabled legend to avoid tick issues // and such (#5205) this.len = ( this.horiz ? legendOptions.symbolWidth : legendOptions.symbolHeight ) || this.defaultLegendLength; } }, normalizedValue: function (value) { if (this.isLog) { value = this.val2lin(value); } return 1 - ((this.max - value) / ((this.max - this.min) || 1)); }, /** * Translate from a value to a color */ toColor: function (value, point) { var pos, stops = this.stops, from, to, color, dataClasses = this.dataClasses, dataClass, i; if (dataClasses) { i = dataClasses.length; while (i--) { dataClass = dataClasses[i]; from = dataClass.from; to = dataClass.to; if ( (from === undefined || value >= from) && (to === undefined || value <= to) ) { color = dataClass.color; if (point) { point.dataClass = i; point.colorIndex = dataClass.colorIndex; } break; } } } else { pos = this.normalizedValue(value); i = stops.length; while (i--) { if (pos > stops[i][0]) { break; } } from = stops[i] || stops[i + 1]; to = stops[i + 1] || from; // The position within the gradient pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1); color = from.color.tweenTo( to.color, pos ); } return color; }, /** * Override the getOffset method to add the whole axis groups inside * the legend. */ getOffset: function () { var group = this.legendGroup, sideOffset = this.chart.axisOffset[this.side]; if (group) { // Hook for the getOffset method to add groups to this parent // group this.axisParent = group; // Call the base Axis.prototype.getOffset.call(this); // First time only if (!this.added) { this.added = true; this.labelLeft = 0; this.labelRight = this.width; } // Reset it to avoid color axis reserving space this.chart.axisOffset[this.side] = sideOffset; } }, /** * Create the color gradient */ setLegendColor: function () { var grad, horiz = this.horiz, reversed = this.reversed, one = reversed ? 1 : 0, zero = reversed ? 0 : 1; grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190 this.legendColor = { linearGradient: { x1: grad[0], y1: grad[1], x2: grad[2], y2: grad[3] }, stops: this.stops }; }, /** * The color axis appears inside the legend and has its own legend * symbol */ drawLegendSymbol: function (legend, item) { var padding = legend.padding, legendOptions = legend.options, horiz = this.horiz, width = pick( legendOptions.symbolWidth, horiz ? this.defaultLegendLength : 12 ), height = pick( legendOptions.symbolHeight, horiz ? 12 : this.defaultLegendLength ), labelPadding = pick( legendOptions.labelPadding, horiz ? 16 : 30 ), itemDistance = pick(legendOptions.itemDistance, 10); this.setLegendColor(); // Create the gradient item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, width, height ).attr({ zIndex: 1 }).add(item.legendGroup); // Set how much space this legend item takes up this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding); this.legendItemHeight = height + padding + (horiz ? labelPadding : 0); }, /** * Fool the legend */ setState: function (state) { each(this.series, function (series) { series.setState(state); }); }, visible: true, setVisible: noop, getSeriesExtremes: function () { var series = this.series, i = series.length; this.dataMin = Infinity; this.dataMax = -Infinity; while (i--) { series[i].getExtremes(); if (series[i].valueMin !== undefined) { this.dataMin = Math.min(this.dataMin, series[i].valueMin); this.dataMax = Math.max(this.dataMax, series[i].valueMax); } } }, drawCrosshair: function (e, point) { var plotX = point && point.plotX, plotY = point && point.plotY, crossPos, axisPos = this.pos, axisLen = this.len; if (point) { crossPos = this.toPixels(point[point.series.colorKey]); if (crossPos < axisPos) { crossPos = axisPos - 2; } else if (crossPos > axisPos + axisLen) { crossPos = axisPos + axisLen + 2; } point.plotX = crossPos; point.plotY = this.len - crossPos; Axis.prototype.drawCrosshair.call(this, e, point); point.plotX = plotX; point.plotY = plotY; if ( this.cross && !this.cross.addedToColorAxis && this.legendGroup ) { this.cross .addClass('highcharts-coloraxis-marker') .add(this.legendGroup); this.cross.addedToColorAxis = true; this.cross.attr({ fill: this.crosshair.color }); } } }, getPlotLinePath: function (a, b, c, d, pos) { // crosshairs only return isNumber(pos) ? // pos can be 0 (#3969) ( this.horiz ? [ 'M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z' ] : [ 'M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z' ] ) : Axis.prototype.getPlotLinePath.call(this, a, b, c, d); }, update: function (newOptions, redraw) { var chart = this.chart, legend = chart.legend; each(this.series, function (series) { // Needed for Axis.update when choropleth colors change series.isDirtyData = true; }); // When updating data classes, destroy old items and make sure new // ones are created (#3207) if (newOptions.dataClasses && legend.allItems) { each(legend.allItems, function (item) { if (item.isDataClass && item.legendGroup) { item.legendGroup.destroy(); } }); chart.isDirtyLegend = true; } // Keep the options structure updated for export. Unlike xAxis and // yAxis, the colorAxis is not an array. (#3207) chart.options[this.coll] = merge(this.userOptions, newOptions); Axis.prototype.update.call(this, newOptions, redraw); if (this.legendItem) { this.setLegendColor(); legend.colorizeItem(this, true); } }, /** * Extend basic axis remove by also removing the legend item. */ remove: function () { if (this.legendItem) { this.chart.legend.destroyItem(this); } Axis.prototype.remove.call(this); }, /** * Get the legend item symbols for data classes */ getDataClassLegendSymbols: function () { var axis = this, chart = this.chart, legendItems = this.legendItems, legendOptions = chart.options.legend, valueDecimals = legendOptions.valueDecimals, valueSuffix = legendOptions.valueSuffix || '', name; if (!legendItems.length) { each(this.dataClasses, function (dataClass, i) { var vis = true, from = dataClass.from, to = dataClass.to; // Assemble the default name. This can be overridden // by legend.options.labelFormatter name = ''; if (from === undefined) { name = '< '; } else if (to === undefined) { name = '> '; } if (from !== undefined) { name += H.numberFormat(from, valueDecimals) + valueSuffix; } if (from !== undefined && to !== undefined) { name += ' - '; } if (to !== undefined) { name += H.numberFormat(to, valueDecimals) + valueSuffix; } // Add a mock object to the legend items legendItems.push(extend({ chart: chart, name: name, options: {}, drawLegendSymbol: LegendSymbolMixin.drawRectangle, visible: true, setState: noop, isDataClass: true, setVisible: function () { vis = this.visible = !vis; each(axis.series, function (series) { each(series.points, function (point) { if (point.dataClass === i) { point.setVisible(vis); } }); }); chart.legend.colorizeItem(this, vis); } }, dataClass)); }); } return legendItems; }, name: '' // Prevents 'undefined' in legend in IE8 }); /** * Handle animation of the color attributes directly */ each(['fill', 'stroke'], function (prop) { H.Fx.prototype[prop + 'Setter'] = function () { this.elem.attr( prop, color(this.start).tweenTo( color(this.end), this.pos ), null, true ); }; }); /** * Extend the chart getAxes method to also get the color axis */ addEvent(Chart, 'afterGetAxes', function () { var options = this.options, colorAxisOptions = options.colorAxis; this.colorAxis = []; if (colorAxisOptions) { new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new } }); /** * Add the color axis. This also removes the axis' own series to prevent * them from showing up individually. */ addEvent(Legend, 'afterGetAllItems', function (e) { var colorAxisItems = [], colorAxis = this.chart.colorAxis[0], i; if (colorAxis && colorAxis.options) { if (colorAxis.options.showInLegend) { // Data classes if (colorAxis.options.dataClasses) { colorAxisItems = colorAxis.getDataClassLegendSymbols(); // Gradient legend } else { // Add this axis on top colorAxisItems.push(colorAxis); } // Don't add the color axis' series each(colorAxis.series, function (series) { H.erase(e.allItems, series); }); } } i = colorAxisItems.length; while (i--) { e.allItems.unshift(colorAxisItems[i]); } }); addEvent(Legend, 'afterColorizeItem', function (e) { if (e.visible && e.item.legendColor) { e.item.legendSymbol.attr({ fill: e.item.legendColor }); } }); // Updates in the legend need to be reflected in the color axis (6888) addEvent(Legend, 'afterUpdate', function () { if (this.chart.colorAxis[0]) { this.chart.colorAxis[0].update({}, arguments[2]); } }); } }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var defined = H.defined, each = H.each, noop = H.noop, seriesTypes = H.seriesTypes; /** * Mixin for maps and heatmaps */ H.colorPointMixin = { /** * Color points have a value option that determines whether or not it is * a null point */ isValid: function () { // undefined is allowed return ( this.value !== null && this.value !== Infinity && this.value !== -Infinity ); }, /** * Set the visibility of a single point */ setVisible: function (vis) { var point = this, method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel'], function (key) { if (point[key]) { point[key][method](); } }); }, setState: function (state) { H.Point.prototype.setState.call(this, state); if (this.graphic) { this.graphic.attr({ zIndex: state === 'hover' ? 1 : 0 }); } } }; H.colorSeriesMixin = { pointArrayMap: ['value'], axisTypes: ['xAxis', 'yAxis', 'colorAxis'], optionalAxis: 'colorAxis', trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], getSymbol: noop, parallelArrays: ['x', 'y', 'value'], colorKey: 'value', pointAttribs: seriesTypes.column.prototype.pointAttribs, /** * In choropleth maps, the color is a result of the value, so this needs * translation too */ translateColors: function () { var series = this, nullColor = this.options.nullColor, colorAxis = this.colorAxis, colorKey = this.colorKey; each(this.data, function (point) { var value = point[colorKey], color; color = point.options.color || ( point.isNull ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color ); if (color) { point.color = color; } }); }, /** * Get the color attibutes to apply on the graphic */ colorAttribs: function (point) { var ret = {}; if (defined(point.color)) { ret[this.colorProp || 'fill'] = point.color; } return ret; } }; }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var addEvent = H.addEvent, Chart = H.Chart, doc = H.doc, each = H.each, extend = H.extend, merge = H.merge, pick = H.pick; function stopEvent(e) { if (e) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } } /** * The MapNavigation handles buttons for navigation in addition to mousewheel * and doubleclick handlers for chart zooming. * * @class Highcharts.MapNavigation * * @param {Highcharts.Chart} chart * The Chart instance. */ function MapNavigation(chart) { this.init(chart); } /** * Initiator function. * * @function Highcharts.MapNavigation#init * * @param {Highcharts.Chart} chart * The Chart instance. * * @return {void} */ MapNavigation.prototype.init = function (chart) { this.chart = chart; chart.mapNavButtons = []; }; /** * Update the map navigation with new options. Calling this is the same as * calling `chart.update({ mapNavigation: {} })`. * * @function Highcharts.MapNavigation#update * * @param {Highcharts.MapNavigationOptions} options * New options for the map navigation. * * @return {void} */ MapNavigation.prototype.update = function (options) { var chart = this.chart, o = chart.options.mapNavigation, buttonOptions, attr, states, hoverStates, selectStates, outerHandler = function (e) { this.handler.call(chart, e); stopEvent(e); // Stop default click event (#4444) }, mapNavButtons = chart.mapNavButtons; // Merge in new options in case of update, and register back to chart // options. if (options) { o = chart.options.mapNavigation = merge(chart.options.mapNavigation, options); } // Destroy buttons in case of dynamic update while (mapNavButtons.length) { mapNavButtons.pop().destroy(); } if (pick(o.enableButtons, o.enabled) && !chart.renderer.forExport) { H.objectEach(o.buttons, function (button, n) { buttonOptions = merge(o.buttonOptions, button); // Presentational attr = buttonOptions.theme; attr.style = merge( buttonOptions.theme.style, buttonOptions.style // #3203 ); states = attr.states; hoverStates = states && states.hover; selectStates = states && states.select; button = chart.renderer.button( buttonOptions.text, 0, 0, outerHandler, attr, hoverStates, selectStates, 0, n === 'zoomIn' ? 'topbutton' : 'bottombutton' ) .addClass('highcharts-map-navigation') .attr({ width: buttonOptions.width, height: buttonOptions.height, title: chart.options.lang[n], padding: buttonOptions.padding, zIndex: 5 }) .add(); button.handler = buttonOptions.onclick; button.align( extend(buttonOptions, { width: button.width, height: 2 * button.height }), null, buttonOptions.alignTo ); // Stop double click event (#4444) addEvent(button.element, 'dblclick', stopEvent); mapNavButtons.push(button); }); } this.updateEvents(o); }; /** * Update events, called internally from the update function. Add new event * handlers, or unbinds events if disabled. * * @function Highcharts.MapNavigation#updateEvents * * @param {Highcharts.MapNavigationOptions} options * Options for map navigation. * * @return {void} */ MapNavigation.prototype.updateEvents = function (options) { var chart = this.chart; // Add the double click event if ( pick(options.enableDoubleClickZoom, options.enabled) || options.enableDoubleClickZoomTo ) { this.unbindDblClick = this.unbindDblClick || addEvent( chart.container, 'dblclick', function (e) { chart.pointer.onContainerDblClick(e); } ); } else if (this.unbindDblClick) { // Unbind and set unbinder to undefined this.unbindDblClick = this.unbindDblClick(); } // Add the mousewheel event if (pick(options.enableMouseWheelZoom, options.enabled)) { this.unbindMouseWheel = this.unbindMouseWheel || addEvent( chart.container, doc.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function (e) { chart.pointer.onContainerMouseWheel(e); // Issue #5011, returning false from non-jQuery event does // not prevent default stopEvent(e); return false; } ); } else if (this.unbindMouseWheel) { // Unbind and set unbinder to undefined this.unbindMouseWheel = this.unbindMouseWheel(); } }; // Add events to the Chart object itself extend(Chart.prototype, /** @lends Chart.prototype */ { /** * Fit an inner box to an outer. If the inner box overflows left or right, * align it to the sides of the outer. If it overflows both sides, fit it * within the outer. This is a pattern that occurs more places in * Highcharts, perhaps it should be elevated to a common utility function. * * @ignore * @function Highcharts.Chart#fitToBox * * @param {Highcharts.BBoxObject} inner * * @param {Highcharts.BBoxObject} outer * * @return {Highcharts.BBoxObject} * The inner box */ fitToBox: function (inner, outer) { each([['x', 'width'], ['y', 'height']], function (dim) { var pos = dim[0], size = dim[1]; if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right // the general size is greater, fit fully to outer if (inner[size] > outer[size]) { inner[size] = outer[size]; inner[pos] = outer[pos]; } else { // align right inner[pos] = outer[pos] + outer[size] - inner[size]; } } if (inner[size] > outer[size]) { inner[size] = outer[size]; } if (inner[pos] < outer[pos]) { inner[pos] = outer[pos]; } }); return inner; }, /** * Highmaps only. Zoom in or out of the map. See also {@link Point#zoomTo}. * See {@link Chart#fromLatLonToPoint} for how to get the `centerX` and * `centerY` parameters for a geographic location. * * @function Highcharts.Chart#mapZoom * * @param {number|undefined} [howMuch] * How much to zoom the map. Values less than 1 zooms in. 0.5 zooms * in to half the current view. 2 zooms to twice the current view. * If omitted, the zoom is reset. * * @param {number|undefined} [centerX] * The X axis position to center around if available space. * * @param {number|undefined} [centerY] * The Y axis position to center around if available space. * * @param {number|undefined} [mouseX] * Fix the zoom to this position if possible. This is used for * example in mousewheel events, where the area under the mouse * should be fixed as we zoom in. * * @param {number|undefined} [mouseY] * Fix the zoom to this position if possible. * * @return {void} */ mapZoom: function (howMuch, centerXArg, centerYArg, mouseX, mouseY) { var chart = this, xAxis = chart.xAxis[0], xRange = xAxis.max - xAxis.min, centerX = pick(centerXArg, xAxis.min + xRange / 2), newXRange = xRange * howMuch, yAxis = chart.yAxis[0], yRange = yAxis.max - yAxis.min, centerY = pick(centerYArg, yAxis.min + yRange / 2), newYRange = yRange * howMuch, fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5, fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5, newXMin = centerX - newXRange * fixToX, newYMin = centerY - newYRange * fixToY, newExt = chart.fitToBox({ x: newXMin, y: newYMin, width: newXRange, height: newYRange }, { x: xAxis.dataMin, y: yAxis.dataMin, width: xAxis.dataMax - xAxis.dataMin, height: yAxis.dataMax - yAxis.dataMin }), zoomOut = newExt.x <= xAxis.dataMin && newExt.width >= xAxis.dataMax - xAxis.dataMin && newExt.y <= yAxis.dataMin && newExt.height >= yAxis.dataMax - yAxis.dataMin; // When mousewheel zooming, fix the point under the mouse if (mouseX) { xAxis.fixTo = [mouseX - xAxis.pos, centerXArg]; } if (mouseY) { yAxis.fixTo = [mouseY - yAxis.pos, centerYArg]; } // Zoom if (howMuch !== undefined && !zoomOut) { xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false); yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false); // Reset zoom } else { xAxis.setExtremes(undefined, undefined, false); yAxis.setExtremes(undefined, undefined, false); } // Prevent zooming until this one is finished animating /* chart.holdMapZoom = true; setTimeout(function () { chart.holdMapZoom = false; }, 200); */ /* delay = animation ? animation.duration || 500 : 0; if (delay) { chart.isMapZooming = true; setTimeout(function () { chart.isMapZooming = false; if (chart.mapZoomQueue) { chart.mapZoom.apply(chart, chart.mapZoomQueue); } chart.mapZoomQueue = null; }, delay); } */ chart.redraw(); } }); /* * Extend the Chart.render method to add zooming and panning */ addEvent(Chart, 'beforeRender', function () { // Render the plus and minus buttons. Doing this before the shapes makes // getBBox much quicker, at least in Chrome. this.mapNavigation = new MapNavigation(this); this.mapNavigation.update(); }); }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var extend = H.extend, pick = H.pick, Pointer = H.Pointer, wrap = H.wrap; // Extend the Pointer extend(Pointer.prototype, { /** * The event handler for the doubleclick event */ onContainerDblClick: function (e) { var chart = this.chart; e = this.normalize(e); if (chart.options.mapNavigation.enableDoubleClickZoomTo) { if ( chart.pointer.inClass(e.target, 'highcharts-tracker') && chart.hoverPoint ) { chart.hoverPoint.zoomTo(); } } else if ( chart.isInsidePlot( e.chartX - chart.plotLeft, e.chartY - chart.plotTop ) ) { chart.mapZoom( 0.5, chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } }, /** * The event handler for the mouse scroll event */ onContainerMouseWheel: function (e) { var chart = this.chart, delta; e = this.normalize(e); // Firefox uses e.detail, WebKit and IE uses wheelDelta delta = e.detail || -(e.wheelDelta / 120); if (chart.isInsidePlot( e.chartX - chart.plotLeft, e.chartY - chart.plotTop) ) { chart.mapZoom( Math.pow( chart.options.mapNavigation.mouseWheelSensitivity, delta ), chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } } }); // The pinchType is inferred from mapNavigation options. wrap(Pointer.prototype, 'zoomOption', function (proceed) { var mapNavigation = this.chart.options.mapNavigation; // Pinch status if (pick(mapNavigation.enableTouchZoom, mapNavigation.enabled)) { this.chart.options.chart.pinchType = 'xy'; } proceed.apply(this, [].slice.call(arguments, 1)); }); // Extend the pinchTranslate method to preserve fixed ratio when zooming wrap( Pointer.prototype, 'pinchTranslate', function ( proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch ) { var xBigger; proceed.call( this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch ); // Keep ratio if (this.chart.options.chart.type === 'map' && this.hasZoom) { xBigger = transform.scaleX > transform.scaleY; this.pinchTranslateDirection( !xBigger, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, xBigger ? transform.scaleX : transform.scaleY ); } } ); }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var colorPointMixin = H.colorPointMixin, colorSeriesMixin = H.colorSeriesMixin, each = H.each, extend = H.extend, isNumber = H.isNumber, LegendSymbolMixin = H.LegendSymbolMixin, map = H.map, merge = H.merge, noop = H.noop, pick = H.pick, isArray = H.isArray, Point = H.Point, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes, splat = H.splat; /** * The map series is used for basic choropleth maps, where each map area has a * color based on its value. * * @sample maps/demo/base/ Choropleth map * @extends plotOptions.scatter * @excluding marker * @product highmaps * @optionparent plotOptions.map */ seriesType('map', 'scatter', { /** * Define the z index of the series. * * @type {Number} * @product highmaps * @apioption plotOptions.series.zIndex */ /** * Whether all areas of the map defined in `mapData` should be rendered. * If `true`, areas which don't correspond to a data point, are rendered * as `null` points. If `false`, those areas are skipped. * * @type {Boolean} * @sample {highmaps} maps/plotoptions/series-allareas-false/ * All areas set to false * @default true * @product highmaps * @apioption plotOptions.series.allAreas */ allAreas: true, animation: false, // makes the complex shapes slow /** * The color to apply to null points. * * In styled mode, the null point fill is set in the * `.highcharts-null-point` class. * * @type {Color} * @sample {highmaps} maps/demo/all-areas-as-null/ Null color * @default #f7f7f7 * @product highmaps */ nullColor: '#f7f7f7', /** * The border color of the map areas. * * In styled mode, the border stroke is given in the `.highcharts-point` * class. * * @type {Color} * @sample {highmaps} maps/plotoptions/series-border/ Borders demo * @default #cccccc * @product highmaps highcharts * @apioption plotOptions.series.borderColor */ borderColor: '#cccccc', /** * The border width of each map area. * * In styled mode, the border stroke width is given in the * `.highcharts-point` class. * * @sample {highmaps} maps/plotoptions/series-border/ Borders demo * @product highmaps highcharts * @apioption plotOptions.series.borderWidth */ borderWidth: 1, /** * Whether to allow pointer interaction like tooltips and mouse events * on null points. * * @type {Boolean} * @default false * @since 4.2.7 * @product highmaps * @apioption plotOptions.map.nullInteraction */ /** * Set this option to `false` to prevent a series from connecting to * the global color axis. This will cause the series to have its own * legend item. * * @type {Boolean} * @default undefined * @product highmaps * @apioption plotOptions.series.colorAxis */ /** * @ignore-option */ marker: null, stickyTracking: false, /** * What property to join the `mapData` to the value data. For example, * if joinBy is "code", the mapData items with a specific code is merged * into the data with the same code. For maps loaded from GeoJSON, the * keys may be held in each point's `properties` object. * * The joinBy option can also be an array of two values, where the first * points to a key in the `mapData`, and the second points to another * key in the `data`. * * When joinBy is `null`, the map items are joined by their position * in the array, which performs much better in maps with many data points. * This is the recommended option if you are printing more than a thousand * data points and have a backend that can preprocess the data into * a parallel array of the mapData. * * @type {String|Array<String>} * @sample {highmaps} maps/plotoptions/series-border/ Joined by "code" * @sample {highmaps} maps/demo/geojson/ GeoJSON joined by an array * @sample {highmaps} maps/series/joinby-null/ Simple data joined by null * @product highmaps * @apioption plotOptions.series.joinBy */ joinBy: 'hc-key', dataLabels: { formatter: function () { // #2945 return this.point.value; }, inside: true, // for the color verticalAlign: 'middle', crop: false, overflow: false, padding: 0 }, /** * @ignore */ turboThreshold: 0, tooltip: { followPointer: true, pointFormat: '{point.name}: {point.value}<br/>' }, states: { /** * Overrides for the normal state. * * @type {Object} * @product highmaps * @apioption plotOptions.series.states.normal */ normal: { /** * Animation options for the fill color when returning from hover * state to normal state. The animation adds some latency in order * to reduce the effect of flickering when hovering in and out of * for example an uneven coastline. * * @type {Object|Boolean} * @sample {highmaps} * maps/plotoptions/series-states-animation-false/ * No animation of fill color * @default true * @product highmaps * @apioption plotOptions.series.states.normal.animation */ animation: true }, hover: { halo: null, /** * The color of the shape in this state * * @type {Color} * @sample {highmaps} maps/plotoptions/series-states-hover/ * Hover options * @product highmaps * @apioption plotOptions.series.states.hover.color */ /** * The border color of the point in this state. * * @type {Color} * @product highmaps * @apioption plotOptions.series.states.hover.borderColor */ /** * The border width of the point in this state * * @type {Number} * @product highmaps * @apioption plotOptions.series.states.hover.borderWidth */ /** * The relative brightness of the point when hovered, relative to * the normal point color. * * @type {Number} * @default 0.2 * @product highmaps * @apioption plotOptions.series.states.hover.brightness */ brightness: 0.2 }, select: { color: '#cccccc' } } // Prototype members }, merge(colorSeriesMixin, { type: 'map', getExtremesFromAll: true, useMapGeometry: true, // get axis extremes from paths, not values forceDL: true, searchPoint: noop, // When tooltip is not shared, this series (and derivatives) requires direct // touch/hover. KD-tree does not apply. directTouch: true, // X axis and Y axis must have same translation slope preserveAspectRatio: true, pointArrayMap: ['value'], /** * Get the bounding box of all paths in the map combined. */ getBox: function (paths) { var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox; // Find the bounding box each(paths || [], function (point) { if (point.path) { if (typeof point.path === 'string') { point.path = H.splitPath(point.path); } var path = point.path || [], i = path.length, even = false, // while loop reads from the end pointMaxX = -MAX_VALUE, pointMinX = MAX_VALUE, pointMaxY = -MAX_VALUE, pointMinY = MAX_VALUE, properties = point.properties; // The first time a map point is used, analyze its box if (!point._foundBox) { while (i--) { if (isNumber(path[i])) { if (even) { // even = x pointMaxX = Math.max(pointMaxX, path[i]); pointMinX = Math.min(pointMinX, path[i]); } else { // odd = Y pointMaxY = Math.max(pointMaxY, path[i]); pointMinY = Math.min(pointMinY, path[i]); } even = !even; } } // Cache point bounding box for use to position data labels, // bubbles etc point._midX = pointMinX + (pointMaxX - pointMinX) * pick( point.middleX, properties && properties['hc-middle-x'], 0.5 ); point._midY = pointMinY + (pointMaxY - pointMinY) * pick( point.middleY, properties && properties['hc-middle-y'], 0.5 ); point._maxX = pointMaxX; point._minX = pointMinX; point._maxY = pointMaxY; point._minY = pointMinY; point.labelrank = pick( point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY) ); point._foundBox = true; } maxX = Math.max(maxX, point._maxX); minX = Math.min(minX, point._minX); maxY = Math.max(maxY, point._maxY); minY = Math.min(minY, point._minY); minRange = Math.min( point._maxX - point._minX, point._maxY - point._minY, minRange ); hasBox = true; } }); // Set the box for the whole series if (hasBox) { this.minY = Math.min(minY, pick(this.minY, MAX_VALUE)); this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE)); this.minX = Math.min(minX, pick(this.minX, MAX_VALUE)); this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE)); // If no minRange option is set, set the default minimum zooming // range to 5 times the size of the smallest element if (xAxis && xAxis.options.minRange === undefined) { xAxis.minRange = Math.min( 5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE ); } if (yAxis && yAxis.options.minRange === undefined) { yAxis.minRange = Math.min( 5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE ); } } }, getExtremes: function () { // Get the actual value extremes for colors Series.prototype.getExtremes.call(this, this.valueData); // Recalculate box on updated data if (this.chart.hasRendered && this.isDirtyData) { this.getBox(this.options.data); } this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Extremes for the mock Y axis this.dataMin = this.minY; this.dataMax = this.maxY; }, /** * Translate the path so that it automatically fits into the plot area box * @param {Object} path */ translatePath: function (path) { var series = this, even = false, // while loop reads from the end xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, i, ret = []; // Preserve the original // Do the translation if (path) { i = path.length; while (i--) { if (isNumber(path[i])) { ret[i] = even ? (path[i] - xMin) * xTransA + xMinPixelPadding : (path[i] - yMin) * yTransA + yMinPixelPadding; even = !even; } else { ret[i] = path[i]; } } } return ret; }, /** * Extend setData to join in mapData. If the allAreas option is true, all * areas from the mapData are used, and those that don't correspond to a * data value are given null values. */ setData: function (data, redraw, animation, updatePoints) { var options = this.options, chartOptions = this.chart.options.chart, globalMapData = chartOptions && chartOptions.map, mapData = options.mapData, joinBy = options.joinBy, joinByNull = joinBy === null, pointArrayMap = options.keys || this.pointArrayMap, dataUsed = [], mapMap = {}, mapPoint, mapTransforms = this.chart.mapTransforms, props, i; // Collect mapData from chart options if not defined on series if (!mapData && globalMapData) { mapData = typeof globalMapData === 'string' ? H.maps[globalMapData] : globalMapData; } if (joinByNull) { joinBy = '_i'; } joinBy = this.joinBy = splat(joinBy); if (!joinBy[1]) { joinBy[1] = joinBy[0]; } // Pick up numeric values, add index // Convert Array point definitions to objects using pointArrayMap if (data) { each(data, function (val, i) { var ix = 0; if (isNumber(val)) { data[i] = { value: val }; } else if (isArray(val)) { data[i] = {}; // Automatically copy first item to hc-key if there is an // extra leading string if ( !options.keys && val.length > pointArrayMap.length && typeof val[0] === 'string' ) { data[i]['hc-key'] = val[0]; ++ix; } // Run through pointArrayMap and what's left of the point // data array in parallel, copying over the values for (var j = 0; j < pointArrayMap.length; ++j, ++ix) { if (pointArrayMap[j] && val[ix] !== undefined) { if (pointArrayMap[j].indexOf('.') > 0) { H.Point.prototype.setNestedProperty( data[i], val[ix], pointArrayMap[j] ); } else { data[i][pointArrayMap[j]] = val[ix]; } } } } if (joinByNull) { data[i]._i = i; } }); } this.getBox(data); // Pick up transform definitions for chart this.chart.mapTransforms = mapTransforms = chartOptions && chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms; // Cache cos/sin of transform rotation angle if (mapTransforms) { H.objectEach(mapTransforms, function (transform) { if (transform.rotation) { transform.cosAngle = Math.cos(transform.rotation); transform.sinAngle = Math.sin(transform.rotation); } }); } if (mapData) { if (mapData.type === 'FeatureCollection') { this.mapTitle = mapData.title; mapData = H.geojson(mapData, this.type, this); } this.mapData = mapData; this.mapMap = {}; for (i = 0; i < mapData.length; i++) { mapPoint = mapData[i]; props = mapPoint.properties; mapPoint._i = i; // Copy the property over to root for faster access if (joinBy[0] && props && props[joinBy[0]]) { mapPoint[joinBy[0]] = props[joinBy[0]]; } mapMap[mapPoint[joinBy[0]]] = mapPoint; } this.mapMap = mapMap; // Registered the point codes that actually hold data if (data && joinBy[1]) { each(data, function (point) { if (mapMap[point[joinBy[1]]]) { dataUsed.push(mapMap[point[joinBy[1]]]); } }); } if (options.allAreas) { this.getBox(mapData); data = data || []; // Registered the point codes that actually hold data if (joinBy[1]) { each(data, function (point) { dataUsed.push(point[joinBy[1]]); }); } // Add those map points that don't correspond to data, which // will be drawn as null points dataUsed = '|' + map(dataUsed, function (point) { return point && point[joinBy[0]]; }).join('|') + '|'; // Faster than array.indexOf each(mapData, function (mapPoint) { if ( !joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1 ) { data.push(merge(mapPoint, { value: null })); // #5050 - adding all areas causes the update // optimization of setData to kick in, even though the // point order has changed updatePoints = false; } }); } else { this.getBox(dataUsed); // Issue #4784 } } Series.prototype.setData.call( this, data, redraw, animation, updatePoints ); }, /** * No graph for the map series */ drawGraph: noop, /** * We need the points' bounding boxes in order to draw the data labels, so * we skip it now and call it from drawPoints instead. */ drawDataLabels: noop, /** * Allow a quick redraw by just translating the area group. Used for zooming * and panning in capable browsers. */ doFullTranslate: function () { return ( this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans ); }, /** * Add the path option for data points. Find the max value for color * calculation. */ translate: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate(); series.generatePoints(); each(series.data, function (point) { // Record the middle point (loosely based on centroid), determined // by the middleX and middleY options. point.plotX = xAxis.toPixels(point._midX, true); point.plotY = yAxis.toPixels(point._midY, true); if (doFullTranslate) { point.shapeType = 'path'; point.shapeArgs = { d: series.translatePath(point.path) }; } }); series.translateColors(); }, /** * Get presentational attributes. In the maps series this runs in both * styled and non-styled mode, because colors hold data when a colorAxis * is used. */ pointAttribs: function (point, state) { var attr; attr = seriesTypes.column.prototype.pointAttribs.call( this, point, state ); // Set the stroke-width on the group element and let all point graphics // inherit. That way we don't have to iterate over all points to update // the stroke-width on zooming. attr['stroke-width'] = pick( point.options[ ( this.pointAttrToOptions && this.pointAttrToOptions['stroke-width'] ) || 'borderWidth' ], 'inherit' ); return attr; }, /** * Use the drawPoints method of column, that is able to handle simple * shapeArgs. Extend it by assigning the tooltip position. */ drawPoints: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans, transformGroup, startTranslateX, startTranslateY, startScaleX, startScaleY; // Set a group that handles transform during zooming and panning in // order to preserve clipping on series.group if (!series.transformGroup) { series.transformGroup = renderer.g() .attr({ scaleX: 1, scaleY: 1 }) .add(group); series.transformGroup.survive = true; } // Draw the shapes again if (series.doFullTranslate()) { // Individual point actions. TODO: Check unstyled. if (chart.hasRendered) { each(series.points, function (point) { // Restore state color on update/redraw (#3529) if (point.shapeArgs) { point.shapeArgs.fill = series.pointAttribs( point, point.state ).fill; } }); } // Draw them in transformGroup series.group = series.transformGroup; seriesTypes.column.prototype.drawPoints.apply(series); series.group = group; // Reset // Add class names each(series.points, function (point) { if (point.graphic) { if (point.name) { point.graphic.addClass( 'highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase() ); } if (point.properties && point.properties['hc-key']) { point.graphic.addClass( 'highcharts-key-' + point.properties['hc-key'].toLowerCase() ); } } }); // Set the base for later scale-zooming. The originX and originY // properties are the axis values in the plot area's upper left // corner. this.baseTrans = { originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA, originY: ( yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA) ), transAX: xAxis.transA, transAY: yAxis.transA }; // Reset transformation in case we're doing a full translate (#3789) this.transformGroup.animate({ translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 }); // Just update the scale and transform for better performance } else { scaleX = xAxis.transA / baseTrans.transAX; scaleY = yAxis.transA / baseTrans.transAY; translateX = xAxis.toPixels(baseTrans.originX, true); translateY = yAxis.toPixels(baseTrans.originY, true); // Handle rounding errors in normal view (#3789) if ( scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01 ) { scaleX = 1; scaleY = 1; translateX = Math.round(translateX); translateY = Math.round(translateY); } // Animate or move to the new zoom level. In order to prevent // flickering as the different transform components are set out of // sync (#5991), we run a fake animator attribute and set scale and // translation synchronously in the same step. // A possible improvement to the API would be to handle this in the // renderer or animation engine itself, to ensure that when we are // animating multiple properties, we make sure that each step for // each property is performed in the same step. Also, for symbols // and for transform properties, it should induce a single // updateTransform and symbolAttr call. transformGroup = this.transformGroup; if (chart.renderer.globalAnimation) { startTranslateX = transformGroup.attr('translateX'); startTranslateY = transformGroup.attr('translateY'); startScaleX = transformGroup.attr('scaleX'); startScaleY = transformGroup.attr('scaleY'); transformGroup .attr({ animator: 0 }) .animate({ animator: 1 }, { step: function (now, fx) { transformGroup.attr({ translateX: startTranslateX + (translateX - startTranslateX) * fx.pos, translateY: startTranslateY + (translateY - startTranslateY) * fx.pos, scaleX: startScaleX + (scaleX - startScaleX) * fx.pos, scaleY: startScaleY + (scaleY - startScaleY) * fx.pos }); } }); // When dragging, animation is off. } else { transformGroup.attr({ translateX: translateX, translateY: translateY, scaleX: scaleX, scaleY: scaleY }); } } // Set the stroke-width directly on the group element so the children // inherit it. We need to use setAttribute directly, because the // stroke-widthSetter method expects a stroke color also to be set. group.element.setAttribute( 'stroke-width', ( series.options[ ( series.pointAttrToOptions && series.pointAttrToOptions['stroke-width'] ) || 'borderWidth' ] || 1 // Styled mode ) / (scaleX || 1) ); this.drawMapDataLabels(); }, /** * Draw the data labels. Special for maps is the time that the data labels * are drawn (after points), and the clipping of the dataLabelsGroup. */ drawMapDataLabels: function () { Series.prototype.drawDataLabels.call(this); if (this.dataLabelsGroup) { this.dataLabelsGroup.clip(this.chart.clipRect); } }, /** * Override render to throw in an async call in IE8. Otherwise it chokes on * the US counties demo. */ render: function () { var series = this, render = Series.prototype.render; // Give IE8 some time to breathe. if (series.chart.renderer.isVML && series.data.length > 3000) { setTimeout(function () { render.call(series); }); } else { render.call(series); } }, /** * The initial animation for the map series. By default, animation is * disabled. Animation of map shapes is not at all supported in VML * browsers. */ animate: function (init) { var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos; if (chart.renderer.isSVG) { if (animation === true) { animation = { duration: 1000 }; } // Initialize the animation if (init) { // Scale down the group and place it in the center group.attr({ translateX: left + xAxis.len / 2, translateY: top + yAxis.len / 2, scaleX: 0.001, // #1499 scaleY: 0.001 }); // Run the animation } else { group.animate({ translateX: left, translateY: top, scaleX: 1, scaleY: 1 }, animation); // Delete this function to allow it only once this.animate = null; } } }, /** * Animate in the new series from the clicked point in the old series. * Depends on the drilldown.js module */ animateDrilldown: function (init) { var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[ this.chart.drilldownLevels.length - 1 ], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale; if (!init) { scale = Math.min( fromBox.width / toBox.width, fromBox.height / toBox.height ); level.shapeArgs = { scaleX: scale, scaleY: scale, translateX: fromBox.x, translateY: fromBox.y }; each(this.points, function (point) { if (point.graphic) { point.graphic .attr(level.shapeArgs) .animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, animationOptions); } }); this.animate = null; } }, drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * When drilling up, pull out the individual point graphics from the lower * series and animate them into the origin point in the upper series. */ animateDrillupFrom: function (level) { seriesTypes.column.prototype.animateDrillupFrom.call(this, level); }, /** * When drilling up, keep the upper series invisible until the lower series * has moved into place */ animateDrillupTo: function (init) { seriesTypes.column.prototype.animateDrillupTo.call(this, init); } // Point class }), extend({ /** * Extend the Point object to split paths */ applyOptions: function (options, x) { var point = Point.prototype.applyOptions.call(this, options, x), series = this.series, joinBy = series.joinBy, mapPoint; if (series.mapData) { mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]]; if (mapPoint) { // This applies only to bubbles if (series.xyFromShape) { point.x = mapPoint._midX; point.y = mapPoint._midY; } extend(point, mapPoint); // copy over properties } else { point.value = point.value || null; } } return point; }, /** * Stop the fade-out */ onMouseOver: function (e) { H.clearTimeout(this.colorInterval); if (this.value !== null || this.series.options.nullInteraction) { Point.prototype.onMouseOver.call(this, e); } else { // #3401 Tooltip doesn't hide when hovering over null points this.series.onMouseOut(e); } }, /** * Highmaps only. Zoom in on the point using the global animation. * * @function #zoomTo * @memberof Point * @sample maps/members/point-zoomto/ * Zoom to points from butons */ zoomTo: function () { var point = this, series = point.series; series.xAxis.setExtremes( point._minX, point._maxX, false ); series.yAxis.setExtremes( point._minY, point._maxY, false ); series.chart.redraw(); } }, colorPointMixin)); /** * An array of objects containing a `path` definition and optionally * a code or property to join in the data as per the `joinBy` option. * * @type {Array<Object>} * @sample {highmaps} maps/demo/category-map/ Map data and joinBy * @product highmaps * @apioption series.mapData */ /** * A `map` series. If the [type](#series.map.type) option is not specified, * it is inherited from [chart.type](#chart.type). * * @type {Object} * @extends series,plotOptions.map * @excluding dataParser,dataURL,marker * @product highmaps * @apioption series.map */ /** * An array of data points for the series. For the `map` series type, * points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values * will be interpreted as `value` options. Example: * * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond * to `[hc-key, value]`. Example: * * ```js * data: [ * ['us-ny', 0], * ['us-mi', 5], * ['us-tx', 3], * ['us-ak', 5] * ] * ``` * * 3. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data * points exceeds the series' [turboThreshold](#series.map.turboThreshold), * this option is not available. * * ```js * data: [{ * value: 6, * name: "Point2", * color: "#00FF00" * }, { * value: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object>} * @product highmaps * @apioption series.map.data */ /** * Individual color for the point. By default the color is either used * to denote the value, or pulled from the global `colors` array. * * @type {Color} * @default undefined * @product highmaps * @apioption series.map.data.color */ /** * Individual data label for each point. The options are the same as * the ones for [plotOptions.series.dataLabels]( * #plotOptions.series.dataLabels). * * @type {Object} * @sample {highmaps} maps/series/data-datalabels/ * Disable data labels for individual areas * @product highmaps * @apioption series.map.data.dataLabels */ /** * The `id` of a series in the [drilldown.series](#drilldown.series) * array to use for a drilldown for this point. * * @type {String} * @sample {highmaps} maps/demo/map-drilldown/ Basic drilldown * @product highmaps * @apioption series.map.data.drilldown */ /** * An id for the point. This can be used after render time to get a * pointer to the point object through `chart.get()`. * * @type {String} * @sample {highmaps} maps/series/data-id/ Highlight a point by id * @product highmaps * @apioption series.map.data.id */ /** * When data labels are laid out on a map, Highmaps runs a simplified * algorithm to detect collision. When two labels collide, the one with * the lowest rank is hidden. By default the rank is computed from the * area. * * @type {Number} * @product highmaps * @apioption series.map.data.labelrank */ /** * The relative mid point of an area, used to place the data label. * Ranges from 0 to 1\. When `mapData` is used, middleX can be defined * there. * * @type {Number} * @default 0.5 * @product highmaps * @apioption series.map.data.middleX */ /** * The relative mid point of an area, used to place the data label. * Ranges from 0 to 1\. When `mapData` is used, middleY can be defined * there. * * @type {Number} * @default 0.5 * @product highmaps * @apioption series.map.data.middleY */ /** * The name of the point as shown in the legend, tooltip, dataLabel * etc. * * @type {String} * @sample {highmaps} maps/series/data-datalabels/ Point names * @product highmaps * @apioption series.map.data.name */ /** * For map and mapline series types, the SVG path for the shape. For * compatibily with old IE, not all SVG path definitions are supported, * but M, L and C operators are safe. * * To achieve a better separation between the structure and the data, * it is recommended to use `mapData` to define that paths instead * of defining them on the data points themselves. * * @type {String} * @sample {highmaps} maps/series/data-path/ Paths defined in data * @product highmaps * @apioption series.map.data.path */ /** * The numeric value of the data point. * * @type {Number} * @product highmaps * @apioption series.map.data.value */ /** * Individual point events * * @extends plotOptions.series.point.events * @product highmaps * @apioption series.map.data.events */ }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var seriesType = H.seriesType, seriesTypes = H.seriesTypes; /** * A mapline series is a special case of the map series where the value colors * are applied to the strokes rather than the fills. It can also be used for * freeform drawing, like dividers, in the map. * * @sample maps/demo/mapline-mappoint/ Mapline and map-point chart * @extends plotOptions.map * @product highmaps * @optionparent plotOptions.mapline */ seriesType('mapline', 'map', { /** * The width of the map line. * * @type {Number} * @default 1 * @product highmaps */ lineWidth: 1, /** * Fill color for the map line shapes * * @type {Color} * @default none * @product highmaps */ fillColor: 'none' }, { type: 'mapline', colorProp: 'stroke', pointAttrToOptions: { 'stroke': 'color', 'stroke-width': 'lineWidth' }, /** * Get presentational attributes */ pointAttribs: function (point, state) { var attr = seriesTypes.map.prototype.pointAttribs.call( this, point, state ); // The difference from a map series is that the stroke takes the point // color attr.fill = this.options.fillColor; return attr; }, drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol }); /** * A `mapline` series. If the [type](#series.mapline.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @type {Object} * @extends series,plotOptions.mapline * @excluding dataParser,dataURL,marker * @product highmaps * @apioption series.mapline */ /** * An array of data points for the series. For the `mapline` series type, * points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values * will be interpreted as `value` options. Example: * * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond * to `[hc-key, value]`. Example: * * ```js * data: [ * ['us-ny', 0], * ['us-mi', 5], * ['us-tx', 3], * ['us-ak', 5] * ] * ``` * * 3. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data * points exceeds the series' [turboThreshold](#series.map.turboThreshold), * this option is not available. * * ```js * data: [{ * value: 6, * name: "Point2", * color: "#00FF00" * }, { * value: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object>} * @product highmaps * @apioption series.mapline.data */ }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var merge = H.merge, Point = H.Point, seriesType = H.seriesType; /** * A mappoint series is a special form of scatter series where the points can * be laid out in map coordinates on top of a map. * * @sample maps/demo/mapline-mappoint/ Map-line and map-point series. * @extends plotOptions.scatter * @product highmaps * @optionparent plotOptions.mappoint */ seriesType('mappoint', 'scatter', { dataLabels: { /** * @default {point.name} * @apioption plotOptions.mappoint.dataLabels.format */ enabled: true, formatter: function () { // #2945 return this.point.name; }, crop: false, defer: false, overflow: false, style: { color: '#000000' } } // Prototype members }, { type: 'mappoint', forceDL: true // Point class }, { applyOptions: function (options, x) { var mergedOptions = ( options.lat !== undefined && options.lon !== undefined ? merge(options, this.series.chart.fromLatLonToPoint(options)) : options ); return Point.prototype.applyOptions.call(this, mergedOptions, x); } }); /** * A `mappoint` series. If the [type](#series.mappoint.type) option * is not specified, it is inherited from [chart.type](#chart.type). * * * @type {Object} * @extends series,plotOptions.mappoint * @excluding dataParser,dataURL * @product highmaps * @apioption series.mappoint */ /** * An array of data points for the series. For the `mappoint` series * type, points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values * will be interpreted as `y` options. The `x` values will be automatically * calculated, either starting at 0 and incremented by 1, or from `pointStart` * and `pointInterval` given in the series options. If the axis has * categories, these will be used. Example: * * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond * to `x,y`. If the first value is a string, it is applied as the name * of the point, and the `x` value is inferred. * * ```js * data: [ * [0, 1], * [1, 8], * [2, 7] * ] * ``` * * 3. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data * points exceeds the series' [turboThreshold](#series.mappoint.turboThreshold), * this option is not available. * * ```js * data: [{ * x: 1, * y: 7, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 4, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object|Array|Number>} * @extends series.map.data * @excluding labelrank,middleX,middleY,path,value * @product highmaps * @apioption series.mappoint.data */ /** * The latitude of the point. Must be combined with the `lon` option * to work. Overrides `x` and `y` values. * * @type {Number} * @sample {highmaps} maps/demo/mappoint-latlon/ Point position by lat/lon * @since 1.1.0 * @product highmaps * @apioption series.mappoint.data.lat */ /** * The longitude of the point. Must be combined with the `lon` option * to work. Overrides `x` and `y` values. * * @type {Number} * @sample {highmaps} maps/demo/mappoint-latlon/ Point position by lat/lon * @since 1.1.0 * @product highmaps * @apioption series.mappoint.data.lon */ /** * The x coordinate of the point in terms of the map path coordinates. * * @type {Number} * @sample {highmaps} maps/demo/mapline-mappoint/ Map point demo * @product highmaps * @apioption series.mappoint.data.x */ /** * The x coordinate of the point in terms of the map path coordinates. * * @type {Number} * @sample {highmaps} maps/demo/mapline-mappoint/ Map point demo * @product highmaps * @apioption series.mappoint.data.y */ }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var arrayMax = H.arrayMax, arrayMin = H.arrayMin, Axis = H.Axis, color = H.color, each = H.each, isNumber = H.isNumber, noop = H.noop, pick = H.pick, pInt = H.pInt, Point = H.Point, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes; /** * A bubble series is a three dimensional series type where each point renders * an X, Y and Z value. Each points is drawn as a bubble where the position * along the X and Y axes mark the X and Y values, and the size of the bubble * relates to the Z value. Requires `highcharts-more.js`. * * @sample {highcharts} highcharts/demo/bubble/ Bubble chart * @extends plotOptions.scatter * @product highcharts highstock * @optionparent plotOptions.bubble */ seriesType('bubble', 'scatter', { dataLabels: { formatter: function () { // #2945 return this.point.z; }, inside: true, verticalAlign: 'middle' }, /** * If there are more points in the series than the `animationLimit`, the * animation won't run. Animation affects overall performance and doesn't * work well with heavy data series. * @since 6.1.0 */ animationLimit: 250, /** * Whether to display negative sized bubbles. The threshold is given * by the [zThreshold](#plotOptions.bubble.zThreshold) option, and negative * bubbles can be visualized by setting * [negativeColor](#plotOptions.bubble.negativeColor). * * @type {Boolean} * @sample {highcharts} highcharts/plotoptions/bubble-negative/ * Negative bubbles * @default true * @since 3.0 * @apioption plotOptions.bubble.displayNegative */ /** * @extends plotOptions.series.marker * @excluding enabled,enabledThreshold,height,radius,width */ marker: { lineColor: null, // inherit from series.color lineWidth: 1, /** * The fill opacity of the bubble markers. */ fillOpacity: 0.5, /** * In bubble charts, the radius is overridden and determined based on * the point's data value. */ /** * @ignore-option */ radius: null, states: { hover: { radiusPlus: 0 } }, /** * A predefined shape or symbol for the marker. Possible values are * "circle", "square", "diamond", "triangle" and "triangle-down". * * Additionally, the URL to a graphic can be given on the form * `url(graphic.png)`. Note that for the image to be applied to exported * charts, its URL needs to be accessible by the export server. * * Custom callbacks for symbol path generation can also be added to * `Highcharts.SVGRenderer.prototype.symbols`. The callback is then * used by its method name, as shown in the demo. * * @validvalue ["circle", "square", "diamond", "triangle", * "triangle-down"] * @sample {highcharts} highcharts/plotoptions/bubble-symbol/ * Bubble chart with various symbols * @sample {highcharts} highcharts/plotoptions/series-marker-symbol/ * General chart with predefined, graphic and custom markers * @since 5.0.11 */ symbol: 'circle' }, /** * Minimum bubble size. Bubbles will automatically size between the * `minSize` and `maxSize` to reflect the `z` value of each bubble. * Can be either pixels (when no unit is given), or a percentage of * the smallest one of the plot width and height. * * @type {Number|String} * @sample {highcharts} highcharts/plotoptions/bubble-size/ Bubble size * @since 3.0 * @product highcharts highstock */ minSize: 8, /** * Maximum bubble size. Bubbles will automatically size between the * `minSize` and `maxSize` to reflect the `z` value of each bubble. * Can be either pixels (when no unit is given), or a percentage of * the smallest one of the plot width and height. * * @type {Number|String} * @sample {highcharts} highcharts/plotoptions/bubble-size/ * Bubble size * @since 3.0 * @product highcharts highstock */ maxSize: '20%', /** * When a point's Z value is below the * [zThreshold](#plotOptions.bubble.zThreshold) setting, this color is used. * * @type {Color} * @sample {highcharts} highcharts/plotoptions/bubble-negative/ * Negative bubbles * @default null * @since 3.0 * @product highcharts * @apioption plotOptions.bubble.negativeColor */ /** * Whether the bubble's value should be represented by the area or the * width of the bubble. The default, `area`, corresponds best to the * human perception of the size of each bubble. * * @validvalue ["area", "width"] * @type {String} * @sample {highcharts} highcharts/plotoptions/bubble-sizeby/ * Comparison of area and size * @default area * @since 3.0.7 * @apioption plotOptions.bubble.sizeBy */ /** * When this is true, the absolute value of z determines the size of * the bubble. This means that with the default `zThreshold` of 0, a * bubble of value -1 will have the same size as a bubble of value 1, * while a bubble of value 0 will have a smaller size according to * `minSize`. * * @type {Boolean} * @sample {highcharts} * highcharts/plotoptions/bubble-sizebyabsolutevalue/ * Size by absolute value, various thresholds * @default false * @since 4.1.9 * @product highcharts * @apioption plotOptions.bubble.sizeByAbsoluteValue */ /** * When this is true, the series will not cause the Y axis to cross * the zero plane (or [threshold](#plotOptions.series.threshold) option) * unless the data actually crosses the plane. * * For example, if `softThreshold` is `false`, a series of 0, 1, 2, * 3 will make the Y axis show negative values according to the `minPadding` * option. If `softThreshold` is `true`, the Y axis starts at 0. * * @since 4.1.9 * @product highcharts */ softThreshold: false, states: { hover: { halo: { size: 5 } } }, tooltip: { pointFormat: '({point.x}, {point.y}), Size: {point.z}' }, turboThreshold: 0, /** * The minimum for the Z value range. Defaults to the highest Z value * in the data. * * @type {Number} * @see [zMin](#plotOptions.bubble.zMin) * @sample {highcharts} highcharts/plotoptions/bubble-zmin-zmax/ * Z has a possible range of 0-100 * @default null * @since 4.0.3 * @product highcharts * @apioption plotOptions.bubble.zMax */ /** * The minimum for the Z value range. Defaults to the lowest Z value * in the data. * * @type {Number} * @see [zMax](#plotOptions.bubble.zMax) * @sample {highcharts} highcharts/plotoptions/bubble-zmin-zmax/ * Z has a possible range of 0-100 * @default null * @since 4.0.3 * @product highcharts * @apioption plotOptions.bubble.zMin */ /** * When [displayNegative](#plotOptions.bubble.displayNegative) is `false`, * bubbles with lower Z values are skipped. When `displayNegative` * is `true` and a [negativeColor](#plotOptions.bubble.negativeColor) * is given, points with lower Z is colored. * * @type {Number} * @sample {highcharts} highcharts/plotoptions/bubble-negative/ * Negative bubbles * @default 0 * @since 3.0 * @product highcharts */ zThreshold: 0, zoneAxis: 'z' // Prototype members }, { pointArrayMap: ['y', 'z'], parallelArrays: ['x', 'y', 'z'], trackerGroups: ['group', 'dataLabelsGroup'], specialGroup: 'group', // To allow clipping (#6296) bubblePadding: true, zoneAxis: 'z', directTouch: true, pointAttribs: function (point, state) { var markerOptions = this.options.marker, fillOpacity = markerOptions.fillOpacity, attr = Series.prototype.pointAttribs.call(this, point, state); if (fillOpacity !== 1) { attr.fill = color(attr.fill).setOpacity(fillOpacity).get('rgba'); } return attr; }, /** * Get the radius for each point based on the minSize, maxSize and each * point's Z value. This must be done prior to Series.translate because * the axis needs to add padding in accordance with the point sizes. */ getRadii: function (zMin, zMax, minSize, maxSize) { var len, i, pos, zData = this.zData, radii = [], options = this.options, sizeByArea = options.sizeBy !== 'width', zThreshold = options.zThreshold, zRange = zMax - zMin, value, radius; // Set the shape type and arguments to be picked up in drawPoints for (i = 0, len = zData.length; i < len; i++) { value = zData[i]; // When sizing by threshold, the absolute value of z determines // the size of the bubble. if (options.sizeByAbsoluteValue && value !== null) { value = Math.abs(value - zThreshold); zMax = zRange = Math.max( zMax - zThreshold, Math.abs(zMin - zThreshold) ); zMin = 0; } if (!isNumber(value)) { radius = null; // Issue #4419 - if value is less than zMin, push a radius that's // always smaller than the minimum size } else if (value < zMin) { radius = minSize / 2 - 1; } else { // Relative size, a number between 0 and 1 pos = zRange > 0 ? (value - zMin) / zRange : 0.5; if (sizeByArea && pos >= 0) { pos = Math.sqrt(pos); } radius = Math.ceil(minSize + pos * (maxSize - minSize)) / 2; } radii.push(radius); } this.radii = radii; }, /** * Perform animation on the bubbles */ animate: function (init) { if ( !init && this.points.length < this.options.animationLimit // #8099 ) { each(this.points, function (point) { var graphic = point.graphic, animationTarget; if (graphic && graphic.width) { // URL symbols don't have width animationTarget = { x: graphic.x, y: graphic.y, width: graphic.width, height: graphic.height }; // Start values graphic.attr({ x: point.plotX, y: point.plotY, width: 1, height: 1 }); // Run animation graphic.animate(animationTarget, this.options.animation); } }, this); // delete this function to allow it only once this.animate = null; } }, /** * Extend the base translate method to handle bubble size */ translate: function () { var i, data = this.data, point, radius, radii = this.radii; // Run the parent method seriesTypes.scatter.prototype.translate.call(this); // Set the shape type and arguments to be picked up in drawPoints i = data.length; while (i--) { point = data[i]; radius = radii ? radii[i] : 0; // #1737 if (isNumber(radius) && radius >= this.minPxSize / 2) { // Shape arguments point.marker = H.extend(point.marker, { radius: radius, width: 2 * radius, height: 2 * radius }); // Alignment box for the data label point.dlBox = { x: point.plotX - radius, y: point.plotY - radius, width: 2 * radius, height: 2 * radius }; } else { // below zThreshold // #1691 point.shapeArgs = point.plotY = point.dlBox = undefined; } } }, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, buildKDTree: noop, applyZones: noop // Point class }, { haloPath: function (size) { return Point.prototype.haloPath.call( this, // #6067 size === 0 ? 0 : (this.marker ? this.marker.radius || 0 : 0) + size ); }, ttBelow: false }); /** * Add logic to pad each axis with the amount of pixels * necessary to avoid the bubbles to overflow. */ Axis.prototype.beforePadding = function () { var axis = this, axisLength = this.len, chart = this.chart, pxMin = 0, pxMax = axisLength, isXAxis = this.isXAxis, dataKey = isXAxis ? 'xData' : 'yData', min = this.min, extremes = {}, smallestSize = Math.min(chart.plotWidth, chart.plotHeight), zMin = Number.MAX_VALUE, zMax = -Number.MAX_VALUE, range = this.max - min, transA = axisLength / range, activeSeries = []; // Handle padding on the second pass, or on redraw each(this.series, function (series) { var seriesOptions = series.options, zData; if ( series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries) ) { // Correction for #1673 axis.allowZoomOutside = true; // Cache it activeSeries.push(series); if (isXAxis) { // because X axis is evaluated first // For each series, translate the size extremes to pixel values each(['minSize', 'maxSize'], function (prop) { var length = seriesOptions[prop], isPercent = /%$/.test(length); length = pInt(length); extremes[prop] = isPercent ? smallestSize * length / 100 : length; }); series.minPxSize = extremes.minSize; // Prioritize min size if conflict to make sure bubbles are // always visible. #5873 series.maxPxSize = Math.max(extremes.maxSize, extremes.minSize); // Find the min and max Z zData = H.grep(series.zData, H.isNumber); if (zData.length) { // #1735 zMin = pick(seriesOptions.zMin, Math.min( zMin, Math.max( arrayMin(zData), seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE ) )); zMax = pick( seriesOptions.zMax, Math.max(zMax, arrayMax(zData)) ); } } } }); each(activeSeries, function (series) { var data = series[dataKey], i = data.length, radius; if (isXAxis) { series.getRadii(zMin, zMax, series.minPxSize, series.maxPxSize); } if (range > 0) { while (i--) { if ( isNumber(data[i]) && axis.dataMin <= data[i] && data[i] <= axis.dataMax ) { radius = series.radii[i]; pxMin = Math.min( ((data[i] - min) * transA) - radius, pxMin ); pxMax = Math.max( ((data[i] - min) * transA) + radius, pxMax ); } } } }); if (activeSeries.length && range > 0 && !this.isLog) { pxMax -= axisLength; transA *= (axisLength + pxMin - pxMax) / axisLength; each( [['min', 'userMin', pxMin], ['max', 'userMax', pxMax]], function (keys) { if (pick(axis.options[keys[0]], axis[keys[1]]) === undefined) { axis[keys[0]] += keys[2] / transA; } } ); } }; /** * A `bubble` series. If the [type](#series.bubble.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @type {Object} * @extends series,plotOptions.bubble * @excluding dataParser,dataURL,stack * @product highcharts highstock * @apioption series.bubble */ /** * An array of data points for the series. For the `bubble` series type, * points can be given in the following ways: * * 1. An array of arrays with 3 or 2 values. In this case, the values * correspond to `x,y,z`. If the first value is a string, it is applied * as the name of the point, and the `x` value is inferred. The `x` * value can also be omitted, in which case the inner arrays should * be of length 2\. Then the `x` value is automatically calculated, * either starting at 0 and incremented by 1, or from `pointStart` and * `pointInterval` given in the series options. * * ```js * data: [ * [0, 1, 2], * [1, 5, 5], * [2, 0, 2] * ] * ``` * * 2. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data * points exceeds the series' [turboThreshold](#series.bubble.turboThreshold), * this option is not available. * * ```js * data: [{ * x: 1, * y: 1, * z: 1, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 5, * z: 4, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object|Array>} * @extends series.line.data * @excluding marker * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * @product highcharts * @apioption series.bubble.data */ /** * The size value for each bubble. The bubbles' diameters are computed * based on the `z`, and controlled by series options like `minSize`, * `maxSize`, `sizeBy`, `zMin` and `zMax`. * * @type {Number} * @product highcharts * @apioption series.bubble.data.z */ /** * @excluding enabled,enabledThreshold,height,radius,width * @apioption series.bubble.marker */ }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var merge = H.merge, Point = H.Point, seriesType = H.seriesType, seriesTypes = H.seriesTypes; // The mapbubble series type if (seriesTypes.bubble) { /** * A map bubble series is a bubble series laid out on top of a map series, * where each bubble is tied to a specific map area. * * @sample maps/demo/map-bubble/ Map bubble chart * * @extends plotOptions.bubble * @product highmaps * @optionparent plotOptions.mapbubble */ seriesType('mapbubble', 'bubble', { /** * The main color of the series. This color affects both the fill and * the stroke of the bubble. For enhanced control, use `marker` options. * * @type {Color} * @sample {highmaps} maps/plotoptions/mapbubble-color/ Pink bubbles * @product highmaps * @apioption plotOptions.mapbubble.color */ /** * Whether to display negative sized bubbles. The threshold is given * by the [zThreshold](#plotOptions.mapbubble.zThreshold) option, and * negative bubbles can be visualized by setting [negativeColor]( * #plotOptions.bubble.negativeColor). * * @type {Boolean} * @default true * @product highmaps * @apioption plotOptions.mapbubble.displayNegative */ /** * @sample {highmaps} maps/demo/map-bubble/ Bubble size * @product highmaps * @apioption plotOptions.mapbubble.maxSize */ /** * @sample {highmaps} maps/demo/map-bubble/ Bubble size * @product highmaps * @apioption plotOptions.mapbubble.minSize */ /** * When a point's Z value is below the [zThreshold]( * #plotOptions.mapbubble.zThreshold) setting, this color is used. * * @type {Color} * @sample {highmaps} maps/plotoptions/mapbubble-negativecolor/ * Negative color below a threshold * @default null * @product highmaps * @apioption plotOptions.mapbubble.negativeColor */ /** * Whether the bubble's value should be represented by the area or the * width of the bubble. The default, `area`, corresponds best to the * human perception of the size of each bubble. * * @validvalue ["area", "width"] * @type {String} * @default area * @product highmaps * @apioption plotOptions.mapbubble.sizeBy */ /** * When this is true, the absolute value of z determines the size of * the bubble. This means that with the default `zThreshold` of 0, a * bubble of value -1 will have the same size as a bubble of value 1, * while a bubble of value 0 will have a smaller size according to * `minSize`. * * @type {Boolean} * @sample {highmaps} highcharts/plotoptions/bubble-sizebyabsolutevalue/ * Size by absolute value, various thresholds * @default false * @since 1.1.9 * @product highmaps * @apioption plotOptions.mapbubble.sizeByAbsoluteValue */ /** * The minimum for the Z value range. Defaults to the highest Z value * in the data. * * @type {Number} * @see [zMax](#plotOptions.mapbubble.zMin) * @sample {highmaps} highcharts/plotoptions/bubble-zmin-zmax/ * Z has a possible range of 0-100 * @default null * @since 1.0.3 * @product highmaps * @apioption plotOptions.mapbubble.zMax */ /** * The minimum for the Z value range. Defaults to the lowest Z value * in the data. * * @type {Number} * @see [zMax](#plotOptions.mapbubble.zMax) * @sample {highmaps} highcharts/plotoptions/bubble-zmin-zmax/ * Z has a possible range of 0-100 * @default null * @since 1.0.3 * @product highmaps * @apioption plotOptions.mapbubble.zMin */ /** * When [displayNegative](#plotOptions.mapbubble.displayNegative) is * `false`, bubbles with lower Z values are skipped. When * `displayNegative` is `true` and a [negativeColor]( * #plotOptions.mapbubble.negativeColor) is given, points with lower Z * is colored. * * @type {Number} * @sample {highmaps} maps/plotoptions/mapbubble-negativecolor/ * Negative color below a threshold * @default 0 * @product highmaps * @apioption plotOptions.mapbubble.zThreshold */ animationLimit: 500, tooltip: { pointFormat: '{point.name}: {point.z}' } // Prototype members }, { xyFromShape: true, type: 'mapbubble', // If one single value is passed, it is interpreted as z pointArrayMap: ['z'], // Return the map area identified by the dataJoinBy option getMapData: seriesTypes.map.prototype.getMapData, getBox: seriesTypes.map.prototype.getBox, setData: seriesTypes.map.prototype.setData // Point class }, { applyOptions: function (options, x) { var point; if ( options && options.lat !== undefined && options.lon !== undefined ) { point = Point.prototype.applyOptions.call( this, merge( options, this.series.chart.fromLatLonToPoint(options) ), x ); } else { point = seriesTypes.map.prototype.pointClass.prototype .applyOptions.call(this, options, x); } return point; }, isValid: function () { return typeof this.z === 'number'; }, ttBelow: false }); } /** * A `mapbubble` series. If the [type](#series.mapbubble.type) option * is not specified, it is inherited from [chart.type](#chart.type). * * * @type {Object} * @extends series,plotOptions.mapbubble * @excluding dataParser,dataURL * @product highmaps * @apioption series.mapbubble */ /** * An array of data points for the series. For the `mapbubble` series * type, points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values * will be interpreted as `z` options. Example: * * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data points * exceeds the series' [turboThreshold](#series.mapbubble.turboThreshold), * this option is not available. * * ```js * data: [{ * z: 9, * name: "Point2", * color: "#00FF00" * }, { * z: 10, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object|Number>} * @extends series.mappoint.data * @excluding labelrank,middleX,middleY,path,value,x,y,lat,lon * @product highmaps * @apioption series.mapbubble.data */ /** * While the `x` and `y` values of the bubble are determined by the * underlying map, the `z` indicates the actual value that gives the * size of the bubble. * * @type {Number} * @sample {highmaps} maps/demo/map-bubble/ Bubble * @product highmaps * @apioption series.mapbubble.data.z */ /** * @excluding enabled,enabledThreshold,height,radius,width * @apioption series.mapbubble.marker */ }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var colorPointMixin = H.colorPointMixin, colorSeriesMixin = H.colorSeriesMixin, each = H.each, LegendSymbolMixin = H.LegendSymbolMixin, merge = H.merge, noop = H.noop, pick = H.pick, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes; /** * A heatmap is a graphical representation of data where the individual values * contained in a matrix are represented as colors. * * @sample highcharts/demo/heatmap/ * Simple heatmap * @sample highcharts/demo/heatmap-canvas/ * Heavy heatmap * @extends {plotOptions.scatter} * @excluding animationLimit,connectEnds,connectNulls,dashStyle, * findNearestPointBy,getExtremesFromAll,linecap,lineWidth,marker, * pointInterval,pointIntervalUnit,pointRange,pointStart,shadow, * softThreshold,stacking,step,threshold * @product highcharts highmaps * @optionparent plotOptions.heatmap */ seriesType('heatmap', 'scatter', { /** * Animation is disabled by default on the heatmap series. * * @type {Boolean|Object} */ animation: false, /** * The border width for each heat map item. */ borderWidth: 0, /** * Padding between the points in the heatmap. * * @type {Number} * @default 0 * @since 6.0 * @apioption plotOptions.heatmap.pointPadding */ /** * The main color of the series. In heat maps this color is rarely used, * as we mostly use the color to denote the value of each point. Unless * options are set in the [colorAxis](#colorAxis), the default value * is pulled from the [options.colors](#colors) array. * * @type {Color} * @default null * @since 4.0 * @product highcharts * @apioption plotOptions.heatmap.color */ /** * The column size - how many X axis units each column in the heatmap * should span. * * @type {Number} * @sample {highcharts} maps/demo/heatmap/ One day * @sample {highmaps} maps/demo/heatmap/ One day * @default 1 * @since 4.0 * @product highcharts highmaps * @apioption plotOptions.heatmap.colsize */ /** * The row size - how many Y axis units each heatmap row should span. * * @type {Number} * @sample {highcharts} maps/demo/heatmap/ 1 by default * @sample {highmaps} maps/demo/heatmap/ 1 by default * @default 1 * @since 4.0 * @product highcharts highmaps * @apioption plotOptions.heatmap.rowsize */ /** * The color applied to null points. In styled mode, a general CSS class is * applied instead. * * @type {Color} */ nullColor: '#f7f7f7', dataLabels: { formatter: function () { // #2945 return this.point.value; }, inside: true, verticalAlign: 'middle', crop: false, overflow: false, padding: 0 // #3837 }, /** * @ignore */ marker: null, /** @ignore */ pointRange: null, // dynamically set to colsize by default tooltip: { pointFormat: '{point.x}, {point.y}: {point.value}<br/>' }, states: { hover: { /** * @ignore */ halo: false, // #3406, halo is disabled on heatmaps by default /** * How much to brighten the point on interaction. Requires the main * color to be defined in hex or rgb(a) format. * * In styled mode, the hover brightening is by default replaced * with a fill-opacity set in the `.highcharts-point:hover` rule. * * @type {Number} * @product highcharts highmaps */ brightness: 0.2 } } }, merge(colorSeriesMixin, { pointArrayMap: ['y', 'value'], hasPointSpecificOptions: true, getExtremesFromAll: true, directTouch: true, /** * Override the init method to add point ranges on both axes. */ init: function () { var options; seriesTypes.scatter.prototype.init.apply(this, arguments); options = this.options; // #3758, prevent resetting in setData options.pointRange = pick(options.pointRange, options.colsize || 1); this.yAxis.axisPointRange = options.rowsize || 1; // general point range }, translate: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, between = function (x, a, b) { return Math.min(Math.max(a, x), b); }; series.generatePoints(); each(series.points, function (point) { var xPad = (options.colsize || 1) / 2, yPad = (options.rowsize || 1) / 2, x1 = between( Math.round( xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1) ), -xAxis.len, 2 * xAxis.len ), x2 = between( Math.round( xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1) ), -xAxis.len, 2 * xAxis.len ), y1 = between( Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len ), y2 = between( Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len ), pointPadding = pick(point.pointPadding, seriesPointPadding); // Set plotX and plotY for use in K-D-Tree and more point.plotX = point.clientX = (x1 + x2) / 2; point.plotY = (y1 + y2) / 2; point.shapeType = 'rect'; point.shapeArgs = { x: Math.min(x1, x2) + pointPadding, y: Math.min(y1, y2) + pointPadding, width: Math.abs(x2 - x1) - pointPadding * 2, height: Math.abs(y2 - y1) - pointPadding * 2 }; }); series.translateColors(); }, drawPoints: function () { seriesTypes.column.prototype.drawPoints.call(this); each(this.points, function (point) { point.graphic.attr(this.colorAttribs(point)); }, this); }, animate: noop, getBox: noop, drawLegendSymbol: LegendSymbolMixin.drawRectangle, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, getExtremes: function () { // Get the extremes from the value data Series.prototype.getExtremes.call(this, this.valueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Get the extremes from the y data Series.prototype.getExtremes.call(this); } }), H.extend({ haloPath: function (size) { if (!size) { return []; } var rect = this.shapeArgs; return [ 'M', rect.x - size, rect.y - size, 'L', rect.x - size, rect.y + rect.height + size, rect.x + rect.width + size, rect.y + rect.height + size, rect.x + rect.width + size, rect.y - size, 'Z' ]; } }, colorPointMixin)); /** * A `heatmap` series. If the [type](#series.heatmap.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @type {Object} * @extends series,plotOptions.heatmap * @excluding dataParser,dataURL,marker,pointRange,stack * @product highcharts highmaps * @apioption series.heatmap */ /** * An array of data points for the series. For the `heatmap` series * type, points can be given in the following ways: * * 1. An array of arrays with 3 or 2 values. In this case, the values * correspond to `x,y,value`. If the first value is a string, it is * applied as the name of the point, and the `x` value is inferred. * The `x` value can also be omitted, in which case the inner arrays * should be of length 2\. Then the `x` value is automatically calculated, * either starting at 0 and incremented by 1, or from `pointStart` * and `pointInterval` given in the series options. * * ```js * data: [ * [0, 9, 7], * [1, 10, 4], * [2, 6, 3] * ] * ``` * * 2. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data * points exceeds the series' [turboThreshold](#series.heatmap.turboThreshold), * this option is not available. * * ```js * data: [{ * x: 1, * y: 3, * value: 10, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 7, * value: 10, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object|Array>} * @extends series.line.data * @excluding marker * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * @product highcharts highmaps * @apioption series.heatmap.data */ /** * The color of the point. In heat maps the point color is rarely set * explicitly, as we use the color to denote the `value`. Options for * this are set in the [colorAxis](#colorAxis) configuration. * * @type {Color} * @product highcharts highmaps * @apioption series.heatmap.data.color */ /** * The value of the point, resulting in a color controled by options * as set in the [colorAxis](#colorAxis) configuration. * * @type {Number} * @product highcharts highmaps * @apioption series.heatmap.data.value */ /** * The x value of the point. For datetime axes, * the X value is the timestamp in milliseconds since 1970. * * @type {Number} * @product highcharts highmaps * @apioption series.heatmap.data.x */ /** * The y value of the point. * * @type {Number} * @product highcharts highmaps * @apioption series.heatmap.data.y */ /** * Point padding for a single point. * * @type {Number} * @sample maps/plotoptions/tilemap-pointpadding Point padding on tiles * @apioption series.heatmap.data.pointPadding */ }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var Chart = H.Chart, each = H.each, extend = H.extend, format = H.format, merge = H.merge, win = H.win, wrap = H.wrap; /** * Test for point in polygon. Polygon defined as array of [x,y] points. */ function pointInPolygon(point, polygon) { var i, j, rel1, rel2, c = false, x = point.x, y = point.y; for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { rel1 = polygon[i][1] > y; rel2 = polygon[j][1] > y; if ( rel1 !== rel2 && ( x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0] ) ) { c = !c; } } return c; } /** * Highmaps only. Get point from latitude and longitude using specified * transform definition. * * @function transformFromLatLon * @memberof Chart.prototype * * @param {Object} latLon * A latitude/longitude object. * @param {Number} latLon.lat * The latitude. * @param {Number} latLon.lon * The longitude. * @param {Object} transform * The transform definition to use as explained in the {@link * https://www.highcharts.com/docs/maps/latlon|documentation}. * * @return {Object} * An object with `x` and `y` properties. * * @sample maps/series/latlon-transform/ * Use specific transformation for lat/lon */ Chart.prototype.transformFromLatLon = function (latLon, transform) { if (win.proj4 === undefined) { H.error(21); return { x: 0, y: null }; } var projected = win.proj4(transform.crs, [latLon.lon, latLon.lat]), cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)), sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)), rotated = transform.rotation ? [ projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle ] : projected; return { x: ( (rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0) ) * (transform.jsonres || 1) + (transform.jsonmarginX || 0), y: ( ((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0) ) * (transform.jsonres || 1) - (transform.jsonmarginY || 0) }; }; /** * Highmaps only. Get latLon from point using specified transform definition. * The method returns an object with the numeric properties `lat` and `lon`. * * @function transformToLatLon * @memberof Chart.prototype * * @param {Point|Object} point * A `Point` instance, or or any object containing the properties `x` * and `y` with numeric values. * @param {Object} transform * The transform definition to use as explained in the {@link * https://www.highcharts.com/docs/maps/latlon|documentation}. * * @return {Object} * An object with `lat` and `lon` properties. * * @sample maps/series/latlon-transform/ * Use specific transformation for lat/lon * */ Chart.prototype.transformToLatLon = function (point, transform) { if (win.proj4 === undefined) { H.error(21); return; } var normalized = { x: ( ( point.x - (transform.jsonmarginX || 0) ) / (transform.jsonres || 1) - (transform.xpan || 0) ) / (transform.scale || 1) + (transform.xoffset || 0), y: ( ( -point.y - (transform.jsonmarginY || 0) ) / (transform.jsonres || 1) + (transform.ypan || 0) ) / (transform.scale || 1) + (transform.yoffset || 0) }, cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)), sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)), // Note: Inverted sinAngle to reverse rotation direction projected = win.proj4(transform.crs, 'WGS84', transform.rotation ? { x: normalized.x * cosAngle + normalized.y * -sinAngle, y: normalized.x * sinAngle + normalized.y * cosAngle } : normalized); return { lat: projected.y, lon: projected.x }; }; /** * Highmaps only. Calculate latitude/longitude values for a point. Returns an * object with the numeric properties `lat` and `lon`. * * @function fromPointToLatLon * @memberof Chart.prototype * * @param {Point|Object} point * A `Point` instance or anything containing `x` and `y` properties * with numeric values * @return {Object} * An object with `lat` and `lon` properties. * * @sample maps/demo/latlon-advanced/ * Advanced lat/lon demo */ Chart.prototype.fromPointToLatLon = function (point) { var transforms = this.mapTransforms, transform; if (!transforms) { H.error(22); return; } for (transform in transforms) { if ( transforms.hasOwnProperty(transform) && transforms[transform].hitZone && pointInPolygon( { x: point.x, y: -point.y }, transforms[transform].hitZone.coordinates[0] ) ) { return this.transformToLatLon(point, transforms[transform]); } } return this.transformToLatLon( point, transforms['default'] // eslint-disable-line dot-notation ); }; /** * Highmaps only. Get chart coordinates from latitude/longitude. Returns an * object with x and y values corresponding to the `xAxis` and `yAxis`. * * @function fromLatLonToPoint * @memberof Chart.prototype * * @param {Object} latLon * Coordinates. * @param {Number} latLon.lat * The latitude. * @param {Number} latLon.lon * The longitude. * * @sample maps/series/latlon-to-point/ * Find a point from lat/lon * * @return {Object} * X and Y coordinates in terms of chart axis values. */ Chart.prototype.fromLatLonToPoint = function (latLon) { var transforms = this.mapTransforms, transform, coords; if (!transforms) { H.error(22); return { x: 0, y: null }; } for (transform in transforms) { if ( transforms.hasOwnProperty(transform) && transforms[transform].hitZone ) { coords = this.transformFromLatLon(latLon, transforms[transform]); if (pointInPolygon( { x: coords.x, y: -coords.y }, transforms[transform].hitZone.coordinates[0] )) { return coords; } } } return this.transformFromLatLon( latLon, transforms['default'] // eslint-disable-line dot-notation ); }; /** * Highmaps only. Restructure a GeoJSON object in preparation to be read * directly by the {@link * https://api.highcharts.com/highmaps/plotOptions.series.mapData| * series.mapData} option. The GeoJSON will be broken down to fit a specific * Highcharts type, either `map`, `mapline` or `mappoint`. Meta data in * GeoJSON's properties object will be copied directly over to * {@link Point.properties} in Highmaps. * * @function #geojson * @memberof Highcharts * * @param {Object} geojson * The GeoJSON structure to parse, represented as a JavaScript object * rather than a JSON string. * @param {String} [hType=map] * The Highmaps series type to prepare for. Setting "map" will return * GeoJSON polygons and multipolygons. Setting "mapline" will return * GeoJSON linestrings and multilinestrings. Setting "mappoint" will * return GeoJSON points and multipoints. * * @return {Object} * An object ready for the `mapData` option. * * @sample maps/demo/geojson/ * Simple areas * @sample maps/demo/geojson-multiple-types/ * Multiple types * */ H.geojson = function (geojson, hType, series) { var mapData = [], path = [], polygonToPath = function (polygon) { var i, len = polygon.length; path.push('M'); for (i = 0; i < len; i++) { if (i === 1) { path.push('L'); } path.push(polygon[i][0], -polygon[i][1]); } }; hType = hType || 'map'; each(geojson.features, function (feature) { var geometry = feature.geometry, type = geometry.type, coordinates = geometry.coordinates, properties = feature.properties, point; path = []; if (hType === 'map' || hType === 'mapbubble') { if (type === 'Polygon') { each(coordinates, polygonToPath); path.push('Z'); } else if (type === 'MultiPolygon') { each(coordinates, function (items) { each(items, polygonToPath); }); path.push('Z'); } if (path.length) { point = { path: path }; } } else if (hType === 'mapline') { if (type === 'LineString') { polygonToPath(coordinates); } else if (type === 'MultiLineString') { each(coordinates, polygonToPath); } if (path.length) { point = { path: path }; } } else if (hType === 'mappoint') { if (type === 'Point') { point = { x: coordinates[0], y: -coordinates[1] }; } } if (point) { mapData.push(extend(point, { name: properties.name || properties.NAME, /** * In Highmaps, when data is loaded from GeoJSON, the GeoJSON * item's properies are copied over here. * * @name #properties * @memberof Point * @type {Object} */ properties: properties })); } }); // Create a credits text that includes map source, to be picked up in // Chart.addCredits if (series && geojson.copyrightShort) { series.chart.mapCredits = format( series.chart.options.credits.mapText, { geojson: geojson } ); series.chart.mapCreditsFull = format( series.chart.options.credits.mapTextFull, { geojson: geojson } ); } return mapData; }; /** * Override addCredits to include map source by default */ wrap(Chart.prototype, 'addCredits', function (proceed, credits) { credits = merge(true, this.options.credits, credits); // Disable credits link if map credits enabled. This to allow for in-text // anchors. if (this.mapCredits) { credits.href = null; } proceed.call(this, credits); // Add full map credits to hover if (this.credits && this.mapCreditsFull) { this.credits.attr({ title: this.mapCreditsFull }); } }); }(Highcharts)); (function (H) { /** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ var Chart = H.Chart, defaultOptions = H.defaultOptions, each = H.each, extend = H.extend, merge = H.merge, pick = H.pick, Renderer = H.Renderer, SVGRenderer = H.SVGRenderer, VMLRenderer = H.VMLRenderer; // Add language extend(defaultOptions.lang, { zoomIn: 'Zoom in', zoomOut: 'Zoom out' }); // Set the default map navigation options /** * @product highmaps * @optionparent mapNavigation */ defaultOptions.mapNavigation = { /** * General options for the map navigation buttons. Individual options * can be given from the [mapNavigation.buttons](#mapNavigation.buttons) * option set. * * @sample {highmaps} maps/mapnavigation/button-theme/ * Theming the navigation buttons * * @type {*} * @product highmaps * @apioption mapNavigation.buttonOptions */ buttonOptions: { /** * What box to align the buttons to. Possible values are `plotBox` * and `spacingBox`. * * @type {string} * @default plotBox * @product highmaps * @validvalue ["plotBox", "spacingBox"] * @apioption mapNavigation.buttonOptions.alignTo */ alignTo: 'plotBox', /** * The alignment of the navigation buttons. * * @type {string} * @default left * @product highmaps * @validvalue ["left", "center", "right"] * @apioption mapNavigation.buttonOptions.align */ align: 'left', /** * The vertical alignment of the buttons. Individual alignment can * be adjusted by each button's `y` offset. * * @type {string} * @default bottom * @product highmaps * @validvalue ["top", "middle", "bottom"] * @apioption mapNavigation.buttonOptions.verticalAlign */ verticalAlign: 'top', /** * The X offset of the buttons relative to its `align` setting. * * @type {number} * @default 0 * @product highmaps * @apioption mapNavigation.buttonOptions.x */ x: 0, /** * The width of the map navigation buttons. * * @type {number} * @default 18 * @product highmaps * @apioption mapNavigation.buttonOptions.width */ width: 18, /** * The pixel height of the map navigation buttons. * * @type {number} * @default 18 * @product highmaps * @apioption mapNavigation.buttonOptions.height */ height: 18, /** * Padding for the navigation buttons. * * @type {number} * @default 5 * @since 5.0.0 * @product highmaps * @apioption mapNavigation.buttonOptions.padding */ padding: 5, /** * Text styles for the map navigation buttons. Defaults to * * <pre>{ * fontSize: '15px', * fontWeight: 'bold', * textAlign: 'center' * }</pre> * * @type {Highcharts.CSSObject} * @product highmaps * @apioption mapNavigation.buttonOptions.style */ style: { fontSize: '15px', fontWeight: 'bold' }, /** * A configuration object for the button theme. The object accepts * SVG properties like `stroke-width`, `stroke` and `fill`. Tri-state * button styles are supported by the `states.hover` and `states.select` * objects. * * @sample {highmaps} maps/mapnavigation/button-theme/ * Themed navigation buttons * * @type {*} * @product highmaps * @apioption mapNavigation.buttonOptions.theme */ theme: { 'stroke-width': 1, 'text-align': 'center' } }, /** * The individual buttons for the map navigation. This usually includes * the zoom in and zoom out buttons. Properties for each button is * inherited from * [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while * individual options can be overridden. But default, the `onclick`, `text` * and `y` options are individual. * * @type {*} * @product highmaps * @apioptions mapNavigation.buttons */ buttons: { /** * Options for the zoom in button. Properties for the zoom in and zoom * out buttons are inherited from * [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while * individual options can be overridden. By default, the `onclick`, * `text` and `y` options are individual. * * @type {*} * @extends mapNavigation.buttonOptions * @product highmaps * @apioptions mapNavigation.buttons.zoomIn */ zoomIn: { /** * Click handler for the button. Defaults to: * * <pre>function () { * this.mapZoom(0.5); * }</pre> * * @type {Function} * @product highmaps */ onclick: function () { this.mapZoom(0.5); }, /** * The text for the button. The tooltip (title) is a language option * given by [lang.zoomIn](#lang.zoomIn). * * @type {String} * @default + * @product highmaps */ text: '+', /** * The position of the zoomIn button relative to the vertical * alignment. * * @type {Number} * @default 0 * @product highmaps */ y: 0 }, /** * Options for the zoom out button. Properties for the zoom in and * zoom out buttons are inherited from * [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while * individual options can be overridden. By default, the `onclick`, * `text` and `y` options are individual. * * @type {*} * @extends mapNavigation.buttonOptions * @product highmaps * @apioptions mapNavigation.buttons.zoomOut */ zoomOut: { /** * Click handler for the button. Defaults to: * * <pre>function () { * this.mapZoom(2); * }</pre> * * @type {Function} * @product highmaps */ onclick: function () { this.mapZoom(2); }, /** * The text for the button. The tooltip (title) is a language option * given by [lang.zoomOut](#lang.zoomIn). * * @type {String} * @default - * @product highmaps */ text: '-', /** * The position of the zoomOut button relative to the vertical * alignment. * * @type {Number} * @default 28 * @product highmaps */ y: 28 } }, /** * Whether to enable navigation buttons. By default it inherits the * [enabled](#mapNavigation.enabled) setting. * * @type {boolean} * @product highmaps * @apioption mapNavigation.enableButtons */ /** * Whether to enable map navigation. The default is not to enable * navigation, as many choropleth maps are simple and don't need it. * Additionally, when touch zoom and mousewheel zoom is enabled, it breaks * the default behaviour of these interactions in the website, and the * implementer should be aware of this. * * Individual interactions can be enabled separately, namely buttons, * multitouch zoom, double click zoom, double click zoom to element and * mousewheel zoom. * * @type {boolean} * @default false * @product highmaps * @apioption mapNavigation.enabled */ /** * Enables zooming in on an area on double clicking in the map. By default * it inherits the [enabled](#mapNavigation.enabled) setting. * * @type {boolean} * @product highmaps * @apioption mapNavigation.enableDoubleClickZoom */ /** * Whether to zoom in on an area when that area is double clicked. * * @sample {highmaps} maps/mapnavigation/doubleclickzoomto/ * Enable double click zoom to * * @type {boolean} * @default false * @product highmaps * @apioption mapNavigation.enableDoubleClickZoomTo */ /** * Enables zooming by mouse wheel. By default it inherits the [enabled]( * #mapNavigation.enabled) setting. * * @type {boolean} * @product highmaps * @apioption mapNavigation.enableMouseWheelZoom */ /** * Whether to enable multitouch zooming. Note that if the chart covers the * viewport, this prevents the user from using multitouch and touchdrag on * the web page, so you should make sure the user is not trapped inside the * chart. By default it inherits the [enabled](#mapNavigation.enabled) * setting. * * @type {boolean} * @product highmaps * @apioption mapNavigation.enableTouchZoom */ /** * Sensitivity of mouse wheel or trackpad scrolling. 1 is no sensitivity, * while with 2, one mousewheel delta will zoom in 50%. * * @type {number} * @default 1.1 * @since 4.2.4 * @product highmaps * @apioption mapNavigation.mouseWheelSensitivity */ mouseWheelSensitivity: 1.1 // enabled: false, // enableButtons: null, // inherit from enabled // enableTouchZoom: null, // inherit from enabled // enableDoubleClickZoom: null, // inherit from enabled // enableDoubleClickZoomTo: false // enableMouseWheelZoom: null, // inherit from enabled }; /** * Utility for reading SVG paths directly. * * @function Highcharts.splitPath * * @param {string} path * * @return {Array<number|string>} */ H.splitPath = function (path) { var i; // Move letters apart path = path.replace(/([A-Za-z])/g, ' $1 '); // Trim path = path.replace(/^\s*/, '').replace(/\s*$/, ''); // Split on spaces and commas path = path.split(/[ ,]+/); // Extra comma to escape gulp.scripts task // Parse numbers for (i = 0; i < path.length; i++) { if (!/[a-zA-Z]/.test(path[i])) { path[i] = parseFloat(path[i]); } } return path; }; // A placeholder for map definitions H.maps = {}; // Create symbols for the zoom buttons function selectiveRoundedRect( x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft ) { return [ 'M', x + rTopLeft, y, // top side 'L', x + w - rTopRight, y, // top right corner 'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight, // right side 'L', x + w, y + h - rBottomRight, // bottom right corner 'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h, // bottom side 'L', x + rBottomLeft, y + h, // bottom left corner 'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft, // left side 'L', x, y + rTopLeft, // top left corner 'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y, 'Z' ]; } SVGRenderer.prototype.symbols.topbutton = function (x, y, w, h, attr) { return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0); }; SVGRenderer.prototype.symbols.bottombutton = function (x, y, w, h, attr) { return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r); }; // The symbol callbacks are generated on the SVGRenderer object in all browsers. // Even VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === VMLRenderer) { each(['topbutton', 'bottombutton'], function (shape) { VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape]; }); } /** * The factory function for creating new map charts. Creates a new {@link Chart| * Chart} object with different default options than the basic Chart. * * @function Highcharts.mapChart * * @param {string|Highcharts.HTMLDOMElement} [renderTo] * The DOM element to render to, or its id. * * @param {Highcharts.Options} options * The chart options structure as described in the {@link * https://api.highcharts.com/highstock|options reference}. * * @param {Function} callback * A function to execute when the chart object is finished loading and * rendering. In most cases the chart is built in one thread, but in * Internet Explorer version 8 or less the chart is sometimes * initialized before the document is ready, and in these cases the * chart object will not be finished synchronously. As a consequence, * code that relies on the newly built Chart object should always run in * the callback. Defining a * {@link https://api.highcharts.com/highstock/chart.events.load| * chart.event.load} handler is equivalent. * * @return {Highcharts.Chart} * The chart object. */ H.Map = H.mapChart = function (a, b, c) { var hasRenderToArg = typeof a === 'string' || a.nodeName, options = arguments[hasRenderToArg ? 1 : 0], hiddenAxis = { endOnTick: false, visible: false, minPadding: 0, maxPadding: 0, startOnTick: false }, seriesOptions, defaultCreditsOptions = H.getOptions().credits; /* For visual testing hiddenAxis.gridLineWidth = 1; hiddenAxis.gridZIndex = 10; hiddenAxis.tickPositions = undefined; // */ // Don't merge the data seriesOptions = options.series; options.series = null; options = merge( { chart: { panning: 'xy', type: 'map' }, credits: { mapText: pick( defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">' + '{geojson.copyrightShort}</a>' ), mapTextFull: pick( defaultCreditsOptions.mapTextFull, '{geojson.copyright}' ) }, tooltip: { followTouchMove: false }, xAxis: hiddenAxis, yAxis: merge(hiddenAxis, { reversed: true }) }, options, // user's options { // forced options chart: { inverted: false, alignTicks: false } } ); options.series = seriesOptions; return hasRenderToArg ? new Chart(a, options, c) : new Chart(options, b); }; }(Highcharts)); return (function () { }()); }));
CKEDITOR.plugins.setLang("flash","lt",{access:"Skripto priėjimas",accessAlways:"Visada",accessNever:"Niekada",accessSameDomain:"Tas pats domenas",alignAbsBottom:"Absoliučią apačią",alignAbsMiddle:"Absoliutų vidurį",alignBaseline:"Apatinę liniją",alignTextTop:"Teksto viršūnę",bgcolor:"Fono spalva",chkFull:"Leisti per visą ekraną",chkLoop:"Ciklas",chkMenu:"Leisti Flash meniu",chkPlay:"Automatinis paleidimas",flashvars:"Flash kintamieji",hSpace:"Hor.Erdvė",properties:"Flash savybės",propertiesTab:"Nustatymai", quality:"Kokybė",qualityAutoHigh:"Automatiškai Gera",qualityAutoLow:"Automatiškai Žema",qualityBest:"Geriausia",qualityHigh:"Gera",qualityLow:"Žema",qualityMedium:"Vidutinė",scale:"Mastelis",scaleAll:"Rodyti visą",scaleFit:"Tikslus atitikimas",scaleNoBorder:"Be rėmelio",title:"Flash savybės",vSpace:"Vert.Erdvė",validateHSpace:"HSpace turi būti skaičius.",validateSrc:"Prašome įvesti nuorodos URL",validateVSpace:"VSpace turi būti skaičius.",windowMode:"Lango režimas",windowModeOpaque:"Nepermatomas", windowModeTransparent:"Permatomas",windowModeWindow:"Langas"});
var urljoin = require('url-join'); var WinChan = require('winchan'); var urlHelper = require('../helper/url'); var assert = require('../helper/assert'); var responseHandler = require('../helper/response-handler'); var PopupHandler = require('../helper/popup-handler'); var objectHelper = require('../helper/object'); var Warn = require('../helper/warn'); var TransactionManager = require('./transaction-manager'); function Popup(webAuth, options) { this.baseOptions = options; this.client = webAuth.client; this.webAuth = webAuth; this.transactionManager = new TransactionManager(this.baseOptions.transaction); this.warn = new Warn({ disableWarnings: !!options._disableDeprecationWarnings }); } /** * Returns a new instance of the popup handler * * @method buildPopupHandler * @private */ Popup.prototype.buildPopupHandler = function() { var pluginHandler = this.baseOptions.plugins.get('popup.getPopupHandler'); if (pluginHandler) { return pluginHandler.getPopupHandler(); } return new PopupHandler(); }; /** * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. * * @method preload * @param {Object} options receives the window height and width and any other window feature to be sent to window.open */ Popup.prototype.preload = function(options) { options = options || {}; var popup = this.buildPopupHandler(); popup.preload(options); return popup; }; /** * Internal use. * * @method getPopupHandler * @private */ Popup.prototype.getPopupHandler = function(options, preload) { if (options.popupHandler) { return options.popupHandler; } if (preload) { return this.preload(options); } return this.buildPopupHandler(); }; /** * Handles the popup logic for the callback page. * * @method callback * @param {Object} options * @param {String} options.hash the url hash. If not provided it will extract from window.location.hash * @param {String} [options.state] value originally sent in `state` parameter to {@link authorize} to mitigate XSRF * @param {String} [options.nonce] value originally sent in `nonce` parameter to {@link authorize} to prevent replay attacks * @param {String} [options._idTokenVerification] makes parseHash perform or skip `id_token` verification. We **strongly** recommend validating the `id_token` yourself if you disable the verification. * @see {@link parseHash} */ Popup.prototype.callback = function(options) { var _this = this; WinChan.onOpen(function(popupOrigin, r, cb) { _this.webAuth.parseHash(options || {}, function(err, data) { return cb(err || data); }); }); }; /** * Shows inside a new window the hosted login page (`/authorize`) in order to start a new authN/authZ transaction and post its result using `postMessage`. * * @method authorize * @param {Object} options * @param {String} [options.domain] your Auth0 domain * @param {String} [options.clientID] your Auth0 client identifier obtained when creating the client in the Auth0 Dashboard * @param {String} options.redirectUri url that the Auth0 will redirect after Auth with the Authorization Response * @param {String} options.responseType type of the response used by OAuth 2.0 flow. It can be any space separated list of the values `code`, `token`, `id_token`. {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0} * @param {String} [options.responseMode] how the Auth response is encoded and redirected back to the client. Supported values are `query`, `fragment` and `form_post`. {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes} * @param {String} [options.state] value used to mitigate XSRF attacks. {@link https://auth0.com/docs/protocols/oauth2/oauth-state} * @param {String} [options.nonce] value used to mitigate replay attacks when using Implicit Grant. {@link https://auth0.com/docs/api-auth/tutorials/nonce} * @param {String} [options.scope] scopes to be requested during Auth. e.g. `openid email` * @param {String} [options.audience] identifier of the resource server who will consume the access token issued after Auth * @param {Boolean} [options.owp] determines if Auth0 should render the relay page or not and the caller is responsible of handling the response. * @param {authorizeCallback} cb * @see {@link https://auth0.com/docs/api/authentication#authorize-client} */ Popup.prototype.authorize = function(options, cb) { var popup; var url; var relayUrl; var popOpts = {}; var pluginHandler = this.baseOptions.plugins.get('popup.authorize'); var params = objectHelper .merge(this.baseOptions, [ 'clientID', 'scope', 'domain', 'audience', 'tenant', 'responseType', 'redirectUri', '_csrf', 'state', '_intstate', 'nonce' ]) .with(objectHelper.blacklist(options, ['popupHandler'])); assert.check( params, { type: 'object', message: 'options parameter is not valid' }, { responseType: { type: 'string', message: 'responseType option is required' } } ); // the relay page should not be necesary as long it happens in the same domain // (a redirectUri shoul be provided). It is necesary when using OWP relayUrl = urljoin(this.baseOptions.rootUrl, 'relay.html'); // if a owp is enabled, it should use the owp flag if (options.owp) { // used by server to render the relay page instead of sending the chunk in the // url to the callback params.owp = true; } else { popOpts.origin = urlHelper.extractOrigin(params.redirectUri); relayUrl = params.redirectUri; } if (options.popupOptions) { popOpts.popupOptions = objectHelper.pick(options.popupOptions, ['width', 'height']); } if (pluginHandler) { params = pluginHandler.processParams(params); } params = this.transactionManager.process(params); delete params.domain; url = this.client.buildAuthorizeUrl(params); popup = this.getPopupHandler(options); return popup.load(url, relayUrl, popOpts, responseHandler(cb)); }; /** * Performs authentication with username/email and password with a database connection inside a new window * * This method is not compatible with API Auth so if you need to fetch API tokens with audience * you should use {@link authorize} or {@link login}. * * @method loginWithCredentials * @param {Object} options * @param {String} [options.redirectUri] url that the Auth0 will redirect after Auth with the Authorization Response * @param {String} [options.responseType] type of the response used. It can be any of the values `code` and `token` * @param {String} [options.responseMode] how the AuthN response is encoded and redirected back to the client. Supported values are `query` and `fragment` * @param {String} [options.scope] scopes to be requested during AuthN. e.g. `openid email` * @param {credentialsCallback} cb */ Popup.prototype.loginWithCredentials = function(options, cb) { var params; var popup; var url; var relayUrl; /* eslint-disable */ assert.check( options, { type: 'object', message: 'options parameter is not valid' }, { clientID: { optional: true, type: 'string', message: 'clientID option is required' }, redirectUri: { optional: true, type: 'string', message: 'redirectUri option is required' }, responseType: { optional: true, type: 'string', message: 'responseType option is required' }, scope: { optional: true, type: 'string', message: 'scope option is required' }, audience: { optional: true, type: 'string', message: 'audience option is required' } } ); /* eslint-enable */ popup = this.getPopupHandler(options); options = objectHelper .merge(this.baseOptions, [ 'clientID', 'scope', 'domain', 'audience', '_csrf', 'state', '_intstate', 'nonce' ]) .with(objectHelper.blacklist(options, ['popupHandler'])); params = objectHelper.pick(options, ['clientID', 'domain']); params.options = objectHelper.toSnakeCase( objectHelper.pick(options, ['password', 'connection', 'state', 'scope', '_csrf', 'device']) ); params.options.username = options.username || options.email; url = urljoin(this.baseOptions.rootUrl, 'sso_dbconnection_popup', options.clientID); relayUrl = urljoin(this.baseOptions.rootUrl, 'relay.html'); return popup.load(url, relayUrl, { params: params }, responseHandler(cb)); }; /** * Verifies the passwordless TOTP and redirects to finish the passwordless transaction * * @method passwordlessVerify * @param {Object} options * @param {String} options.type `sms` or `email` * @param {String} options.phoneNumber only if type = sms * @param {String} options.email only if type = email * @param {String} options.connection the connection name * @param {String} options.verificationCode the TOTP code * @param {Function} cb */ Popup.prototype.passwordlessVerify = function(options, cb) { var _this = this; return this.client.passwordless.verify( objectHelper.blacklist(options, ['popupHandler']), function(err) { if (err) { return cb(err); } options.username = options.phoneNumber || options.email; options.password = options.verificationCode; delete options.email; delete options.phoneNumber; delete options.verificationCode; delete options.type; _this.client.loginWithResourceOwner(options, cb); } ); }; /** * Signs up a new user and automatically logs the user in after the signup. * * This method is not compatible with API Auth so if you need to fetch API tokens with audience * you should use {@link authorize} or {@link signupAndAuthorize}. * * @method signupAndLogin * @param {Object} options * @param {String} options.email user email address * @param {String} options.password user password * @param {String} options.connection name of the connection where the user will be created * @param {credentialsCallback} cb */ Popup.prototype.signupAndLogin = function(options, cb) { var _this = this; // Preload popup to avoid the browser to block it since the login happens later var popupHandler = this.getPopupHandler(options, true); options.popupHandler = popupHandler; return this.client.dbConnection.signup( objectHelper.blacklist(options, ['popupHandler']), function(err) { if (err) { if (popupHandler._current_popup) { popupHandler._current_popup.kill(); } return cb(err); } _this.loginWithCredentials(options, cb); } ); }; module.exports = Popup;
hljs.registerLanguage("erlang-repl",function(){"use strict";return function(e){ return{name:"Erlang REPL",keywords:{built_in:"spawn spawn_link self", keyword:"after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if let not of or orelse|10 query receive rem try when xor" },contains:[{className:"meta",begin:"^[0-9]+> ",relevance:10 },e.COMMENT("%","$"),{className:"number", begin:"\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)", relevance:0},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{ begin:"\\?(::)?([A-Z]\\w*(::)?)+"},{begin:"->"},{begin:"ok"},{begin:"!"},{ begin:"(\\b[a-z'][a-zA-Z0-9_']*:[a-z'][a-zA-Z0-9_']*)|(\\b[a-z'][a-zA-Z0-9_']*)", relevance:0},{begin:"[A-Z][a-zA-Z0-9_']*",relevance:0}]}}}());
/*! * QUnit 1.15.0 * http://qunitjs.com/ * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-08-08T16:00Z */ (function( window ) { var QUnit, config, onErrorFnPrev, fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" ), toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, // Keep a local reference to Date (GH-283) Date = window.Date, now = Date.now || function() { return new Date().getTime(); }, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, defined = { document: typeof window.document !== "undefined", setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { var x = "qunit-test-string"; try { sessionStorage.setItem( x, x ); sessionStorage.removeItem( x ); return true; } catch ( e ) { return false; } }()) }, /** * Provides a normalized error string, correcting an issue * with IE 7 (and prior) where Error.prototype.toString is * not properly implemented * * Based on http://es5.github.com/#x15.11.4.4 * * @param {String|Error} error * @return {String} error message */ errorString = function( error ) { var name, message, errorString = error.toString(); if ( errorString.substring( 0, 7 ) === "[object" ) { name = error.name ? error.name.toString() : "Error"; message = error.message ? error.message.toString() : ""; if ( name && message ) { return name + ": " + message; } else if ( name ) { return name; } else if ( message ) { return message; } else { return "Error"; } } else { return errorString; } }, /** * Makes a clone of an object using only Array or Object as base, * and copies over the own enumerable properties. * * @param {Object} obj * @return {Object} New object with only the own properties (recursively). */ objectValues = function( obj ) { var key, val, vals = QUnit.is( "array", obj ) ? [] : {}; for ( key in obj ) { if ( hasOwn.call( obj, key ) ) { val = obj[ key ]; vals[ key ] = val === Object( val ) ? objectValues( val ) : val; } } return vals; }; // Root QUnit object. // `QUnit` initialized at top of scope QUnit = { // call on start of module test to prepend name to all tests module: function( name, testEnvironment ) { config.currentModule = name; config.currentModuleTestEnvironment = testEnvironment; config.modules[ name ] = true; }, asyncTest: function( testName, expected, callback ) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test( testName, expected, callback, true ); }, test: function( testName, expected, callback, async ) { var test; if ( arguments.length === 2 ) { callback = expected; expected = null; } test = new Test({ testName: testName, expected: expected, async: async, callback: callback, module: config.currentModule, moduleTestEnvironment: config.currentModuleTestEnvironment, stack: sourceFromStacktrace( 2 ) }); if ( !validTest( test ) ) { return; } test.queue(); }, start: function( count ) { var message; // QUnit hasn't been initialized yet. // Note: RequireJS (et al) may delay onLoad if ( config.semaphore === undefined ) { QUnit.begin(function() { // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first setTimeout(function() { QUnit.start( count ); }); }); return; } config.semaphore -= count || 1; // don't start until equal number of stop-calls if ( config.semaphore > 0 ) { return; } // Set the starting time when the first test is run QUnit.config.started = QUnit.config.started || now(); // ignore if start is called more often then stop if ( config.semaphore < 0 ) { config.semaphore = 0; message = "Called start() while already started (QUnit.config.semaphore was 0 already)"; if ( config.current ) { QUnit.pushFailure( message, sourceFromStacktrace( 2 ) ); } else { throw new Error( message ); } return; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { setTimeout(function() { if ( config.semaphore > 0 ) { return; } if ( config.timeout ) { clearTimeout( config.timeout ); } config.blocking = false; process( true ); }, 13 ); } else { config.blocking = false; process( true ); } }, stop: function( count ) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout( config.timeout ); config.timeout = setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout ); } } }; // We use the prototype to distinguish between properties that should // be exposed as globals (and in exports) and those that shouldn't (function() { function F() {} F.prototype = QUnit; QUnit = new F(); // Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; }()); /** * Config object: Maintain internal state * Later exposed as QUnit.config * `config` initialized at top of scope */ config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, // by default, scroll to top of the page when suite is done scrolltop: true, // when enabled, all tests must call expect() requireExpects: false, // add checkboxes that are persisted in the query-string // when enabled, the id is set to `true` as a `QUnit.config` property urlConfig: [ { id: "noglobals", label: "Check for Globals", tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." }, { id: "notrycatch", label: "No try-catch", tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." } ], // Set of all modules. modules: {}, callbacks: {} }; // Initialize more QUnit.config and QUnit.urlParams (function() { var i, current, location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}; if ( params[ 0 ] ) { for ( i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; if ( urlParams[ current[ 0 ] ] ) { urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] ); } else { urlParams[ current[ 0 ] ] = current[ 1 ]; } } } QUnit.urlParams = urlParams; // String search anywhere in moduleName+testName config.filter = urlParams.filter; // Exact match of the module name config.module = urlParams.module; config.testNumber = []; if ( urlParams.testNumber ) { // Ensure that urlParams.testNumber is an array urlParams.testNumber = [].concat( urlParams.testNumber ); for ( i = 0; i < urlParams.testNumber.length; i++ ) { current = urlParams.testNumber[ i ]; config.testNumber.push( parseInt( current, 10 ) ); } } // Figure out if we're running the tests from a server or not QUnit.isLocal = location.protocol === "file:"; }()); extend( QUnit, { config: config, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) === type; }, objectType: function( obj ) { if ( typeof obj === "undefined" ) { return "undefined"; } // Consider: typeof null === object if ( obj === null ) { return "null"; } var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ), type = match && match[ 1 ] || ""; switch ( type ) { case "Number": if ( isNaN( obj ) ) { return "nan"; } return "number"; case "String": case "Boolean": case "Array": case "Date": case "RegExp": case "Function": return type.toLowerCase(); } if ( typeof obj === "object" ) { return "object"; } return undefined; }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var key, querystring = "?"; for ( key in params ) { if ( hasOwn.call( params, key ) ) { querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } } return window.location.protocol + "//" + window.location.host + window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend }); /** * @deprecated: Created for backwards compatibility with test runner that set the hook function * into QUnit.{hook}, instead of invoking it and passing the hook function. * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. * Doing this allows us to tell if the following methods have been overwritten on the actual * QUnit object. */ extend( QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback( "begin" ), // done: { failed, passed, total, runtime } done: registerLoggingCallback( "done" ), // log: { result, actual, expected, message } log: registerLoggingCallback( "log" ), // testStart: { name } testStart: registerLoggingCallback( "testStart" ), // testDone: { name, failed, passed, total, runtime } testDone: registerLoggingCallback( "testDone" ), // moduleStart: { name } moduleStart: registerLoggingCallback( "moduleStart" ), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback( "moduleDone" ) }); QUnit.load = function() { runLoggingCallbacks( "begin", { totalTests: Test.count }); // Initialize the configuration options extend( config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: 0, updateRate: 1000, autostart: true, filter: "", semaphore: 1 }, true ); config.blocking = false; if ( config.autostart ) { QUnit.start(); } }; // `onErrorFnPrev` initialized at top of scope // Preserve other handlers onErrorFnPrev = window.onerror; // Cover uncaught exceptions // Returning true will suppress the default browser handler, // returning false will let it run. window.onerror = function( error, filePath, linerNr ) { var ret = false; if ( onErrorFnPrev ) { ret = onErrorFnPrev( error, filePath, linerNr ); } // Treat return value as window.onerror itself does, // Only do our handling if not suppressed. if ( ret !== true ) { if ( QUnit.config.current ) { if ( QUnit.config.current.ignoreGlobalErrors ) { return true; } QUnit.pushFailure( error, filePath + ":" + linerNr ); } else { QUnit.test( "global failure", extend(function() { QUnit.pushFailure( error, filePath + ":" + linerNr ); }, { validTest: validTest } ) ); } return false; } return ret; }; function done() { config.autorun = true; // Log the last module results if ( config.previousModule ) { runLoggingCallbacks( "moduleDone", { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } delete config.previousModule; var runtime = now() - config.started, passed = config.stats.all - config.stats.bad; runLoggingCallbacks( "done", { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime }); } /** @return Boolean: true if this test should be ran */ function validTest( test ) { var include, filter = config.filter && config.filter.toLowerCase(), module = config.module && config.module.toLowerCase(), fullName = ( test.module + ": " + test.testName ).toLowerCase(); // Internally-generated tests are always valid if ( test.callback && test.callback.validTest === validTest ) { delete test.callback.validTest; return true; } if ( config.testNumber.length > 0 ) { if ( inArray( test.testNumber, config.testNumber ) < 0 ) { return false; } } if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { return false; } if ( !filter ) { return true; } include = filter.charAt( 0 ) !== "!"; if ( !include ) { filter = filter.slice( 1 ); } // If the filter matches, we need to honour include if ( fullName.indexOf( filter ) !== -1 ) { return include; } // Otherwise, do the opposite return !include; } // Doesn't support IE6 to IE9 // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack function extractStacktrace( e, offset ) { offset = offset === undefined ? 4 : offset; var stack, include, i; if ( e.stacktrace ) { // Opera 12.x return e.stacktrace.split( "\n" )[ offset + 3 ]; } else if ( e.stack ) { // Firefox, Chrome, Safari 6+, IE10+, PhantomJS and Node stack = e.stack.split( "\n" ); if ( /^error$/i.test( stack[ 0 ] ) ) { stack.shift(); } if ( fileName ) { include = []; for ( i = offset; i < stack.length; i++ ) { if ( stack[ i ].indexOf( fileName ) !== -1 ) { break; } include.push( stack[ i ] ); } if ( include.length ) { return include.join( "\n" ); } } return stack[ offset ]; } else if ( e.sourceURL ) { // Safari < 6 // exclude useless self-reference for generated Error objects if ( /qunit.js$/.test( e.sourceURL ) ) { return; } // for actual exceptions, this is useful return e.sourceURL + ":" + e.line; } } function sourceFromStacktrace( offset ) { try { throw new Error(); } catch ( e ) { return extractStacktrace( e, offset ); } } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process( last ); } } function process( last ) { function next() { process( last ); } var start = now(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( now() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { setTimeout( next, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( hasOwn.call( window, key ) ) { // in Opera sometimes DOM element ids show up here, ignore them if ( /^qunit-test-output/.test( key ) ) { continue; } config.pollution.push( key ); } } } } function checkPollution() { var newGlobals, deletedGlobals, old = config.pollution; saveGlobal(); newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) ); } deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var i, j, result = a.slice(); for ( i = 0; i < result.length; i++ ) { for ( j = 0; j < b.length; j++ ) { if ( result[ i ] === b[ j ] ) { result.splice( i, 1 ); i--; break; } } } return result; } function extend( a, b, undefOnly ) { for ( var prop in b ) { if ( hasOwn.call( b, prop ) ) { // Avoid "Member not found" error in IE8 caused by messing with window.constructor if ( !( prop === "constructor" && a === window ) ) { if ( b[ prop ] === undefined ) { delete a[ prop ]; } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) { a[ prop ] = b[ prop ]; } } } } return a; } function registerLoggingCallback( key ) { // Initialize key collection of logging callback if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) { config.callbacks[ key ] = []; } return function( callback ) { config.callbacks[ key ].push( callback ); }; } function runLoggingCallbacks( key, args ) { var i, l, callbacks; callbacks = config.callbacks[ key ]; for ( i = 0, l = callbacks.length; i < l; i++ ) { callbacks[ i ]( args ); } } // from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } function Test( settings ) { extend( this, settings ); this.assert = new Assert( this ); this.assertions = []; this.testNumber = ++Test.count; } Test.count = 0; Test.prototype = { setup: function() { if ( // Emit moduleStart when we're switching from one module to another this.module !== config.previousModule || // They could be equal (both undefined) but if the previousModule property doesn't // yet exist it means this is the first test in a suite that isn't wrapped in a // module, in which case we'll just emit a moduleStart event for 'undefined'. // Without this, reporters can get testStart before moduleStart which is a problem. !hasOwn.call( config, "previousModule" ) ) { if ( hasOwn.call( config, "previousModule" ) ) { runLoggingCallbacks( "moduleDone", { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( "moduleStart", { name: this.module }); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment ); this.started = now(); runLoggingCallbacks( "testStart", { name: this.testName, module: this.module, testNumber: this.testNumber }); if ( !config.pollution ) { saveGlobal(); } if ( config.notrycatch ) { this.testEnvironment.setup.call( this.testEnvironment, this.assert ); return; } try { this.testEnvironment.setup.call( this.testEnvironment, this.assert ); } catch ( e ) { this.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); } }, run: function() { config.current = this; if ( this.async ) { QUnit.stop(); } this.callbackStarted = now(); if ( config.notrycatch ) { this.callback.call( this.testEnvironment, this.assert ); this.callbackRuntime = now() - this.callbackStarted; return; } try { this.callback.call( this.testEnvironment, this.assert ); this.callbackRuntime = now() - this.callbackStarted; } catch ( e ) { this.callbackRuntime = now() - this.callbackStarted; this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; if ( config.notrycatch ) { if ( typeof this.callbackRuntime === "undefined" ) { this.callbackRuntime = now() - this.callbackStarted; } this.testEnvironment.teardown.call( this.testEnvironment, this.assert ); return; } else { try { this.testEnvironment.teardown.call( this.testEnvironment, this.assert ); } catch ( e ) { this.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); } } checkPollution(); }, finish: function() { config.current = this; if ( config.requireExpects && this.expected === null ) { this.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); } else if ( this.expected !== null && this.expected !== this.assertions.length ) { this.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); } else if ( this.expected === null && !this.assertions.length ) { this.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); } var i, bad = 0; this.runtime = now() - this.started; config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; for ( i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[ i ].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } runLoggingCallbacks( "testDone", { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length, runtime: this.runtime, // HTML Reporter use assertions: this.assertions, testNumber: this.testNumber, // DEPRECATED: this property will be removed in 2.0.0, use runtime instead duration: this.runtime }); config.current = undefined; }, queue: function() { var bad, test = this; function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // `bad` initialized at top of scope // defer when previous test run passed, if storage is available bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); if ( bad ) { run(); } else { synchronize( run, true ); } }, push: function( result, actual, expected, message ) { var source, details = { module: this.module, name: this.testName, result: result, message: message, actual: actual, expected: expected, testNumber: this.testNumber }; if ( !result ) { source = sourceFromStacktrace(); if ( source ) { details.source = source; } } runLoggingCallbacks( "log", details ); this.assertions.push({ result: !!result, message: message }); }, pushFailure: function( message, source, actual ) { if ( !this instanceof Test ) { throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace( 2 ) ); } var details = { module: this.module, name: this.testName, result: false, message: message || "error", actual: actual || null, testNumber: this.testNumber }; if ( source ) { details.source = source; } runLoggingCallbacks( "log", details ); this.assertions.push({ result: false, message: message }); } }; QUnit.pushFailure = function() { if ( !QUnit.config.current ) { throw new Error( "pushFailure() assertion outside test context, in " + sourceFromStacktrace( 2 ) ); } // Gets current test obj var currentTest = QUnit.config.current.assert.test; return currentTest.pushFailure.apply( currentTest, arguments ); }; function Assert( testContext ) { this.test = testContext; } // Assert helpers QUnit.assert = Assert.prototype = { // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. expect: function( asserts ) { if ( arguments.length === 1 ) { this.test.expected = asserts; } else { return this.test.expected; } }, // Exports test.push() to the user API push: function() { var assert = this; // Backwards compatibility fix. // Allows the direct use of global exported assertions and QUnit.assert.* // Although, it's use is not recommended as it can leak assertions // to other tests from async tests, because we only get a reference to the current test, // not exactly the test where assertion were intended to be called. if ( !QUnit.config.current ) { throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) ); } if ( !( assert instanceof Assert ) ) { assert = QUnit.config.current.assert; } return assert.test.push.apply( assert.test, arguments ); }, /** * Asserts rough true-ish result. * @name ok * @function * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function( result, message ) { message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " + QUnit.dump.parse( result ) ); if ( !!result ) { this.push( true, result, true, message ); } else { this.test.pushFailure( message, null, result ); } }, /** * Assert that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * @name equal * @function * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); */ equal: function( actual, expected, message ) { /*jshint eqeqeq:false */ this.push( expected == actual, actual, expected, message ); }, /** * @name notEqual * @function */ notEqual: function( actual, expected, message ) { /*jshint eqeqeq:false */ this.push( expected != actual, actual, expected, message ); }, /** * @name propEqual * @function */ propEqual: function( actual, expected, message ) { actual = objectValues( actual ); expected = objectValues( expected ); this.push( QUnit.equiv( actual, expected ), actual, expected, message ); }, /** * @name notPropEqual * @function */ notPropEqual: function( actual, expected, message ) { actual = objectValues( actual ); expected = objectValues( expected ); this.push( !QUnit.equiv( actual, expected ), actual, expected, message ); }, /** * @name deepEqual * @function */ deepEqual: function( actual, expected, message ) { this.push( QUnit.equiv( actual, expected ), actual, expected, message ); }, /** * @name notDeepEqual * @function */ notDeepEqual: function( actual, expected, message ) { this.push( !QUnit.equiv( actual, expected ), actual, expected, message ); }, /** * @name strictEqual * @function */ strictEqual: function( actual, expected, message ) { this.push( expected === actual, actual, expected, message ); }, /** * @name notStrictEqual * @function */ notStrictEqual: function( actual, expected, message ) { this.push( expected !== actual, actual, expected, message ); }, "throws": function( block, expected, message ) { var actual, expectedType, expectedOutput = expected, ok = false; // 'expected' is optional unless doing string comparison if ( message == null && typeof expected === "string" ) { message = expected; expected = null; } this.test.ignoreGlobalErrors = true; try { block.call( this.test.testEnvironment ); } catch (e) { actual = e; } this.test.ignoreGlobalErrors = false; if ( actual ) { expectedType = QUnit.objectType( expected ); // we don't want to validate thrown error if ( !expected ) { ok = true; expectedOutput = null; // expected is a regexp } else if ( expectedType === "regexp" ) { ok = expected.test( errorString( actual ) ); // expected is a string } else if ( expectedType === "string" ) { ok = expected === errorString( actual ); // expected is a constructor, maybe an Error constructor } else if ( expectedType === "function" && actual instanceof expected ) { ok = true; // expected is an Error object } else if ( expectedType === "object" ) { ok = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message; // expected is a validation function which returns true if validation passed } else if ( expectedType === "function" && expected.call( {}, actual ) === true ) { expectedOutput = null; ok = true; } this.push( ok, actual, expectedOutput, message ); } else { this.test.pushFailure( message, null, "No exception was thrown." ); } } }; // Test for equality any JavaScript type. // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = (function() { // Call the o related callback with the given arguments. function bindCallbacks( o, callbacks, args ) { var prop = QUnit.objectType( o ); if ( prop ) { if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { return callbacks[ prop ].apply( callbacks, args ); } else { return callbacks[ prop ]; // or undefined } } } // the real equiv function var innerEquiv, // stack to decide between skip/abort functions callers = [], // stack to avoiding loops from circular referencing parents = [], parentsB = [], getProto = Object.getPrototypeOf || function( obj ) { /* jshint camelcase: false, proto: true */ return obj.__proto__; }, callbacks = (function() { // for string, boolean, number and null function useStrictEquality( b, a ) { /*jshint eqeqeq:false */ if ( b instanceof a.constructor || a instanceof b.constructor ) { // to catch short annotation VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function( b ) { return isNaN( b ); }, "date": function( b, a ) { return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function( b, a ) { return QUnit.objectType( b ) === "regexp" && // the regex itself a.source === b.source && // and its modifiers a.global === b.global && // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function() { var caller = callers[ callers.length - 1 ]; return caller !== Object && typeof caller !== "undefined"; }, "array": function( b, a ) { var i, j, len, loop, aCircular, bCircular; // b could be an object literal here if ( QUnit.objectType( b ) !== "array" ) { return false; } len = a.length; if ( len !== b.length ) { // safe and faster return false; } // track reference to avoid circular references parents.push( a ); parentsB.push( b ); for ( i = 0; i < len; i++ ) { loop = false; for ( j = 0; j < parents.length; j++ ) { aCircular = parents[ j ] === a[ i ]; bCircular = parentsB[ j ] === b[ i ]; if ( aCircular || bCircular ) { if ( a[ i ] === b[ i ] || aCircular && bCircular ) { loop = true; } else { parents.pop(); parentsB.pop(); return false; } } } if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) { parents.pop(); parentsB.pop(); return false; } } parents.pop(); parentsB.pop(); return true; }, "object": function( b, a ) { /*jshint forin:false */ var i, j, loop, aCircular, bCircular, // Default to true eq = true, aProperties = [], bProperties = []; // comparing constructors is more strict than using // instanceof if ( a.constructor !== b.constructor ) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if ( !( ( getProto( a ) === null && getProto( b ) === Object.prototype ) || ( getProto( b ) === null && getProto( a ) === Object.prototype ) ) ) { return false; } } // stack constructor before traversing properties callers.push( a.constructor ); // track reference to avoid circular references parents.push( a ); parentsB.push( b ); // be strict: don't ensure hasOwnProperty and go deep for ( i in a ) { loop = false; for ( j = 0; j < parents.length; j++ ) { aCircular = parents[ j ] === a[ i ]; bCircular = parentsB[ j ] === b[ i ]; if ( aCircular || bCircular ) { if ( a[ i ] === b[ i ] || aCircular && bCircular ) { loop = true; } else { eq = false; break; } } } aProperties.push( i ); if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) { eq = false; break; } } parents.pop(); parentsB.pop(); callers.pop(); // unstack, we are done for ( i in b ) { bProperties.push( i ); // collect b's properties } // Ensures identical properties name return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); } }; }()); innerEquiv = function() { // can take multiple arguments var args = [].slice.apply( arguments ); if ( args.length < 2 ) { return true; // end transition } return ( (function( a, b ) { if ( a === b ) { return true; // catch the most you can } else if ( a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType( a ) !== QUnit.objectType( b ) ) { // don't lose time with error prone cases return false; } else { return bindCallbacks( a, callbacks, [ b, a ] ); } // apply transition with (1..n) arguments }( args[ 0 ], args[ 1 ] ) ) && innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) ); }; return innerEquiv; }()); // Based on jsDump by Ariel Flesler // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html QUnit.dump = (function() { function quote( str ) { return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\""; } function literal( o ) { return o + ""; } function join( pre, arr, post ) { var s = dump.separator(), base = dump.indent(), inner = dump.indent( 1 ); if ( arr.join ) { arr = arr.join( "," + s + inner ); } if ( !arr ) { return pre + post; } return [ pre, inner + arr, base + post ].join( s ); } function array( arr, stack ) { var i = arr.length, ret = new Array( i ); this.up(); while ( i-- ) { ret[ i ] = this.parse( arr[ i ], undefined, stack ); } this.down(); return join( "[", ret, "]" ); } var reName = /^function (\w+)/, dump = { // type is used mostly internally, you can fix a (custom)type in advance parse: function( obj, type, stack ) { stack = stack || []; var inStack, res, parser = this.parsers[ type || this.typeOf( obj ) ]; type = typeof parser; inStack = inArray( obj, stack ); if ( inStack !== -1 ) { return "recursion(" + ( inStack - stack.length ) + ")"; } if ( type === "function" ) { stack.push( obj ); res = parser.call( this, obj, stack ); stack.pop(); return res; } return ( type === "string" ) ? parser : this.parsers.error; }, typeOf: function( obj ) { var type; if ( obj === null ) { type = "null"; } else if ( typeof obj === "undefined" ) { type = "undefined"; } else if ( QUnit.is( "regexp", obj ) ) { type = "regexp"; } else if ( QUnit.is( "date", obj ) ) { type = "date"; } else if ( QUnit.is( "function", obj ) ) { type = "function"; } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { type = "window"; } else if ( obj.nodeType === 9 ) { type = "document"; } else if ( obj.nodeType ) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null && typeof obj[ 0 ] === "undefined" ) ) ) ) { type = "array"; } else if ( obj.constructor === Error.prototype.constructor ) { type = "error"; } else { type = typeof obj; } return type; }, separator: function() { return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? "&nbsp;" : " "; }, // extra can be a number, shortcut for increasing-calling-decreasing indent: function( extra ) { if ( !this.multiline ) { return ""; } var chr = this.indentChar; if ( this.HTML ) { chr = chr.replace( /\t/g, " " ).replace( / /g, "&nbsp;" ); } return new Array( this.depth + ( extra || 0 ) ).join( chr ); }, up: function( a ) { this.depth += a || 1; }, down: function( a ) { this.depth -= a || 1; }, setParser: function( name, parser ) { this.parsers[ name ] = parser; }, // The next 3 are exposed so you can use them quote: quote, literal: literal, join: join, // depth: 1, // This is the list of parsers, to modify them, use dump.setParser parsers: { window: "[Window]", document: "[Document]", error: function( error ) { return "Error(\"" + error.message + "\")"; }, unknown: "[Unknown]", "null": "null", "undefined": "undefined", "function": function( fn ) { var ret = "function", // functions never have name in IE name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ]; if ( name ) { ret += " " + name; } ret += "( "; ret = [ ret, dump.parse( fn, "functionArgs" ), "){" ].join( "" ); return join( ret, dump.parse( fn, "functionCode" ), "}" ); }, array: array, nodelist: array, "arguments": array, object: function( map, stack ) { /*jshint forin:false */ var ret = [], keys, key, val, i, nonEnumerableProperties; dump.up(); keys = []; for ( key in map ) { keys.push( key ); } // Some properties are not always enumerable on Error objects. nonEnumerableProperties = [ "message", "name" ]; for ( i in nonEnumerableProperties ) { key = nonEnumerableProperties[ i ]; if ( key in map && !( key in keys ) ) { keys.push( key ); } } keys.sort(); for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; val = map[ key ]; ret.push( dump.parse( key, "key" ) + ": " + dump.parse( val, undefined, stack ) ); } dump.down(); return join( "{", ret, "}" ); }, node: function( node ) { var len, i, val, open = dump.HTML ? "&lt;" : "<", close = dump.HTML ? "&gt;" : ">", tag = node.nodeName.toLowerCase(), ret = open + tag, attrs = node.attributes; if ( attrs ) { for ( i = 0, len = attrs.length; i < len; i++ ) { val = attrs[ i ].nodeValue; // IE6 includes all attributes in .attributes, even ones not explicitly set. // Those have values like undefined, null, 0, false, "" or "inherit". if ( val && val !== "inherit" ) { ret += " " + attrs[ i ].nodeName + "=" + dump.parse( val, "attribute" ); } } } ret += close; // Show content of TextNode or CDATASection if ( node.nodeType === 3 || node.nodeType === 4 ) { ret += node.nodeValue; } return ret + open + "/" + tag + close; }, // function calls it internally, it's the arguments part of the function functionArgs: function( fn ) { var args, l = fn.length; if ( !l ) { return ""; } args = new Array( l ); while ( l-- ) { // 97 is 'a' args[ l ] = String.fromCharCode( 97 + l ); } return " " + args.join( ", " ) + " "; }, // object calls it internally, the key part of an item in a map key: quote, // function calls it internally, it's the content of the function functionCode: "[code]", // node calls it internally, it's an html attribute value attribute: quote, string: quote, date: quote, regexp: literal, number: literal, "boolean": literal }, // if true, entities are escaped ( <, >, \t, space and \n ) HTML: false, // indentation unit indentChar: " ", // if true, items in a collection, are separated by a \n, else just a space. multiline: true }; return dump; }()); // back compat QUnit.jsDump = QUnit.dump; // For browser, export only select globals if ( typeof window !== "undefined" ) { // Deprecated // Extend assert methods to QUnit and Global scope through Backwards compatibility (function() { var i, assertions = Assert.prototype; function applyCurrent( current ) { return function() { var assert = new Assert( QUnit.config.current ); current.apply( assert, arguments ); }; } for ( i in assertions ) { QUnit[ i ] = applyCurrent( assertions[ i ] ); } })(); (function() { var i, l, keys = [ "test", "module", "expect", "asyncTest", "start", "stop", "ok", "equal", "notEqual", "propEqual", "notPropEqual", "deepEqual", "notDeepEqual", "strictEqual", "notStrictEqual", "throws" ]; for ( i = 0, l = keys.length; i < l; i++ ) { window[ keys[ i ] ] = QUnit[ keys[ i ] ]; } })(); window.QUnit = QUnit; } // For CommonJS environments, export everything if ( typeof module !== "undefined" && module.exports ) { module.exports = QUnit; } // Get a reference to the global object, like window in browsers }( (function() { return this; })() )); /*istanbul ignore next */ /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { var hasOwn = Object.prototype.hasOwnProperty; /*jshint eqeqeq:false, eqnull:true */ function diff( o, n ) { var i, ns = {}, os = {}; for ( i = 0; i < n.length; i++ ) { if ( !hasOwn.call( ns, n[ i ] ) ) { ns[ n[ i ] ] = { rows: [], o: null }; } ns[ n[ i ] ].rows.push( i ); } for ( i = 0; i < o.length; i++ ) { if ( !hasOwn.call( os, o[ i ] ) ) { os[ o[ i ] ] = { rows: [], n: null }; } os[ o[ i ] ].rows.push( i ); } for ( i in ns ) { if ( hasOwn.call( ns, i ) ) { if ( ns[ i ].rows.length === 1 && hasOwn.call( os, i ) && os[ i ].rows.length === 1 ) { n[ ns[ i ].rows[ 0 ] ] = { text: n[ ns[ i ].rows[ 0 ] ], row: os[ i ].rows[ 0 ] }; o[ os[ i ].rows[ 0 ] ] = { text: o[ os[ i ].rows[ 0 ] ], row: ns[ i ].rows[ 0 ] }; } } } for ( i = 0; i < n.length - 1; i++ ) { if ( n[ i ].text != null && n[ i + 1 ].text == null && n[ i ].row + 1 < o.length && o[ n[ i ].row + 1 ].text == null && n[ i + 1 ] == o[ n[ i ].row + 1 ] ) { n[ i + 1 ] = { text: n[ i + 1 ], row: n[ i ].row + 1 }; o[ n[ i ].row + 1 ] = { text: o[ n[ i ].row + 1 ], row: i + 1 }; } } for ( i = n.length - 1; i > 0; i-- ) { if ( n[ i ].text != null && n[ i - 1 ].text == null && n[ i ].row > 0 && o[ n[ i ].row - 1 ].text == null && n[ i - 1 ] == o[ n[ i ].row - 1 ] ) { n[ i - 1 ] = { text: n[ i - 1 ], row: n[ i ].row - 1 }; o[ n[ i ].row - 1 ] = { text: o[ n[ i ].row - 1 ], row: i - 1 }; } } return { o: o, n: n }; } return function( o, n ) { o = o.replace( /\s+$/, "" ); n = n.replace( /\s+$/, "" ); var i, pre, str = "", out = diff( o === "" ? [] : o.split( /\s+/ ), n === "" ? [] : n.split( /\s+/ ) ), oSpace = o.match( /\s+/g ), nSpace = n.match( /\s+/g ); if ( oSpace == null ) { oSpace = [ " " ]; } else { oSpace.push( " " ); } if ( nSpace == null ) { nSpace = [ " " ]; } else { nSpace.push( " " ); } if ( out.n.length === 0 ) { for ( i = 0; i < out.o.length; i++ ) { str += "<del>" + out.o[ i ] + oSpace[ i ] + "</del>"; } } else { if ( out.n[ 0 ].text == null ) { for ( n = 0; n < out.o.length && out.o[ n ].text == null; n++ ) { str += "<del>" + out.o[ n ] + oSpace[ n ] + "</del>"; } } for ( i = 0; i < out.n.length; i++ ) { if ( out.n[ i ].text == null ) { str += "<ins>" + out.n[ i ] + nSpace[ i ] + "</ins>"; } else { // `pre` initialized at top of scope pre = ""; for ( n = out.n[ i ].row + 1; n < out.o.length && out.o[ n ].text == null; n++ ) { pre += "<del>" + out.o[ n ] + oSpace[ n ] + "</del>"; } str += " " + out.n[ i ].text + nSpace[ i ] + pre; } } } return str; }; }()); (function() { // Deprecated QUnit.init - Ref #530 // Re-initialize the configuration options QUnit.init = function() { var tests, banner, result, qunit, config = QUnit.config; config.stats = { all: 0, bad: 0 }; config.moduleStats = { all: 0, bad: 0 }; config.started = 0; config.updateRate = 1000; config.blocking = false; config.autostart = true; config.autorun = false; config.filter = ""; config.queue = []; config.semaphore = 1; // Return on non-browser environments // This is necessary to not break on node tests if ( typeof window === "undefined" ) { return; } qunit = id( "qunit" ); if ( qunit ) { qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>"; } tests = id( "qunit-tests" ); banner = id( "qunit-banner" ); result = id( "qunit-testresult" ); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = "Running...<br/>&nbsp;"; } }; // Resets the test setup. Useful for tests that modify the DOM. /* DEPRECATED: Use multiple tests instead of resetting inside a test. Use testStart or testDone for custom cleanup. This method will throw an error in 2.0, and will be removed in 2.1 */ QUnit.reset = function() { // Return on non-browser environments // This is necessary to not break on node tests if ( typeof window === "undefined" ) { return; } var fixture = id( "qunit-fixture" ); if ( fixture ) { fixture.innerHTML = config.fixture; } }; // Don't load the HTML Reporter on non-Browser environments if ( typeof window === "undefined" ) { return; } var config = QUnit.config, hasOwn = Object.prototype.hasOwnProperty, defined = { document: typeof window.document !== "undefined", sessionStorage: (function() { var x = "qunit-test-string"; try { sessionStorage.setItem( x, x ); sessionStorage.removeItem( x ); return true; } catch ( e ) { return false; } }()) }; /** * Escape text for attribute or text content. */ function escapeText( s ) { if ( !s ) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace( /['"<>&]/g, function( s ) { switch ( s ) { case "'": return "&#039;"; case "\"": return "&quot;"; case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; } }); } /** * @param {HTMLElement} elem * @param {string} type * @param {Function} fn */ function addEvent( elem, type, fn ) { if ( elem.addEventListener ) { // Standards-based browsers elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { // support: IE <9 elem.attachEvent( "on" + type, fn ); } } /** * @param {Array|NodeList} elems * @param {string} type * @param {Function} fn */ function addEvents( elems, type, fn ) { var i = elems.length; while ( i-- ) { addEvent( elems[ i ], type, fn ); } } function hasClass( elem, name ) { return ( " " + elem.className + " " ).indexOf( " " + name + " " ) >= 0; } function addClass( elem, name ) { if ( !hasClass( elem, name ) ) { elem.className += ( elem.className ? " " : "" ) + name; } } function toggleClass( elem, name ) { if ( hasClass( elem, name ) ) { removeClass( elem, name ); } else { addClass( elem, name ); } } function removeClass( elem, name ) { var set = " " + elem.className + " "; // Class name may appear multiple times while ( set.indexOf( " " + name + " " ) >= 0 ) { set = set.replace( " " + name + " ", " " ); } // trim for prettiness elem.className = typeof set.trim === "function" ? set.trim() : set.replace( /^\s+|\s+$/g, "" ); } function id( name ) { return defined.document && document.getElementById && document.getElementById( name ); } function getUrlConfigHtml() { var i, j, val, escaped, escapedTooltip, selection = false, len = config.urlConfig.length, urlConfigHtml = ""; for ( i = 0; i < len; i++ ) { val = config.urlConfig[ i ]; if ( typeof val === "string" ) { val = { id: val, label: val }; } escaped = escapeText( val.id ); escapedTooltip = escapeText( val.tooltip ); config[ val.id ] = QUnit.urlParams[ val.id ]; if ( !val.value || typeof val.value === "string" ) { urlConfigHtml += "<input id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' type='checkbox'" + ( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) + ( config[ val.id ] ? " checked='checked'" : "" ) + " title='" + escapedTooltip + "'><label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + "</label>"; } else { urlConfigHtml += "<label for='qunit-urlconfig-" + escaped + "' title='" + escapedTooltip + "'>" + val.label + ": </label><select id='qunit-urlconfig-" + escaped + "' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>"; if ( QUnit.is( "array", val.value ) ) { for ( j = 0; j < val.value.length; j++ ) { escaped = escapeText( val.value[ j ] ); urlConfigHtml += "<option value='" + escaped + "'" + ( config[ val.id ] === val.value[ j ] ? ( selection = true ) && " selected='selected'" : "" ) + ">" + escaped + "</option>"; } } else { for ( j in val.value ) { if ( hasOwn.call( val.value, j ) ) { urlConfigHtml += "<option value='" + escapeText( j ) + "'" + ( config[ val.id ] === j ? ( selection = true ) && " selected='selected'" : "" ) + ">" + escapeText( val.value[ j ] ) + "</option>"; } } } if ( config[ val.id ] && !selection ) { escaped = escapeText( config[ val.id ] ); urlConfigHtml += "<option value='" + escaped + "' selected='selected' disabled='disabled'>" + escaped + "</option>"; } urlConfigHtml += "</select>"; } } return urlConfigHtml; } function toolbarUrlConfigContainer() { var urlConfigContainer = document.createElement( "span" ); urlConfigContainer.innerHTML = getUrlConfigHtml(); // For oldIE support: // * Add handlers to the individual elements instead of the container // * Use "click" instead of "change" for checkboxes // * Fallback from event.target to event.srcElement addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", function( event ) { var params = {}, target = event.target || event.srcElement; params[ target.name ] = target.checked ? target.defaultValue || true : undefined; window.location = QUnit.url( params ); }); addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", function( event ) { var params = {}, target = event.target || event.srcElement; params[ target.name ] = target.options[ target.selectedIndex ].value || undefined; window.location = QUnit.url( params ); }); return urlConfigContainer; } function getModuleNames() { var i, moduleNames = []; for ( i in config.modules ) { if ( config.modules.hasOwnProperty( i ) ) { moduleNames.push( i ); } } moduleNames.sort(function( a, b ) { return a.localeCompare( b ); }); return moduleNames; } function toolbarModuleFilterHtml() { var i, moduleFilterHtml = "", moduleNames = getModuleNames(); if ( moduleNames.length <= 1 ) { return false; } moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label>" + "<select id='qunit-modulefilter' name='modulefilter'><option value='' " + ( config.module === undefined ? "selected='selected'" : "" ) + ">< All Modules ></option>"; for ( i = 0; i < moduleNames.length; i++ ) { moduleFilterHtml += "<option value='" + escapeText( encodeURIComponent( moduleNames[ i ] ) ) + "' " + ( config.module === moduleNames[ i ] ? "selected='selected'" : "" ) + ">" + escapeText( moduleNames[ i ] ) + "</option>"; } moduleFilterHtml += "</select>"; return moduleFilterHtml; } function toolbarModuleFilter() { var moduleFilter = document.createElement( "span" ), moduleFilterHtml = toolbarModuleFilterHtml(); if ( !moduleFilterHtml ) { return false; } moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); moduleFilter.innerHTML = moduleFilterHtml; addEvent( moduleFilter.lastChild, "change", function() { var selectBox = moduleFilter.getElementsByTagName( "select" )[ 0 ], selectedModule = decodeURIComponent( selectBox.options[ selectBox.selectedIndex ].value ); window.location = QUnit.url({ module: ( selectedModule === "" ) ? undefined : selectedModule, // Remove any existing filters filter: undefined, testNumber: undefined }); }); return moduleFilter; } function toolbarFilter() { var testList = id( "qunit-tests" ), filter = document.createElement( "input" ); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { if ( filter.checked ) { addClass( testList, "hidepass" ); if ( defined.sessionStorage ) { sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); } } else { removeClass( testList, "hidepass" ); if ( defined.sessionStorage ) { sessionStorage.removeItem( "qunit-filter-passed-tests" ); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { filter.checked = true; addClass( testList, "hidepass" ); } return filter; } function toolbarLabel() { var label = document.createElement( "label" ); label.setAttribute( "for", "qunit-filter-pass" ); label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." ); label.innerHTML = "Hide passed tests"; return label; } function appendToolbar() { var moduleFilter, toolbar = id( "qunit-testrunner-toolbar" ); if ( toolbar ) { toolbar.appendChild( toolbarFilter() ); toolbar.appendChild( toolbarLabel() ); toolbar.appendChild( toolbarUrlConfigContainer() ); moduleFilter = toolbarModuleFilter(); if ( moduleFilter ) { toolbar.appendChild( moduleFilter ); } } } function appendBanner() { var banner = id( "qunit-banner" ); if ( banner ) { banner.className = ""; banner.innerHTML = "<a href='" + QUnit.url({ filter: undefined, module: undefined, testNumber: undefined }) + "'>" + banner.innerHTML + "</a> "; } } function appendTestResults() { var tests = id( "qunit-tests" ), result = id( "qunit-testresult" ); if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { tests.innerHTML = ""; result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = "Running...<br>&nbsp;"; } } function storeFixture() { var fixture = id( "qunit-fixture" ); if ( fixture ) { config.fixture = fixture.innerHTML; } } function appendUserAgent() { var userAgent = id( "qunit-userAgent" ); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } } // HTML Reporter initialization and load QUnit.begin(function() { var qunit = id( "qunit" ); if ( qunit ) { qunit.innerHTML = "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" + "<h2 id='qunit-banner'></h2>" + "<div id='qunit-testrunner-toolbar'></div>" + "<h2 id='qunit-userAgent'></h2>" + "<ol id='qunit-tests'></ol>"; } appendBanner(); appendTestResults(); appendUserAgent(); appendToolbar(); storeFixture(); }); QUnit.done(function( details ) { var i, key, banner = id( "qunit-banner" ), tests = id( "qunit-tests" ), html = [ "Tests completed in ", details.runtime, " milliseconds.<br>", "<span class='passed'>", details.passed, "</span> assertions of <span class='total'>", details.total, "</span> passed, <span class='failed'>", details.failed, "</span> failed." ].join( "" ); if ( banner ) { banner.className = details.failed ? "qunit-fail" : "qunit-pass"; } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && defined.document && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ ( details.failed ? "\u2716" : "\u2714" ), document.title.replace( /^[\u2714\u2716] /i, "" ) ].join( " " ); } // clear own sessionStorage items if all tests passed if ( config.reorder && defined.sessionStorage && details.failed === 0 ) { for ( i = 0; i < sessionStorage.length; i++ ) { key = sessionStorage.key( i++ ); if ( key.indexOf( "qunit-test-" ) === 0 ) { sessionStorage.removeItem( key ); } } } // scroll back to top to show results if ( config.scrolltop && window.scrollTo ) { window.scrollTo( 0, 0 ); } }); function getNameHtml( name, module ) { var nameHtml = ""; if ( module ) { nameHtml = "<span class='module-name'>" + escapeText( module ) + "</span>: "; } nameHtml += "<span class='test-name'>" + escapeText( name ) + "</span>"; return nameHtml; } QUnit.testStart(function( details ) { var a, b, li, running, assertList, name = getNameHtml( details.name, details.module ), tests = id( "qunit-tests" ); if ( tests ) { b = document.createElement( "strong" ); b.innerHTML = name; a = document.createElement( "a" ); a.innerHTML = "Rerun"; a.href = QUnit.url({ testNumber: details.testNumber }); li = document.createElement( "li" ); li.appendChild( b ); li.appendChild( a ); li.className = "running"; li.id = "qunit-test-output" + details.testNumber; assertList = document.createElement( "ol" ); assertList.className = "qunit-assert-list"; li.appendChild( assertList ); tests.appendChild( li ); } running = id( "qunit-testresult" ); if ( running ) { running.innerHTML = "Running: <br>" + name; } }); QUnit.log(function( details ) { var assertList, assertLi, message, expected, actual, testItem = id( "qunit-test-output" + details.testNumber ); if ( !testItem ) { return; } message = escapeText( details.message ) || ( details.result ? "okay" : "failed" ); message = "<span class='test-message'>" + message + "</span>"; // pushFailure doesn't provide details.expected // when it calls, it's implicit to also not show expected and diff stuff // Also, we need to check details.expected existence, as it can exist and be undefined if ( !details.result && hasOwn.call( details, "expected" ) ) { expected = escapeText( QUnit.dump.parse( details.expected ) ); actual = escapeText( QUnit.dump.parse( details.actual ) ); message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + expected + "</pre></td></tr>"; if ( actual !== expected ) { message += "<tr class='test-actual'><th>Result: </th><td><pre>" + actual + "</pre></td></tr>" + "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>"; } if ( details.source ) { message += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( details.source ) + "</pre></td></tr>"; } message += "</table>"; // this occours when pushFailure is set and we have an extracted stack trace } else if ( !details.result && details.source ) { message += "<table>" + "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( details.source ) + "</pre></td></tr>" + "</table>"; } assertList = testItem.getElementsByTagName( "ol" )[ 0 ]; assertLi = document.createElement( "li" ); assertLi.className = details.result ? "pass" : "fail"; assertLi.innerHTML = message; assertList.appendChild( assertLi ); }); QUnit.testDone(function( details ) { var testTitle, time, testItem, assertList, good, bad, testCounts, tests = id( "qunit-tests" ); // QUnit.reset() is deprecated and will be replaced for a new // fixture reset function on QUnit 2.0/2.1. // It's still called here for backwards compatibility handling QUnit.reset(); if ( !tests ) { return; } testItem = id( "qunit-test-output" + details.testNumber ); assertList = testItem.getElementsByTagName( "ol" )[ 0 ]; good = details.passed; bad = details.failed; // store result when possible if ( config.reorder && defined.sessionStorage ) { if ( bad ) { sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad ); } else { sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name ); } } if ( bad === 0 ) { addClass( assertList, "qunit-collapsed" ); } // testItem.firstChild is the test name testTitle = testItem.firstChild; testCounts = bad ? "<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " : ""; testTitle.innerHTML += " <b class='counts'>(" + testCounts + details.assertions.length + ")</b>"; addEvent( testTitle, "click", function() { toggleClass( assertList, "qunit-collapsed" ); }); time = document.createElement( "span" ); time.className = "runtime"; time.innerHTML = details.runtime + " ms"; testItem.className = bad ? "fail" : "pass"; testItem.insertBefore( time, assertList ); }); if ( !defined.document || document.readyState === "complete" ) { config.autorun = true; } if ( defined.document ) { addEvent( window, "load", QUnit.load ); } })();
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.13.2_A4.10_T1.2; * @section: 11.13.2, 11.10.2; * @assertion: The production x ^= y is the same as x = x ^ y; * @description: Type(x) and Type(y) vary between primitive number and Number object; */ //CHECK#1 x = 1; x ^= 1; if (x !== 0) { $ERROR('#1: x = 1; x ^= 1; x === 0. Actual: ' + (x)); } //CHECK#2 x = new Number(1); x ^= 1; if (x !== 0) { $ERROR('#2: x = new Number(1); x ^= 1; x === 0. Actual: ' + (x)); } //CHECK#3 x = 1; x ^= new Number(1); if (x !== 0) { $ERROR('#3: x = 1; x ^= new Number(1); x === 0. Actual: ' + (x)); } //CHECK#4 x = new Number(1); x ^= new Number(1); if (x !== 0) { $ERROR('#4: x = new Number(1); x ^= new Number(1); x === 0. Actual: ' + (x)); }
Kanboard.Screenshot = function(app) { this.app = app; this.pasteCatcher = null; }; Kanboard.Screenshot.prototype.onPopoverOpened = function() { if (this.app.hasId("screenshot-zone")) { this.initialize(); } }; // Setup event listener and workarounds Kanboard.Screenshot.prototype.initialize = function() { this.destroy(); if (! window.Clipboard) { // Create a contenteditable element this.pasteCatcher = document.createElement("div"); this.pasteCatcher.id = "screenshot-pastezone"; this.pasteCatcher.contentEditable = "true"; // Insert the content editable at the top to avoid scrolling down in the board view this.pasteCatcher.style.opacity = 0; this.pasteCatcher.style.position = "fixed"; this.pasteCatcher.style.top = 0; this.pasteCatcher.style.right = 0; this.pasteCatcher.style.width = 0; document.body.insertBefore(this.pasteCatcher, document.body.firstChild); // Set focus on the contenteditable element this.pasteCatcher.focus(); // Set the focus when clicked anywhere in the document document.addEventListener("click", this.setFocus.bind(this)); // Set the focus when clicked in screenshot dropzone (popover) document.getElementById("screenshot-zone").addEventListener("click", this.setFocus.bind(this)); } window.addEventListener("paste", this.pasteHandler.bind(this)); }; // Destroy contentEditable element Kanboard.Screenshot.prototype.destroy = function() { if (this.pasteCatcher != null) { document.body.removeChild(this.pasteCatcher); } else if (document.getElementById("screenshot-pastezone")) { document.body.removeChild(document.getElementById("screenshot-pastezone")); } document.removeEventListener("click", this.setFocus.bind(this)); this.pasteCatcher = null; }; // Set focus on contentEditable element Kanboard.Screenshot.prototype.setFocus = function() { if (this.pasteCatcher !== null) { this.pasteCatcher.focus(); } }; // Paste event callback Kanboard.Screenshot.prototype.pasteHandler = function(e) { // Firefox doesn't have the property e.clipboardData.items (only Chrome) if (e.clipboardData && e.clipboardData.items) { var items = e.clipboardData.items; if (items) { for (var i = 0; i < items.length; i++) { // Find an image in pasted elements if (items[i].type.indexOf("image") !== -1) { var blob = items[i].getAsFile(); // Get the image as base64 data var reader = new FileReader(); var self = this; reader.onload = function(event) { self.createImage(event.target.result); }; reader.readAsDataURL(blob); } } } } else { // Handle Firefox setTimeout(this.checkInput.bind(this), 100); } }; // Parse the input in the paste catcher element Kanboard.Screenshot.prototype.checkInput = function() { var child = this.pasteCatcher.childNodes[0]; if (child) { // If the user pastes an image, the src attribute // will represent the image as a base64 encoded string. if (child.tagName === "IMG") { this.createImage(child.src); } } this.pasteCatcher.innerHTML = ""; }; // Creates a new image from a given source Kanboard.Screenshot.prototype.createImage = function(blob) { var pastedImage = new Image(); pastedImage.src = blob; // Send the image content to the form variable pastedImage.onload = function() { var sourceSplit = blob.split("base64,"); var sourceString = sourceSplit[1]; $("input[name=screenshot]").val(sourceString); }; var zone = document.getElementById("screenshot-zone"); zone.innerHTML = ""; zone.className = "screenshot-pasted"; zone.appendChild(pastedImage); this.destroy(); this.initialize(); };
/* * Copyright (c) 2014 - present Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, describe, it, expect, runs, spyOn */ define(function (require, exports, module) { 'use strict'; var MainViewFactory = require("view/MainViewFactory"); describe("ViewFactory", function () { function createMockFactory() { return { canOpenFile: function (fullPath) { return (fullPath === "blah"); } }; } it("should register a factory", function () { runs(function () { var factory = createMockFactory(); spyOn(factory, "canOpenFile"); MainViewFactory.registerViewFactory(factory); MainViewFactory.findSuitableFactoryForPath(); expect(factory.canOpenFile).toHaveBeenCalled(); }); }); it("should find a factory", function () { runs(function () { var factory = createMockFactory(); MainViewFactory.registerViewFactory(factory); var result = MainViewFactory.findSuitableFactoryForPath("blah"); expect(result).toBeTruthy(); }); }); it("should not find a factory", function () { runs(function () { var factory = createMockFactory(); MainViewFactory.registerViewFactory(factory); var result = MainViewFactory.findSuitableFactoryForPath("blahblah"); expect(result).toBeFalsy(); }); }); }); });
/*! * Jade - Compiler * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var nodes = require('./nodes') , filters = require('./filters') , doctypes = require('./doctypes') , selfClosing = require('./self-closing') , utils = require('./utils'); // if browser // // if (!Object.keys) { // Object.keys = function(obj){ // var arr = []; // for (var key in obj) { // if (obj.hasOwnProperty(key)) { // arr.push(key); // } // } // return arr; // } // } // // if (!String.prototype.trimLeft) { // String.prototype.trimLeft = function(){ // return this.replace(/^\s+/, ''); // } // } // // end /** * Initialize `Compiler` with the given `node`. * * @param {Node} node * @param {Object} options * @api public */ var Compiler = module.exports = function Compiler(node, options) { this.options = options = options || {}; this.node = node; this.hasCompiledDoctype = false; this.hasCompiledTag = false; this.pp = options.pretty || false; this.debug = false !== options.compileDebug; this.indents = 0; this.parentIndents = 0; if (options.doctype) this.setDoctype(options.doctype); }; /** * Compiler prototype. */ Compiler.prototype = { /** * Compile parse tree to JavaScript. * * @api public */ compile: function(){ this.buf = ['var interp;']; if (this.pp) this.buf.push("var __indent = [];"); this.lastBufferedIdx = -1; this.visit(this.node); return this.buf.join('\n'); }, /** * Sets the default doctype `name`. Sets terse mode to `true` when * html 5 is used, causing self-closing tags to end with ">" vs "/>", * and boolean attributes are not mirrored. * * @param {string} name * @api public */ setDoctype: function(name){ var doctype = doctypes[(name || 'default').toLowerCase()]; doctype = doctype || '<!DOCTYPE ' + name + '>'; this.doctype = doctype; this.terse = '5' == name || 'html' == name; this.xml = 0 == this.doctype.indexOf('<?xml'); }, /** * Buffer the given `str` optionally escaped. * * @param {String} str * @param {Boolean} esc * @api public */ buffer: function(str, esc){ if (esc) str = utils.escape(str); if (this.lastBufferedIdx == this.buf.length) { this.lastBuffered += str; this.buf[this.lastBufferedIdx - 1] = "buf.push('" + this.lastBuffered + "');" } else { this.buf.push("buf.push('" + str + "');"); this.lastBuffered = str; this.lastBufferedIdx = this.buf.length; } }, /** * Buffer an indent based on the current `indent` * property and an additional `offset`. * * @param {Number} offset * @param {Boolean} newline * @api public */ prettyIndent: function(offset, newline){ offset = offset || 0; newline = newline ? '\\n' : ''; this.buffer(newline + Array(this.indents + offset).join(' ')); if (this.parentIndents) this.buf.push("buf.push.apply(buf, __indent);"); }, /** * Visit `node`. * * @param {Node} node * @api public */ visit: function(node){ var debug = this.debug; if (debug) { this.buf.push('__jade.unshift({ lineno: ' + node.line + ', filename: ' + (node.filename ? '"' + node.filename + '"' : '__jade[0].filename') + ' });'); } // Massive hack to fix our context // stack for - else[ if] etc if (false === node.debug && this.debug) { this.buf.pop(); this.buf.pop(); } this.visitNode(node); if (debug) this.buf.push('__jade.shift();'); }, /** * Visit `node`. * * @param {Node} node * @api public */ visitNode: function(node){ var name = node.constructor.name || node.constructor.toString().match(/function ([^(\s]+)()/)[1]; return this['visit' + name](node); }, /** * Visit case `node`. * * @param {Literal} node * @api public */ visitCase: function(node){ var _ = this.withinCase; this.withinCase = true; this.buf.push('switch (' + node.expr + '){'); this.visit(node.block); this.buf.push('}'); this.withinCase = _; }, /** * Visit when `node`. * * @param {Literal} node * @api public */ visitWhen: function(node){ if ('default' == node.expr) { this.buf.push('default:'); } else { this.buf.push('case ' + node.expr + ':'); } this.visit(node.block); this.buf.push(' break;'); }, /** * Visit literal `node`. * * @param {Literal} node * @api public */ visitLiteral: function(node){ var str = node.str.replace(/\n/g, '\\\\n'); this.buffer(str); }, /** * Visit all nodes in `block`. * * @param {Block} block * @api public */ visitBlock: function(block){ var len = block.nodes.length , escape = this.escape , pp = this.pp // Pretty print multi-line text if (pp && len > 1 && !escape && block.nodes[0].isText && block.nodes[1].isText) this.prettyIndent(1, true); for (var i = 0; i < len; ++i) { // Pretty print text if (pp && i > 0 && !escape && block.nodes[i].isText && block.nodes[i-1].isText) this.prettyIndent(1, false); this.visit(block.nodes[i]); // Multiple text nodes are separated by newlines if (block.nodes[i+1] && block.nodes[i].isText && block.nodes[i+1].isText) this.buffer('\\n'); } }, /** * Visit `doctype`. Sets terse mode to `true` when html 5 * is used, causing self-closing tags to end with ">" vs "/>", * and boolean attributes are not mirrored. * * @param {Doctype} doctype * @api public */ visitDoctype: function(doctype){ if (doctype && (doctype.val || !this.doctype)) { this.setDoctype(doctype.val || 'default'); } if (this.doctype) this.buffer(this.doctype); this.hasCompiledDoctype = true; }, /** * Visit `mixin`, generating a function that * may be called within the template. * * @param {Mixin} mixin * @api public */ visitMixin: function(mixin){ var name = mixin.name.replace(/-/g, '_') + '_mixin' , args = mixin.args || ''; if (mixin.call) { if (this.pp) this.buf.push("__indent.push('" + Array(this.indents + 1).join(' ') + "');") if (mixin.block) { if (args) { this.buf.push(name + '(' + args + ', function(){'); } else { this.buf.push(name + '(function(){'); } this.buf.push('var buf = [];'); this.visit(mixin.block); this.buf.push('return buf.join("");'); this.buf.push('}());\n'); } else { this.buf.push(name + '(' + args + ');'); } if (this.pp) this.buf.push("__indent.pop();") } else { args = args ? args.split(/ *, */).concat('content').join(', ') : 'content'; this.buf.push('var ' + name + ' = function(' + args + '){'); if (this.pp) this.parentIndents++; this.visit(mixin.block); if (this.pp) this.parentIndents--; this.buf.push('}'); } }, /** * Visit `tag` buffering tag markup, generating * attributes, visiting the `tag`'s code and block. * * @param {Tag} tag * @api public */ visitTag: function(tag){ this.indents++; var name = tag.name; if (!this.hasCompiledTag) { if (!this.hasCompiledDoctype && 'html' == name) { this.visitDoctype(); } this.hasCompiledTag = true; } // pretty print if (this.pp && !tag.isInline()) { this.prettyIndent(0, true); } if (~selfClosing.indexOf(name) && !this.xml) { this.buffer('<' + name); this.visitAttributes(tag.attrs); this.terse ? this.buffer('>') : this.buffer('/>'); } else { // Optimize attributes buffering if (tag.attrs.length) { this.buffer('<' + name); if (tag.attrs.length) this.visitAttributes(tag.attrs); this.buffer('>'); } else { this.buffer('<' + name + '>'); } if (tag.code) this.visitCode(tag.code); this.escape = 'pre' == tag.name; this.visit(tag.block); // pretty print if (this.pp && !tag.isInline() && 'pre' != tag.name && !tag.canInline()) { this.prettyIndent(0, true); } this.buffer('</' + name + '>'); } this.indents--; }, /** * Visit `filter`, throwing when the filter does not exist. * * @param {Filter} filter * @api public */ visitFilter: function(filter){ var fn = filters[filter.name]; // unknown filter if (!fn) { if (filter.isASTFilter) { throw new Error('unknown ast filter "' + filter.name + ':"'); } else { throw new Error('unknown filter ":' + filter.name + '"'); } } if (filter.isASTFilter) { this.buf.push(fn(filter.block, this, filter.attrs)); } else { var text = filter.block.nodes.map(function(node){ return node.val }).join('\n'); filter.attrs = filter.attrs || {}; filter.attrs.filename = this.options.filename; this.buffer(utils.text(fn(text, filter.attrs))); } }, /** * Visit `text` node. * * @param {Text} text * @api public */ visitText: function(text){ text = utils.text(text.val); if (this.escape) text = escape(text); this.buffer(text); }, /** * Visit a `comment`, only buffering when the buffer flag is set. * * @param {Comment} comment * @api public */ visitComment: function(comment){ if (!comment.buffer) return; if (this.pp) this.prettyIndent(1, true); this.buffer('<!--' + utils.escape(comment.val) + '-->'); }, /** * Visit a `BlockComment`. * * @param {Comment} comment * @api public */ visitBlockComment: function(comment){ if (!comment.buffer) return; if (0 == comment.val.trim().indexOf('if')) { this.buffer('<!--[' + comment.val.trim() + ']>'); this.visit(comment.block); this.buffer('<![endif]-->'); } else { this.buffer('<!--' + comment.val); this.visit(comment.block); this.buffer('-->'); } }, /** * Visit `code`, respecting buffer / escape flags. * If the code is followed by a block, wrap it in * a self-calling function. * * @param {Code} code * @api public */ visitCode: function(code){ // Wrap code blocks with {}. // we only wrap unbuffered code blocks ATM // since they are usually flow control // Buffer code if (code.buffer) { var val = code.val.trimLeft(); this.buf.push('var __val__ = ' + val); val = 'null == __val__ ? "" : __val__'; if (code.escape) val = 'escape(' + val + ')'; this.buf.push("buf.push(" + val + ");"); } else { this.buf.push(code.val); } // Block support if (code.block) { if (!code.buffer) this.buf.push('{'); this.visit(code.block); if (!code.buffer) this.buf.push('}'); } }, /** * Visit `each` block. * * @param {Each} each * @api public */ visitEach: function(each){ this.buf.push('' + '// iterate ' + each.obj + '\n' + ';(function(){\n' + ' if (\'number\' == typeof ' + each.obj + '.length) {\n' + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); this.visit(each.block); this.buf.push('' + ' }\n' + ' } else {\n' + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' // if browser // + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' // end + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); this.visit(each.block); // if browser // this.buf.push(' }\n'); // end this.buf.push(' }\n }\n}).call(this);\n'); }, /** * Visit `attrs`. * * @param {Array} attrs * @api public */ visitAttributes: function(attrs){ var buf = [] , classes = [] , escaped = {}; if (this.terse) buf.push('terse: true'); attrs.forEach(function(attr){ escaped[attr.name] = attr.escaped; if (attr.name == 'class') { classes.push('(' + attr.val + ')'); } else { var pair = "'" + attr.name + "':(" + attr.val + ')'; buf.push(pair); } }); if (classes.length) { classes = classes.join(" + ' ' + "); buf.push("class: " + classes); } buf = buf.join(', ').replace('class:', '"class":'); this.buf.push("buf.push(attrs({ " + buf + " }, " + JSON.stringify(escaped) + "));"); } }; /** * Escape the given string of `html`. * * @param {String} html * @return {String} * @api private */ function escape(html){ return String(html) .replace(/&(?!\w+;)/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); }
#!/usr/bin/env node "use strict"; /* eslint-disable no-console */ const consoleReporter = require("./console-reporter"); const pathToSuites = require("./path-to-suites"); const benchmarks = require("."); const fs = require("fs"); const path = require("path"); const toFileUrl = require("../lib/jsdom/utils").toFileUrl; const optimist = require("optimist") .usage("Run the jsdom benchmark suite") .alias("s", "suites") .string("s") .describe("s", "suites that you want to run. ie: -s dom/construction/createElement,dom/foo") .describe("bundle", "generate the JavaScript bundle required to run benchmarks in a browser") .alias("h", "help") .describe("h", "show the help"); if (optimist.argv.help) { optimist.showHelp(); return; } if (optimist.argv.bundle) { const bundle = require("browserify")({ debug: true }); bundle.require(path.resolve(__dirname, ".."), { expose: "jsdom" }); bundle.require(path.resolve(__dirname, "browser-runner.js"), { expose: "jsdom-browser-runner" }); bundle.bundle() .pipe(fs.createWriteStream(path.resolve(__dirname, "browser-bundle.js"))) .on("finish", () => { console.info("Open the following page in Chrome to begin benchmarking:", toFileUrl(path.resolve(__dirname, "browser-runner.html"))); }); return; } let suitesToRun; if (optimist.argv.suites) { suitesToRun = pathToSuites(benchmarks, optimist.argv.suites.trim().split(/,/)); } else { suitesToRun = pathToSuites(benchmarks); } suitesToRun.forEach(consoleReporter); function runNext() { /* eslint-disable no-invalid-this */ if (this && this.off) { // there is no .once() this.off("complete", runNext); } /* eslint-enable no-invalid-this */ const suite = suitesToRun.shift(); if (!suite) { console.log("Done!"); return; } suite.off("complete", runNext); suite.on("complete", runNext); suite.run({ async: true }); } runNext();
var express = require('express'); var router = express.Router(); var util = require('util'); var constants = require('../util/constants'); var utils = require('../util/utils') var string = function (coverage) { var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjQ="; var base64UrlString = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw"; router.put('/:scenario', function (req, res, next) { if (req.params.scenario === 'null') { if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage['putStringNull']++; res.status(200).end(); } else { utils.send400(res, next, "Did not like null req '" + util.inspect(req) + "'"); } } else if (req.params.scenario === 'empty') { if (req.body !== '') { utils.send400(res, next, "Did not like empty req '" + util.inspect(req.body) + "'"); } else { coverage['putStringEmpty']++; res.status(200).end(); } } else if (req.params.scenario === 'mbcs') { if (req.body !== constants.MULTIBYTE_BUFFER_BODY) { utils.send400(res, next, "Did not like mbcs req '" + util.inspect(req.body) + "'"); } else { coverage['putStringMultiByteCharacters']++; res.status(200).end(); } } else if (req.params.scenario === 'whitespace') { if (req.body !== ' Now is the time for all good men to come to the aid of their country ') { utils.send400(res, next, "Did not like whitespace req '" + util.inspect(req.body) + "'"); } else { coverage['putStringWithLeadingAndTrailingWhitespace']++; res.status(200).end(); } } else if (req.params.scenario === 'base64UrlEncoding') { if (req.body !== 'YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw') { utils.send400(res, next, "Did not like base64url req '" + util.inspect(req.body) + "'"); } else { coverage['putStringBase64UrlEncoded']++; res.status(200).end(); } } else { utils.send400(res, next, 'Request path must contain true or false'); } }); router.get('/:scenario', function (req, res, next) { if (req.params.scenario === 'null') { coverage['getStringNull']++; res.status(200).end(); } else if (req.params.scenario === 'base64Encoding') { coverage['getStringBase64Encoded']++; res.status(200).end('"' + base64String + '"'); } else if (req.params.scenario === 'base64UrlEncoding') { coverage['getStringBase64UrlEncoded']++; res.status(200).end('"' + base64UrlString + '"'); } else if (req.params.scenario === 'nullBase64UrlEncoding') { coverage['getStringNullBase64UrlEncoding']++; res.status(200).end(); } else if (req.params.scenario === 'notProvided') { coverage['getStringNotProvided']++; res.status(200).end(); } else if (req.params.scenario === 'empty') { coverage['getStringEmpty']++; res.status(200).end('\"\"'); } else if (req.params.scenario === 'mbcs') { coverage['getStringMultiByteCharacters']++; res.status(200).end('"' + constants.MULTIBYTE_BUFFER_BODY + '"'); } else if (req.params.scenario === 'whitespace') { coverage['getStringWithLeadingAndTrailingWhitespace']++; res.status(200).end('\" Now is the time for all good men to come to the aid of their country \"'); } else { res.status(400).end('Request path must contain null or empty or mbcs or whitespace'); } }); router.get('/enum/notExpandable', function (req, res, next) { coverage['getEnumNotExpandable']++; res.status(200).end('"red color"'); }); router.put('/enum/notExpandable', function (req, res, next) { if (req.body === 'red color') { coverage['putEnumNotExpandable']++; res.status(200).end(); } else { utils.send400(res, next, "Did not like enum in the req '" + util.inspect(req.body) + "'"); } }); } string.prototype.router = router; module.exports = string;
/** * @author sunag / http://www.sunag.com.br/ */ import { FloatNode } from '../inputs/FloatNode.js'; import { NodeLib } from '../core/NodeLib.js'; function TimerNode( scale, scope, timeScale ) { FloatNode.call( this ); this.scale = scale !== undefined ? scale : 1; this.scope = scope || TimerNode.GLOBAL; this.timeScale = timeScale !== undefined ? timeScale : scale !== undefined; } TimerNode.GLOBAL = 'global'; TimerNode.LOCAL = 'local'; TimerNode.DELTA = 'delta'; TimerNode.prototype = Object.create( FloatNode.prototype ); TimerNode.prototype.constructor = TimerNode; TimerNode.prototype.nodeType = "Timer"; TimerNode.prototype.getReadonly = function () { // never use TimerNode as readonly but aways as "uniform" return false; }; TimerNode.prototype.getUnique = function () { // share TimerNode "uniform" input if is used on more time with others TimerNode return this.timeScale && ( this.scope === TimerNode.GLOBAL || this.scope === TimerNode.DELTA ); }; TimerNode.prototype.updateFrame = function ( frame ) { var scale = this.timeScale ? this.scale : 1; switch ( this.scope ) { case TimerNode.LOCAL: this.value += frame.delta * scale; break; case TimerNode.DELTA: this.value = frame.delta * scale; break; default: this.value = frame.time * scale; } }; TimerNode.prototype.copy = function ( source ) { FloatNode.prototype.copy.call( this, source ); this.scope = source.scope; this.scale = source.scale; this.timeScale = source.timeScale; }; TimerNode.prototype.toJSON = function ( meta ) { var data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); data.scope = this.scope; data.scale = this.scale; data.timeScale = this.timeScale; } return data; }; NodeLib.addKeyword( 'time', function () { return new TimerNode(); } ); export { TimerNode };
#!/usr/bin/env node const path = require('path'); const fs = require('fs'); const GitHubApi = require('github'); const github = new GitHubApi(); /** CONFIGURATION: change these things if you want to tweak how the runs are made. */ /** Path to the local material2. By default based on the location of this script. */ const localRepo = path.resolve(__dirname, '..', '..'); /** Where to write the output from the presubmit script. */ const logDir = '/tmp/pr-presubmit-logs'; /** * The presubmit script to use (can change this if you want to use a locally modified script). * The default path is stored in an environment variable because it references an internal-Google * location. */ const presubmitScript = `${process.env.MAT_PRESUBMIT_DIR}/material-presubmit.sh`; /** Time to start presubmits. */ const startTime = '9:30 pm'; /** Number of minutes between presubmit runs. */ const intervalMinutes = 10; /** Instead of querying github for PR numbers, manually provide the PR numbers to be presubmit */ const explicitPullRequests = []; /** END OF CONFIGURATION. */ /** Number of intervals that have scheduled tasks already. */ let presubmitCount = 0; if (explicitPullRequests.length) { writeScheduleScript(explicitPullRequests.map(n => ({number: n}))); } else { // Fetch PRs that are merge-ready but not merge-safe github.search.issues({ per_page: 100, q: 'repo:angular/material2 is:open type:pr label:"pr: merge ready" -label:"pr: merge safe"', }, (error, response) => { if (response) { writeScheduleScript(response.data.items); } else { console.error('Fetching merge-ready PRs failed.'); console.error(error); } }); } function writeScheduleScript(prs) { let script = `#!/bin/bash \n\n` + `mkdir -p ${logDir} \n\n` + `# Be sure you have no locally modified files in your git client before running this. \n\n`; // Generate a command for each file to be piped into the `at` command, scheduling it to run at // a later time. for (const pr of prs) { script += `echo '(` + `cd ${localRepo} ; ` + `${presubmitScript} ${pr.number} --global 2>&1 > ${logDir}/pr-${pr.number}.txt ` + `)' | ` + `at ${startTime} today + ${intervalMinutes * presubmitCount} min ` + `\n`; presubmitCount++; } fs.writeFileSync(path.join(localRepo, 'dist', 'schedule-presubmit.sh'), script, 'utf-8'); console.log('schedule-presubmit.sh written to dist'); console.log('Be sure to prodaccess overnight and that you have no locally modified files'); }
/** * @fileoverview Tests for no-caller rule. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/no-caller"), { RuleTester } = require("../../../lib/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const ruleTester = new RuleTester(); ruleTester.run("no-caller", rule, { valid: [ "var x = arguments.length", "var x = arguments", "var x = arguments[0]", "var x = arguments[caller]" ], invalid: [ { code: "var x = arguments.callee", errors: [{ messageId: "unexpected", data: { prop: "callee" }, type: "MemberExpression" }] }, { code: "var x = arguments.caller", errors: [{ messageId: "unexpected", data: { prop: "caller" }, type: "MemberExpression" }] } ] });
import NotFound from './NotFound' export default NotFound
/** * @author alteredq / http://alteredqualia.com/ */ import { Box3, MathUtils, MeshLambertMaterial, Object3D, TextureLoader, UVMapping, sRGBEncoding } from "../../../build/three.module.js"; import { MD2Loader } from "../loaders/MD2Loader.js"; import { MorphBlendMesh } from "../misc/MorphBlendMesh.js"; var MD2CharacterComplex = function () { var scope = this; this.scale = 1; // animation parameters this.animationFPS = 6; this.transitionFrames = 15; // movement model parameters this.maxSpeed = 275; this.maxReverseSpeed = - 275; this.frontAcceleration = 600; this.backAcceleration = 600; this.frontDecceleration = 600; this.angularSpeed = 2.5; // rig this.root = new Object3D(); this.meshBody = null; this.meshWeapon = null; this.controls = null; // skins this.skinsBody = []; this.skinsWeapon = []; this.weapons = []; this.currentSkin = undefined; // this.onLoadComplete = function () {}; // internals this.meshes = []; this.animations = {}; this.loadCounter = 0; // internal movement control variables this.speed = 0; this.bodyOrientation = 0; this.walkSpeed = this.maxSpeed; this.crouchSpeed = this.maxSpeed * 0.5; // internal animation parameters this.activeAnimation = null; this.oldAnimation = null; // API this.enableShadows = function ( enable ) { for ( var i = 0; i < this.meshes.length; i ++ ) { this.meshes[ i ].castShadow = enable; this.meshes[ i ].receiveShadow = enable; } }; this.setVisible = function ( enable ) { for ( var i = 0; i < this.meshes.length; i ++ ) { this.meshes[ i ].visible = enable; this.meshes[ i ].visible = enable; } }; this.shareParts = function ( original ) { this.animations = original.animations; this.walkSpeed = original.walkSpeed; this.crouchSpeed = original.crouchSpeed; this.skinsBody = original.skinsBody; this.skinsWeapon = original.skinsWeapon; // BODY var mesh = createPart( original.meshBody.geometry, this.skinsBody[ 0 ] ); mesh.scale.set( this.scale, this.scale, this.scale ); this.root.position.y = original.root.position.y; this.root.add( mesh ); this.meshBody = mesh; this.meshes.push( mesh ); // WEAPONS for ( var i = 0; i < original.weapons.length; i ++ ) { var meshWeapon = createPart( original.weapons[ i ].geometry, this.skinsWeapon[ i ] ); meshWeapon.scale.set( this.scale, this.scale, this.scale ); meshWeapon.visible = false; meshWeapon.name = original.weapons[ i ].name; this.root.add( meshWeapon ); this.weapons[ i ] = meshWeapon; this.meshWeapon = meshWeapon; this.meshes.push( meshWeapon ); } }; this.loadParts = function ( config ) { this.animations = config.animations; this.walkSpeed = config.walkSpeed; this.crouchSpeed = config.crouchSpeed; this.loadCounter = config.weapons.length * 2 + config.skins.length + 1; var weaponsTextures = []; for ( var i = 0; i < config.weapons.length; i ++ ) weaponsTextures[ i ] = config.weapons[ i ][ 1 ]; // SKINS this.skinsBody = loadTextures( config.baseUrl + "skins/", config.skins ); this.skinsWeapon = loadTextures( config.baseUrl + "skins/", weaponsTextures ); // BODY var loader = new MD2Loader(); loader.load( config.baseUrl + config.body, function ( geo ) { var boundingBox = new Box3(); boundingBox.setFromBufferAttribute( geo.attributes.position ); scope.root.position.y = - scope.scale * boundingBox.min.y; var mesh = createPart( geo, scope.skinsBody[ 0 ] ); mesh.scale.set( scope.scale, scope.scale, scope.scale ); scope.root.add( mesh ); scope.meshBody = mesh; scope.meshes.push( mesh ); checkLoadingComplete(); } ); // WEAPONS var generateCallback = function ( index, name ) { return function ( geo ) { var mesh = createPart( geo, scope.skinsWeapon[ index ] ); mesh.scale.set( scope.scale, scope.scale, scope.scale ); mesh.visible = false; mesh.name = name; scope.root.add( mesh ); scope.weapons[ index ] = mesh; scope.meshWeapon = mesh; scope.meshes.push( mesh ); checkLoadingComplete(); }; }; for ( var i = 0; i < config.weapons.length; i ++ ) { loader.load( config.baseUrl + config.weapons[ i ][ 0 ], generateCallback( i, config.weapons[ i ][ 0 ] ) ); } }; this.setPlaybackRate = function ( rate ) { if ( this.meshBody ) this.meshBody.duration = this.meshBody.baseDuration / rate; if ( this.meshWeapon ) this.meshWeapon.duration = this.meshWeapon.baseDuration / rate; }; this.setWireframe = function ( wireframeEnabled ) { if ( wireframeEnabled ) { if ( this.meshBody ) this.meshBody.material = this.meshBody.materialWireframe; if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialWireframe; } else { if ( this.meshBody ) this.meshBody.material = this.meshBody.materialTexture; if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialTexture; } }; this.setSkin = function ( index ) { if ( this.meshBody && this.meshBody.material.wireframe === false ) { this.meshBody.material.map = this.skinsBody[ index ]; this.currentSkin = index; } }; this.setWeapon = function ( index ) { for ( var i = 0; i < this.weapons.length; i ++ ) this.weapons[ i ].visible = false; var activeWeapon = this.weapons[ index ]; if ( activeWeapon ) { activeWeapon.visible = true; this.meshWeapon = activeWeapon; if ( this.activeAnimation ) { activeWeapon.playAnimation( this.activeAnimation ); this.meshWeapon.setAnimationTime( this.activeAnimation, this.meshBody.getAnimationTime( this.activeAnimation ) ); } } }; this.setAnimation = function ( animationName ) { if ( animationName === this.activeAnimation || ! animationName ) return; if ( this.meshBody ) { this.meshBody.setAnimationWeight( animationName, 0 ); this.meshBody.playAnimation( animationName ); this.oldAnimation = this.activeAnimation; this.activeAnimation = animationName; this.blendCounter = this.transitionFrames; } if ( this.meshWeapon ) { this.meshWeapon.setAnimationWeight( animationName, 0 ); this.meshWeapon.playAnimation( animationName ); } }; this.update = function ( delta ) { if ( this.controls ) this.updateMovementModel( delta ); if ( this.animations ) { this.updateBehaviors(); this.updateAnimations( delta ); } }; this.updateAnimations = function ( delta ) { var mix = 1; if ( this.blendCounter > 0 ) { mix = ( this.transitionFrames - this.blendCounter ) / this.transitionFrames; this.blendCounter -= 1; } if ( this.meshBody ) { this.meshBody.update( delta ); this.meshBody.setAnimationWeight( this.activeAnimation, mix ); this.meshBody.setAnimationWeight( this.oldAnimation, 1 - mix ); } if ( this.meshWeapon ) { this.meshWeapon.update( delta ); this.meshWeapon.setAnimationWeight( this.activeAnimation, mix ); this.meshWeapon.setAnimationWeight( this.oldAnimation, 1 - mix ); } }; this.updateBehaviors = function () { var controls = this.controls; var animations = this.animations; var moveAnimation, idleAnimation; // crouch vs stand if ( controls.crouch ) { moveAnimation = animations[ "crouchMove" ]; idleAnimation = animations[ "crouchIdle" ]; } else { moveAnimation = animations[ "move" ]; idleAnimation = animations[ "idle" ]; } // actions if ( controls.jump ) { moveAnimation = animations[ "jump" ]; idleAnimation = animations[ "jump" ]; } if ( controls.attack ) { if ( controls.crouch ) { moveAnimation = animations[ "crouchAttack" ]; idleAnimation = animations[ "crouchAttack" ]; } else { moveAnimation = animations[ "attack" ]; idleAnimation = animations[ "attack" ]; } } // set animations if ( controls.moveForward || controls.moveBackward || controls.moveLeft || controls.moveRight ) { if ( this.activeAnimation !== moveAnimation ) { this.setAnimation( moveAnimation ); } } if ( Math.abs( this.speed ) < 0.2 * this.maxSpeed && ! ( controls.moveLeft || controls.moveRight || controls.moveForward || controls.moveBackward ) ) { if ( this.activeAnimation !== idleAnimation ) { this.setAnimation( idleAnimation ); } } // set animation direction if ( controls.moveForward ) { if ( this.meshBody ) { this.meshBody.setAnimationDirectionForward( this.activeAnimation ); this.meshBody.setAnimationDirectionForward( this.oldAnimation ); } if ( this.meshWeapon ) { this.meshWeapon.setAnimationDirectionForward( this.activeAnimation ); this.meshWeapon.setAnimationDirectionForward( this.oldAnimation ); } } if ( controls.moveBackward ) { if ( this.meshBody ) { this.meshBody.setAnimationDirectionBackward( this.activeAnimation ); this.meshBody.setAnimationDirectionBackward( this.oldAnimation ); } if ( this.meshWeapon ) { this.meshWeapon.setAnimationDirectionBackward( this.activeAnimation ); this.meshWeapon.setAnimationDirectionBackward( this.oldAnimation ); } } }; this.updateMovementModel = function ( delta ) { var controls = this.controls; // speed based on controls if ( controls.crouch ) this.maxSpeed = this.crouchSpeed; else this.maxSpeed = this.walkSpeed; this.maxReverseSpeed = - this.maxSpeed; if ( controls.moveForward ) this.speed = MathUtils.clamp( this.speed + delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed ); if ( controls.moveBackward ) this.speed = MathUtils.clamp( this.speed - delta * this.backAcceleration, this.maxReverseSpeed, this.maxSpeed ); // orientation based on controls // (don't just stand while turning) var dir = 1; if ( controls.moveLeft ) { this.bodyOrientation += delta * this.angularSpeed; this.speed = MathUtils.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed ); } if ( controls.moveRight ) { this.bodyOrientation -= delta * this.angularSpeed; this.speed = MathUtils.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed ); } // speed decay if ( ! ( controls.moveForward || controls.moveBackward ) ) { if ( this.speed > 0 ) { var k = exponentialEaseOut( this.speed / this.maxSpeed ); this.speed = MathUtils.clamp( this.speed - k * delta * this.frontDecceleration, 0, this.maxSpeed ); } else { var k = exponentialEaseOut( this.speed / this.maxReverseSpeed ); this.speed = MathUtils.clamp( this.speed + k * delta * this.backAcceleration, this.maxReverseSpeed, 0 ); } } // displacement var forwardDelta = this.speed * delta; this.root.position.x += Math.sin( this.bodyOrientation ) * forwardDelta; this.root.position.z += Math.cos( this.bodyOrientation ) * forwardDelta; // steering this.root.rotation.y = this.bodyOrientation; }; // internal helpers function loadTextures( baseUrl, textureUrls ) { var textureLoader = new TextureLoader(); var textures = []; for ( var i = 0; i < textureUrls.length; i ++ ) { textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], checkLoadingComplete ); textures[ i ].mapping = UVMapping; textures[ i ].name = textureUrls[ i ]; textures[ i ].encoding = sRGBEncoding; } return textures; } function createPart( geometry, skinMap ) { var materialWireframe = new MeshLambertMaterial( { color: 0xffaa00, wireframe: true, morphTargets: true, morphNormals: true } ); var materialTexture = new MeshLambertMaterial( { color: 0xffffff, wireframe: false, map: skinMap, morphTargets: true, morphNormals: true } ); // var mesh = new MorphBlendMesh( geometry, materialTexture ); mesh.rotation.y = - Math.PI / 2; // mesh.materialTexture = materialTexture; mesh.materialWireframe = materialWireframe; // mesh.autoCreateAnimations( scope.animationFPS ); return mesh; } function checkLoadingComplete() { scope.loadCounter -= 1; if ( scope.loadCounter === 0 ) scope.onLoadComplete(); } function exponentialEaseOut( k ) { return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1; } }; export { MD2CharacterComplex };
!function(t){t.LiquidDistortMaterial=function(){t.Material.apply(this,arguments)},t.LiquidDistortMaterial.prototype=Object.create(t.Material.prototype),t._extendWithGettersSetters(t.LiquidDistortMaterial.prototype,{constructor:t.LiquidDistortMaterial,init:function(){this.mainImage=[t.Assets.Shaders.Noise3D,"void mainImage( out vec4 mainImage, in vec2 fragCoord )","{"," // Setup ========================================================================"," vec2 uv = fragCoord.xy / uResolution.xy;"," float z = uSeed + uGlobalTime * uSpeed;"," uv += snoise(vec3(uv, z)) * uVolatility;"," mainImage = textTexture(uv);","}"].join("\n"),this.uniforms={uSpeed:{type:"1f",value:1},uVolatility:{type:"1f",value:.15},uSeed:{type:"1f",value:.1}}}})}(this.Blotter);
Object_shallowCopyFrom_(Array.prototype,{ asPath: function() { return this.join("/"); } });
var api = { pageVisited: function(info) { Triggers.processRequest(info); Meteor.call('livechat:pageVisited', visitor.getToken(), info); } }; window.addEventListener('message', function(msg) { if (typeof msg.data === 'object' && msg.data.src !== undefined && msg.data.src === 'rocketchat') { if (api[msg.data.fn] !== undefined && typeof api[msg.data.fn] === 'function') { var args = [].concat(msg.data.args || []) api[msg.data.fn].apply(null, args); } } }, false); // tell parent window that we are ready Meteor.startup(function() { parentCall('ready'); });
var request = require('supertest'); var app = require('./index.js'); describe('Templating', function () { it('should return the template', function (done) { var html = '<!DOCTYPE html><head><html><title>Koa Templating</title></html><body><p>Hello!</p></body></head>'; request(app.listen()) .get('/') .expect(200) .expect('Content-Type', /text\/html/) .expect(html, done); }) })
"use strict"; var core_1 = require('@angular/core'); var NgTranscludeDirective = (function () { function NgTranscludeDirective(_viewRef) { this._viewRef = _viewRef; this.viewRef = _viewRef; } Object.defineProperty(NgTranscludeDirective.prototype, "ngTransclude", { get: function () { return this._ngTransclude; }, set: function (templateRef) { this._ngTransclude = templateRef; if (templateRef) { this.viewRef.createEmbeddedView(templateRef); } }, enumerable: true, configurable: true }); NgTranscludeDirective.decorators = [ { type: core_1.Directive, args: [{ selector: '[ngTransclude]' },] }, ]; /** @nocollapse */ NgTranscludeDirective.ctorParameters = [ { type: core_1.ViewContainerRef, }, ]; NgTranscludeDirective.propDecorators = { 'ngTransclude': [{ type: core_1.Input },], }; return NgTranscludeDirective; }()); exports.NgTranscludeDirective = NgTranscludeDirective;
dojo.provide("dojo.tests.aspect"); var aspect = dojo.require("dojo.aspect"); doh.register("tests.aspect", [ function before(t){ var order = []; var obj = { method: function(a){ order.push(a); } }; var signal = aspect.before(obj, "method", function(a){ order.push(a); return [a+1]; }); obj.method(0); obj.method(2); var signal2 = aspect.before(obj, "method", function(a){ order.push(a); return [a+1]; }); obj.method(4); signal.remove(); obj.method(7); signal2.remove(); obj.method(9); t.is(order, [0,1,2,3,4,5,6,7,8,9]); }, function after(t){ var order = []; var obj = { method: function(a){ order.push(a); return a+1; } }; var signal = aspect.after(obj, "method", function(a){ order.push(0); return a+1; }); obj.method(0); // 0, 0 var signal2 = aspect.after(obj, "method", function(a){ order.push(a); }); obj.method(3); // 3, 0, 5 var signal3 = aspect.after(obj, "method", function(a){ order.push(3); }, true); obj.method(3); // 3, 0, 5, 3 signal2.remove(); obj.method(6); // 6, 0, 3 signal3.remove(); var signal4 = aspect.after(obj, "method", function(a){ order.push(4); }, true); signal.remove(); obj.method(7); // 7, 4 signal4.remove(); var signal5 = aspect.after(obj, "method", function(a){ order.push(a); aspect.after(obj, "method", function(a){ order.push(a); }); aspect.after(obj, "method", function(a){ order.push(a); }).remove(); return a+1; }); var signal6 = aspect.after(obj, "method", function(a){ order.push(a); return a+2; }); obj.method(8); // 8, 9, 10 obj.method(8); // 8, 9, 10, 12 t.is([0, 0, 3, 0, 5, 3, 0, 5, 3, 6, 0, 3, 7, 4, 8, 9, 10, 8, 9, 10, 12], order); obj = {method: function(){}}; aspect.after(obj, "method", function(){ return false; }, true); t.t(obj.method() === false); }, function around(t){ var order = []; var obj = { method: function(a){ order.push(a); return a+1; } }; var beforeSignal = aspect.before(obj, "method", function(a){ order.push(a); }); var signal = aspect.around(obj, "method", function(original){ return function(a){ a= a + 1; a = original(a); order.push(a); return a+1; }; }); order.push(obj.method(0)); obj.method(4); t.is(order, [0,1,2,3,4,5,6]); }, function delegation(t){ var order = []; var proto = { foo: function(x){ order.push(x); return x; }, bar: function(){ } }; aspect.after(proto, "foo", function(x){ order.push(x + 1); return x; }); aspect.after(proto, "bar", function(x){ t.t(this.isInstance); }); proto.foo(0); function Class(){ } Class.prototype = proto; var instance = new Class(); instance.isInstance = true; aspect.after(instance, "foo", function(x){ order.push(x + 2); return x; }); instance.bar(); instance.foo(2); proto.foo(5); t.is(order, [0,1,2,3,4,5,6]); } ] );
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ Ext.define('ExtThemeNeptune.panel.Tool', { override: 'Ext.panel.Tool', height: 16, width: 16 });
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["jsonld"] = factory(); else root["jsonld"] = factory(); })(typeof self !== 'undefined' ? self : this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 73); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(38)('wks'); var uid = __webpack_require__(20); var Symbol = __webpack_require__(1).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 1 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var graphTypes = __webpack_require__(5); var types = __webpack_require__(4); // TODO: move `IdentifierIssuer` to its own package var IdentifierIssuer = __webpack_require__(45).IdentifierIssuer; var JsonLdError = __webpack_require__(6); // constants var REGEX_LINK_HEADERS = /(?:<[^>]*?>|"[^"]*?"|[^,])+/g; var REGEX_LINK_HEADER = /\s*<([^>]*?)>\s*(?:;\s*(.*))?/; var REGEX_LINK_HEADER_PARAMS = /(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g; var DEFAULTS = { headers: { accept: 'application/ld+json, application/json' } }; var api = {}; module.exports = api; api.IdentifierIssuer = IdentifierIssuer; // define setImmediate and nextTick //// nextTick implementation with browser-compatible fallback //// // from https://github.com/caolan/async/blob/master/lib/async.js // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? // not a direct alias (for IE10 compatibility) function (fn) { return _setImmediate(fn); } : function (fn) { return setTimeout(fn, 0); }; if ((typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && typeof process.nextTick === 'function') { api.nextTick = process.nextTick; } else { api.nextTick = _delay; } api.setImmediate = _setImmediate ? _delay : api.nextTick; /** * Clones an object, array, or string/number. If a typed JavaScript object * is given, such as a Date, it will be converted to a string. * * @param value the value to clone. * * @return the cloned value. */ api.clone = function (value) { if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { var rval = void 0; if (types.isArray(value)) { rval = []; for (var i = 0; i < value.length; ++i) { rval[i] = api.clone(value[i]); } } else if (types.isObject(value)) { rval = {}; for (var key in value) { rval[key] = api.clone(value[key]); } } else { rval = value.toString(); } return rval; } return value; }; /** * Builds an HTTP headers object for making a JSON-LD request from custom * headers and asserts the `accept` header isn't overridden. * * @param headers an object of headers with keys as header names and values * as header values. * * @return an object of headers with a valid `accept` header. */ api.buildHeaders = function () { var headers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var hasAccept = Object.keys(headers).some(function (h) { return h.toLowerCase() === 'accept'; }); if (hasAccept) { throw new RangeError('Accept header may not be specified; only "' + DEFAULTS.headers.accept + '" is supported.'); } return Object.assign({ 'Accept': DEFAULTS.headers.accept }, headers); }; /** * Parses a link header. The results will be key'd by the value of "rel". * * Link: <http://json-ld.org/contexts/person.jsonld>; * rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json" * * Parses as: { * 'http://www.w3.org/ns/json-ld#context': { * target: http://json-ld.org/contexts/person.jsonld, * type: 'application/ld+json' * } * } * * If there is more than one "rel" with the same IRI, then entries in the * resulting map for that "rel" will be arrays. * * @param header the link header to parse. */ api.parseLinkHeader = function (header) { var rval = {}; // split on unbracketed/unquoted commas var entries = header.match(REGEX_LINK_HEADERS); for (var i = 0; i < entries.length; ++i) { var match = entries[i].match(REGEX_LINK_HEADER); if (!match) { continue; } var result = { target: match[1] }; var params = match[2]; while (match = REGEX_LINK_HEADER_PARAMS.exec(params)) { result[match[1]] = match[2] === undefined ? match[3] : match[2]; } var rel = result['rel'] || ''; if (Array.isArray(rval[rel])) { rval[rel].push(result); } else if (rel in rval) { rval[rel] = [rval[rel], result]; } else { rval[rel] = result; } } return rval; }; /** * Throws an exception if the given value is not a valid @type value. * * @param v the value to check. */ api.validateTypeValue = function (v) { // can be a string or an empty object if (types.isString(v) || types.isEmptyObject(v)) { return; } // must be an array var isValid = false; if (types.isArray(v)) { // must contain only strings isValid = true; for (var i = 0; i < v.length; ++i) { if (!types.isString(v[i])) { isValid = false; break; } } } if (!isValid) { throw new JsonLdError('Invalid JSON-LD syntax; "@type" value must a string, an array of ' + 'strings, or an empty object.', 'jsonld.SyntaxError', { code: 'invalid type value', value: v }); } }; /** * Returns true if the given subject has the given property. * * @param subject the subject to check. * @param property the property to look for. * * @return true if the subject has the given property, false if not. */ api.hasProperty = function (subject, property) { if (property in subject) { var value = subject[property]; return !types.isArray(value) || value.length > 0; } return false; }; /** * Determines if the given value is a property of the given subject. * * @param subject the subject to check. * @param property the property to check. * @param value the value to check. * * @return true if the value exists, false if not. */ api.hasValue = function (subject, property, value) { if (api.hasProperty(subject, property)) { var val = subject[property]; var isList = graphTypes.isList(val); if (types.isArray(val) || isList) { if (isList) { val = val['@list']; } for (var i = 0; i < val.length; ++i) { if (api.compareValues(value, val[i])) { return true; } } } else if (!types.isArray(value)) { // avoid matching the set of values with an array value parameter return api.compareValues(value, val); } } return false; }; /** * Adds a value to a subject. If the value is an array, all values in the * array will be added. * * @param subject the subject to add the value to. * @param property the property that relates the value to the subject. * @param value the value to add. * @param [options] the options to use: * [propertyIsArray] true if the property is always an array, false * if not (default: false). * [allowDuplicate] true to allow duplicates, false not to (uses a * simple shallow comparison of subject ID or value) (default: true). */ api.addValue = function (subject, property, value, options) { options = options || {}; if (!('propertyIsArray' in options)) { options.propertyIsArray = false; } if (!('allowDuplicate' in options)) { options.allowDuplicate = true; } if (types.isArray(value)) { if (value.length === 0 && options.propertyIsArray && !(property in subject)) { subject[property] = []; } for (var i = 0; i < value.length; ++i) { api.addValue(subject, property, value[i], options); } } else if (property in subject) { // check if subject already has value if duplicates not allowed var hasValue = !options.allowDuplicate && api.hasValue(subject, property, value); // make property an array if value not present or always an array if (!types.isArray(subject[property]) && (!hasValue || options.propertyIsArray)) { subject[property] = [subject[property]]; } // add new value if (!hasValue) { subject[property].push(value); } } else { // add new value as set or single value subject[property] = options.propertyIsArray ? [value] : value; } }; /** * Gets all of the values for a subject's property as an array. * * @param subject the subject. * @param property the property. * * @return all of the values for a subject's property as an array. */ api.getValues = function (subject, property) { return [].concat(subject[property] || []); }; /** * Removes a property from a subject. * * @param subject the subject. * @param property the property. */ api.removeProperty = function (subject, property) { delete subject[property]; }; /** * Removes a value from a subject. * * @param subject the subject. * @param property the property that relates the value to the subject. * @param value the value to remove. * @param [options] the options to use: * [propertyIsArray] true if the property is always an array, false * if not (default: false). */ api.removeValue = function (subject, property, value, options) { options = options || {}; if (!('propertyIsArray' in options)) { options.propertyIsArray = false; } // filter out value var values = api.getValues(subject, property).filter(function (e) { return !api.compareValues(e, value); }); if (values.length === 0) { api.removeProperty(subject, property); } else if (values.length === 1 && !options.propertyIsArray) { subject[property] = values[0]; } else { subject[property] = values; } }; /** * Relabels all blank nodes in the given JSON-LD input. * * @param input the JSON-LD input. * @param [options] the options to use: * [issuer] an IdentifierIssuer to use to label blank nodes. */ api.relabelBlankNodes = function (input, options) { options = options || {}; var issuer = options.issuer || new IdentifierIssuer('_:b'); return _labelBlankNodes(issuer, input); }; /** * Compares two JSON-LD values for equality. Two JSON-LD values will be * considered equal if: * * 1. They are both primitives of the same type and value. * 2. They are both @values with the same @value, @type, @language, * and @index, OR * 3. They both have @ids they are the same. * * @param v1 the first value. * @param v2 the second value. * * @return true if v1 and v2 are considered equal, false if not. */ api.compareValues = function (v1, v2) { // 1. equal primitives if (v1 === v2) { return true; } // 2. equal @values if (graphTypes.isValue(v1) && graphTypes.isValue(v2) && v1['@value'] === v2['@value'] && v1['@type'] === v2['@type'] && v1['@language'] === v2['@language'] && v1['@index'] === v2['@index']) { return true; } // 3. equal @ids if (types.isObject(v1) && '@id' in v1 && types.isObject(v2) && '@id' in v2) { return v1['@id'] === v2['@id']; } return false; }; /** * Compares two strings first based on length and then lexicographically. * * @param a the first string. * @param b the second string. * * @return -1 if a < b, 1 if a > b, 0 if a == b. */ api.compareShortestLeast = function (a, b) { if (a.length < b.length) { return -1; } if (b.length < a.length) { return 1; } if (a === b) { return 0; } return a < b ? -1 : 1; }; api.normalizeDocumentLoader = function (fn) { if (fn.length < 2) { return api.callbackify(fn); } return function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) { var callback, _args = arguments; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: callback = _args[1]; return _context.abrupt('return', new Promise(function (resolve, reject) { try { fn(url, function (err, remoteDoc) { if (typeof callback === 'function') { return _invokeCallback(callback, err, remoteDoc); } else if (err) { reject(err); } else { resolve(remoteDoc); } }); } catch (e) { if (typeof callback === 'function') { return _invokeCallback(callback, e); } reject(e); } })); case 2: case 'end': return _context.stop(); } } }, _callee, this); })); return function (_x2) { return _ref.apply(this, arguments); }; }(); }; api.callbackify = function (fn) { return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var callback, result; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: callback = args[args.length - 1]; if (typeof callback === 'function') { args.pop(); } result = void 0; _context2.prev = 3; _context2.next = 6; return fn.apply(null, args); case 6: result = _context2.sent; _context2.next = 14; break; case 9: _context2.prev = 9; _context2.t0 = _context2['catch'](3); if (!(typeof callback === 'function')) { _context2.next = 13; break; } return _context2.abrupt('return', _invokeCallback(callback, _context2.t0)); case 13: throw _context2.t0; case 14: if (!(typeof callback === 'function')) { _context2.next = 16; break; } return _context2.abrupt('return', _invokeCallback(callback, null, result)); case 16: return _context2.abrupt('return', result); case 17: case 'end': return _context2.stop(); } } }, _callee2, this, [[3, 9]]); })); }; function _invokeCallback(callback, err, result) { // execute on next tick to prevent "unhandled rejected promise" // and simulate what would have happened in a promiseless API api.nextTick(function () { return callback(err, result); }); } /** * Labels the blank nodes in the given value using the given IdentifierIssuer. * * @param issuer the IdentifierIssuer to use. * @param element the element with blank nodes to rename. * * @return the element. */ function _labelBlankNodes(issuer, element) { if (types.isArray(element)) { for (var i = 0; i < element.length; ++i) { element[i] = _labelBlankNodes(issuer, element[i]); } } else if (graphTypes.isList(element)) { element['@list'] = _labelBlankNodes(issuer, element['@list']); } else if (types.isObject(element)) { // relabel blank node if (graphTypes.isBlankNode(element)) { element['@id'] = issuer.getId(element['@id']); } // recursively apply to all keys var keys = Object.keys(element).sort(); for (var ki = 0; ki < keys.length; ++ki) { var key = keys[ki]; if (key !== '@id') { element[key] = _labelBlankNodes(issuer, element[key]); } } } return element; } /***/ }), /* 3 */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.3' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var api = {}; module.exports = api; /** * Returns true if the given value is an Array. * * @param v the value to check. * * @return true if the value is an Array, false if not. */ api.isArray = Array.isArray; /** * Returns true if the given value is a Boolean. * * @param v the value to check. * * @return true if the value is a Boolean, false if not. */ api.isBoolean = function (v) { return typeof v === 'boolean' || Object.prototype.toString.call(v) === '[object Boolean]'; }; /** * Returns true if the given value is a double. * * @param v the value to check. * * @return true if the value is a double, false if not. */ api.isDouble = function (v) { return api.isNumber(v) && String(v).indexOf('.') !== -1; }; /** * Returns true if the given value is an empty Object. * * @param v the value to check. * * @return true if the value is an empty Object, false if not. */ api.isEmptyObject = function (v) { return api.isObject(v) && Object.keys(v).length === 0; }; /** * Returns true if the given value is a Number. * * @param v the value to check. * * @return true if the value is a Number, false if not. */ api.isNumber = function (v) { return typeof v === 'number' || Object.prototype.toString.call(v) === '[object Number]'; }; /** * Returns true if the given value is numeric. * * @param v the value to check. * * @return true if the value is numeric, false if not. */ api.isNumeric = function (v) { return !isNaN(parseFloat(v)) && isFinite(v); }; /** * Returns true if the given value is an Object. * * @param v the value to check. * * @return true if the value is an Object, false if not. */ api.isObject = function (v) { return Object.prototype.toString.call(v) === '[object Object]'; }; /** * Returns true if the given value is a String. * * @param v the value to check. * * @return true if the value is a String, false if not. */ api.isString = function (v) { return typeof v === 'string' || Object.prototype.toString.call(v) === '[object String]'; }; /** * Returns true if the given value is undefined. * * @param v the value to check. * * @return true if the value is undefined, false if not. */ api.isUndefined = function (v) { return typeof v === 'undefined'; }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var types = __webpack_require__(4); var api = {}; module.exports = api; /** * Returns true if the given value is a subject with properties. * * @param v the value to check. * * @return true if the value is a subject with properties, false if not. */ api.isSubject = function (v) { // Note: A value is a subject if all of these hold true: // 1. It is an Object. // 2. It is not a @value, @set, or @list. // 3. It has more than 1 key OR any existing key is not @id. if (types.isObject(v) && !('@value' in v || '@set' in v || '@list' in v)) { var keyCount = Object.keys(v).length; return keyCount > 1 || !('@id' in v); } return false; }; /** * Returns true if the given value is a subject reference. * * @param v the value to check. * * @return true if the value is a subject reference, false if not. */ api.isSubjectReference = function (v) { return ( // Note: A value is a subject reference if all of these hold true: // 1. It is an Object. // 2. It has a single key: @id. types.isObject(v) && Object.keys(v).length === 1 && '@id' in v ); }; /** * Returns true if the given value is a @value. * * @param v the value to check. * * @return true if the value is a @value, false if not. */ api.isValue = function (v) { return ( // Note: A value is a @value if all of these hold true: // 1. It is an Object. // 2. It has the @value property. types.isObject(v) && '@value' in v ); }; /** * Returns true if the given value is a @list. * * @param v the value to check. * * @return true if the value is a @list, false if not. */ api.isList = function (v) { return ( // Note: A value is a @list if all of these hold true: // 1. It is an Object. // 2. It has the @list property. types.isObject(v) && '@list' in v ); }; /** * Returns true if the given value is a simple @graph. * * @return true if the value is a simple @graph, false if not. */ api.isSimpleGraph = function (v) { // Note: A value is a simple graph if all of these hold true: // 1. It is an object. // 2. It has an `@graph` key. // 3. It has only 1 key or 2 keys where one of them is `@index`. if (!types.isObject(v)) { return false; } var keyLength = Object.keys(v).length; return '@graph' in v && (keyLength === 1 || keyLength === 2 && '@index' in v); }; /** * Returns true if the given value is a blank node. * * @param v the value to check. * * @return true if the value is a blank node, false if not. */ api.isBlankNode = function (v) { // Note: A value is a blank node if all of these hold true: // 1. It is an Object. // 2. If it has an @id key its value begins with '_:'. // 3. It has no keys OR is not a @value, @set, or @list. if (types.isObject(v)) { if ('@id' in v) { return v['@id'].indexOf('_:') === 0; } return Object.keys(v).length === 0 || !('@value' in v || '@set' in v || '@list' in v); } return false; }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } module.exports = function (_Error) { _inherits(JsonLdError, _Error); /** * Creates a JSON-LD Error. * * @param msg the error message. * @param type the error type. * @param details the error details. */ function JsonLdError() { var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'An unspecified JSON-LD error occurred.'; var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'jsonld.Error'; var details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _classCallCheck(this, JsonLdError); var _this = _possibleConstructorReturn(this, (JsonLdError.__proto__ || Object.getPrototypeOf(JsonLdError)).call(this, message)); _this.name = name; _this.message = message; _this.details = details; return _this; } return JsonLdError; }(Error); /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(1); var core = __webpack_require__(3); var hide = __webpack_require__(11); var redefine = __webpack_require__(16); var ctx = __webpack_require__(27); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); var key, own, out, exp; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // extend global if (target) redefine(target, key, out, type & $export.U); // export if (exports[key] != out) hide(exports, key, exp); if (IS_PROTO && expProto[key] != out) expProto[key] = out; } }; global.core = core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(9); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 9 */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 10 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(12); var createDesc = __webpack_require__(26); module.exports = __webpack_require__(13) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(8); var IE8_DOM_DEFINE = __webpack_require__(51); var toPrimitive = __webpack_require__(35); var dP = Object.defineProperty; exports.f = __webpack_require__(13) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(19)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var api = {}; module.exports = api; // define setImmediate and nextTick //// nextTick implementation with browser-compatible fallback //// // from https://github.com/caolan/async/blob/master/lib/async.js // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? // not a direct alias (for IE10 compatibility) function (fn) { return _setImmediate(fn); } : function (fn) { return setTimeout(fn, 0); }; if ((typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && typeof process.nextTick === 'function') { api.nextTick = process.nextTick; } else { api.nextTick = _delay; } api.setImmediate = _setImmediate ? _delay : api.nextTick; /** * Clones an object, array, or string/number. If a typed JavaScript object * is given, such as a Date, it will be converted to a string. * * @param value the value to clone. * * @return the cloned value. */ api.clone = function (value) { if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { var rval = void 0; if (Array.isArray(value)) { rval = []; for (var i = 0; i < value.length; ++i) { rval[i] = api.clone(value[i]); } } else if (api.isObject(value)) { rval = {}; for (var key in value) { rval[key] = api.clone(value[key]); } } else { rval = value.toString(); } return rval; } return value; }; /** * Returns true if the given value is an Object. * * @param v the value to check. * * @return true if the value is an Object, false if not. */ api.isObject = function (v) { return Object.prototype.toString.call(v) === '[object Object]'; }; /** * Returns true if the given value is undefined. * * @param v the value to check. * * @return true if the value is undefined, false if not. */ api.isUndefined = function (v) { return typeof v === 'undefined'; }; api.callbackify = function (fn) { return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var callback, result; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: callback = args[args.length - 1]; if (typeof callback === 'function') { args.pop(); } result = void 0; _context.prev = 3; _context.next = 6; return fn.apply(null, args); case 6: result = _context.sent; _context.next = 14; break; case 9: _context.prev = 9; _context.t0 = _context['catch'](3); if (!(typeof callback === 'function')) { _context.next = 13; break; } return _context.abrupt('return', _invokeCallback(callback, _context.t0)); case 13: throw _context.t0; case 14: if (!(typeof callback === 'function')) { _context.next = 16; break; } return _context.abrupt('return', _invokeCallback(callback, null, result)); case 16: return _context.abrupt('return', result); case 17: case 'end': return _context.stop(); } } }, _callee, this, [[3, 9]]); })); }; function _invokeCallback(callback, err, result) { try { return callback(err, result); } catch (unhandledError) { // throw unhandled errors to prevent "unhandled rejected promise" // and simulate what would have happened in a promiseless API process.nextTick(function () { throw unhandledError; }); } } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _retrieveContextUrls = function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(input, options) { // recursive function that will retrieve all @context URLs in documents var retrieve = function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(doc, cycles, documentLoader) { var _this = this; var urls, queue; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(Object.keys(cycles).length > MAX_CONTEXT_URLS)) { _context3.next = 2; break; } throw new JsonLdError('Maximum number of @context URLs exceeded.', 'jsonld.ContextUrlError', { code: 'loading remote context failed', max: MAX_CONTEXT_URLS }); case 2: // find all URLs in the given document, reusing already retrieved URLs urls = {}; Object.keys(_urls).forEach(function (url) { if (_urls[url] !== false) { urls[url] = _urls[url]; } }); _findContextUrls(doc, urls, false, options.base); // queue all unretrieved URLs queue = Object.keys(urls).filter(function (u) { return urls[u] === false; }); // retrieve URLs in queue return _context3.abrupt('return', Promise.all(queue.map(function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(url) { var _cycles, remoteDoc, ctx; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(url in cycles)) { _context2.next = 2; break; } throw new JsonLdError('Cyclical @context URLs detected.', 'jsonld.ContextUrlError', { code: 'recursive context inclusion', url: url }); case 2: _cycles = util.clone(cycles); _cycles[url] = true; remoteDoc = void 0; ctx = void 0; _context2.prev = 6; _context2.next = 9; return documentLoader(url); case 9: remoteDoc = _context2.sent; ctx = remoteDoc.document || null; // parse string context as JSON if (_isString(ctx)) { ctx = JSON.parse(ctx); } _context2.next = 17; break; case 14: _context2.prev = 14; _context2.t0 = _context2['catch'](6); throw new JsonLdError('Dereferencing a URL did not result in a valid JSON-LD object. ' + 'Possible causes are an inaccessible URL perhaps due to ' + 'a same-origin policy (ensure the server uses CORS if you are ' + 'using client-side JavaScript), too many redirects, a ' + 'non-JSON response, or more than one HTTP Link Header was ' + 'provided for a remote context.', 'jsonld.InvalidUrl', { code: 'loading remote context failed', url: url, cause: _context2.t0 }); case 17: if (_isObject(ctx)) { _context2.next = 19; break; } throw new JsonLdError('Dereferencing a URL did not result in a JSON object. The ' + 'response was valid JSON, but it was not a JSON object.', 'jsonld.InvalidUrl', { code: 'invalid remote context', url: url }); case 19: // use empty context if no @context key is present if (!('@context' in ctx)) { ctx = { '@context': {} }; } else { ctx = { '@context': ctx['@context'] }; } // append @context URL to context if given if (remoteDoc.contextUrl) { if (!_isArray(ctx['@context'])) { ctx['@context'] = [ctx['@context']]; } ctx['@context'].push(remoteDoc.contextUrl); } // recurse _context2.next = 23; return retrieve(ctx, _cycles, documentLoader); case 23: // store retrieved context w/replaced @context URLs urls[url] = ctx['@context']; // replace all @context URLs in the document _findContextUrls(doc, urls, true, options.base); case 25: case 'end': return _context2.stop(); } } }, _callee2, _this, [[6, 14]]); })); return function (_x8) { return _ref5.apply(this, arguments); }; }()))); case 7: case 'end': return _context3.stop(); } } }, _callee3, this); })); return function retrieve(_x5, _x6, _x7) { return _ref4.apply(this, arguments); }; }(); var documentLoader, _urls; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: documentLoader = util.normalizeDocumentLoader(options.documentLoader); // retrieve all @context URLs in input _urls = {}; _context4.next = 4; return retrieve(input, {}, documentLoader); case 4: return _context4.abrupt('return', input); case 5: case 'end': return _context4.stop(); } } }, _callee4, this); })); return function _retrieveContextUrls(_x3, _x4) { return _ref3.apply(this, arguments); }; }(); /** * Finds all @context URLs in the given JSON-LD input. * * @param input the JSON-LD input. * @param urls a map of URLs (url => false/@contexts). * @param replace true to replace the URLs in the given input with the * @contexts from the urls map, false not to. * @param base the base IRI to use to resolve relative IRIs. * * @return true if new URLs to retrieve were found, false if not. */ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var util = __webpack_require__(2); var ActiveContextCache = __webpack_require__(130); var JsonLdError = __webpack_require__(6); var _require = __webpack_require__(4), _isArray = _require.isArray, _isObject = _require.isObject, _isString = _require.isString, _isUndefined = _require.isUndefined; var _require2 = __webpack_require__(25), _isAbsoluteIri = _require2.isAbsolute, _isRelativeIri = _require2.isRelative, prependBase = _require2.prependBase, parseUrl = _require2.parse; var MAX_CONTEXT_URLS = 10; var api = {}; module.exports = api; api.cache = new ActiveContextCache(); /** * Processes a local context and returns a new active context. * * @param activeCtx the current active context. * @param localCtx the local context to process. * @param options the context processing options. * * @return the new active context. */ api.process = function (_ref) { var activeCtx = _ref.activeCtx, localCtx = _ref.localCtx, options = _ref.options; // normalize local context to an array of @context objects if (_isObject(localCtx) && '@context' in localCtx && _isArray(localCtx['@context'])) { localCtx = localCtx['@context']; } var ctxs = _isArray(localCtx) ? localCtx : [localCtx]; // no contexts in array, clone existing context if (ctxs.length === 0) { return activeCtx.clone(); } // process each context in order, update active context // on each iteration to ensure proper caching var rval = activeCtx; for (var i = 0; i < ctxs.length; ++i) { var ctx = ctxs[i]; // reset to initial context if (ctx === null) { rval = activeCtx = api.getInitialContext(options); continue; } // dereference @context key if present if (_isObject(ctx) && '@context' in ctx) { ctx = ctx['@context']; } // context must be an object by now, all URLs retrieved before this call if (!_isObject(ctx)) { throw new JsonLdError('Invalid JSON-LD syntax; @context must be an object.', 'jsonld.SyntaxError', { code: 'invalid local context', context: ctx }); } // get context from cache if available if (api.cache) { var cached = api.cache.get(activeCtx, ctx); if (cached) { rval = activeCtx = cached; continue; } } // update active context and clone new one before updating activeCtx = rval; rval = rval.clone(); // define context mappings for keys in local context var defined = {}; // handle @version if ('@version' in ctx) { if (ctx['@version'] !== 1.1) { throw new JsonLdError('Unsupported JSON-LD version: ' + ctx['@version'], 'jsonld.UnsupportedVersion', { code: 'invalid @version value', context: ctx }); } if (activeCtx.processingMode && activeCtx.processingMode.indexOf('json-ld-1.1') !== 0) { throw new JsonLdError('@version: ' + ctx['@version'] + ' not compatible with ' + activeCtx.processingMode, 'jsonld.ProcessingModeConflict', { code: 'processing mode conflict', context: ctx }); } rval.processingMode = 'json-ld-1.1'; rval['@version'] = ctx['@version']; defined['@version'] = true; } // if not set explicitly, set processingMode to "json-ld-1.0" rval.processingMode = rval.processingMode || activeCtx.processingMode || 'json-ld-1.0'; // handle @base if ('@base' in ctx) { var base = ctx['@base']; if (base === null) { // no action } else if (_isAbsoluteIri(base)) { base = parseUrl(base); } else if (_isRelativeIri(base)) { base = parseUrl(prependBase(activeCtx['@base'].href, base)); } else { throw new JsonLdError('Invalid JSON-LD syntax; the value of "@base" in a ' + '@context must be an absolute IRI, a relative IRI, or null.', 'jsonld.SyntaxError', { code: 'invalid base IRI', context: ctx }); } rval['@base'] = base; defined['@base'] = true; } // handle @vocab if ('@vocab' in ctx) { var value = ctx['@vocab']; if (value === null) { delete rval['@vocab']; } else if (!_isString(value)) { throw new JsonLdError('Invalid JSON-LD syntax; the value of "@vocab" in a ' + '@context must be a string or null.', 'jsonld.SyntaxError', { code: 'invalid vocab mapping', context: ctx }); } else if (!_isAbsoluteIri(value)) { throw new JsonLdError('Invalid JSON-LD syntax; the value of "@vocab" in a ' + '@context must be an absolute IRI.', 'jsonld.SyntaxError', { code: 'invalid vocab mapping', context: ctx }); } else { rval['@vocab'] = value; } defined['@vocab'] = true; } // handle @language if ('@language' in ctx) { var _value = ctx['@language']; if (_value === null) { delete rval['@language']; } else if (!_isString(_value)) { throw new JsonLdError('Invalid JSON-LD syntax; the value of "@language" in a ' + '@context must be a string or null.', 'jsonld.SyntaxError', { code: 'invalid default language', context: ctx }); } else { rval['@language'] = _value.toLowerCase(); } defined['@language'] = true; } // process all other keys for (var key in ctx) { api.createTermDefinition(rval, ctx, key, defined); } // cache result if (api.cache) { api.cache.set(activeCtx, ctx, rval); } } return rval; }; /** * Creates a term definition during context processing. * * @param activeCtx the current active context. * @param localCtx the local context being processed. * @param term the term in the local context to define the mapping for. * @param defined a map of defining/defined keys to detect cycles and prevent * double definitions. */ api.createTermDefinition = function (activeCtx, localCtx, term, defined) { if (term in defined) { // term already defined if (defined[term]) { return; } // cycle detected throw new JsonLdError('Cyclical context definition detected.', 'jsonld.CyclicalContext', { code: 'cyclic IRI mapping', context: localCtx, term: term }); } // now defining term defined[term] = false; if (api.isKeyword(term)) { throw new JsonLdError('Invalid JSON-LD syntax; keywords cannot be overridden.', 'jsonld.SyntaxError', { code: 'keyword redefinition', context: localCtx, term: term }); } if (term === '') { throw new JsonLdError('Invalid JSON-LD syntax; a term cannot be an empty string.', 'jsonld.SyntaxError', { code: 'invalid term definition', context: localCtx }); } // remove old mapping if (activeCtx.mappings[term]) { delete activeCtx.mappings[term]; } // get context term value var value = localCtx[term]; // clear context entry if (value === null || _isObject(value) && value['@id'] === null) { activeCtx.mappings[term] = null; defined[term] = true; return; } // convert short-hand value to object w/@id if (_isString(value)) { value = { '@id': value }; } if (!_isObject(value)) { throw new JsonLdError('Invalid JSON-LD syntax; @context term values must be ' + 'strings or objects.', 'jsonld.SyntaxError', { code: 'invalid term definition', context: localCtx }); } // create new mapping var mapping = activeCtx.mappings[term] = {}; mapping.reverse = false; // make sure term definition only has expected keywords var validKeys = ['@container', '@id', '@language', '@reverse', '@type']; for (var kw in value) { if (!validKeys.includes(kw)) { throw new JsonLdError('Invalid JSON-LD syntax; a term definition must not contain ' + kw, 'jsonld.SyntaxError', { code: 'invalid term definition', context: localCtx }); } } if ('@reverse' in value) { if ('@id' in value) { throw new JsonLdError('Invalid JSON-LD syntax; a @reverse term definition must not ' + 'contain @id.', 'jsonld.SyntaxError', { code: 'invalid reverse property', context: localCtx }); } var reverse = value['@reverse']; if (!_isString(reverse)) { throw new JsonLdError('Invalid JSON-LD syntax; a @context @reverse value must be a string.', 'jsonld.SyntaxError', { code: 'invalid IRI mapping', context: localCtx }); } // expand and add @id mapping var _id = api.expandIri(activeCtx, reverse, { vocab: true, base: false }, localCtx, defined); if (!_isAbsoluteIri(_id)) { throw new JsonLdError('Invalid JSON-LD syntax; a @context @reverse value must be an ' + 'absolute IRI or a blank node identifier.', 'jsonld.SyntaxError', { code: 'invalid IRI mapping', context: localCtx }); } mapping['@id'] = _id; mapping.reverse = true; } else if ('@id' in value) { var _id2 = value['@id']; if (!_isString(_id2)) { throw new JsonLdError('Invalid JSON-LD syntax; a @context @id value must be an array ' + 'of strings or a string.', 'jsonld.SyntaxError', { code: 'invalid IRI mapping', context: localCtx }); } if (_id2 !== term) { // expand and add @id mapping _id2 = api.expandIri(activeCtx, _id2, { vocab: true, base: false }, localCtx, defined); if (!_isAbsoluteIri(_id2) && !api.isKeyword(_id2)) { throw new JsonLdError('Invalid JSON-LD syntax; a @context @id value must be an ' + 'absolute IRI, a blank node identifier, or a keyword.', 'jsonld.SyntaxError', { code: 'invalid IRI mapping', context: localCtx }); } mapping['@id'] = _id2; } } // always compute whether term has a colon as an optimization for // _compactIri var colon = term.indexOf(':'); mapping._termHasColon = colon !== -1; if (!('@id' in mapping)) { // see if the term has a prefix if (mapping._termHasColon) { var prefix = term.substr(0, colon); if (prefix in localCtx) { // define parent prefix api.createTermDefinition(activeCtx, localCtx, prefix, defined); } if (activeCtx.mappings[prefix]) { // set @id based on prefix parent var suffix = term.substr(colon + 1); mapping['@id'] = activeCtx.mappings[prefix]['@id'] + suffix; } else { // term is an absolute IRI mapping['@id'] = term; } } else { // non-IRIs *must* define @ids if @vocab is not available if (!('@vocab' in activeCtx)) { throw new JsonLdError('Invalid JSON-LD syntax; @context terms must define an @id.', 'jsonld.SyntaxError', { code: 'invalid IRI mapping', context: localCtx, term: term }); } // prepend vocab to term mapping['@id'] = activeCtx['@vocab'] + term; } } // IRI mapping now defined defined[term] = true; if ('@type' in value) { var type = value['@type']; if (!_isString(type)) { throw new JsonLdError('Invalid JSON-LD syntax; an @context @type values must be a string.', 'jsonld.SyntaxError', { code: 'invalid type mapping', context: localCtx }); } if (type !== '@id' && type !== '@vocab') { // expand @type to full IRI type = api.expandIri(activeCtx, type, { vocab: true, base: false }, localCtx, defined); if (!_isAbsoluteIri(type)) { throw new JsonLdError('Invalid JSON-LD syntax; an @context @type value must be an ' + 'absolute IRI.', 'jsonld.SyntaxError', { code: 'invalid type mapping', context: localCtx }); } if (type.indexOf('_:') === 0) { throw new JsonLdError('Invalid JSON-LD syntax; an @context @type values must be an IRI, ' + 'not a blank node identifier.', 'jsonld.SyntaxError', { code: 'invalid type mapping', context: localCtx }); } } // add @type to mapping mapping['@type'] = type; } if ('@container' in value) { // normalize container to an array form var container = _isString(value['@container']) ? [value['@container']] : value['@container'] || []; var validContainers = ['@list', '@set', '@index', '@language']; var isValid = true; var hasSet = container.includes('@set'); // JSON-LD 1.1 support if (activeCtx.processingMode && activeCtx.processingMode.indexOf('json-ld-1.1') === 0) { // TODO: @id and @type validContainers.push('@graph'); // check container length isValid &= container.length <= (hasSet ? 2 : 1); } else { // in JSON-LD 1.0, container must not be an array (it must be a string, which is one of the validContainers) isValid &= !_isArray(value['@container']); // check container length isValid &= container.length <= 1; } // check against valid containers isValid &= container.every(function (c) { return validContainers.includes(c); }); // @set not allowed with @list isValid &= !(hasSet && container.includes('@list')); if (!isValid) { throw new JsonLdError('Invalid JSON-LD syntax; @context @container value must be ' + 'one of the following: ' + validContainers.join(', '), 'jsonld.SyntaxError', { code: 'invalid container mapping', context: localCtx }); } if (mapping.reverse && !container.every(function (c) { return ['@index', '@set'].includes(c); })) { throw new JsonLdError('Invalid JSON-LD syntax; @context @container value for a @reverse ' + 'type definition must be @index or @set.', 'jsonld.SyntaxError', { code: 'invalid reverse property', context: localCtx }); } // add @container to mapping mapping['@container'] = container; } if ('@language' in value && !('@type' in value)) { var language = value['@language']; if (language !== null && !_isString(language)) { throw new JsonLdError('Invalid JSON-LD syntax; @context @language value must be ' + 'a string or null.', 'jsonld.SyntaxError', { code: 'invalid language mapping', context: localCtx }); } // add @language to mapping if (language !== null) { language = language.toLowerCase(); } mapping['@language'] = language; } // disallow aliasing @context and @preserve var id = mapping['@id']; if (id === '@context' || id === '@preserve') { throw new JsonLdError('Invalid JSON-LD syntax; @context and @preserve cannot be aliased.', 'jsonld.SyntaxError', { code: 'invalid keyword alias', context: localCtx }); } }; /** * Expands a string to a full IRI. The string may be a term, a prefix, a * relative IRI, or an absolute IRI. The associated absolute IRI will be * returned. * * @param activeCtx the current active context. * @param value the string to expand. * @param relativeTo options for how to resolve relative IRIs: * base: true to resolve against the base IRI, false not to. * vocab: true to concatenate after @vocab, false not to. * @param localCtx the local context being processed (only given if called * during context processing). * @param defined a map for tracking cycles in context definitions (only given * if called during context processing). * * @return the expanded value. */ api.expandIri = function (activeCtx, value, relativeTo, localCtx, defined) { // already expanded if (value === null || api.isKeyword(value)) { return value; } // ensure value is interpreted as a string value = String(value); // define term dependency if not defined if (localCtx && value in localCtx && defined[value] !== true) { api.createTermDefinition(activeCtx, localCtx, value, defined); } relativeTo = relativeTo || {}; if (relativeTo.vocab) { var mapping = activeCtx.mappings[value]; // value is explicitly ignored with a null mapping if (mapping === null) { return null; } if (mapping) { // value is a term return mapping['@id']; } } // split value into prefix:suffix var colon = value.indexOf(':'); if (colon !== -1) { var prefix = value.substr(0, colon); var suffix = value.substr(colon + 1); // do not expand blank nodes (prefix of '_') or already-absolute // IRIs (suffix of '//') if (prefix === '_' || suffix.indexOf('//') === 0) { return value; } // prefix dependency not defined, define it if (localCtx && prefix in localCtx) { api.createTermDefinition(activeCtx, localCtx, prefix, defined); } // use mapping if prefix is defined var _mapping = activeCtx.mappings[prefix]; if (_mapping) { return _mapping['@id'] + suffix; } // already absolute IRI return value; } // prepend vocab if (relativeTo.vocab && '@vocab' in activeCtx) { return activeCtx['@vocab'] + value; } // prepend base if (relativeTo.base) { return prependBase(activeCtx['@base'], value); } return value; }; /** * Gets the initial context. * * @param options the options to use: * [base] the document base IRI. * * @return the initial context. */ api.getInitialContext = function (options) { var base = parseUrl(options.base || ''); return { '@base': base, processingMode: options.processingMode, mappings: {}, inverse: null, getInverse: _createInverseContext, clone: _cloneActiveContext }; /** * Generates an inverse context for use in the compaction algorithm, if * not already generated for the given active context. * * @return the inverse context. */ function _createInverseContext() { var activeCtx = this; // lazily create inverse if (activeCtx.inverse) { return activeCtx.inverse; } var inverse = activeCtx.inverse = {}; // variables for building fast CURIE map var fastCurieMap = activeCtx.fastCurieMap = {}; var irisToTerms = {}; // handle default language var defaultLanguage = activeCtx['@language'] || '@none'; // create term selections for each mapping in the context, ordered by // shortest and then lexicographically least var mappings = activeCtx.mappings; var terms = Object.keys(mappings).sort(util.compareShortestLeast); for (var i = 0; i < terms.length; ++i) { var term = terms[i]; var mapping = mappings[term]; if (mapping === null) { continue; } var container = mapping['@container'] || '@none'; container = [].concat(container).sort().join(''); // iterate over every IRI in the mapping var ids = [].concat(mapping['@id']); for (var ii = 0; ii < ids.length; ++ii) { var iri = ids[ii]; var entry = inverse[iri]; var isKeyword = api.isKeyword(iri); if (!entry) { // initialize entry inverse[iri] = entry = {}; if (!isKeyword && !mapping._termHasColon) { // init IRI to term map and fast CURIE prefixes irisToTerms[iri] = [term]; var fastCurieEntry = { iri: iri, terms: irisToTerms[iri] }; if (iri[0] in fastCurieMap) { fastCurieMap[iri[0]].push(fastCurieEntry); } else { fastCurieMap[iri[0]] = [fastCurieEntry]; } } } else if (!isKeyword && !mapping._termHasColon) { // add IRI to term match irisToTerms[iri].push(term); } // add new entry if (!entry[container]) { entry[container] = { '@language': {}, '@type': {}, '@any': {} }; } entry = entry[container]; _addPreferredTerm(term, entry['@any'], '@none'); if (mapping.reverse) { // term is preferred for values using @reverse _addPreferredTerm(term, entry['@type'], '@reverse'); } else if ('@type' in mapping) { // term is preferred for values using specific type _addPreferredTerm(term, entry['@type'], mapping['@type']); } else if ('@language' in mapping) { // term is preferred for values using specific language var language = mapping['@language'] || '@null'; _addPreferredTerm(term, entry['@language'], language); } else { // term is preferred for values w/default language or no type and // no language // add an entry for the default language _addPreferredTerm(term, entry['@language'], defaultLanguage); // add entries for no type and no language _addPreferredTerm(term, entry['@type'], '@none'); _addPreferredTerm(term, entry['@language'], '@none'); } } } // build fast CURIE map for (var key in fastCurieMap) { _buildIriMap(fastCurieMap, key, 1); } return inverse; } /** * Runs a recursive algorithm to build a lookup map for quickly finding * potential CURIEs. * * @param iriMap the map to build. * @param key the current key in the map to work on. * @param idx the index into the IRI to compare. */ function _buildIriMap(iriMap, key, idx) { var entries = iriMap[key]; var next = iriMap[key] = {}; var iri = void 0; var letter = void 0; for (var i = 0; i < entries.length; ++i) { iri = entries[i].iri; if (idx >= iri.length) { letter = ''; } else { letter = iri[idx]; } if (letter in next) { next[letter].push(entries[i]); } else { next[letter] = [entries[i]]; } } for (var _key in next) { if (_key === '') { continue; } _buildIriMap(next, _key, idx + 1); } } /** * Adds the term for the given entry if not already added. * * @param term the term to add. * @param entry the inverse context typeOrLanguage entry to add to. * @param typeOrLanguageValue the key in the entry to add to. */ function _addPreferredTerm(term, entry, typeOrLanguageValue) { if (!(typeOrLanguageValue in entry)) { entry[typeOrLanguageValue] = term; } } /** * Clones an active context, creating a child active context. * * @return a clone (child) of the active context. */ function _cloneActiveContext() { var child = {}; child['@base'] = this['@base']; child.mappings = util.clone(this.mappings); child.clone = this.clone; child.inverse = null; child.getInverse = this.getInverse; if ('@language' in this) { child['@language'] = this['@language']; } if ('@vocab' in this) { child['@vocab'] = this['@vocab']; } return child; } }; /** * Gets the value for the given active context key and type, null if none is * set. * * @param ctx the active context. * @param key the context key. * @param [type] the type of value to get (eg: '@id', '@type'), if not * specified gets the entire entry for a key, null if not found. * * @return the value. */ api.getContextValue = function (ctx, key, type) { // return null for invalid key if (key === null) { return null; } // get specific entry information if (ctx.mappings[key]) { var entry = ctx.mappings[key]; if (_isUndefined(type)) { // return whole entry return entry; } if (type in entry) { // return entry value for type return entry[type]; } } // get default language if (type === '@language' && type in ctx) { return ctx[type]; } return null; }; /** * Retrieves external @context URLs using the given document loader. Every * instance of @context in the input that refers to a URL will be replaced * with the JSON @context found at that URL. * * @param input the JSON-LD input with possible contexts. * @param options the options to use: * documentLoader(url, [callback(err, remoteDoc)]) the document loader. * @param callback(err, input) called once the operation completes. */ api.getAllContexts = function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(input, options) { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt('return', _retrieveContextUrls(input, options)); case 1: case 'end': return _context.stop(); } } }, _callee, undefined); })); return function (_x, _x2) { return _ref2.apply(this, arguments); }; }(); /** * Returns whether or not the given value is a keyword. * * @param v the value to check. * * @return true if the value is a keyword, false if not. */ api.isKeyword = function (v) { if (!_isString(v)) { return false; } switch (v) { case '@base': case '@container': case '@context': case '@default': case '@embed': case '@explicit': case '@graph': case '@id': case '@index': case '@language': case '@list': case '@omitDefault': case '@preserve': case '@requireAll': case '@reverse': case '@set': case '@type': case '@value': case '@version': case '@vocab': return true; } return false; }; function _findContextUrls(input, urls, replace, base) { if (_isArray(input)) { for (var i = 0; i < input.length; ++i) { _findContextUrls(input[i], urls, replace, base); } return; } if (!_isObject(input)) { // no @context URLs can be found in non-object input return; } // input is an object for (var key in input) { if (key !== '@context') { _findContextUrls(input[key], urls, replace, base); continue; } // get @context var ctx = input[key]; if (_isArray(ctx)) { // array @context var length = ctx.length; for (var _i = 0; _i < length; ++_i) { var _ctx = ctx[_i]; if (_isString(_ctx)) { _ctx = prependBase(base, _ctx); // replace w/@context if requested if (replace) { if (urls[_ctx] !== false) { _ctx = urls[_ctx]; if (_isArray(_ctx)) { // add flattened context Array.prototype.splice.apply(ctx, [_i, 1].concat(_ctx)); _i += _ctx.length - 1; length = ctx.length; } else { ctx[_i] = _ctx; } } } else if (!(_ctx in urls)) { // @context URL found urls[_ctx] = false; } } } } else if (_isString(ctx)) { // string @context ctx = prependBase(base, ctx); // replace w/@context if requested if (replace) { if (urls[ctx] !== false) { input[key] = urls[ctx]; } } else if (!(ctx in urls)) { // @context URL found urls[ctx] = false; } } } } /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(1); var hide = __webpack_require__(11); var has = __webpack_require__(10); var SRC = __webpack_require__(20)('src'); var TO_STRING = 'toString'; var $toString = Function[TO_STRING]; var TPL = ('' + $toString).split(TO_STRING); __webpack_require__(3).inspectSource = function (it) { return $toString.call(it); }; (module.exports = function (O, key, val, safe) { var isFunction = typeof val == 'function'; if (isFunction) has(val, 'name') || hide(val, 'name', key); if (O[key] === val) return; if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if (O === global) { O[key] = val; } else if (!safe) { delete O[key]; hide(O, key, val); } else if (O[key]) { O[key] = val; } else { hide(O, key, val); } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString() { return typeof this == 'function' && this[SRC] || $toString.call(this); }); /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(53); var defined = __webpack_require__(29); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /* 18 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /* 19 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /* 20 */ /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(55); var enumBugKeys = __webpack_require__(40); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /* 22 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 23 */ /***/ (function(module, exports) { /** * Node.js module for Forge. * * @author Dave Longley * * Copyright 2011-2016 Digital Bazaar, Inc. */ module.exports = { // default options options: { usePureJavaScript: false } }; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; var XSD = 'http://www.w3.org/2001/XMLSchema#'; module.exports = { LINK_HEADER_REL: 'http://www.w3.org/ns/json-ld#context', RDF: RDF, RDF_LIST: RDF + 'List', RDF_FIRST: RDF + 'first', RDF_REST: RDF + 'rest', RDF_NIL: RDF + 'nil', RDF_TYPE: RDF + 'type', RDF_PLAIN_LITERAL: RDF + 'PlainLiteral', RDF_XML_LITERAL: RDF + 'XMLLiteral', RDF_OBJECT: RDF + 'object', RDF_LANGSTRING: RDF + 'langString', XSD: XSD, XSD_BOOLEAN: XSD + 'boolean', XSD_DOUBLE: XSD + 'double', XSD_INTEGER: XSD + 'integer', XSD_STRING: XSD + 'string' }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var types = __webpack_require__(4); var api = {}; module.exports = api; // define URL parser // parseUri 1.2.2 // (c) Steven Levithan <stevenlevithan.com> // MIT License // with local jsonld.js modifications api.parsers = { simple: { // RFC 3986 basic parts keys: ['href', 'scheme', 'authority', 'path', 'query', 'fragment'], regex: /^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/ }, full: { keys: ['href', 'protocol', 'scheme', 'authority', 'auth', 'user', 'password', 'hostname', 'port', 'path', 'directory', 'file', 'query', 'fragment'], regex: /^(([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; api.parse = function (str, parser) { var parsed = {}; var o = api.parsers[parser || 'full']; var m = o.regex.exec(str); var i = o.keys.length; while (i--) { parsed[o.keys[i]] = m[i] === undefined ? null : m[i]; } // remove default ports in found in URLs if (parsed.scheme === 'https' && parsed.port === '443' || parsed.scheme === 'http' && parsed.port === '80') { parsed.href = parsed.href.replace(':' + parsed.port, ''); parsed.authority = parsed.authority.replace(':' + parsed.port, ''); parsed.port = null; } parsed.normalizedPath = api.removeDotSegments(parsed.path); return parsed; }; /** * Prepends a base IRI to the given relative IRI. * * @param base the base IRI. * @param iri the relative IRI. * * @return the absolute IRI. */ api.prependBase = function (base, iri) { // skip IRI processing if (base === null) { return iri; } // already an absolute IRI if (iri.indexOf(':') !== -1) { return iri; } // parse base if it is a string if (types.isString(base)) { base = api.parse(base || ''); } // parse given IRI var rel = api.parse(iri); // per RFC3986 5.2.2 var transform = { protocol: base.protocol || '' }; if (rel.authority !== null) { transform.authority = rel.authority; transform.path = rel.path; transform.query = rel.query; } else { transform.authority = base.authority; if (rel.path === '') { transform.path = base.path; if (rel.query !== null) { transform.query = rel.query; } else { transform.query = base.query; } } else { if (rel.path.indexOf('/') === 0) { // IRI represents an absolute path transform.path = rel.path; } else { // merge paths var path = base.path; // append relative path to the end of the last directory from base path = path.substr(0, path.lastIndexOf('/') + 1); if (path.length > 0 && path.substr(-1) !== '/') { path += '/'; } path += rel.path; transform.path = path; } transform.query = rel.query; } } if (rel.path !== '') { // remove slashes and dots in path transform.path = api.removeDotSegments(transform.path); } // construct URL var rval = transform.protocol; if (transform.authority !== null) { rval += '//' + transform.authority; } rval += transform.path; if (transform.query !== null) { rval += '?' + transform.query; } if (rel.fragment !== null) { rval += '#' + rel.fragment; } // handle empty base if (rval === '') { rval = './'; } return rval; }; /** * Removes a base IRI from the given absolute IRI. * * @param base the base IRI. * @param iri the absolute IRI. * * @return the relative IRI if relative to base, otherwise the absolute IRI. */ api.removeBase = function (base, iri) { // skip IRI processing if (base === null) { return iri; } if (types.isString(base)) { base = api.parse(base || ''); } // establish base root var root = ''; if (base.href !== '') { root += (base.protocol || '') + '//' + (base.authority || ''); } else if (iri.indexOf('//')) { // support network-path reference with empty base root += '//'; } // IRI not relative to base if (iri.indexOf(root) !== 0) { return iri; } // remove root from IRI and parse remainder var rel = api.parse(iri.substr(root.length)); // remove path segments that match (do not remove last segment unless there // is a hash or query) var baseSegments = base.normalizedPath.split('/'); var iriSegments = rel.normalizedPath.split('/'); var last = rel.fragment || rel.query ? 0 : 1; while (baseSegments.length > 0 && iriSegments.length > last) { if (baseSegments[0] !== iriSegments[0]) { break; } baseSegments.shift(); iriSegments.shift(); } // use '../' for each non-matching base segment var rval = ''; if (baseSegments.length > 0) { // don't count the last segment (if it ends with '/' last path doesn't // count and if it doesn't end with '/' it isn't a path) baseSegments.pop(); for (var i = 0; i < baseSegments.length; ++i) { rval += '../'; } } // prepend remaining segments rval += iriSegments.join('/'); // add query and hash if (rel.query !== null) { rval += '?' + rel.query; } if (rel.fragment !== null) { rval += '#' + rel.fragment; } // handle empty base if (rval === '') { rval = './'; } return rval; }; /** * Removes dot segments from a URL path. * * @param path the path to remove dot segments from. */ api.removeDotSegments = function (path) { // RFC 3986 5.2.4 (reworked) // empty path shortcut if (path.length === 0) { return ''; } var input = path.split('/'); var output = []; while (input.length > 0) { var next = input.shift(); var done = input.length === 0; if (next === '.') { if (done) { // ensure output has trailing / output.push(''); } continue; } if (next === '..') { output.pop(); if (done) { // ensure output has trailing / output.push(''); } continue; } output.push(next); } // ensure output has leading / if (output.length > 0 && output[0] !== '') { output.unshift(''); } if (output.length === 1 && output[0] === '') { return '/'; } return output.join('/'); }; // TODO: time better isAbsolute/isRelative checks using full regexes: // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html // regex to check for absolute IRI (starting scheme and ':') or blank node IRI var isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):/; /** * Returns true if the given value is an absolute IRI or blank node IRI, false * if not. * Note: This weak check only checks for a correct starting scheme. * * @param v the value to check. * * @return true if the value is an absolute IRI, false if not. */ api.isAbsolute = function (v) { return types.isString(v) && isAbsoluteRegex.test(v); }; /** * Returns true if the given value is a relative IRI, false if not. * Note: this is a weak check. * * @param v the value to check. * * @return true if the value is a relative IRI, false if not. */ api.isRelative = function (v) { return types.isString(v); }; /***/ }), /* 26 */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(28); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /* 28 */ /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 29 */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /* 30 */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /* 31 */ /***/ (function(module, exports) { module.exports = false; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__(12).f; var has = __webpack_require__(10); var TAG = __webpack_require__(0)('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _require = __webpack_require__(15), isKeyword = _require.isKeyword; var graphTypes = __webpack_require__(5); var types = __webpack_require__(4); var util = __webpack_require__(2); var JsonLdError = __webpack_require__(6); var api = {}; module.exports = api; /** * Creates a merged JSON-LD node map (node ID => node). * * @param input the expanded JSON-LD to create a node map of. * @param [options] the options to use: * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. * * @return the node map. */ api.createMergedNodeMap = function (input, options) { options = options || {}; // produce a map of all subjects and name each bnode var issuer = options.issuer || new util.IdentifierIssuer('_:b'); var graphs = { '@default': {} }; api.createNodeMap(input, graphs, '@default', issuer); // add all non-default graphs to default graph return api.mergeNodeMaps(graphs); }; /** * Recursively flattens the subjects in the given JSON-LD expanded input * into a node map. * * @param input the JSON-LD expanded input. * @param graphs a map of graph name to subject map. * @param graph the name of the current graph. * @param issuer the blank node identifier issuer. * @param name the name assigned to the current input if it is a bnode. * @param list the list to append to, null for none. */ api.createNodeMap = function (input, graphs, graph, issuer, name, list) { // recurse through array if (types.isArray(input)) { for (var i = 0; i < input.length; ++i) { api.createNodeMap(input[i], graphs, graph, issuer, undefined, list); } return; } // add non-object to list if (!types.isObject(input)) { if (list) { list.push(input); } return; } // add values to list if (graphTypes.isValue(input)) { if ('@type' in input) { var type = input['@type']; // rename @type blank node if (type.indexOf('_:') === 0) { input['@type'] = type = issuer.getId(type); } } if (list) { list.push(input); } return; } // Note: At this point, input must be a subject. // spec requires @type to be named first, so assign names early if ('@type' in input) { var _types = input['@type']; for (var _i = 0; _i < _types.length; ++_i) { var _type = _types[_i]; if (_type.indexOf('_:') === 0) { issuer.getId(_type); } } } // get name for subject if (types.isUndefined(name)) { name = graphTypes.isBlankNode(input) ? issuer.getId(input['@id']) : input['@id']; } // add subject reference to list if (list) { list.push({ '@id': name }); } // create new subject or merge into existing one var subjects = graphs[graph]; var subject = subjects[name] = subjects[name] || {}; subject['@id'] = name; var properties = Object.keys(input).sort(); for (var pi = 0; pi < properties.length; ++pi) { var property = properties[pi]; // skip @id if (property === '@id') { continue; } // handle reverse properties if (property === '@reverse') { var referencedNode = { '@id': name }; var reverseMap = input['@reverse']; for (var reverseProperty in reverseMap) { var items = reverseMap[reverseProperty]; for (var ii = 0; ii < items.length; ++ii) { var item = items[ii]; var itemName = item['@id']; if (graphTypes.isBlankNode(item)) { itemName = issuer.getId(itemName); } api.createNodeMap(item, graphs, graph, issuer, itemName); util.addValue(subjects[itemName], reverseProperty, referencedNode, { propertyIsArray: true, allowDuplicate: false }); } } continue; } // recurse into graph if (property === '@graph') { // add graph subjects map entry if (!(name in graphs)) { graphs[name] = {}; } var g = graph === '@merged' ? graph : name; api.createNodeMap(input[property], graphs, g, issuer); continue; } // copy non-@type keywords if (property !== '@type' && isKeyword(property)) { if (property === '@index' && property in subject && (input[property] !== subject[property] || input[property]['@id'] !== subject[property]['@id'])) { throw new JsonLdError('Invalid JSON-LD syntax; conflicting @index property detected.', 'jsonld.SyntaxError', { code: 'conflicting indexes', subject: subject }); } subject[property] = input[property]; continue; } // iterate over objects var objects = input[property]; // if property is a bnode, assign it a new id if (property.indexOf('_:') === 0) { property = issuer.getId(property); } // ensure property is added for empty arrays if (objects.length === 0) { util.addValue(subject, property, [], { propertyIsArray: true }); continue; } for (var oi = 0; oi < objects.length; ++oi) { var o = objects[oi]; if (property === '@type') { // rename @type blank nodes o = o.indexOf('_:') === 0 ? issuer.getId(o) : o; } // handle embedded subject or subject reference if (graphTypes.isSubject(o) || graphTypes.isSubjectReference(o)) { // relabel blank node @id var id = graphTypes.isBlankNode(o) ? issuer.getId(o['@id']) : o['@id']; // add reference and recurse util.addValue(subject, property, { '@id': id }, { propertyIsArray: true, allowDuplicate: false }); api.createNodeMap(o, graphs, graph, issuer, id); } else if (graphTypes.isList(o)) { // handle @list var _list = []; api.createNodeMap(o['@list'], graphs, graph, issuer, name, _list); o = { '@list': _list }; util.addValue(subject, property, o, { propertyIsArray: true, allowDuplicate: false }); } else { // handle @value api.createNodeMap(o, graphs, graph, issuer, name); util.addValue(subject, property, o, { propertyIsArray: true, allowDuplicate: false }); } } } }; api.mergeNodeMaps = function (graphs) { // add all non-default graphs to default graph var defaultGraph = graphs['@default']; var graphNames = Object.keys(graphs).sort(); for (var i = 0; i < graphNames.length; ++i) { var graphName = graphNames[i]; if (graphName === '@default') { continue; } var nodeMap = graphs[graphName]; var subject = defaultGraph[graphName]; if (!subject) { defaultGraph[graphName] = subject = { '@id': graphName, '@graph': [] }; } else if (!('@graph' in subject)) { subject['@graph'] = []; } var graph = subject['@graph']; var ids = Object.keys(nodeMap).sort(); for (var ii = 0; ii < ids.length; ++ii) { var node = nodeMap[ids[ii]]; // only add full subjects if (!graphTypes.isSubjectReference(node)) { graph.push(node); } } } return defaultGraph; }; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(9); var document = __webpack_require__(1).document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(9); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(37); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /* 37 */ /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(1); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); module.exports = function (key) { return store[key] || (store[key] = {}); }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__(38)('keys'); var uid = __webpack_require__(20); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /* 40 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /* 41 */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(18); var TAG = __webpack_require__(0)('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (e) { /* empty */ } }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 25.4.1.5 NewPromiseCapability(C) var aFunction = __webpack_require__(28); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(1); var core = __webpack_require__(3); var LIBRARY = __webpack_require__(31); var wksExt = __webpack_require__(65); var defineProperty = __webpack_require__(12).f; module.exports = function (name) { var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * An implementation of the RDF Dataset Normalization specification. * This library works in the browser and node.js. * * BSD 3-Clause License * Copyright (c) 2016-2017 Digital Bazaar, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. *.now * Neither the name of the Digital Bazaar, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var util = __webpack_require__(14); var URDNA2015 = __webpack_require__(68); var URGNA2012 = __webpack_require__(124); var URDNA2015Sync = __webpack_require__(72); var URGNA2012Sync = __webpack_require__(125); var URDNA2015Native = void 0; try { URDNA2015Native = __webpack_require__(126)('urdna2015'); } catch (e) {} var api = {}; module.exports = api; // expose helpers api.NQuads = __webpack_require__(48); api.IdentifierIssuer = __webpack_require__(46); /** * Asynchronously canonizes an RDF dataset. * * @param dataset the dataset to canonize. * @param [options] the options to use: * [algorithm] the canonicalization algorithm to use, `URDNA2015` or * `URGNA2012` (default: `URGNA2012`). * [usePureJavaScript] only use JavaScript implementation * (default: false). * @param callback(err, canonical) called once the operation completes. * * @return a Promise that resolves to the canonicalized RDF Dataset. */ api.canonize = util.callbackify(function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(dataset, options) { var callback, promise; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: callback = void 0; promise = new Promise(function (resolve, reject) { callback = function callback(err, canonical) { if (err) { return reject(err); } /*if(options.format === 'application/nquads') { canonical = canonical.join(''); } canonical = _parseNQuads(canonical.join(''));*/ resolve(canonical); }; }); // back-compat with legacy dataset if (!Array.isArray(dataset)) { dataset = api.NQuads.legacyDatasetToQuads(dataset); } // TODO: convert algorithms to Promise-based async if (!(options.algorithm === 'URDNA2015')) { _context.next = 7; break; } if (URDNA2015Native && !options.usePureJavaScript) { URDNA2015Native.main({ dataset: dataset }, callback); } else { new URDNA2015(options).main(dataset, callback); } _context.next = 12; break; case 7: if (!(options.algorithm === 'URGNA2012')) { _context.next = 11; break; } new URGNA2012(options).main(dataset, callback); _context.next = 12; break; case 11: throw new Error('Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); case 12: return _context.abrupt('return', promise); case 13: case 'end': return _context.stop(); } } }, _callee, this); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }()); /** * Synchronously canonizes an RDF dataset. * * @param dataset the dataset to canonize. * @param [options] the options to use: * [algorithm] the canonicalization algorithm to use, `URDNA2015` or * `URGNA2012` (default: `URGNA2012`). * * @return the RDF dataset in canonical form. */ api.canonizeSync = function (dataset, options) { // back-compat with legacy dataset if (!Array.isArray(dataset)) { dataset = api.NQuads.legacyDatasetToQuads(dataset); } if (options.algorithm === 'URDNA2015') { if (URDNA2015Native && !options.usePureJavaScript) { return URDNA2015Native.mainSync({ dataset: dataset }); } return new URDNA2015Sync(options).main(dataset); } if (options.algorithm === 'URGNA2012') { return new URGNA2012Sync(options).main(dataset); } throw new Error('Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); }; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var util = __webpack_require__(14); module.exports = function () { /** * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique * identifiers, keeping track of any previously issued identifiers. * * @param prefix the prefix to use ('<prefix><counter>'). */ function IdentifierIssuer(prefix) { _classCallCheck(this, IdentifierIssuer); this.prefix = prefix; this.counter = 0; this.existing = {}; } /** * Copies this IdentifierIssuer. * * @return a copy of this IdentifierIssuer. */ _createClass(IdentifierIssuer, [{ key: 'clone', value: function clone() { var copy = new IdentifierIssuer(this.prefix); copy.counter = this.counter; copy.existing = util.clone(this.existing); return copy; } /** * Gets the new identifier for the given old identifier, where if no old * identifier is given a new identifier will be generated. * * @param [old] the old identifier to get the new identifier for. * * @return the new identifier. */ }, { key: 'getId', value: function getId(old) { // return existing old identifier if (old && old in this.existing) { return this.existing[old]; } // get next identifier var identifier = this.prefix + this.counter; this.counter += 1; // save mapping if (old) { this.existing[old] = identifier; } return identifier; } /** * Returns true if the given old identifer has already been assigned a new * identifier. * * @param old the old identifier to check. * * @return true if the old identifier has been assigned a new identifier, false * if not. */ }, { key: 'hasId', value: function hasId(old) { return old in this.existing; } }]); return IdentifierIssuer; }(); /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { /** * Node.js module for Forge message digests. * * @author Dave Longley * * Copyright 2011-2017 Digital Bazaar, Inc. */ var forge = __webpack_require__(23); module.exports = forge.md = forge.md || {}; forge.md.algorithms = forge.md.algorithms || {}; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var util = __webpack_require__(121); var TERMS = ['subject', 'predicate', 'object', 'graph']; var RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; var RDF_LANGSTRING = RDF + 'langString'; var XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string'; // build regexes var REGEX = {}; (function () { var iri = '(?:<([^:]+:[^>]*)>)'; var bnode = '(_:(?:[A-Za-z0-9]+))'; var plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"'; var datatype = '(?:\\^\\^' + iri + ')'; var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))'; var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)'; var ws = '[ \\t]+'; var wso = '[ \\t]*'; // define quad part regexes var subject = '(?:' + iri + '|' + bnode + ')' + ws; var property = iri + ws; var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso; var graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))'; // end of line and empty regexes REGEX.eoln = /(?:\r\n)|(?:\n)|(?:\r)/g; REGEX.empty = new RegExp('^' + wso + '$'); // full quad regex REGEX.quad = new RegExp('^' + wso + subject + property + object + graphName + wso + '$'); })(); module.exports = function () { function NQuads() { _classCallCheck(this, NQuads); } _createClass(NQuads, null, [{ key: 'parse', /** * Parses RDF in the form of N-Quads. * * @param input the N-Quads input to parse. * * @return an RDF dataset (an array of quads per http://rdf.js.org/). */ value: function parse(input) { // build RDF dataset var dataset = []; var graphs = {}; // split N-Quad input into lines var lines = input.split(REGEX.eoln); var lineNumber = 0; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = lines[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var line = _step.value; lineNumber++; // skip empty lines if (REGEX.empty.test(line)) { continue; } // parse quad var match = line.match(REGEX.quad); if (match === null) { throw new Error('N-Quads parse error on line ' + lineNumber + '.'); } // create RDF quad var quad = {}; // get subject if (!util.isUndefined(match[1])) { quad.subject = { termType: 'NamedNode', value: match[1] }; } else { quad.subject = { termType: 'BlankNode', value: match[2] }; } // get predicate quad.predicate = { termType: 'NamedNode', value: match[3] }; // get object if (!util.isUndefined(match[4])) { quad.object = { termType: 'NamedNode', value: match[4] }; } else if (!util.isUndefined(match[5])) { quad.object = { termType: 'BlankNode', value: match[5] }; } else { quad.object = { termType: 'Literal', value: undefined, datatype: { termType: 'NamedNode' } }; if (!util.isUndefined(match[7])) { quad.object.datatype.value = match[7]; } else if (!util.isUndefined(match[8])) { quad.object.datatype.value = RDF_LANGSTRING; quad.object.language = match[8]; } else { quad.object.datatype.value = XSD_STRING; } var unescaped = match[6].replace(/\\"/g, '"').replace(/\\t/g, '\t').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\\\/g, '\\'); quad.object.value = unescaped; } // get graph if (!util.isUndefined(match[9])) { quad.graph = { termType: 'NamedNode', value: match[9] }; } else if (!util.isUndefined(match[10])) { quad.graph = { termType: 'BlankNode', value: match[10] }; } else { quad.graph = { termType: 'DefaultGraph', value: '' }; } // only add quad if it is unique in its graph if (!(quad.graph.value in graphs)) { graphs[quad.graph.value] = [quad]; dataset.push(quad); } else { var unique = true; var quads = graphs[quad.graph.value]; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = quads[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var q = _step2.value; if (_compareTriples(q, quad)) { unique = false; break; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (unique) { quads.push(quad); dataset.push(quad); } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return dataset; } /** * Converts an RDF dataset to N-Quads. * * @param dataset (array of quads) the RDF dataset to convert. * * @return the N-Quads string. */ }, { key: 'serialize', value: function serialize(dataset) { if (!Array.isArray(dataset)) { dataset = NQuads.legacyDatasetToQuads(dataset); } var quads = []; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = dataset[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var quad = _step3.value; quads.push(NQuads.serializeQuad(quad)); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } return quads.sort().join(''); } /** * Converts an RDF quad to an N-Quad string (a single quad). * * @param quad the RDF quad convert. * * @return the N-Quad string. */ }, { key: 'serializeQuad', value: function serializeQuad(quad) { var s = quad.subject; var p = quad.predicate; var o = quad.object; var g = quad.graph; var nquad = ''; // subject and predicate can only be NamedNode or BlankNode [s, p].forEach(function (term) { if (term.termType === 'NamedNode') { nquad += '<' + term.value + '>'; } else { nquad += term.value; } nquad += ' '; }); // object is NamedNode, BlankNode, or Literal if (o.termType === 'NamedNode') { nquad += '<' + o.value + '>'; } else if (o.termType === 'BlankNode') { nquad += o.value; } else { var escaped = o.value.replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\"/g, '\\"'); nquad += '"' + escaped + '"'; if (o.datatype.value === RDF_LANGSTRING) { if (o.language) { nquad += '@' + o.language; } } else if (o.datatype.value !== XSD_STRING) { nquad += '^^<' + o.datatype.value + '>'; } } // graph can only be NamedNode or BlankNode (or DefaultGraph, but that // does not add to `nquad`) if (g.termType === 'NamedNode') { nquad += ' <' + g.value + '>'; } else if (g.termType === 'BlankNode') { nquad += ' ' + g.value; } nquad += ' .\n'; return nquad; } /** * Converts a legacy-formatted dataset to an array of quads dataset per * http://rdf.js.org/. * * @param dataset the legacy dataset to convert. * * @return the array of quads dataset. */ }, { key: 'legacyDatasetToQuads', value: function legacyDatasetToQuads(dataset) { var quads = []; var termTypeMap = { 'blank node': 'BlankNode', 'IRI': 'NamedNode', 'literal': 'Literal' }; var _loop = function _loop(graphName) { var triples = dataset[graphName]; triples.forEach(function (triple) { var quad = {}; for (var componentName in triple) { var oldComponent = triple[componentName]; var newComponent = { termType: termTypeMap[oldComponent.type], value: oldComponent.value }; if (newComponent.termType === 'Literal') { newComponent.datatype = { termType: 'NamedNode' }; if ('datatype' in oldComponent) { newComponent.datatype.value = oldComponent.datatype; } if ('language' in oldComponent) { if (!('datatype' in oldComponent)) { newComponent.datatype.value = RDF_LANGSTRING; } newComponent.language = oldComponent.language; } else if (!('datatype' in oldComponent)) { newComponent.datatype.value = XSD_STRING; } } quad[componentName] = newComponent; } if (graphName === '@default') { quad.graph = { termType: 'DefaultGraph', value: '' }; } else { quad.graph = { termType: graphName.startsWith('_:') ? 'BlankNode' : 'NamedNode', value: graphName }; } quads.push(quad); }); }; for (var graphName in dataset) { _loop(graphName); } return quads; } }]); return NQuads; }(); /** * Compares two RDF triples for equality. * * @param t1 the first triple. * @param t2 the second triple. * * @return true if the triples are the same, false if not. */ function _compareTriples(t1, t2) { for (var k in t1) { if (t1[k].termType !== t2[k].termType || t1[k].value !== t2[k].value) { return false; } } if (t1.termType !== 'Literal') { return true; } return t1.object.datatype.termType === t2.object.datatype.termType && t1.object.datatype.value === t2.object.datatype.value && t1.object.language === t2.object.language; } /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Ignore module for browserify (see package.json) /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __webpack_require__(2), callbackify = _require.callbackify, normalizeDocumentLoader = _require.normalizeDocumentLoader; module.exports = function () { /** * Creates a simple queue for requesting documents. */ function RequestQueue() { _classCallCheck(this, RequestQueue); this._requests = {}; this.add = callbackify(this.add.bind(this)); } _createClass(RequestQueue, [{ key: 'wrapLoader', value: function wrapLoader(loader) { var self = this; self._loader = normalizeDocumentLoader(loader); return function (url) { return self.add.apply(self, arguments); }; } }, { key: 'add', value: function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) { var self, promise; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: self = this; promise = self._requests[url]; if (!promise) { _context.next = 4; break; } return _context.abrupt('return', Promise.resolve(promise)); case 4: // queue URL and load it promise = self._requests[url] = self._loader(url); _context.prev = 5; _context.next = 8; return promise; case 8: return _context.abrupt('return', _context.sent); case 9: _context.prev = 9; delete self._requests[url]; return _context.finish(9); case 12: case 'end': return _context.stop(); } } }, _callee, this, [[5,, 9, 12]]); })); function add(_x) { return _ref.apply(this, arguments); } return add; }() }]); return RequestQueue; }(); /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(13) && !__webpack_require__(19)(function () { return Object.defineProperty(__webpack_require__(34)('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(17); var toLength = __webpack_require__(36); var toAbsoluteIndex = __webpack_require__(77); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(18); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = __webpack_require__(0)('unscopables'); var ArrayProto = Array.prototype; if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(11)(ArrayProto, UNSCOPABLES, {}); module.exports = function (key) { ArrayProto[UNSCOPABLES][key] = true; }; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__(10); var toIObject = __webpack_require__(17); var arrayIndexOf = __webpack_require__(52)(false); var IE_PROTO = __webpack_require__(39)('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(29); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 19.1.3.6 Object.prototype.toString() var classof = __webpack_require__(42); var test = {}; test[__webpack_require__(0)('toStringTag')] = 'z'; if (test + '' != '[object z]') { __webpack_require__(16)(Object.prototype, 'toString', function toString() { return '[object ' + classof(this) + ']'; }, true); } /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(31); var $export = __webpack_require__(7); var redefine = __webpack_require__(16); var hide = __webpack_require__(11); var has = __webpack_require__(10); var Iterators = __webpack_require__(22); var $iterCreate = __webpack_require__(84); var setToStringTag = __webpack_require__(32); var getPrototypeOf = __webpack_require__(86); var ITERATOR = __webpack_require__(0)('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = (!BUGGY && $native) || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(8); var dPs = __webpack_require__(85); var enumBugKeys = __webpack_require__(40); var IE_PROTO = __webpack_require__(39)('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(34)('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__(60).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__(1).document; module.exports = document && document.documentElement; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(8); var aFunction = __webpack_require__(28); var SPECIES = __webpack_require__(0)('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(27); var invoke = __webpack_require__(96); var html = __webpack_require__(60); var cel = __webpack_require__(34); var global = __webpack_require__(1); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; var MessageChannel = global.MessageChannel; var Dispatch = global.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function () { var id = +this; // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function (event) { run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!setTask || !clearTask) { setTask = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (__webpack_require__(18)(process) == 'process') { defer = function (id) { process.nextTick(ctx(run, id, 1)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if (MessageChannel) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { defer = function (id) { global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in cel('script')) { defer = function (id) { html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }), /* 63 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return { e: false, v: exec() }; } catch (e) { return { e: true, v: e }; } }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(8); var isObject = __webpack_require__(9); var newPromiseCapability = __webpack_require__(43); module.exports = function (C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__(0); /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(55); var hiddenKeys = __webpack_require__(40).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; /***/ }), /* 67 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var AsyncAlgorithm = __webpack_require__(118); var IdentifierIssuer = __webpack_require__(46); var MessageDigest = __webpack_require__(69); var Permutator = __webpack_require__(71); var NQuads = __webpack_require__(48); var util = __webpack_require__(14); var POSITIONS = { 'subject': 's', 'object': 'o', 'graph': 'g' }; module.exports = function (_AsyncAlgorithm) { _inherits(URDNA2015, _AsyncAlgorithm); function URDNA2015(options) { _classCallCheck(this, URDNA2015); options = options || {}; var _this = _possibleConstructorReturn(this, (URDNA2015.__proto__ || Object.getPrototypeOf(URDNA2015)).call(this, options)); _this.name = 'URDNA2015'; _this.options = Object.assign({}, options); _this.blankNodeInfo = {}; _this.hashToBlankNodes = {}; _this.canonicalIssuer = new IdentifierIssuer('_:c14n'); _this.hashAlgorithm = 'sha256'; _this.quads; return _this; } // 4.4) Normalization Algorithm _createClass(URDNA2015, [{ key: 'main', value: function main(dataset, callback) { var self = this; self.schedule.start = Date.now(); var result = void 0; self.quads = dataset; // 1) Create the normalization state. // Note: Optimize by generating non-normalized blank node map concurrently. var nonNormalized = {}; self.waterfall([function (callback) { // 2) For every quad in input dataset: self.forEach(dataset, function (quad, idx, callback) { // 2.1) For each blank node that occurs in the quad, add a reference // to the quad using the blank node identifier in the blank node to // quads map, creating a new entry if necessary. self.forEachComponent(quad, function (component) { if (component.termType !== 'BlankNode') { return; } var id = component.value; if (id in self.blankNodeInfo) { self.blankNodeInfo[id].quads.push(quad); } else { nonNormalized[id] = true; self.blankNodeInfo[id] = { quads: [quad] }; } }); callback(); }, callback); }, function (callback) { // 3) Create a list of non-normalized blank node identifiers // non-normalized identifiers and populate it using the keys from the // blank node to quads map. // Note: We use a map here and it was generated during step 2. // 4) Initialize simple, a boolean flag, to true. var simple = true; // 5) While simple is true, issue canonical identifiers for blank nodes: self.whilst(function () { return simple; }, function (callback) { // 5.1) Set simple to false. simple = false; // 5.2) Clear hash to blank nodes map. self.hashToBlankNodes = {}; self.waterfall([function (callback) { // 5.3) For each blank node identifier identifier in // non-normalized identifiers: self.forEach(nonNormalized, function (value, id, callback) { // 5.3.1) Create a hash, hash, according to the Hash First // Degree Quads algorithm. self.hashFirstDegreeQuads(id, function (err, hash) { if (err) { return callback(err); } // 5.3.2) Add hash and identifier to hash to blank nodes map, // creating a new entry if necessary. if (hash in self.hashToBlankNodes) { self.hashToBlankNodes[hash].push(id); } else { self.hashToBlankNodes[hash] = [id]; } callback(); }); }, callback); }, function (callback) { // 5.4) For each hash to identifier list mapping in hash to blank // nodes map, lexicographically-sorted by hash: var hashes = Object.keys(self.hashToBlankNodes).sort(); self.forEach(hashes, function (hash, i, callback) { // 5.4.1) If the length of identifier list is greater than 1, // continue to the next mapping. var idList = self.hashToBlankNodes[hash]; if (idList.length > 1) { return callback(); } // 5.4.2) Use the Issue Identifier algorithm, passing canonical // issuer and the single blank node identifier in identifier // list, identifier, to issue a canonical replacement identifier // for identifier. // TODO: consider changing `getId` to `issue` var id = idList[0]; self.canonicalIssuer.getId(id); // 5.4.3) Remove identifier from non-normalized identifiers. delete nonNormalized[id]; // 5.4.4) Remove hash from the hash to blank nodes map. delete self.hashToBlankNodes[hash]; // 5.4.5) Set simple to true. simple = true; callback(); }, callback); }], callback); }, callback); }, function (callback) { // 6) For each hash to identifier list mapping in hash to blank nodes // map, lexicographically-sorted by hash: var hashes = Object.keys(self.hashToBlankNodes).sort(); self.forEach(hashes, function (hash, idx, callback) { // 6.1) Create hash path list where each item will be a result of // running the Hash N-Degree Quads algorithm. var hashPathList = []; // 6.2) For each blank node identifier identifier in identifier list: var idList = self.hashToBlankNodes[hash]; self.waterfall([function (callback) { self.forEach(idList, function (id, idx, callback) { // 6.2.1) If a canonical identifier has already been issued for // identifier, continue to the next identifier. if (self.canonicalIssuer.hasId(id)) { return callback(); } // 6.2.2) Create temporary issuer, an identifier issuer // initialized with the prefix _:b. var issuer = new IdentifierIssuer('_:b'); // 6.2.3) Use the Issue Identifier algorithm, passing temporary // issuer and identifier, to issue a new temporary blank node // identifier for identifier. issuer.getId(id); // 6.2.4) Run the Hash N-Degree Quads algorithm, passing // temporary issuer, and append the result to the hash path // list. self.hashNDegreeQuads(id, issuer, function (err, result) { if (err) { return callback(err); } hashPathList.push(result); callback(); }); }, callback); }, function (callback) { // 6.3) For each result in the hash path list, // lexicographically-sorted by the hash in result: // TODO: use `String.localeCompare`? hashPathList.sort(function (a, b) { return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0; }); self.forEach(hashPathList, function (result, idx, callback) { // 6.3.1) For each blank node identifier, existing identifier, // that was issued a temporary identifier by identifier issuer // in result, issue a canonical identifier, in the same order, // using the Issue Identifier algorithm, passing canonical // issuer and existing identifier. for (var existing in result.issuer.existing) { self.canonicalIssuer.getId(existing); } callback(); }, callback); }], callback); }, callback); }, function (callback) { /* Note: At this point all blank nodes in the set of RDF quads have been assigned canonical identifiers, which have been stored in the canonical issuer. Here each quad is updated by assigning each of its blank nodes its new identifier. */ // 7) For each quad, quad, in input dataset: var normalized = []; self.waterfall([function (callback) { self.forEach(self.quads, function (quad, idx, callback) { // 7.1) Create a copy, quad copy, of quad and replace any existing // blank node identifiers using the canonical identifiers // previously issued by canonical issuer. // Note: We optimize away the copy here. self.forEachComponent(quad, function (component) { if (component.termType === 'BlankNode' && !component.value.startsWith(self.canonicalIssuer.prefix)) { component.value = self.canonicalIssuer.getId(component.value); } }); // 7.2) Add quad copy to the normalized dataset. normalized.push(NQuads.serializeQuad(quad)); callback(); }, callback); }, function (callback) { // sort normalized output normalized.sort(); // 8) Return the normalized dataset. result = normalized.join(''); return callback(); }], callback); }], function (err) { return callback(err, result); }); } // 4.6) Hash First Degree Quads }, { key: 'hashFirstDegreeQuads', value: function hashFirstDegreeQuads(id, callback) { var self = this; // return cached hash var info = self.blankNodeInfo[id]; if ('hash' in info) { return callback(null, info.hash); } // 1) Initialize nquads to an empty list. It will be used to store quads in // N-Quads format. var nquads = []; // 2) Get the list of quads quads associated with the reference blank node // identifier in the blank node to quads map. var quads = info.quads; // 3) For each quad quad in quads: self.forEach(quads, function (quad, idx, callback) { // 3.1) Serialize the quad in N-Quads format with the following special // rule: // 3.1.1) If any component in quad is an blank node, then serialize it // using a special identifier as follows: var copy = { predicate: quad.predicate }; self.forEachComponent(quad, function (component, key) { // 3.1.2) If the blank node's existing blank node identifier matches the // reference blank node identifier then use the blank node identifier // _:a, otherwise, use the blank node identifier _:z. copy[key] = self.modifyFirstDegreeComponent(id, component, key); }); nquads.push(NQuads.serializeQuad(copy)); callback(); }, function (err) { if (err) { return callback(err); } // 4) Sort nquads in lexicographical order. nquads.sort(); // 5) Return the hash that results from passing the sorted, joined nquads // through the hash algorithm. var md = new MessageDigest(self.hashAlgorithm); for (var i = 0; i < nquads.length; ++i) { md.update(nquads[i]); } // TODO: represent as byte buffer instead to cut memory usage in half info.hash = md.digest(); callback(null, info.hash); }); } // 4.7) Hash Related Blank Node }, { key: 'hashRelatedBlankNode', value: function hashRelatedBlankNode(related, quad, issuer, position, callback) { var self = this; // 1) Set the identifier to use for related, preferring first the canonical // identifier for related if issued, second the identifier issued by issuer // if issued, and last, if necessary, the result of the Hash First Degree // Quads algorithm, passing related. var id = void 0; self.waterfall([function (callback) { if (self.canonicalIssuer.hasId(related)) { id = self.canonicalIssuer.getId(related); return callback(); } if (issuer.hasId(related)) { id = issuer.getId(related); return callback(); } self.hashFirstDegreeQuads(related, function (err, hash) { if (err) { return callback(err); } id = hash; callback(); }); }], function (err) { if (err) { return callback(err); } // 2) Initialize a string input to the value of position. // Note: We use a hash object instead. var md = new MessageDigest(self.hashAlgorithm); md.update(position); // 3) If position is not g, append <, the value of the predicate in quad, // and > to input. if (position !== 'g') { md.update(self.getRelatedPredicate(quad)); } // 4) Append identifier to input. md.update(id); // 5) Return the hash that results from passing input through the hash // algorithm. // TODO: represent as byte buffer instead to cut memory usage in half return callback(null, md.digest()); }); } // 4.8) Hash N-Degree Quads }, { key: 'hashNDegreeQuads', value: function hashNDegreeQuads(id, issuer, callback) { var self = this; // 1) Create a hash to related blank nodes map for storing hashes that // identify related blank nodes. // Note: 2) and 3) handled within `createHashToRelated` var hashToRelated = void 0; var md = new MessageDigest(self.hashAlgorithm); self.waterfall([function (callback) { return self.createHashToRelated(id, issuer, function (err, result) { if (err) { return callback(err); } hashToRelated = result; callback(); }); }, function (callback) { // 4) Create an empty string, data to hash. // Note: We created a hash object `md` above instead. // 5) For each related hash to blank node list mapping in hash to // related blank nodes map, sorted lexicographically by related hash: var hashes = Object.keys(hashToRelated).sort(); self.forEach(hashes, function (hash, idx, callback) { // 5.1) Append the related hash to the data to hash. md.update(hash); // 5.2) Create a string chosen path. var chosenPath = ''; // 5.3) Create an unset chosen issuer variable. var chosenIssuer = void 0; // 5.4) For each permutation of blank node list: var permutator = new Permutator(hashToRelated[hash]); self.whilst(function () { return permutator.hasNext(); }, function (nextPermutation) { var permutation = permutator.next(); // 5.4.1) Create a copy of issuer, issuer copy. var issuerCopy = issuer.clone(); // 5.4.2) Create a string path. var path = ''; // 5.4.3) Create a recursion list, to store blank node identifiers // that must be recursively processed by this algorithm. var recursionList = []; self.waterfall([function (callback) { // 5.4.4) For each related in permutation: self.forEach(permutation, function (related, idx, callback) { // 5.4.4.1) If a canonical identifier has been issued for // related, append it to path. if (self.canonicalIssuer.hasId(related)) { path += self.canonicalIssuer.getId(related); } else { // 5.4.4.2) Otherwise: // 5.4.4.2.1) If issuer copy has not issued an identifier // for related, append related to recursion list. if (!issuerCopy.hasId(related)) { recursionList.push(related); } // 5.4.4.2.2) Use the Issue Identifier algorithm, passing // issuer copy and related and append the result to path. path += issuerCopy.getId(related); } // 5.4.4.3) If chosen path is not empty and the length of path // is greater than or equal to the length of chosen path and // path is lexicographically greater than chosen path, then // skip to the next permutation. if (chosenPath.length !== 0 && path.length >= chosenPath.length && path > chosenPath) { // FIXME: may cause inaccurate total depth calculation return nextPermutation(); } callback(); }, callback); }, function (callback) { // 5.4.5) For each related in recursion list: self.forEach(recursionList, function (related, idx, callback) { // 5.4.5.1) Set result to the result of recursively executing // the Hash N-Degree Quads algorithm, passing related for // identifier and issuer copy for path identifier issuer. self.hashNDegreeQuads(related, issuerCopy, function (err, result) { if (err) { return callback(err); } // 5.4.5.2) Use the Issue Identifier algorithm, passing // issuer copy and related and append the result to path. path += issuerCopy.getId(related); // 5.4.5.3) Append <, the hash in result, and > to path. path += '<' + result.hash + '>'; // 5.4.5.4) Set issuer copy to the identifier issuer in // result. issuerCopy = result.issuer; // 5.4.5.5) If chosen path is not empty and the length of // path is greater than or equal to the length of chosen // path and path is lexicographically greater than chosen // path, then skip to the next permutation. if (chosenPath.length !== 0 && path.length >= chosenPath.length && path > chosenPath) { // FIXME: may cause inaccurate total depth calculation return nextPermutation(); } callback(); }); }, callback); }, function (callback) { // 5.4.6) If chosen path is empty or path is lexicographically // less than chosen path, set chosen path to path and chosen // issuer to issuer copy. if (chosenPath.length === 0 || path < chosenPath) { chosenPath = path; chosenIssuer = issuerCopy; } callback(); }], nextPermutation); }, function (err) { if (err) { return callback(err); } // 5.5) Append chosen path to data to hash. md.update(chosenPath); // 5.6) Replace issuer, by reference, with chosen issuer. issuer = chosenIssuer; callback(); }); }, callback); }], function (err) { // 6) Return issuer and the hash that results from passing data to hash // through the hash algorithm. callback(err, { hash: md.digest(), issuer: issuer }); }); } // helper for modifying component during Hash First Degree Quads }, { key: 'modifyFirstDegreeComponent', value: function modifyFirstDegreeComponent(id, component) { if (component.termType !== 'BlankNode') { return component; } component = util.clone(component); component.value = component.value === id ? '_:a' : '_:z'; return component; } // helper for getting a related predicate }, { key: 'getRelatedPredicate', value: function getRelatedPredicate(quad) { return '<' + quad.predicate.value + '>'; } // helper for creating hash to related blank nodes map }, { key: 'createHashToRelated', value: function createHashToRelated(id, issuer, callback) { var self = this; // 1) Create a hash to related blank nodes map for storing hashes that // identify related blank nodes. var hashToRelated = {}; // 2) Get a reference, quads, to the list of quads in the blank node to // quads map for the key identifier. var quads = self.blankNodeInfo[id].quads; // 3) For each quad in quads: self.forEach(quads, function (quad, idx, callback) { // 3.1) For each component in quad, if component is the subject, object, // and graph name and it is a blank node that is not identified by // identifier: self.forEach(quad, function (component, key, callback) { if (key === 'predicate' || !(component.termType === 'BlankNode' && component.value !== id)) { return callback(); } // 3.1.1) Set hash to the result of the Hash Related Blank Node // algorithm, passing the blank node identifier for component as // related, quad, path identifier issuer as issuer, and position as // either s, o, or g based on whether component is a subject, object, // graph name, respectively. var related = component.value; var position = POSITIONS[key]; self.hashRelatedBlankNode(related, quad, issuer, position, function (err, hash) { if (err) { return callback(err); } // 3.1.2) Add a mapping of hash to the blank node identifier for // component to hash to related blank nodes map, adding an entry as // necessary. if (hash in hashToRelated) { hashToRelated[hash].push(related); } else { hashToRelated[hash] = [related]; } callback(); }); }, callback); }, function (err) { return callback(err, hashToRelated); }); } // helper that iterates over quad components (skips predicate) }, { key: 'forEachComponent', value: function forEachComponent(quad, op) { for (var key in quad) { // skip `predicate` if (key === 'predicate') { continue; } op(quad[key], key, quad); } } }]); return URDNA2015; }(AsyncAlgorithm); /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var forge = __webpack_require__(23); __webpack_require__(47); __webpack_require__(119); __webpack_require__(120); module.exports = function () { /** * Creates a new MessageDigest. * * @param algorithm the algorithm to use. */ function MessageDigest(algorithm) { _classCallCheck(this, MessageDigest); this.md = forge.md[algorithm].create(); } _createClass(MessageDigest, [{ key: 'update', value: function update(msg) { this.md.update(msg, 'utf8'); } }, { key: 'digest', value: function digest() { return this.md.digest().toHex(); } }]); return MessageDigest; }(); /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { /** * Utility functions for web applications. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. */ var forge = __webpack_require__(23); /* Utilities API */ var util = module.exports = forge.util = forge.util || {}; // define setImmediate and nextTick (function() { // use native nextTick if(typeof process !== 'undefined' && process.nextTick) { util.nextTick = process.nextTick; if(typeof setImmediate === 'function') { util.setImmediate = setImmediate; } else { // polyfill setImmediate with nextTick, older versions of node // (those w/o setImmediate) won't totally starve IO util.setImmediate = util.nextTick; } return; } // polyfill nextTick with native setImmediate if(typeof setImmediate === 'function') { util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; util.nextTick = function(callback) { return setImmediate(callback); }; return; } /* Note: A polyfill upgrade pattern is used here to allow combining polyfills. For example, MutationObserver is fast, but blocks UI updates, so it needs to allow UI updates periodically, so it falls back on postMessage or setTimeout. */ // polyfill with setTimeout util.setImmediate = function(callback) { setTimeout(callback, 0); }; // upgrade polyfill to use postMessage if(typeof window !== 'undefined' && typeof window.postMessage === 'function') { var msg = 'forge.setImmediate'; var callbacks = []; util.setImmediate = function(callback) { callbacks.push(callback); // only send message when one hasn't been sent in // the current turn of the event loop if(callbacks.length === 1) { window.postMessage(msg, '*'); } }; function handler(event) { if(event.source === window && event.data === msg) { event.stopPropagation(); var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); } } window.addEventListener('message', handler, true); } // upgrade polyfill to use MutationObserver if(typeof MutationObserver !== 'undefined') { // polyfill with MutationObserver var now = Date.now(); var attr = true; var div = document.createElement('div'); var callbacks = []; new MutationObserver(function() { var copy = callbacks.slice(); callbacks.length = 0; copy.forEach(function(callback) { callback(); }); }).observe(div, {attributes: true}); var oldSetImmediate = util.setImmediate; util.setImmediate = function(callback) { if(Date.now() - now > 15) { now = Date.now(); oldSetImmediate(callback); } else { callbacks.push(callback); // only trigger observer when it hasn't been triggered in // the current turn of the event loop if(callbacks.length === 1) { div.setAttribute('a', attr = !attr); } } }; } util.nextTick = util.setImmediate; })(); // check if running under Node.js util.isNodejs = typeof process !== 'undefined' && process.versions && process.versions.node; // define isArray util.isArray = Array.isArray || function(x) { return Object.prototype.toString.call(x) === '[object Array]'; }; // define isArrayBuffer util.isArrayBuffer = function(x) { return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; }; // define isArrayBufferView util.isArrayBufferView = function(x) { return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; }; /** * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for * algorithms where bit manipulation, JavaScript limitations, and/or algorithm * design only allow for byte operations of a limited size. * * @param n number of bits. * * Throw Error if n invalid. */ function _checkBitsParam(n) { if(!(n === 8 || n === 16 || n === 24 || n === 32)) { throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); } } // TODO: set ByteBuffer to best available backing util.ByteBuffer = ByteStringBuffer; /** Buffer w/BinaryString backing */ /** * Constructor for a binary string backed byte buffer. * * @param [b] the bytes to wrap (either encoded as string, one byte per * character, or as an ArrayBuffer or Typed Array). */ function ByteStringBuffer(b) { // TODO: update to match DataBuffer API // the data in this buffer this.data = ''; // the pointer for reading from this buffer this.read = 0; if(typeof b === 'string') { this.data = b; } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { // convert native buffer to forge buffer // FIXME: support native buffers internally instead var arr = new Uint8Array(b); try { this.data = String.fromCharCode.apply(null, arr); } catch(e) { for(var i = 0; i < arr.length; ++i) { this.putByte(arr[i]); } } } else if(b instanceof ByteStringBuffer || (typeof b === 'object' && typeof b.data === 'string' && typeof b.read === 'number')) { // copy existing buffer this.data = b.data; this.read = b.read; } // used for v8 optimization this._constructedStringLength = 0; } util.ByteStringBuffer = ByteStringBuffer; /* Note: This is an optimization for V8-based browsers. When V8 concatenates a string, the strings are only joined logically using a "cons string" or "constructed/concatenated string". These containers keep references to one another and can result in very large memory usage. For example, if a 2MB string is constructed by concatenating 4 bytes together at a time, the memory usage will be ~44MB; so ~22x increase. The strings are only joined together when an operation requiring their joining takes place, such as substr(). This function is called when adding data to this buffer to ensure these types of strings are periodically joined to reduce the memory footprint. */ var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { this._constructedStringLength += x; if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { // this substr() should cause the constructed string to join this.data.substr(0, 1); this._constructedStringLength = 0; } }; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.ByteStringBuffer.prototype.length = function() { return this.data.length - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.ByteStringBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putByte = function(b) { return this.putBytes(String.fromCharCode(b)); }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { b = String.fromCharCode(b); var d = this.data; while(n > 0) { if(n & 1) { d += b; } n >>>= 1; if(n > 0) { b += b; } } this.data = d; this._optimizeConstructedString(n); return this; }; /** * Puts bytes in this buffer. * * @param bytes the bytes (as a UTF-8 encoded string) to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBytes = function(bytes) { this.data += bytes; this._optimizeConstructedString(bytes.length); return this; }; /** * Puts a UTF-16 encoded string into this buffer. * * @param str the string to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.putString = function(str) { return this.putBytes(util.encodeUtf8(str)); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16 = function(i) { return this.putBytes( String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24 = function(i) { return this.putBytes( String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32 = function(i) { return this.putBytes( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt16Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF)); }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt24Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF)); }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt32Le = function(i) { return this.putBytes( String.fromCharCode(i & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 24 & 0xFF)); }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); var bytes = ''; do { n -= 8; bytes += String.fromCharCode((i >> n) & 0xFF); } while(n > 0); return this.putBytes(bytes); }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { // putInt checks n if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.ByteStringBuffer.prototype.putBuffer = function(buffer) { return this.putBytes(buffer.getBytes()); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.ByteStringBuffer.prototype.getByte = function() { return this.data.charCodeAt(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16 = function() { var rval = ( this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1)); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24 = function() { var rval = ( this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32 = function() { var rval = ( this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3)); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.ByteStringBuffer.prototype.getInt16Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.ByteStringBuffer.prototype.getInt24Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.ByteStringBuffer.prototype.getInt32Le = function() { var rval = ( this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by ceil(n/8). * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.charCodeAt(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.ByteStringBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out into a UTF-8 string and clears them from the buffer. * * @param count the number of bytes to read, undefined or null for all. * * @return a UTF-8 string of bytes. */ util.ByteStringBuffer.prototype.getBytes = function(count) { var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a UTF-8 encoded string of the bytes from this buffer without modifying * the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of UTF-8 encoded characters. */ util.ByteStringBuffer.prototype.bytes = function(count) { return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.ByteStringBuffer.prototype.at = function(i) { return this.data.charCodeAt(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.ByteStringBuffer.prototype.setAt = function(i, b) { this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.ByteStringBuffer.prototype.last = function() { return this.data.charCodeAt(this.data.length - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.ByteStringBuffer.prototype.copy = function() { var c = util.createBuffer(this.data); c.read = this.read; return c; }; /** * Compacts this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.compact = function() { if(this.read > 0) { this.data = this.data.slice(this.read); this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.ByteStringBuffer.prototype.clear = function() { this.data = ''; this.read = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.ByteStringBuffer.prototype.truncate = function(count) { var len = Math.max(0, this.length() - count); this.data = this.data.substr(this.read, len); this.read = 0; return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.ByteStringBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.length; ++i) { var b = this.data.charCodeAt(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a UTF-16 string (standard JavaScript string). * * @return a UTF-16 string. */ util.ByteStringBuffer.prototype.toString = function() { return util.decodeUtf8(this.bytes()); }; /** End Buffer w/BinaryString backing */ /** Buffer w/UInt8Array backing */ /** * FIXME: Experimental. Do not use yet. * * Constructor for an ArrayBuffer-backed byte buffer. * * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a * TypedArray. * * If a string is given, its encoding should be provided as an option, * otherwise it will default to 'binary'. A 'binary' string is encoded such * that each character is one byte in length and size. * * If an ArrayBuffer, DataView, or TypedArray is given, it will be used * *directly* without any copying. Note that, if a write to the buffer requires * more space, the buffer will allocate a new backing ArrayBuffer to * accommodate. The starting read and write offsets for the buffer may be * given as options. * * @param [b] the initial bytes for this buffer. * @param options the options to use: * [readOffset] the starting read offset to use (default: 0). * [writeOffset] the starting write offset to use (default: the * length of the first parameter). * [growSize] the minimum amount, in bytes, to grow the buffer by to * accommodate writes (default: 1024). * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the * first parameter, if it is a string (default: 'binary'). */ function DataBuffer(b, options) { // default options options = options || {}; // pointers for read from/write to buffer this.read = options.readOffset || 0; this.growSize = options.growSize || 1024; var isArrayBuffer = util.isArrayBuffer(b); var isArrayBufferView = util.isArrayBufferView(b); if(isArrayBuffer || isArrayBufferView) { // use ArrayBuffer directly if(isArrayBuffer) { this.data = new DataView(b); } else { // TODO: adjust read/write offset based on the type of view // or specify that this must be done in the options ... that the // offsets are byte-based this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); } this.write = ('writeOffset' in options ? options.writeOffset : this.data.byteLength); return; } // initialize to empty array buffer and add any given bytes using putBytes this.data = new DataView(new ArrayBuffer(0)); this.write = 0; if(b !== null && b !== undefined) { this.putBytes(b); } if('writeOffset' in options) { this.write = options.writeOffset; } } util.DataBuffer = DataBuffer; /** * Gets the number of bytes in this buffer. * * @return the number of bytes in this buffer. */ util.DataBuffer.prototype.length = function() { return this.write - this.read; }; /** * Gets whether or not this buffer is empty. * * @return true if this buffer is empty, false if not. */ util.DataBuffer.prototype.isEmpty = function() { return this.length() <= 0; }; /** * Ensures this buffer has enough empty space to accommodate the given number * of bytes. An optional parameter may be given that indicates a minimum * amount to grow the buffer if necessary. If the parameter is not given, * the buffer will be grown by some previously-specified default amount * or heuristic. * * @param amount the number of bytes to accommodate. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if * necessary. */ util.DataBuffer.prototype.accommodate = function(amount, growSize) { if(this.length() >= amount) { return this; } growSize = Math.max(growSize || this.growSize, amount); // grow buffer var src = new Uint8Array( this.data.buffer, this.data.byteOffset, this.data.byteLength); var dst = new Uint8Array(this.length() + growSize); dst.set(src); this.data = new DataView(dst.buffer); return this; }; /** * Puts a byte in this buffer. * * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.putByte = function(b) { this.accommodate(1); this.data.setUint8(this.write++, b); return this; }; /** * Puts a byte in this buffer N times. * * @param b the byte to put. * @param n the number of bytes of value b to put. * * @return this buffer. */ util.DataBuffer.prototype.fillWithByte = function(b, n) { this.accommodate(n); for(var i = 0; i < n; ++i) { this.data.setUint8(b); } return this; }; /** * Puts bytes in this buffer. The bytes may be given as a string, an * ArrayBuffer, a DataView, or a TypedArray. * * @param bytes the bytes to put. * @param [encoding] the encoding for the first parameter ('binary', 'utf8', * 'utf16', 'hex'), if it is a string (default: 'binary'). * * @return this buffer. */ util.DataBuffer.prototype.putBytes = function(bytes, encoding) { if(util.isArrayBufferView(bytes)) { var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); var len = src.byteLength - src.byteOffset; this.accommodate(len); var dst = new Uint8Array(this.data.buffer, this.write); dst.set(src); this.write += len; return this; } if(util.isArrayBuffer(bytes)) { var src = new Uint8Array(bytes); this.accommodate(src.byteLength); var dst = new Uint8Array(this.data.buffer); dst.set(src, this.write); this.write += src.byteLength; return this; } // bytes is a util.DataBuffer or equivalent if(bytes instanceof util.DataBuffer || (typeof bytes === 'object' && typeof bytes.read === 'number' && typeof bytes.write === 'number' && util.isArrayBufferView(bytes.data))) { var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); this.accommodate(src.byteLength); var dst = new Uint8Array(bytes.data.byteLength, this.write); dst.set(src); this.write += src.byteLength; return this; } if(bytes instanceof util.ByteStringBuffer) { // copy binary string and process as the same as a string parameter below bytes = bytes.data; encoding = 'binary'; } // string conversion encoding = encoding || 'binary'; if(typeof bytes === 'string') { var view; // decode from string if(encoding === 'hex') { this.accommodate(Math.ceil(bytes.length / 2)); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.hex.decode(bytes, view, this.write); return this; } if(encoding === 'base64') { this.accommodate(Math.ceil(bytes.length / 4) * 3); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.base64.decode(bytes, view, this.write); return this; } // encode text as UTF-8 bytes if(encoding === 'utf8') { // encode as UTF-8 then decode string as raw binary bytes = util.encodeUtf8(bytes); encoding = 'binary'; } // decode string as raw binary if(encoding === 'binary' || encoding === 'raw') { // one byte per character this.accommodate(bytes.length); view = new Uint8Array(this.data.buffer, this.write); this.write += util.binary.raw.decode(view); return this; } // encode text as UTF-16 bytes if(encoding === 'utf16') { // two bytes per character this.accommodate(bytes.length * 2); view = new Uint16Array(this.data.buffer, this.write); this.write += util.text.utf16.encode(view); return this; } throw new Error('Invalid encoding: ' + encoding); } throw Error('Invalid parameter: ' + bytes); }; /** * Puts the given buffer into this buffer. * * @param buffer the buffer to put into this one. * * @return this buffer. */ util.DataBuffer.prototype.putBuffer = function(buffer) { this.putBytes(buffer); buffer.clear(); return this; }; /** * Puts a string into this buffer. * * @param str the string to put. * @param [encoding] the encoding for the string (default: 'utf16'). * * @return this buffer. */ util.DataBuffer.prototype.putString = function(str) { return this.putBytes(str, 'utf16'); }; /** * Puts a 16-bit integer in this buffer in big-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16 = function(i) { this.accommodate(2); this.data.setInt16(this.write, i); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in big-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24 = function(i) { this.accommodate(3); this.data.setInt16(this.write, i >> 8 & 0xFFFF); this.data.setInt8(this.write, i >> 16 & 0xFF); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in big-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32 = function(i) { this.accommodate(4); this.data.setInt32(this.write, i); this.write += 4; return this; }; /** * Puts a 16-bit integer in this buffer in little-endian order. * * @param i the 16-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt16Le = function(i) { this.accommodate(2); this.data.setInt16(this.write, i, true); this.write += 2; return this; }; /** * Puts a 24-bit integer in this buffer in little-endian order. * * @param i the 24-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt24Le = function(i) { this.accommodate(3); this.data.setInt8(this.write, i >> 16 & 0xFF); this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); this.write += 3; return this; }; /** * Puts a 32-bit integer in this buffer in little-endian order. * * @param i the 32-bit integer. * * @return this buffer. */ util.DataBuffer.prototype.putInt32Le = function(i) { this.accommodate(4); this.data.setInt32(this.write, i, true); this.write += 4; return this; }; /** * Puts an n-bit integer in this buffer in big-endian order. * * @param i the n-bit integer. * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return this buffer. */ util.DataBuffer.prototype.putInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); do { n -= 8; this.data.setInt8(this.write++, (i >> n) & 0xFF); } while(n > 0); return this; }; /** * Puts a signed n-bit integer in this buffer in big-endian order. Two's * complement representation is used. * * @param i the n-bit integer. * @param n the number of bits in the integer. * * @return this buffer. */ util.DataBuffer.prototype.putSignedInt = function(i, n) { _checkBitsParam(n); this.accommodate(n / 8); if(i < 0) { i += 2 << (n - 1); } return this.putInt(i, n); }; /** * Gets a byte from this buffer and advances the read pointer by 1. * * @return the byte. */ util.DataBuffer.prototype.getByte = function() { return this.data.getInt8(this.read++); }; /** * Gets a uint16 from this buffer in big-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16 = function() { var rval = this.data.getInt16(this.read); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in big-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24 = function() { var rval = ( this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2)); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in big-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32 = function() { var rval = this.data.getInt32(this.read); this.read += 4; return rval; }; /** * Gets a uint16 from this buffer in little-endian order and advances the read * pointer by 2. * * @return the uint16. */ util.DataBuffer.prototype.getInt16Le = function() { var rval = this.data.getInt16(this.read, true); this.read += 2; return rval; }; /** * Gets a uint24 from this buffer in little-endian order and advances the read * pointer by 3. * * @return the uint24. */ util.DataBuffer.prototype.getInt24Le = function() { var rval = ( this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8); this.read += 3; return rval; }; /** * Gets a uint32 from this buffer in little-endian order and advances the read * pointer by 4. * * @return the word. */ util.DataBuffer.prototype.getInt32Le = function() { var rval = this.data.getInt32(this.read, true); this.read += 4; return rval; }; /** * Gets an n-bit integer from this buffer in big-endian order and advances the * read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getInt = function(n) { _checkBitsParam(n); var rval = 0; do { // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. rval = (rval << 8) + this.data.getInt8(this.read++); n -= 8; } while(n > 0); return rval; }; /** * Gets a signed n-bit integer from this buffer in big-endian order, using * two's complement, and advances the read pointer by n/8. * * @param n the number of bits in the integer (8, 16, 24, or 32). * * @return the integer. */ util.DataBuffer.prototype.getSignedInt = function(n) { // getInt checks n var x = this.getInt(n); var max = 2 << (n - 2); if(x >= max) { x -= max << 1; } return x; }; /** * Reads bytes out into a UTF-8 string and clears them from the buffer. * * @param count the number of bytes to read, undefined or null for all. * * @return a UTF-8 string of bytes. */ util.DataBuffer.prototype.getBytes = function(count) { // TODO: deprecate this method, it is poorly named and // this.toString('binary') replaces it // add a toTypedArray()/toArrayBuffer() function var rval; if(count) { // read count bytes count = Math.min(this.length(), count); rval = this.data.slice(this.read, this.read + count); this.read += count; } else if(count === 0) { rval = ''; } else { // read all bytes, optimize to only copy when needed rval = (this.read === 0) ? this.data : this.data.slice(this.read); this.clear(); } return rval; }; /** * Gets a UTF-8 encoded string of the bytes from this buffer without modifying * the read pointer. * * @param count the number of bytes to get, omit to get all. * * @return a string full of UTF-8 encoded characters. */ util.DataBuffer.prototype.bytes = function(count) { // TODO: deprecate this method, it is poorly named, add "getString()" return (typeof(count) === 'undefined' ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count)); }; /** * Gets a byte at the given index without modifying the read pointer. * * @param i the byte index. * * @return the byte. */ util.DataBuffer.prototype.at = function(i) { return this.data.getUint8(this.read + i); }; /** * Puts a byte at the given index without modifying the read pointer. * * @param i the byte index. * @param b the byte to put. * * @return this buffer. */ util.DataBuffer.prototype.setAt = function(i, b) { this.data.setUint8(i, b); return this; }; /** * Gets the last byte without modifying the read pointer. * * @return the last byte. */ util.DataBuffer.prototype.last = function() { return this.data.getUint8(this.write - 1); }; /** * Creates a copy of this buffer. * * @return the copy. */ util.DataBuffer.prototype.copy = function() { return new util.DataBuffer(this); }; /** * Compacts this buffer. * * @return this buffer. */ util.DataBuffer.prototype.compact = function() { if(this.read > 0) { var src = new Uint8Array(this.data.buffer, this.read); var dst = new Uint8Array(src.byteLength); dst.set(src); this.data = new DataView(dst); this.write -= this.read; this.read = 0; } return this; }; /** * Clears this buffer. * * @return this buffer. */ util.DataBuffer.prototype.clear = function() { this.data = new DataView(new ArrayBuffer(0)); this.read = this.write = 0; return this; }; /** * Shortens this buffer by triming bytes off of the end of this buffer. * * @param count the number of bytes to trim off. * * @return this buffer. */ util.DataBuffer.prototype.truncate = function(count) { this.write = Math.max(0, this.length() - count); this.read = Math.min(this.read, this.write); return this; }; /** * Converts this buffer to a hexadecimal string. * * @return a hexadecimal string. */ util.DataBuffer.prototype.toHex = function() { var rval = ''; for(var i = this.read; i < this.data.byteLength; ++i) { var b = this.data.getUint8(i); if(b < 16) { rval += '0'; } rval += b.toString(16); } return rval; }; /** * Converts this buffer to a string, using the given encoding. If no * encoding is given, 'utf8' (UTF-8) is used. * * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', * 'base64' (default: 'utf8'). * * @return a string representation of the bytes in this buffer. */ util.DataBuffer.prototype.toString = function(encoding) { var view = new Uint8Array(this.data, this.read, this.length()); encoding = encoding || 'utf8'; // encode to string if(encoding === 'binary' || encoding === 'raw') { return util.binary.raw.encode(view); } if(encoding === 'hex') { return util.binary.hex.encode(view); } if(encoding === 'base64') { return util.binary.base64.encode(view); } // decode to text if(encoding === 'utf8') { return util.text.utf8.decode(view); } if(encoding === 'utf16') { return util.text.utf16.decode(view); } throw new Error('Invalid encoding: ' + encoding); }; /** End Buffer w/UInt8Array backing */ /** * Creates a buffer that stores bytes. A value may be given to put into the * buffer that is either a string of bytes or a UTF-16 string that will * be encoded using UTF-8 (to do the latter, specify 'utf8' as the encoding). * * @param [input] the bytes to wrap (as a string) or a UTF-16 string to encode * as UTF-8. * @param [encoding] (default: 'raw', other: 'utf8'). */ util.createBuffer = function(input, encoding) { // TODO: deprecate, use new ByteBuffer() instead encoding = encoding || 'raw'; if(input !== undefined && encoding === 'utf8') { input = util.encodeUtf8(input); } return new util.ByteBuffer(input); }; /** * Fills a string with a particular value. If you want the string to be a byte * string, pass in String.fromCharCode(theByte). * * @param c the character to fill the string with, use String.fromCharCode * to fill the string with a byte value. * @param n the number of characters of value c to fill with. * * @return the filled string. */ util.fillString = function(c, n) { var s = ''; while(n > 0) { if(n & 1) { s += c; } n >>>= 1; if(n > 0) { c += c; } } return s; }; /** * Performs a per byte XOR between two byte strings and returns the result as a * string of bytes. * * @param s1 first string of bytes. * @param s2 second string of bytes. * @param n the number of bytes to XOR. * * @return the XOR'd result. */ util.xorBytes = function(s1, s2, n) { var s3 = ''; var b = ''; var t = ''; var i = 0; var c = 0; for(; n > 0; --n, ++i) { b = s1.charCodeAt(i) ^ s2.charCodeAt(i); if(c >= 10) { s3 += t; t = ''; c = 0; } t += String.fromCharCode(b); ++c; } s3 += t; return s3; }; /** * Converts a hex string into a 'binary' encoded string of bytes. * * @param hex the hexadecimal string to convert. * * @return the binary-encoded string of bytes. */ util.hexToBytes = function(hex) { // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." var rval = ''; var i = 0; if(hex.length & 1 == 1) { // odd number of characters, convert first character alone i = 1; rval += String.fromCharCode(parseInt(hex[0], 16)); } // convert 2 characters (1 byte) at a time for(; i < hex.length; i += 2) { rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } return rval; }; /** * Converts a 'binary' encoded string of bytes to hex. * * @param bytes the byte string to convert. * * @return the string of hexadecimal characters. */ util.bytesToHex = function(bytes) { // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." return util.createBuffer(bytes).toHex(); }; /** * Converts an 32-bit integer to 4-big-endian byte string. * * @param i the integer. * * @return the byte string. */ util.int32ToBytes = function(i) { return ( String.fromCharCode(i >> 24 & 0xFF) + String.fromCharCode(i >> 16 & 0xFF) + String.fromCharCode(i >> 8 & 0xFF) + String.fromCharCode(i & 0xFF)); }; // base64 characters, reverse mapping var _base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var _base64Idx = [ /*43 -43 = 0*/ /*'+', 1, 2, 3,'/' */ 62, -1, -1, -1, 63, /*'0','1','2','3','4','5','6','7','8','9' */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /*15, 16, 17,'=', 19, 20, 21 */ -1, -1, -1, 64, -1, -1, -1, /*65 - 43 = 22*/ /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, /*91 - 43 = 48 */ /*48, 49, 50, 51, 52, 53 */ -1, -1, -1, -1, -1, -1, /*97 - 43 = 54*/ /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 ]; /** * Base64 encodes a 'binary' encoded string of bytes. * * @param input the binary encoded string of bytes to base64-encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the base64-encoded output. */ util.encode64 = function(input, maxline) { // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." var line = ''; var output = ''; var chr1, chr2, chr3; var i = 0; while(i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); // encode 4 character group line += _base64.charAt(chr1 >> 2); line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); if(isNaN(chr2)) { line += '=='; } else { line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } if(maxline && line.length > maxline) { output += line.substr(0, maxline) + '\r\n'; line = line.substr(maxline); } } output += line; return output; }; /** * Base64 decodes a string into a 'binary' encoded string of bytes. * * @param input the base64-encoded input. * * @return the binary encoded string. */ util.decode64 = function(input) { // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." // remove all non-base64 characters input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); var output = ''; var enc1, enc2, enc3, enc4; var i = 0; while(i < input.length) { enc1 = _base64Idx[input.charCodeAt(i++) - 43]; enc2 = _base64Idx[input.charCodeAt(i++) - 43]; enc3 = _base64Idx[input.charCodeAt(i++) - 43]; enc4 = _base64Idx[input.charCodeAt(i++) - 43]; output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); if(enc3 !== 64) { // decoded at least 2 bytes output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); if(enc4 !== 64) { // decoded 3 bytes output += String.fromCharCode(((enc3 & 3) << 6) | enc4); } } } return output; }; /** * UTF-8 encodes the given UTF-16 encoded string (a standard JavaScript * string). Non-ASCII characters will be encoded as multiple bytes according * to UTF-8. * * @param str the string to encode. * * @return the UTF-8 encoded string. */ util.encodeUtf8 = function(str) { return unescape(encodeURIComponent(str)); }; /** * Decodes a UTF-8 encoded string into a UTF-16 string. * * @param str the string to decode. * * @return the UTF-16 encoded string (standard JavaScript string). */ util.decodeUtf8 = function(str) { return decodeURIComponent(escape(str)); }; // binary encoding/decoding tools // FIXME: Experimental. Do not use yet. util.binary = { raw: {}, hex: {}, base64: {} }; /** * Encodes a Uint8Array as a binary-encoded string. This encoding uses * a value between 0 and 255 for each character. * * @param bytes the Uint8Array to encode. * * @return the binary-encoded string. */ util.binary.raw.encode = function(bytes) { return String.fromCharCode.apply(null, bytes); }; /** * Decodes a binary-encoded string to a Uint8Array. This encoding uses * a value between 0 and 255 for each character. * * @param str the binary-encoded string to decode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.raw.decode = function(str, output, offset) { var out = output; if(!out) { out = new Uint8Array(str.length); } offset = offset || 0; var j = offset; for(var i = 0; i < str.length; ++i) { out[j++] = str.charCodeAt(i); } return output ? (j - offset) : out; }; /** * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or * ByteBuffer as a string of hexadecimal characters. * * @param bytes the bytes to convert. * * @return the string of hexadecimal characters. */ util.binary.hex.encode = util.bytesToHex; /** * Decodes a hex-encoded string to a Uint8Array. * * @param hex the hexadecimal string to convert. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.hex.decode = function(hex, output, offset) { var out = output; if(!out) { out = new Uint8Array(Math.ceil(hex.length / 2)); } offset = offset || 0; var i = 0, j = offset; if(hex.length & 1) { // odd number of characters, convert first character alone i = 1; out[j++] = parseInt(hex[0], 16); } // convert 2 characters (1 byte) at a time for(; i < hex.length; i += 2) { out[j++] = parseInt(hex.substr(i, 2), 16); } return output ? (j - offset) : out; }; /** * Base64-encodes a Uint8Array. * * @param input the Uint8Array to encode. * @param maxline the maximum number of encoded characters per line to use, * defaults to none. * * @return the base64-encoded output string. */ util.binary.base64.encode = function(input, maxline) { var line = ''; var output = ''; var chr1, chr2, chr3; var i = 0; while(i < input.byteLength) { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; // encode 4 character group line += _base64.charAt(chr1 >> 2); line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); if(isNaN(chr2)) { line += '=='; } else { line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); } if(maxline && line.length > maxline) { output += line.substr(0, maxline) + '\r\n'; line = line.substr(maxline); } } output += line; return output; }; /** * Decodes a base64-encoded string to a Uint8Array. * * @param input the base64-encoded input string. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.binary.base64.decode = function(input, output, offset) { var out = output; if(!out) { out = new Uint8Array(Math.ceil(input.length / 4) * 3); } // remove all non-base64 characters input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); offset = offset || 0; var enc1, enc2, enc3, enc4; var i = 0, j = offset; while(i < input.length) { enc1 = _base64Idx[input.charCodeAt(i++) - 43]; enc2 = _base64Idx[input.charCodeAt(i++) - 43]; enc3 = _base64Idx[input.charCodeAt(i++) - 43]; enc4 = _base64Idx[input.charCodeAt(i++) - 43]; out[j++] = (enc1 << 2) | (enc2 >> 4); if(enc3 !== 64) { // decoded at least 2 bytes out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); if(enc4 !== 64) { // decoded 3 bytes out[j++] = ((enc3 & 3) << 6) | enc4; } } } // make sure result is the exact decoded length return output ? (j - offset) : out.subarray(0, j); }; // text encoding/decoding tools // FIXME: Experimental. Do not use yet. util.text = { utf8: {}, utf16: {} }; /** * Encodes the given string as UTF-8 in a Uint8Array. * * @param str the string to encode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.text.utf8.encode = function(str, output, offset) { str = util.encodeUtf8(str); var out = output; if(!out) { out = new Uint8Array(str.length); } offset = offset || 0; var j = offset; for(var i = 0; i < str.length; ++i) { out[j++] = str.charCodeAt(i); } return output ? (j - offset) : out; }; /** * Decodes the UTF-8 contents from a Uint8Array. * * @param bytes the Uint8Array to decode. * * @return the resulting string. */ util.text.utf8.decode = function(bytes) { return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); }; /** * Encodes the given string as UTF-16 in a Uint8Array. * * @param str the string to encode. * @param [output] an optional Uint8Array to write the output to; if it * is too small, an exception will be thrown. * @param [offset] the start offset for writing to the output (default: 0). * * @return the Uint8Array or the number of bytes written if output was given. */ util.text.utf16.encode = function(str, output, offset) { var out = output; if(!out) { out = new Uint8Array(str.length * 2); } var view = new Uint16Array(out.buffer); offset = offset || 0; var j = offset; var k = offset; for(var i = 0; i < str.length; ++i) { view[k++] = str.charCodeAt(i); j += 2; } return output ? (j - offset) : out; }; /** * Decodes the UTF-16 contents from a Uint8Array. * * @param bytes the Uint8Array to decode. * * @return the resulting string. */ util.text.utf16.decode = function(bytes) { return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); }; /** * Deflates the given data using a flash interface. * * @param api the flash interface. * @param bytes the data. * @param raw true to return only raw deflate data, false to include zlib * header and trailer. * * @return the deflated data as a string. */ util.deflate = function(api, bytes, raw) { bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); // strip zlib header and trailer if necessary if(raw) { // zlib header is 2 bytes (CMF,FLG) where FLG indicates that // there is a 4-byte DICT (alder-32) block before the data if // its 5th bit is set var start = 2; var flg = bytes.charCodeAt(1); if(flg & 0x20) { start = 6; } // zlib trailer is 4 bytes of adler-32 bytes = bytes.substring(start, bytes.length - 4); } return bytes; }; /** * Inflates the given data using a flash interface. * * @param api the flash interface. * @param bytes the data. * @param raw true if the incoming data has no zlib header or trailer and is * raw DEFLATE data. * * @return the inflated data as a string, null on error. */ util.inflate = function(api, bytes, raw) { // TODO: add zlib header and trailer if necessary/possible var rval = api.inflate(util.encode64(bytes)).rval; return (rval === null) ? null : util.decode64(rval); }; /** * Sets a storage object. * * @param api the storage interface. * @param id the storage ID to use. * @param obj the storage object, null to remove. */ var _setStorageObject = function(api, id, obj) { if(!api) { throw new Error('WebStorage not available.'); } var rval; if(obj === null) { rval = api.removeItem(id); } else { // json-encode and base64-encode object obj = util.encode64(JSON.stringify(obj)); rval = api.setItem(id, obj); } // handle potential flash error if(typeof(rval) !== 'undefined' && rval.rval !== true) { var error = new Error(rval.error.message); error.id = rval.error.id; error.name = rval.error.name; throw error; } }; /** * Gets a storage object. * * @param api the storage interface. * @param id the storage ID to use. * * @return the storage object entry or null if none exists. */ var _getStorageObject = function(api, id) { if(!api) { throw new Error('WebStorage not available.'); } // get the existing entry var rval = api.getItem(id); /* Note: We check api.init because we can't do (api == localStorage) on IE because of "Class doesn't support Automation" exception. Only the flash api has an init method so this works too, but we need a better solution in the future. */ // flash returns item wrapped in an object, handle special case if(api.init) { if(rval.rval === null) { if(rval.error) { var error = new Error(rval.error.message); error.id = rval.error.id; error.name = rval.error.name; throw error; } // no error, but also no item rval = null; } else { rval = rval.rval; } } // handle decoding if(rval !== null) { // base64-decode and json-decode data rval = JSON.parse(util.decode64(rval)); } return rval; }; /** * Stores an item in local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. * @param data the data for the item (any javascript object/primitive). */ var _setItem = function(api, id, key, data) { // get storage object var obj = _getStorageObject(api, id); if(obj === null) { // create a new storage object obj = {}; } // update key obj[key] = data; // set storage object _setStorageObject(api, id, obj); }; /** * Gets an item from local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. * * @return the item. */ var _getItem = function(api, id, key) { // get storage object var rval = _getStorageObject(api, id); if(rval !== null) { // return data at key rval = (key in rval) ? rval[key] : null; } return rval; }; /** * Removes an item from local storage. * * @param api the storage interface. * @param id the storage ID to use. * @param key the key for the item. */ var _removeItem = function(api, id, key) { // get storage object var obj = _getStorageObject(api, id); if(obj !== null && key in obj) { // remove key delete obj[key]; // see if entry has no keys remaining var empty = true; for(var prop in obj) { empty = false; break; } if(empty) { // remove entry entirely if no keys are left obj = null; } // set storage object _setStorageObject(api, id, obj); } }; /** * Clears the local disk storage identified by the given ID. * * @param api the storage interface. * @param id the storage ID to use. */ var _clearItems = function(api, id) { _setStorageObject(api, id, null); }; /** * Calls a storage function. * * @param func the function to call. * @param args the arguments for the function. * @param location the location argument. * * @return the return value from the function. */ var _callStorageFunction = function(func, args, location) { var rval = null; // default storage types if(typeof(location) === 'undefined') { location = ['web', 'flash']; } // apply storage types in order of preference var type; var done = false; var exception = null; for(var idx in location) { type = location[idx]; try { if(type === 'flash' || type === 'both') { if(args[0] === null) { throw new Error('Flash local storage not available.'); } rval = func.apply(this, args); done = (type === 'flash'); } if(type === 'web' || type === 'both') { args[0] = localStorage; rval = func.apply(this, args); done = true; } } catch(ex) { exception = ex; } if(done) { break; } } if(!done) { throw exception; } return rval; }; /** * Stores an item on local disk. * * The available types of local storage include 'flash', 'web', and 'both'. * * The type 'flash' refers to flash local storage (SharedObject). In order * to use flash local storage, the 'api' parameter must be valid. The type * 'web' refers to WebStorage, if supported by the browser. The type 'both' * refers to storing using both 'flash' and 'web', not just one or the * other. * * The location array should list the storage types to use in order of * preference: * * ['flash']: flash only storage * ['web']: web only storage * ['both']: try to store in both * ['flash','web']: store in flash first, but if not available, 'web' * ['web','flash']: store in web first, but if not available, 'flash' * * The location array defaults to: ['web', 'flash'] * * @param api the flash interface, null to use only WebStorage. * @param id the storage ID to use. * @param key the key for the item. * @param data the data for the item (any javascript object/primitive). * @param location an array with the preferred types of storage to use. */ util.setItem = function(api, id, key, data, location) { _callStorageFunction(_setItem, arguments, location); }; /** * Gets an item on local disk. * * Set setItem() for details on storage types. * * @param api the flash interface, null to use only WebStorage. * @param id the storage ID to use. * @param key the key for the item. * @param location an array with the preferred types of storage to use. * * @return the item. */ util.getItem = function(api, id, key, location) { return _callStorageFunction(_getItem, arguments, location); }; /** * Removes an item on local disk. * * Set setItem() for details on storage types. * * @param api the flash interface. * @param id the storage ID to use. * @param key the key for the item. * @param location an array with the preferred types of storage to use. */ util.removeItem = function(api, id, key, location) { _callStorageFunction(_removeItem, arguments, location); }; /** * Clears the local disk storage identified by the given ID. * * Set setItem() for details on storage types. * * @param api the flash interface if flash is available. * @param id the storage ID to use. * @param location an array with the preferred types of storage to use. */ util.clearItems = function(api, id, location) { _callStorageFunction(_clearItems, arguments, location); }; /** * Parses the scheme, host, and port from an http(s) url. * * @param str the url string. * * @return the parsed url object or null if the url is invalid. */ util.parseUrl = function(str) { // FIXME: this regex looks a bit broken var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g; regex.lastIndex = 0; var m = regex.exec(str); var url = (m === null) ? null : { full: str, scheme: m[1], host: m[2], port: m[3], path: m[4] }; if(url) { url.fullHost = url.host; if(url.port) { if(url.port !== 80 && url.scheme === 'http') { url.fullHost += ':' + url.port; } else if(url.port !== 443 && url.scheme === 'https') { url.fullHost += ':' + url.port; } } else if(url.scheme === 'http') { url.port = 80; } else if(url.scheme === 'https') { url.port = 443; } url.full = url.scheme + '://' + url.fullHost; } return url; }; /* Storage for query variables */ var _queryVariables = null; /** * Returns the window location query variables. Query is parsed on the first * call and the same object is returned on subsequent calls. The mapping * is from keys to an array of values. Parameters without values will have * an object key set but no value added to the value array. Values are * unescaped. * * ...?k1=v1&k2=v2: * { * "k1": ["v1"], * "k2": ["v2"] * } * * ...?k1=v1&k1=v2: * { * "k1": ["v1", "v2"] * } * * ...?k1=v1&k2: * { * "k1": ["v1"], * "k2": [] * } * * ...?k1=v1&k1: * { * "k1": ["v1"] * } * * ...?k1&k1: * { * "k1": [] * } * * @param query the query string to parse (optional, default to cached * results from parsing window location search query). * * @return object mapping keys to variables. */ util.getQueryVariables = function(query) { var parse = function(q) { var rval = {}; var kvpairs = q.split('&'); for(var i = 0; i < kvpairs.length; i++) { var pos = kvpairs[i].indexOf('='); var key; var val; if(pos > 0) { key = kvpairs[i].substring(0, pos); val = kvpairs[i].substring(pos + 1); } else { key = kvpairs[i]; val = null; } if(!(key in rval)) { rval[key] = []; } // disallow overriding object prototype keys if(!(key in Object.prototype) && val !== null) { rval[key].push(unescape(val)); } } return rval; }; var rval; if(typeof(query) === 'undefined') { // set cached variables if needed if(_queryVariables === null) { if(typeof(window) !== 'undefined' && window.location && window.location.search) { // parse window search query _queryVariables = parse(window.location.search.substring(1)); } else { // no query variables available _queryVariables = {}; } } rval = _queryVariables; } else { // parse given query rval = parse(query); } return rval; }; /** * Parses a fragment into a path and query. This method will take a URI * fragment and break it up as if it were the main URI. For example: * /bar/baz?a=1&b=2 * results in: * { * path: ["bar", "baz"], * query: {"k1": ["v1"], "k2": ["v2"]} * } * * @return object with a path array and query object. */ util.parseFragment = function(fragment) { // default to whole fragment var fp = fragment; var fq = ''; // split into path and query if possible at the first '?' var pos = fragment.indexOf('?'); if(pos > 0) { fp = fragment.substring(0, pos); fq = fragment.substring(pos + 1); } // split path based on '/' and ignore first element if empty var path = fp.split('/'); if(path.length > 0 && path[0] === '') { path.shift(); } // convert query into object var query = (fq === '') ? {} : util.getQueryVariables(fq); return { pathString: fp, queryString: fq, path: path, query: query }; }; /** * Makes a request out of a URI-like request string. This is intended to * be used where a fragment id (after a URI '#') is parsed as a URI with * path and query parts. The string should have a path beginning and * delimited by '/' and optional query parameters following a '?'. The * query should be a standard URL set of key value pairs delimited by * '&'. For backwards compatibility the initial '/' on the path is not * required. The request object has the following API, (fully described * in the method code): * { * path: <the path string part>. * query: <the query string part>, * getPath(i): get part or all of the split path array, * getQuery(k, i): get part or all of a query key array, * getQueryLast(k, _default): get last element of a query key array. * } * * @return object with request parameters. */ util.makeRequest = function(reqString) { var frag = util.parseFragment(reqString); var req = { // full path string path: frag.pathString, // full query string query: frag.queryString, /** * Get path or element in path. * * @param i optional path index. * * @return path or part of path if i provided. */ getPath: function(i) { return (typeof(i) === 'undefined') ? frag.path : frag.path[i]; }, /** * Get query, values for a key, or value for a key index. * * @param k optional query key. * @param i optional query key index. * * @return query, values for a key, or value for a key index. */ getQuery: function(k, i) { var rval; if(typeof(k) === 'undefined') { rval = frag.query; } else { rval = frag.query[k]; if(rval && typeof(i) !== 'undefined') { rval = rval[i]; } } return rval; }, getQueryLast: function(k, _default) { var rval; var vals = req.getQuery(k); if(vals) { rval = vals[vals.length - 1]; } else { rval = _default; } return rval; } }; return req; }; /** * Makes a URI out of a path, an object with query parameters, and a * fragment. Uses jQuery.param() internally for query string creation. * If the path is an array, it will be joined with '/'. * * @param path string path or array of strings. * @param query object with query parameters. (optional) * @param fragment fragment string. (optional) * * @return string object with request parameters. */ util.makeLink = function(path, query, fragment) { // join path parts if needed path = jQuery.isArray(path) ? path.join('/') : path; var qstr = jQuery.param(query || {}); fragment = fragment || ''; return path + ((qstr.length > 0) ? ('?' + qstr) : '') + ((fragment.length > 0) ? ('#' + fragment) : ''); }; /** * Follows a path of keys deep into an object hierarchy and set a value. * If a key does not exist or it's value is not an object, create an * object in it's place. This can be destructive to a object tree if * leaf nodes are given as non-final path keys. * Used to avoid exceptions from missing parts of the path. * * @param object the starting object. * @param keys an array of string keys. * @param value the value to set. */ util.setPath = function(object, keys, value) { // need to start at an object if(typeof(object) === 'object' && object !== null) { var i = 0; var len = keys.length; while(i < len) { var next = keys[i++]; if(i == len) { // last object[next] = value; } else { // more var hasNext = (next in object); if(!hasNext || (hasNext && typeof(object[next]) !== 'object') || (hasNext && object[next] === null)) { object[next] = {}; } object = object[next]; } } } }; /** * Follows a path of keys deep into an object hierarchy and return a value. * If a key does not exist, create an object in it's place. * Used to avoid exceptions from missing parts of the path. * * @param object the starting object. * @param keys an array of string keys. * @param _default value to return if path not found. * * @return the value at the path if found, else default if given, else * undefined. */ util.getPath = function(object, keys, _default) { var i = 0; var len = keys.length; var hasNext = true; while(hasNext && i < len && typeof(object) === 'object' && object !== null) { var next = keys[i++]; hasNext = next in object; if(hasNext) { object = object[next]; } } return (hasNext ? object : _default); }; /** * Follow a path of keys deep into an object hierarchy and delete the * last one. If a key does not exist, do nothing. * Used to avoid exceptions from missing parts of the path. * * @param object the starting object. * @param keys an array of string keys. */ util.deletePath = function(object, keys) { // need to start at an object if(typeof(object) === 'object' && object !== null) { var i = 0; var len = keys.length; while(i < len) { var next = keys[i++]; if(i == len) { // last delete object[next]; } else { // more if(!(next in object) || (typeof(object[next]) !== 'object') || (object[next] === null)) { break; } object = object[next]; } } } }; /** * Check if an object is empty. * * Taken from: * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 * * @param object the object to check. */ util.isEmpty = function(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) { return false; } } return true; }; /** * Format with simple printf-style interpolation. * * %%: literal '%' * %s,%o: convert next argument into a string. * * @param format the string to format. * @param ... arguments to interpolate into the format string. */ util.format = function(format) { var re = /%./g; // current match var match; // current part var part; // current arg index var argi = 0; // collected parts to recombine later var parts = []; // last index found var last = 0; // loop while matches remain while((match = re.exec(format))) { part = format.substring(last, re.lastIndex - 2); // don't add empty strings (ie, parts between %s%s) if(part.length > 0) { parts.push(part); } last = re.lastIndex; // switch on % code var code = match[0][1]; switch(code) { case 's': case 'o': // check if enough arguments were given if(argi < arguments.length) { parts.push(arguments[argi++ + 1]); } else { parts.push('<?>'); } break; // FIXME: do proper formating for numbers, etc //case 'f': //case 'd': case '%': parts.push('%'); break; default: parts.push('<%' + code + '?>'); } } // add trailing part of format string parts.push(format.substring(last)); return parts.join(''); }; /** * Formats a number. * * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ */ util.formatNumber = function(number, decimals, dec_point, thousands_sep) { // http://kevin.vanzonneveld.net // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfix by: Michael White (http://crestidg.com) // + bugfix by: Benjamin Lupton // + bugfix by: Allan Jensen (http://www.winternet.no) // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // * example 1: number_format(1234.5678, 2, '.', ''); // * returns 1: 1234.57 var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; var d = dec_point === undefined ? ',' : dec_point; var t = thousands_sep === undefined ? '.' : thousands_sep, s = n < 0 ? '-' : ''; var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; var j = (i.length > 3) ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); }; /** * Formats a byte size. * * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ */ util.formatSize = function(size) { if(size >= 1073741824) { size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; } else if(size >= 1048576) { size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; } else if(size >= 1024) { size = util.formatNumber(size / 1024, 0) + ' KiB'; } else { size = util.formatNumber(size, 0) + ' bytes'; } return size; }; /** * Converts an IPv4 or IPv6 string representation into bytes (in network order). * * @param ip the IPv4 or IPv6 address to convert. * * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't * be parsed. */ util.bytesFromIP = function(ip) { if(ip.indexOf('.') !== -1) { return util.bytesFromIPv4(ip); } if(ip.indexOf(':') !== -1) { return util.bytesFromIPv6(ip); } return null; }; /** * Converts an IPv4 string representation into bytes (in network order). * * @param ip the IPv4 address to convert. * * @return the 4-byte address or null if the address can't be parsed. */ util.bytesFromIPv4 = function(ip) { ip = ip.split('.'); if(ip.length !== 4) { return null; } var b = util.createBuffer(); for(var i = 0; i < ip.length; ++i) { var num = parseInt(ip[i], 10); if(isNaN(num)) { return null; } b.putByte(num); } return b.getBytes(); }; /** * Converts an IPv6 string representation into bytes (in network order). * * @param ip the IPv6 address to convert. * * @return the 16-byte address or null if the address can't be parsed. */ util.bytesFromIPv6 = function(ip) { var blanks = 0; ip = ip.split(':').filter(function(e) { if(e.length === 0) ++blanks; return true; }); var zeros = (8 - ip.length + blanks) * 2; var b = util.createBuffer(); for(var i = 0; i < 8; ++i) { if(!ip[i] || ip[i].length === 0) { b.fillWithByte(0, zeros); zeros = 0; continue; } var bytes = util.hexToBytes(ip[i]); if(bytes.length < 2) { b.putByte(0); } b.putBytes(bytes); } return b.getBytes(); }; /** * Converts 4-bytes into an IPv4 string representation or 16-bytes into * an IPv6 string representation. The bytes must be in network order. * * @param bytes the bytes to convert. * * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, * respectively, are given, otherwise null. */ util.bytesToIP = function(bytes) { if(bytes.length === 4) { return util.bytesToIPv4(bytes); } if(bytes.length === 16) { return util.bytesToIPv6(bytes); } return null; }; /** * Converts 4-bytes into an IPv4 string representation. The bytes must be * in network order. * * @param bytes the bytes to convert. * * @return the IPv4 string representation or null for an invalid # of bytes. */ util.bytesToIPv4 = function(bytes) { if(bytes.length !== 4) { return null; } var ip = []; for(var i = 0; i < bytes.length; ++i) { ip.push(bytes.charCodeAt(i)); } return ip.join('.'); }; /** * Converts 16-bytes into an IPv16 string representation. The bytes must be * in network order. * * @param bytes the bytes to convert. * * @return the IPv16 string representation or null for an invalid # of bytes. */ util.bytesToIPv6 = function(bytes) { if(bytes.length !== 16) { return null; } var ip = []; var zeroGroups = []; var zeroMaxGroup = 0; for(var i = 0; i < bytes.length; i += 2) { var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); // canonicalize zero representation while(hex[0] === '0' && hex !== '0') { hex = hex.substr(1); } if(hex === '0') { var last = zeroGroups[zeroGroups.length - 1]; var idx = ip.length; if(!last || idx !== last.end + 1) { zeroGroups.push({start: idx, end: idx}); } else { last.end = idx; if((last.end - last.start) > (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { zeroMaxGroup = zeroGroups.length - 1; } } } ip.push(hex); } if(zeroGroups.length > 0) { var group = zeroGroups[zeroMaxGroup]; // only shorten group of length > 0 if(group.end - group.start > 0) { ip.splice(group.start, group.end - group.start + 1, ''); if(group.start === 0) { ip.unshift(''); } if(group.end === 7) { ip.push(''); } } } return ip.join(':'); }; /** * Estimates the number of processes that can be run concurrently. If * creating Web Workers, keep in mind that the main JavaScript process needs * its own core. * * @param options the options to use: * update true to force an update (not use the cached value). * @param callback(err, max) called once the operation completes. */ util.estimateCores = function(options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; if('cores' in util && !options.update) { return callback(null, util.cores); } if(typeof navigator !== 'undefined' && 'hardwareConcurrency' in navigator && navigator.hardwareConcurrency > 0) { util.cores = navigator.hardwareConcurrency; return callback(null, util.cores); } if(typeof Worker === 'undefined') { // workers not available util.cores = 1; return callback(null, util.cores); } if(typeof Blob === 'undefined') { // can't estimate, default to 2 util.cores = 2; return callback(null, util.cores); } // create worker concurrency estimation code as blob var blobUrl = URL.createObjectURL(new Blob(['(', function() { self.addEventListener('message', function(e) { // run worker for 4 ms var st = Date.now(); var et = st + 4; while(Date.now() < et); self.postMessage({st: st, et: et}); }); }.toString(), ')()'], {type: 'application/javascript'})); // take 5 samples using 16 workers sample([], 5, 16); function sample(max, samples, numWorkers) { if(samples === 0) { // get overlap average var avg = Math.floor(max.reduce(function(avg, x) { return avg + x; }, 0) / max.length); util.cores = Math.max(1, avg); URL.revokeObjectURL(blobUrl); return callback(null, util.cores); } map(numWorkers, function(err, results) { max.push(reduce(numWorkers, results)); sample(max, samples - 1, numWorkers); }); } function map(numWorkers, callback) { var workers = []; var results = []; for(var i = 0; i < numWorkers; ++i) { var worker = new Worker(blobUrl); worker.addEventListener('message', function(e) { results.push(e.data); if(results.length === numWorkers) { for(var i = 0; i < numWorkers; ++i) { workers[i].terminate(); } callback(null, results); } }); workers.push(worker); } for(var i = 0; i < numWorkers; ++i) { workers[i].postMessage(i); } } function reduce(numWorkers, results) { // find overlapping time windows var overlaps = []; for(var n = 0; n < numWorkers; ++n) { var r1 = results[n]; var overlap = overlaps[n] = []; for(var i = 0; i < numWorkers; ++i) { if(n === i) { continue; } var r2 = results[i]; if((r1.st > r2.st && r1.st < r2.et) || (r2.st > r1.st && r2.st < r1.et)) { overlap.push(i); } } } // get maximum overlaps ... don't include overlapping worker itself // as the main JS process was also being scheduled during the work and // would have to be subtracted from the estimate anyway return overlaps.reduce(function(max, overlap) { return Math.max(max, overlap.length); }, 0); } }; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ // TODO: convert to ES6 iterable var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = function () { /** * A Permutator iterates over all possible permutations of the given array * of elements. * * @param list the array of elements to iterate over. */ function Permutator(list) { _classCallCheck(this, Permutator); // original array this.list = list.sort(); // indicates whether there are more permutations this.done = false; // directional info for permutation algorithm this.left = {}; for (var i = 0; i < list.length; ++i) { this.left[list[i]] = true; } } /** * Returns true if there is another permutation. * * @return true if there is another permutation, false if not. */ _createClass(Permutator, [{ key: 'hasNext', value: function hasNext() { return !this.done; } /** * Gets the next permutation. Call hasNext() to ensure there is another one * first. * * @return the next permutation. */ }, { key: 'next', value: function next() { // copy current permutation var rval = this.list.slice(); /* Calculate the next permutation using the Steinhaus-Johnson-Trotter permutation algorithm. */ // get largest mobile element k // (mobile: element is greater than the one it is looking at) var k = null; var pos = 0; var length = this.list.length; for (var i = 0; i < length; ++i) { var element = this.list[i]; var left = this.left[element]; if ((k === null || element > k) && (left && i > 0 && element > this.list[i - 1] || !left && i < length - 1 && element > this.list[i + 1])) { k = element; pos = i; } } // no more permutations if (k === null) { this.done = true; } else { // swap k and the element it is looking at var swap = this.left[k] ? pos - 1 : pos + 1; this.list[pos] = this.list[swap]; this.list[swap] = k; // reverse the direction of all elements larger than k for (var _i = 0; _i < length; ++_i) { if (this.list[_i] > k) { this.left[this.list[_i]] = !this.left[this.list[_i]]; } } } return rval; } }]); return Permutator; }(); /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var IdentifierIssuer = __webpack_require__(46); var MessageDigest = __webpack_require__(69); var Permutator = __webpack_require__(71); var NQuads = __webpack_require__(48); var util = __webpack_require__(14); var POSITIONS = { 'subject': 's', 'object': 'o', 'graph': 'g' }; module.exports = function () { function URDNA2015Sync() { _classCallCheck(this, URDNA2015Sync); this.name = 'URDNA2015'; this.blankNodeInfo = {}; this.hashToBlankNodes = {}; this.canonicalIssuer = new IdentifierIssuer('_:c14n'); this.hashAlgorithm = 'sha256'; this.quads; } // 4.4) Normalization Algorithm _createClass(URDNA2015Sync, [{ key: 'main', value: function main(dataset) { var self = this; self.quads = dataset; // 1) Create the normalization state. // Note: Optimize by generating non-normalized blank node map concurrently. var nonNormalized = {}; // 2) For every quad in input dataset: var _loop = function _loop(quad) { // 2.1) For each blank node that occurs in the quad, add a reference // to the quad using the blank node identifier in the blank node to // quads map, creating a new entry if necessary. self.forEachComponent(quad, function (component) { if (component.termType !== 'BlankNode') { return; } var id = component.value; if (id in self.blankNodeInfo) { self.blankNodeInfo[id].quads.push(quad); } else { nonNormalized[id] = true; self.blankNodeInfo[id] = { quads: [quad] }; } }); }; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = dataset[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var quad = _step.value; _loop(quad); } // 3) Create a list of non-normalized blank node identifiers // non-normalized identifiers and populate it using the keys from the // blank node to quads map. // Note: We use a map here and it was generated during step 2. // 4) Initialize simple, a boolean flag, to true. } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var simple = true; // 5) While simple is true, issue canonical identifiers for blank nodes: while (simple) { // 5.1) Set simple to false. simple = false; // 5.2) Clear hash to blank nodes map. self.hashToBlankNodes = {}; // 5.3) For each blank node identifier identifier in non-normalized // identifiers: for (var id in nonNormalized) { // 5.3.1) Create a hash, hash, according to the Hash First Degree // Quads algorithm. var hash = self.hashFirstDegreeQuads(id); // 5.3.2) Add hash and identifier to hash to blank nodes map, // creating a new entry if necessary. if (hash in self.hashToBlankNodes) { self.hashToBlankNodes[hash].push(id); } else { self.hashToBlankNodes[hash] = [id]; } } // 5.4) For each hash to identifier list mapping in hash to blank // nodes map, lexicographically-sorted by hash: var _hashes = Object.keys(self.hashToBlankNodes).sort(); for (var i = 0; i < _hashes.length; ++i) { // 5.4.1) If the length of identifier list is greater than 1, // continue to the next mapping. var _hash = _hashes[i]; var idList = self.hashToBlankNodes[_hash]; if (idList.length > 1) { continue; } // 5.4.2) Use the Issue Identifier algorithm, passing canonical // issuer and the single blank node identifier in identifier // list, identifier, to issue a canonical replacement identifier // for identifier. // TODO: consider changing `getId` to `issue` var _id = idList[0]; self.canonicalIssuer.getId(_id); // 5.4.3) Remove identifier from non-normalized identifiers. delete nonNormalized[_id]; // 5.4.4) Remove hash from the hash to blank nodes map. delete self.hashToBlankNodes[_hash]; // 5.4.5) Set simple to true. simple = true; } } // 6) For each hash to identifier list mapping in hash to blank nodes map, // lexicographically-sorted by hash: var hashes = Object.keys(self.hashToBlankNodes).sort(); for (var _i = 0; _i < hashes.length; ++_i) { // 6.1) Create hash path list where each item will be a result of // running the Hash N-Degree Quads algorithm. var hashPathList = []; // 6.2) For each blank node identifier identifier in identifier list: var _hash2 = hashes[_i]; var _idList = self.hashToBlankNodes[_hash2]; for (var j = 0; j < _idList.length; ++j) { // 6.2.1) If a canonical identifier has already been issued for // identifier, continue to the next identifier. var _id2 = _idList[j]; if (self.canonicalIssuer.hasId(_id2)) { continue; } // 6.2.2) Create temporary issuer, an identifier issuer // initialized with the prefix _:b. var issuer = new IdentifierIssuer('_:b'); // 6.2.3) Use the Issue Identifier algorithm, passing temporary // issuer and identifier, to issue a new temporary blank node // identifier for identifier. issuer.getId(_id2); // 6.2.4) Run the Hash N-Degree Quads algorithm, passing // temporary issuer, and append the result to the hash path list. var result = self.hashNDegreeQuads(_id2, issuer); hashPathList.push(result); } // 6.3) For each result in the hash path list, // lexicographically-sorted by the hash in result: // TODO: use `String.localeCompare`? hashPathList.sort(function (a, b) { return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0; }); for (var _j = 0; _j < hashPathList.length; ++_j) { // 6.3.1) For each blank node identifier, existing identifier, // that was issued a temporary identifier by identifier issuer // in result, issue a canonical identifier, in the same order, // using the Issue Identifier algorithm, passing canonical // issuer and existing identifier. var _result = hashPathList[_j]; for (var existing in _result.issuer.existing) { self.canonicalIssuer.getId(existing); } } } /* Note: At this point all blank nodes in the set of RDF quads have been assigned canonical identifiers, which have been stored in the canonical issuer. Here each quad is updated by assigning each of its blank nodes its new identifier. */ // 7) For each quad, quad, in input dataset: var normalized = []; for (var _i2 = 0; _i2 < self.quads.length; ++_i2) { // 7.1) Create a copy, quad copy, of quad and replace any existing // blank node identifiers using the canonical identifiers // previously issued by canonical issuer. // Note: We optimize away the copy here. var quad = self.quads[_i2]; self.forEachComponent(quad, function (component) { if (component.termType === 'BlankNode' && !component.value.startsWith(self.canonicalIssuer.prefix)) { component.value = self.canonicalIssuer.getId(component.value); } }); // 7.2) Add quad copy to the normalized dataset. normalized.push(NQuads.serializeQuad(quad)); } // sort normalized output normalized.sort(); // 8) Return the normalized dataset. return normalized.join(''); } // 4.6) Hash First Degree Quads }, { key: 'hashFirstDegreeQuads', value: function hashFirstDegreeQuads(id) { var self = this; // return cached hash var info = self.blankNodeInfo[id]; if ('hash' in info) { return info.hash; } // 1) Initialize nquads to an empty list. It will be used to store quads in // N-Quads format. var nquads = []; // 2) Get the list of quads `quads` associated with the reference blank node // identifier in the blank node to quads map. var quads = info.quads; // 3) For each quad `quad` in `quads`: var _loop2 = function _loop2(i) { var quad = quads[i]; // 3.1) Serialize the quad in N-Quads format with the following special // rule: // 3.1.1) If any component in quad is an blank node, then serialize it // using a special identifier as follows: var copy = { predicate: quad.predicate }; self.forEachComponent(quad, function (component, key) { // 3.1.2) If the blank node's existing blank node identifier matches // the reference blank node identifier then use the blank node // identifier _:a, otherwise, use the blank node identifier _:z. copy[key] = self.modifyFirstDegreeComponent(id, component, key); }); nquads.push(NQuads.serializeQuad(copy)); }; for (var i = 0; i < quads.length; ++i) { _loop2(i); } // 4) Sort nquads in lexicographical order. nquads.sort(); // 5) Return the hash that results from passing the sorted, joined nquads // through the hash algorithm. var md = new MessageDigest(self.hashAlgorithm); for (var i = 0; i < nquads.length; ++i) { md.update(nquads[i]); } // TODO: represent as byte buffer instead to cut memory usage in half info.hash = md.digest(); return info.hash; } // 4.7) Hash Related Blank Node }, { key: 'hashRelatedBlankNode', value: function hashRelatedBlankNode(related, quad, issuer, position) { var self = this; // 1) Set the identifier to use for related, preferring first the canonical // identifier for related if issued, second the identifier issued by issuer // if issued, and last, if necessary, the result of the Hash First Degree // Quads algorithm, passing related. var id = void 0; if (self.canonicalIssuer.hasId(related)) { id = self.canonicalIssuer.getId(related); } else if (issuer.hasId(related)) { id = issuer.getId(related); } else { id = self.hashFirstDegreeQuads(related); } // 2) Initialize a string input to the value of position. // Note: We use a hash object instead. var md = new MessageDigest(self.hashAlgorithm); md.update(position); // 3) If position is not g, append <, the value of the predicate in quad, // and > to input. if (position !== 'g') { md.update(self.getRelatedPredicate(quad)); } // 4) Append identifier to input. md.update(id); // 5) Return the hash that results from passing input through the hash // algorithm. // TODO: represent as byte buffer instead to cut memory usage in half return md.digest(); } // 4.8) Hash N-Degree Quads }, { key: 'hashNDegreeQuads', value: function hashNDegreeQuads(id, issuer) { var self = this; // 1) Create a hash to related blank nodes map for storing hashes that // identify related blank nodes. // Note: 2) and 3) handled within `createHashToRelated` var md = new MessageDigest(self.hashAlgorithm); var hashToRelated = self.createHashToRelated(id, issuer); // 4) Create an empty string, data to hash. // Note: We created a hash object `md` above instead. // 5) For each related hash to blank node list mapping in hash to related // blank nodes map, sorted lexicographically by related hash: var hashes = Object.keys(hashToRelated).sort(); for (var i = 0; i < hashes.length; ++i) { // 5.1) Append the related hash to the data to hash. var hash = hashes[i]; md.update(hash); // 5.2) Create a string chosen path. var chosenPath = ''; // 5.3) Create an unset chosen issuer variable. var chosenIssuer = void 0; // 5.4) For each permutation of blank node list: var permutator = new Permutator(hashToRelated[hash]); while (permutator.hasNext()) { var permutation = permutator.next(); // 5.4.1) Create a copy of issuer, issuer copy. var issuerCopy = issuer.clone(); // 5.4.2) Create a string path. var path = ''; // 5.4.3) Create a recursion list, to store blank node identifiers // that must be recursively processed by this algorithm. var recursionList = []; // 5.4.4) For each related in permutation: var nextPermutation = false; for (var j = 0; j < permutation.length; ++j) { // 5.4.4.1) If a canonical identifier has been issued for // related, append it to path. var related = permutation[j]; if (self.canonicalIssuer.hasId(related)) { path += self.canonicalIssuer.getId(related); } else { // 5.4.4.2) Otherwise: // 5.4.4.2.1) If issuer copy has not issued an identifier for // related, append related to recursion list. if (!issuerCopy.hasId(related)) { recursionList.push(related); } // 5.4.4.2.2) Use the Issue Identifier algorithm, passing // issuer copy and related and append the result to path. path += issuerCopy.getId(related); } // 5.4.4.3) If chosen path is not empty and the length of path // is greater than or equal to the length of chosen path and // path is lexicographically greater than chosen path, then // skip to the next permutation. if (chosenPath.length !== 0 && path.length >= chosenPath.length && path > chosenPath) { nextPermutation = true; break; } } if (nextPermutation) { continue; } // 5.4.5) For each related in recursion list: for (var _j2 = 0; _j2 < recursionList.length; ++_j2) { // 5.4.5.1) Set result to the result of recursively executing // the Hash N-Degree Quads algorithm, passing related for // identifier and issuer copy for path identifier issuer. var _related = recursionList[_j2]; var result = self.hashNDegreeQuads(_related, issuerCopy); // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer // copy and related and append the result to path. path += issuerCopy.getId(_related); // 5.4.5.3) Append <, the hash in result, and > to path. path += '<' + result.hash + '>'; // 5.4.5.4) Set issuer copy to the identifier issuer in // result. issuerCopy = result.issuer; // 5.4.5.5) If chosen path is not empty and the length of path // is greater than or equal to the length of chosen path and // path is lexicographically greater than chosen path, then // skip to the next permutation. if (chosenPath.length !== 0 && path.length >= chosenPath.length && path > chosenPath) { nextPermutation = true; break; } } if (nextPermutation) { continue; } // 5.4.6) If chosen path is empty or path is lexicographically // less than chosen path, set chosen path to path and chosen // issuer to issuer copy. if (chosenPath.length === 0 || path < chosenPath) { chosenPath = path; chosenIssuer = issuerCopy; } } // 5.5) Append chosen path to data to hash. md.update(chosenPath); // 5.6) Replace issuer, by reference, with chosen issuer. issuer = chosenIssuer; } // 6) Return issuer and the hash that results from passing data to hash // through the hash algorithm. return { hash: md.digest(), issuer: issuer }; } // helper for modifying component during Hash First Degree Quads }, { key: 'modifyFirstDegreeComponent', value: function modifyFirstDegreeComponent(id, component) { if (component.termType !== 'BlankNode') { return component; } component = util.clone(component); component.value = component.value === id ? '_:a' : '_:z'; return component; } // helper for getting a related predicate }, { key: 'getRelatedPredicate', value: function getRelatedPredicate(quad) { return '<' + quad.predicate.value + '>'; } // helper for creating hash to related blank nodes map }, { key: 'createHashToRelated', value: function createHashToRelated(id, issuer) { var self = this; // 1) Create a hash to related blank nodes map for storing hashes that // identify related blank nodes. var hashToRelated = {}; // 2) Get a reference, quads, to the list of quads in the blank node to // quads map for the key identifier. var quads = self.blankNodeInfo[id].quads; // 3) For each quad in quads: for (var i = 0; i < quads.length; ++i) { // 3.1) For each component in quad, if component is the subject, object, // and graph name and it is a blank node that is not identified by // identifier: var quad = quads[i]; for (var key in quad) { var component = quad[key]; if (key === 'predicate' || !(component.termType === 'BlankNode' && component.value !== id)) { continue; } // 3.1.1) Set hash to the result of the Hash Related Blank Node // algorithm, passing the blank node identifier for component as // related, quad, path identifier issuer as issuer, and position as // either s, o, or g based on whether component is a subject, object, // graph name, respectively. var related = component.value; var position = POSITIONS[key]; var hash = self.hashRelatedBlankNode(related, quad, issuer, position); // 3.1.2) Add a mapping of hash to the blank node identifier for // component to hash to related blank nodes map, adding an entry as // necessary. if (hash in hashToRelated) { hashToRelated[hash].push(related); } else { hashToRelated[hash] = [related]; } } } return hashToRelated; } // helper that iterates over quad components (skips predicate) }, { key: 'forEachComponent', value: function forEachComponent(quad, op) { for (var key in quad) { // skip `predicate` if (key === 'predicate') { continue; } op(quad[key], key, quad); } } }]); return URDNA2015Sync; }(); /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(74); __webpack_require__(75); __webpack_require__(78); __webpack_require__(81); __webpack_require__(103); __webpack_require__(108); module.exports = __webpack_require__(117); /***/ }), /* 74 */ /***/ (function(module, exports) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ !(function(global) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. runtime.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return Promise.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; resolve(result); }, reject); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { if (delegate.iterator.return) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; })( // In sloppy mode, unbound `this` refers to the global object, fallback to // Function constructor if we're in global strict mode. That is sadly a form // of indirect eval which violates Content Security Policy. (function() { return this })() || Function("return this")() ); /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(76); module.exports = __webpack_require__(3).Array.includes; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/Array.prototype.includes var $export = __webpack_require__(7); var $includes = __webpack_require__(52)(true); $export($export.P, 'Array', { includes: function includes(el /* , fromIndex = 0 */) { return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(54)('includes'); /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(37); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(79); module.exports = __webpack_require__(3).Object.assign; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(7); $export($export.S + $export.F, 'Object', { assign: __webpack_require__(80) }); /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(21); var gOPS = __webpack_require__(41); var pIE = __webpack_require__(30); var toObject = __webpack_require__(56); var IObject = __webpack_require__(53); var $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(19)(function () { var A = {}; var B = {}; // eslint-disable-next-line no-undef var S = Symbol(); var K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function (k) { B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source) { // eslint-disable-line no-unused-vars var T = toObject(target); var aLen = arguments.length; var index = 1; var getSymbols = gOPS.f; var isEnum = pIE.f; while (aLen > index) { var S = IObject(arguments[index++]); var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); var length = keys.length; var j = 0; var key; while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; } return T; } : $assign; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(57); __webpack_require__(82); __webpack_require__(87); __webpack_require__(90); __webpack_require__(101); __webpack_require__(102); module.exports = __webpack_require__(3).Promise; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $at = __webpack_require__(83)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(58)(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(37); var defined = __webpack_require__(29); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__(59); var descriptor = __webpack_require__(26); var setToStringTag = __webpack_require__(32); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(11)(IteratorPrototype, __webpack_require__(0)('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(12); var anObject = __webpack_require__(8); var getKeys = __webpack_require__(21); module.exports = __webpack_require__(13) ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(10); var toObject = __webpack_require__(56); var IE_PROTO = __webpack_require__(39)('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { var $iterators = __webpack_require__(88); var getKeys = __webpack_require__(21); var redefine = __webpack_require__(16); var global = __webpack_require__(1); var hide = __webpack_require__(11); var Iterators = __webpack_require__(22); var wks = __webpack_require__(0); var ITERATOR = wks('iterator'); var TO_STRING_TAG = wks('toStringTag'); var ArrayValues = Iterators.Array; var DOMIterables = { CSSRuleList: true, // TODO: Not spec compliant, should be false. CSSStyleDeclaration: false, CSSValueList: false, ClientRectList: false, DOMRectList: false, DOMStringList: false, DOMTokenList: true, DataTransferItemList: false, FileList: false, HTMLAllCollection: false, HTMLCollection: false, HTMLFormElement: false, HTMLSelectElement: false, MediaList: true, // TODO: Not spec compliant, should be false. MimeTypeArray: false, NamedNodeMap: false, NodeList: true, PaintRequestList: false, Plugin: false, PluginArray: false, SVGLengthList: false, SVGNumberList: false, SVGPathSegList: false, SVGPointList: false, SVGStringList: false, SVGTransformList: false, SourceBufferList: false, StyleSheetList: true, // TODO: Not spec compliant, should be false. TextTrackCueList: false, TextTrackList: false, TouchList: false }; for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { var NAME = collections[i]; var explicit = DOMIterables[NAME]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; var key; if (proto) { if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); } } /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__(54); var step = __webpack_require__(89); var Iterators = __webpack_require__(22); var toIObject = __webpack_require__(17); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(58)(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /* 89 */ /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(31); var global = __webpack_require__(1); var ctx = __webpack_require__(27); var classof = __webpack_require__(42); var $export = __webpack_require__(7); var isObject = __webpack_require__(9); var aFunction = __webpack_require__(28); var anInstance = __webpack_require__(91); var forOf = __webpack_require__(92); var speciesConstructor = __webpack_require__(61); var task = __webpack_require__(62).set; var microtask = __webpack_require__(97)(); var newPromiseCapabilityModule = __webpack_require__(43); var perform = __webpack_require__(63); var promiseResolve = __webpack_require__(64); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function () { /* empty */ }; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { // correct subclassing with @@species support var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[__webpack_require__(0)('species')] = function (exec) { exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch (e) { /* empty */ } }(); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function (reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); if (domain) domain.exit(); } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { reject(e); } }; while (chain.length > i) run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function (promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function (promise) { return promise._h !== 1 && (promise._a || promise._c).length === 0; }; var onHandleUnhandled = function (promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function (value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function (value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); // wrap } }; // constructor polyfill if (!USE_NATIVE) { // 25.4.3.1 Promise(executor) $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(98)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); __webpack_require__(32)($Promise, PROMISE); __webpack_require__(99)(PROMISE); Wrapper = __webpack_require__(3)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(100)(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } }); /***/ }), /* 91 */ /***/ (function(module, exports) { module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(27); var call = __webpack_require__(93); var isArrayIter = __webpack_require__(94); var anObject = __webpack_require__(8); var toLength = __webpack_require__(36); var getIterFn = __webpack_require__(95); var BREAK = {}; var RETURN = {}; var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(8); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(22); var ITERATOR = __webpack_require__(0)('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(42); var ITERATOR = __webpack_require__(0)('iterator'); var Iterators = __webpack_require__(22); module.exports = __webpack_require__(3).getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /* 96 */ /***/ (function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(1); var macrotask = __webpack_require__(62).set; var Observer = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; var isNode = __webpack_require__(18)(process) == 'process'; module.exports = function () { var head, last, notify; var flush = function () { var parent, fn; if (isNode && (parent = process.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (e) { if (head) notify(); else last = undefined; throw e; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (isNode) { notify = function () { process.nextTick(flush); }; // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 } else if (Observer && !(global.navigator && global.navigator.standalone)) { var toggle = true; var node = document.createTextNode(''); new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new notify = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise && Promise.resolve) { var promise = Promise.resolve(); notify = function () { promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { var redefine = __webpack_require__(16); module.exports = function (target, src, safe) { for (var key in src) redefine(target, key, src[key], safe); return target; }; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(1); var dP = __webpack_require__(12); var DESCRIPTORS = __webpack_require__(13); var SPECIES = __webpack_require__(0)('species'); module.exports = function (KEY) { var C = global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function () { return this; } }); }; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(0)('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; // eslint-disable-next-line no-throw-literal Array.from(riter, function () { throw 2; }); } catch (e) { /* empty */ } module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) { /* empty */ } return safe; }; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-finally var $export = __webpack_require__(7); var core = __webpack_require__(3); var global = __webpack_require__(1); var speciesConstructor = __webpack_require__(61); var promiseResolve = __webpack_require__(64); $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { var C = speciesConstructor(this, core.Promise || global.Promise); var isFunction = typeof onFinally == 'function'; return this.then( isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally ); } }); /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-try var $export = __webpack_require__(7); var newPromiseCapability = __webpack_require__(43); var perform = __webpack_require__(63); $export($export.S, 'Promise', { 'try': function (callbackfn) { var promiseCapability = newPromiseCapability.f(this); var result = perform(callbackfn); (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); return promiseCapability.promise; } }); /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(104); module.exports = __webpack_require__(3).String.startsWith; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) var $export = __webpack_require__(7); var toLength = __webpack_require__(36); var context = __webpack_require__(105); var STARTS_WITH = 'startsWith'; var $startsWith = ''[STARTS_WITH]; $export($export.P + $export.F * __webpack_require__(107)(STARTS_WITH), 'String', { startsWith: function startsWith(searchString /* , position = 0 */) { var that = context(this, searchString, STARTS_WITH); var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); var search = String(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { // helper for String#{startsWith, endsWith, includes} var isRegExp = __webpack_require__(106); var defined = __webpack_require__(29); module.exports = function (that, searchString, NAME) { if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); return String(defined(that)); }; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { // 7.2.8 IsRegExp(argument) var isObject = __webpack_require__(9); var cof = __webpack_require__(18); var MATCH = __webpack_require__(0)('match'); module.exports = function (it) { var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { var MATCH = __webpack_require__(0)('match'); module.exports = function (KEY) { var re = /./; try { '/./'[KEY](re); } catch (e) { try { re[MATCH] = false; return !'/./'[KEY](re); } catch (f) { /* empty */ } } return true; }; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(109); __webpack_require__(57); __webpack_require__(115); __webpack_require__(116); module.exports = __webpack_require__(3).Symbol; /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // ECMAScript 6 symbols shim var global = __webpack_require__(1); var has = __webpack_require__(10); var DESCRIPTORS = __webpack_require__(13); var $export = __webpack_require__(7); var redefine = __webpack_require__(16); var META = __webpack_require__(110).KEY; var $fails = __webpack_require__(19); var shared = __webpack_require__(38); var setToStringTag = __webpack_require__(32); var uid = __webpack_require__(20); var wks = __webpack_require__(0); var wksExt = __webpack_require__(65); var wksDefine = __webpack_require__(44); var enumKeys = __webpack_require__(111); var isArray = __webpack_require__(112); var anObject = __webpack_require__(8); var isObject = __webpack_require__(9); var toIObject = __webpack_require__(17); var toPrimitive = __webpack_require__(35); var createDesc = __webpack_require__(26); var _create = __webpack_require__(59); var gOPNExt = __webpack_require__(113); var $GOPD = __webpack_require__(114); var $DP = __webpack_require__(12); var $keys = __webpack_require__(21); var gOPD = $GOPD.f; var dP = $DP.f; var gOPN = gOPNExt.f; var $Symbol = global.Symbol; var $JSON = global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE = 'prototype'; var HIDDEN = wks('_hidden'); var TO_PRIMITIVE = wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = shared('symbol-registry'); var AllSymbols = shared('symbols'); var OPSymbols = shared('op-symbols'); var ObjectProto = Object[PROTOTYPE]; var USE_NATIVE = typeof $Symbol == 'function'; var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function () { return _create(dP({}, 'a', { get: function () { return dP(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (it, key, D) { var protoDesc = gOPD(ObjectProto, key); if (protoDesc) delete ObjectProto[key]; dP(it, key, D); if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); } : dP; var wrap = function (tag) { var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { return typeof it == 'symbol'; } : function (it) { return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D) { if (it === ObjectProto) $defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if (has(AllSymbols, key)) { if (!D.enumerable) { if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; D = _create(D, { enumerable: createDesc(0, false) }); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P) { anObject(it); var keys = enumKeys(P = toIObject(P)); var i = 0; var l = keys.length; var key; while (l > i) $defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P) { return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key) { var E = isEnum.call(this, key = toPrimitive(key, true)); if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { it = toIObject(it); key = toPrimitive(key, true); if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; var D = gOPD(it, key); if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it) { var names = gOPN(toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { var IS_OP = it === ObjectProto; var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if (!USE_NATIVE) { $Symbol = function Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function (value) { if (this === ObjectProto) $set.call(OPSymbols, value); if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString() { return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(66).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(30).f = $propertyIsEnumerable; __webpack_require__(41).f = $getOwnPropertySymbols; if (DESCRIPTORS && !__webpack_require__(31)) { redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function (name) { return wrap(wks(name)); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); for (var es6Symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function (key) { return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; }, useSetter: function () { setter = true; }, useSimple: function () { setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it) { var args = [it]; var i = 1; var replacer, $replacer; while (arguments.length > i) args.push(arguments[i++]); $replacer = replacer = args[1]; if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!isArray(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(11)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(20)('meta'); var isObject = __webpack_require__(9); var has = __webpack_require__(10); var setDesc = __webpack_require__(12).f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__(19)(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(21); var gOPS = __webpack_require__(41); var pIE = __webpack_require__(30); module.exports = function (it) { var result = getKeys(it); var getSymbols = gOPS.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = pIE.f; var i = 0; var key; while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); } return result; }; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(18); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(17); var gOPN = __webpack_require__(66).f; var toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return gOPN(it); } catch (e) { return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__(30); var createDesc = __webpack_require__(26); var toIObject = __webpack_require__(17); var toPrimitive = __webpack_require__(35); var has = __webpack_require__(10); var IE8_DOM_DEFINE = __webpack_require__(51); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(13) ? gOPD : function getOwnPropertyDescriptor(O, P) { O = toIObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return gOPD(O, P); } catch (e) { /* empty */ } if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(44)('asyncIterator'); /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(44)('observable'); /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /** * A JavaScript implementation of the JSON-LD API. * * @author Dave Longley * * @license BSD 3-Clause License * Copyright (c) 2011-2017 Digital Bazaar, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Digital Bazaar, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { var canonize = __webpack_require__(45); var util = __webpack_require__(2); var IdentifierIssuer = util.IdentifierIssuer; var JsonLdError = __webpack_require__(6); var NQuads = __webpack_require__(127); var Rdfa = __webpack_require__(128); var _require = __webpack_require__(129), _expand = _require.expand; var _require2 = __webpack_require__(131), _flatten = _require2.flatten; var _require3 = __webpack_require__(132), _frameMerged = _require3.frameMerged; var _require4 = __webpack_require__(133), _fromRDF = _require4.fromRDF; var _require5 = __webpack_require__(134), _toRDF = _require5.toRDF; var _require6 = __webpack_require__(4), _isArray = _require6.isArray, _isObject = _require6.isObject, _isString = _require6.isString; var _require7 = __webpack_require__(5), _isSubjectReference = _require7.isSubjectReference; var _require8 = __webpack_require__(15), _getInitialContext = _require8.getInitialContext, _processContext = _require8.process, _getAllContexts = _require8.getAllContexts; var _require9 = __webpack_require__(135), _compact = _require9.compact, _compactIri = _require9.compactIri, _removePreserve = _require9.removePreserve; var _require10 = __webpack_require__(33), _createNodeMap = _require10.createNodeMap, _createMergedNodeMap = _require10.createMergedNodeMap, _mergeNodeMaps = _require10.mergeNodeMaps; // determine if in-browser or using node.js var _nodejs = typeof process !== 'undefined' && process.versions && process.versions.node; var _browser = !_nodejs && (typeof window !== 'undefined' || typeof self !== 'undefined'); // attaches jsonld API to the given object var wrapper = function wrapper(jsonld) { var _this = this; /* Core API */ /** * Performs JSON-LD compaction. * * @param input the JSON-LD input to compact. * @param ctx the context to compact with. * @param [options] options to use: * [base] the base IRI to use. * [compactArrays] true to compact arrays to single values when * appropriate, false not to (default: true). * [graph] true to always output a top-level graph (default: false). * [expandContext] a context to expand with. * [skipExpansion] true to assume the input is expanded and skip * expansion, false not to, defaults to false. * [documentLoader(url, callback(err, remoteDoc))] the document loader. * [expansionMap(info)] a function that can be used to custom map * unmappable values (or to throw an error when they are detected); * if this function returns `undefined` then the default behavior * will be used. * [framing] true if compaction is occuring during a framing operation. * [compactionMap(info)] a function that can be used to custom map * unmappable values (or to throw an error when they are detected); * if this function returns `undefined` then the default behavior * will be used. * @param [callback(err, compacted)] called once the operation completes. * * @return a Promise that resolves to the compacted output. */ jsonld.compact = util.callbackify(function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(input, ctx, options) { var expanded, activeCtx, compacted, tmp, i, hasContext, graphAlias, graph, _graph, key, _graph2, _args = arguments; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(_args.length < 2)) { _context.next = 2; break; } throw new TypeError('Could not compact, too few arguments.'); case 2: if (!(ctx === null)) { _context.next = 4; break; } throw new JsonLdError('The compaction context must not be null.', 'jsonld.CompactError', { code: 'invalid local context' }); case 4: if (!(input === null)) { _context.next = 6; break; } return _context.abrupt('return', null); case 6: // set default options options = _setDefaults(options, { base: _isString(input) ? input : '', compactArrays: true, graph: false, skipExpansion: false, link: false }); if (options.link) { // force skip expansion when linking, "link" is not part of the public // API, it should only be called from framing options.skipExpansion = true; } // expand input expanded = void 0; if (!options.skipExpansion) { _context.next = 13; break; } expanded = input; _context.next = 16; break; case 13: _context.next = 15; return jsonld.expand(input, options); case 15: expanded = _context.sent; case 16: _context.next = 18; return jsonld.processContext(_getInitialContext(options), ctx, options); case 18: activeCtx = _context.sent; // do compaction compacted = _compact({ activeCtx: activeCtx, element: expanded, options: options, compactionMap: options.compactionMap }); // perform clean up if (options.compactArrays && !options.graph && _isArray(compacted)) { if (compacted.length === 1) { // simplify to a single item compacted = compacted[0]; } else if (compacted.length === 0) { // simplify to an empty object compacted = {}; } } else if (options.graph && _isObject(compacted)) { // always use array if graph option is on compacted = [compacted]; } // follow @context key if (_isObject(ctx) && '@context' in ctx) { ctx = ctx['@context']; } // build output context ctx = util.clone(ctx); if (!_isArray(ctx)) { ctx = [ctx]; } // remove empty contexts tmp = ctx; ctx = []; for (i = 0; i < tmp.length; ++i) { if (!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) { ctx.push(tmp[i]); } } // remove array if only one context hasContext = ctx.length > 0; if (ctx.length === 1) { ctx = ctx[0]; } // add context and/or @graph if (_isArray(compacted)) { // use '@graph' keyword graphAlias = _compactIri({ activeCtx: activeCtx, iri: '@graph', relativeTo: { vocab: true } }); graph = compacted; compacted = {}; if (hasContext) { compacted['@context'] = ctx; } compacted[graphAlias] = graph; } else if (_isObject(compacted) && hasContext) { // reorder keys so @context is first _graph = compacted; compacted = { '@context': ctx }; for (key in _graph) { compacted[key] = _graph[key]; } } if (options.framing) { // get graph alias _graph2 = _compactIri({ activeCtx: activeCtx, iri: '@graph', relativeTo: { vocab: true } }); // remove @preserve from results options.link = {}; compacted[_graph2] = _removePreserve(activeCtx, compacted[_graph2], options); } return _context.abrupt('return', compacted); case 32: case 'end': return _context.stop(); } } }, _callee, this); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }()); /** * Performs JSON-LD expansion. * * @param input the JSON-LD input to expand. * @param [options] the options to use: * [base] the base IRI to use. * [expandContext] a context to expand with. * [keepFreeFloatingNodes] true to keep free-floating nodes, * false not to, defaults to false. * [documentLoader(url, callback(err, remoteDoc))] the document loader. * [expansionMap(info)] a function that can be used to custom map * unmappable values (or to throw an error when they are detected); * if this function returns `undefined` then the default behavior * will be used. * @param [callback(err, expanded)] called once the operation completes. * * @return a Promise that resolves to the expanded output. */ jsonld.expand = util.callbackify(function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(input, options) { var toResolve, contextsToProcess, expandContext, defaultBase, remoteDoc, activeCtx, expanded, _args2 = arguments; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(_args2.length < 1)) { _context2.next = 2; break; } throw new TypeError('Could not expand, too few arguments.'); case 2: // set default options options = _setDefaults(options, { keepFreeFloatingNodes: false }); if (options.expansionMap === false) { options.expansionMap = undefined; } // build set of objects that may have @contexts to resolve toResolve = {}; // build set of contexts to process prior to expansion contextsToProcess = []; // if an `expandContext` has been given ensure it gets resolved if ('expandContext' in options) { expandContext = util.clone(options.expandContext); if (_isObject(expandContext) && '@context' in expandContext) { toResolve.expandContext = expandContext; } else { toResolve.expandContext = { '@context': expandContext }; } contextsToProcess.push(toResolve.expandContext); } // if input is a string, attempt to dereference remote document defaultBase = void 0; if (_isString(input)) { _context2.next = 12; break; } // input is not a URL, do not need to retrieve it first toResolve.input = util.clone(input); _context2.next = 18; break; case 12: _context2.next = 14; return jsonld.get(input, options); case 14: remoteDoc = _context2.sent; defaultBase = remoteDoc.documentUrl; toResolve.input = remoteDoc.document; if (remoteDoc.contextUrl) { // context included in HTTP link header and must be resolved toResolve.remoteContext = { '@context': remoteDoc.contextUrl }; contextsToProcess.push(toResolve.remoteContext); } case 18: // set default base if (!('base' in options)) { options.base = defaultBase || ''; } // get all contexts in `toResolve` _context2.next = 21; return _getAllContexts(toResolve, options); case 21: // process any additional contexts activeCtx = _getInitialContext(options); contextsToProcess.forEach(function (localCtx) { activeCtx = _processContext({ activeCtx: activeCtx, localCtx: localCtx, options: options }); }); // expand resolved input expanded = _expand({ activeCtx: activeCtx, element: toResolve.input, options: options, expansionMap: options.expansionMap }); // optimize away @graph with no other properties if (_isObject(expanded) && '@graph' in expanded && Object.keys(expanded).length === 1) { expanded = expanded['@graph']; } else if (expanded === null) { expanded = []; } // normalize to an array if (!_isArray(expanded)) { expanded = [expanded]; } return _context2.abrupt('return', expanded); case 27: case 'end': return _context2.stop(); } } }, _callee2, this); })); return function (_x4, _x5) { return _ref2.apply(this, arguments); }; }()); /** * Performs JSON-LD flattening. * * @param input the JSON-LD to flatten. * @param ctx the context to use to compact the flattened output, or null. * @param [options] the options to use: * [base] the base IRI to use. * [expandContext] a context to expand with. * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, flattened)] called once the operation completes. * * @return a Promise that resolves to the flattened output. */ jsonld.flatten = util.callbackify(function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(input, ctx, options) { var expanded, flattened, compacted, _args3 = arguments; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(_args3.length < 1)) { _context3.next = 2; break; } return _context3.abrupt('return', new TypeError('Could not flatten, too few arguments.')); case 2: if (typeof ctx === 'function') { ctx = null; } else { ctx = ctx || null; } // set default options options = _setDefaults(options, { base: _isString(input) ? input : '' }); // expand input _context3.next = 6; return jsonld.expand(input, options); case 6: expanded = _context3.sent; // do flattening flattened = _flatten(expanded); if (!(ctx === null)) { _context3.next = 10; break; } return _context3.abrupt('return', flattened); case 10: // compact result (force @graph option to true, skip expansion) options.graph = true; options.skipExpansion = true; _context3.next = 14; return jsonld.compact(flattened, ctx, options); case 14: compacted = _context3.sent; return _context3.abrupt('return', compacted); case 16: case 'end': return _context3.stop(); } } }, _callee3, this); })); return function (_x6, _x7, _x8) { return _ref3.apply(this, arguments); }; }()); /** * Performs JSON-LD framing. * * @param input the JSON-LD input to frame. * @param frame the JSON-LD frame to use. * @param [options] the framing options. * [base] the base IRI to use. * [expandContext] a context to expand with. * [embed] default @embed flag: '@last', '@always', '@never', '@link' * (default: '@last'). * [explicit] default @explicit flag (default: false). * [requireAll] default @requireAll flag (default: true). * [omitDefault] default @omitDefault flag (default: false). * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, framed)] called once the operation completes. * * @return a Promise that resolves to the framed output. */ jsonld.frame = util.callbackify(function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(input, frame, options) { var remoteDoc, ctx, frameContext, expanded, opts, expandedFrame, framed, compacted, _args4 = arguments; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (!(_args4.length < 2)) { _context4.next = 2; break; } throw new TypeError('Could not frame, too few arguments.'); case 2: // set default options options = _setDefaults(options, { base: _isString(input) ? input : '', embed: '@last', explicit: false, requireAll: true, omitDefault: false }); // if frame is a string, attempt to dereference remote document if (!_isString(frame)) { _context4.next = 9; break; } _context4.next = 6; return jsonld.get(frame, options); case 6: remoteDoc = _context4.sent; frame = remoteDoc.document; if (remoteDoc.contextUrl) { // inject link header @context into frame ctx = frame['@context']; if (!ctx) { ctx = remoteDoc.contextUrl; } else if (_isArray(ctx)) { ctx.push(remoteDoc.contextUrl); } else { ctx = [ctx, remoteDoc.contextUrl]; } frame['@context'] = ctx; } case 9: frameContext = frame ? frame['@context'] || {} : {}; // expand input _context4.next = 12; return jsonld.expand(input, options); case 12: expanded = _context4.sent; // expand frame opts = util.clone(options); opts.isFrame = true; opts.keepFreeFloatingNodes = true; _context4.next = 18; return jsonld.expand(frame, opts); case 18: expandedFrame = _context4.sent; // do merged framing framed = _frameMerged(expanded, expandedFrame, opts); // compact result (force @graph option to true, skip expansion, // check for linked embeds) opts.graph = true; opts.skipExpansion = true; opts.link = {}; opts.framing = true; _context4.next = 26; return jsonld.compact(framed, frameContext, opts); case 26: compacted = _context4.sent; return _context4.abrupt('return', compacted); case 28: case 'end': return _context4.stop(); } } }, _callee4, this); })); return function (_x9, _x10, _x11) { return _ref4.apply(this, arguments); }; }()); /** * **Experimental** * * Links a JSON-LD document's nodes in memory. * * @param input the JSON-LD document to link. * @param [ctx] the JSON-LD context to apply. * @param [options] the options to use: * [base] the base IRI to use. * [expandContext] a context to expand with. * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, linked)] called once the operation completes. * * @return a Promise that resolves to the linked output. */ jsonld.link = util.callbackify(function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(input, ctx, options) { var frame; return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: // API matches running frame with a wildcard frame and embed: '@link' // get arguments frame = {}; if (ctx) { frame['@context'] = ctx; } frame['@embed'] = '@link'; return _context5.abrupt('return', jsonld.frame(input, frame, options)); case 4: case 'end': return _context5.stop(); } } }, _callee5, this); })); return function (_x12, _x13, _x14) { return _ref5.apply(this, arguments); }; }()); /** * Performs RDF dataset normalization on the given input. The input is JSON-LD * unless the 'inputFormat' option is used. The output is an RDF dataset * unless the 'format' option is used. * * @param input the input to normalize as JSON-LD or as a format specified by * the 'inputFormat' option. * @param [options] the options to use: * [algorithm] the normalization algorithm to use, `URDNA2015` or * `URGNA2012` (default: `URGNA2012`). * [base] the base IRI to use. * [expandContext] a context to expand with. * [inputFormat] the format if input is not JSON-LD: * 'application/n-quads' for N-Quads. * [format] the format if output is a string: * 'application/n-quads' for N-Quads. * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, normalized)] called once the operation completes. * * @return a Promise that resolves to the normalized output. */ jsonld.normalize = jsonld.canonize = util.callbackify(function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(input, options) { var parsedInput, opts, dataset, _args6 = arguments; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (!(_args6.length < 1)) { _context6.next = 2; break; } throw new TypeError('Could not canonize, too few arguments.'); case 2: // set default options options = _setDefaults(options, { base: _isString(input) ? input : '', algorithm: 'URDNA2015' }); if (!('inputFormat' in options)) { _context6.next = 8; break; } if (!(options.inputFormat !== 'application/n-quads' && options.inputFormat !== 'application/nquads')) { _context6.next = 6; break; } throw new JsonLdError('Unknown canonicalization input format.', 'jsonld.CanonizeError'); case 6: // TODO: `await` for async parsers parsedInput = NQuads.parse(input); // do canonicalization return _context6.abrupt('return', canonize.canonize(parsedInput, options)); case 8: // convert to RDF dataset then do normalization opts = util.clone(options); delete opts.format; opts.produceGeneralizedRdf = false; _context6.next = 13; return jsonld.toRDF(input, opts); case 13: dataset = _context6.sent; return _context6.abrupt('return', canonize.canonize(dataset, options)); case 15: case 'end': return _context6.stop(); } } }, _callee6, this); })); return function (_x15, _x16) { return _ref6.apply(this, arguments); }; }()); /** * Converts an RDF dataset to JSON-LD. * * @param dataset a serialized string of RDF in a format specified by the * format option or an RDF dataset to convert. * @param [options] the options to use: * [format] the format if dataset param must first be parsed: * 'application/n-quads' for N-Quads (default). * [rdfParser] a custom RDF-parser to use to parse the dataset. * [useRdfType] true to use rdf:type, false to use @type * (default: false). * [useNativeTypes] true to convert XSD types into native types * (boolean, integer, double), false not to (default: false). * @param [callback(err, output)] called once the operation completes. * * @return a Promise that resolves to the JSON-LD document. */ jsonld.fromRDF = util.callbackify(function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(dataset, options) { var _options, format, rdfParser, parsedDataset, _args7 = arguments; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: if (!(_args7.length < 1)) { _context7.next = 2; break; } throw new TypeError('Could not convert from RDF, too few arguments.'); case 2: // set default options options = _setDefaults(options, { format: _isString(dataset) ? 'application/n-quads' : undefined }); _options = options, format = _options.format, rdfParser = _options.rdfParser; // handle special format if (!format) { _context7.next = 10; break; } // check supported formats rdfParser = rdfParser || _rdfParsers[format]; if (rdfParser) { _context7.next = 8; break; } throw new JsonLdError('Unknown input format.', 'jsonld.UnknownFormat', { format: format }); case 8: _context7.next = 11; break; case 10: // no-op parser, assume dataset already parsed rdfParser = function rdfParser() { return dataset; }; case 11: // TODO: call `normalizeAsyncFn` on parser fn // rdfParser can be callback, promise-based, or synchronous parsedDataset = void 0; if (rdfParser.length > 1) { // convert callback-based rdf parser to promise-based parsedDataset = new Promise(function (resolve, reject) { rdfParser(dataset, function (err, dataset) { if (err) { reject(err); } else { resolve(dataset); } }); }); } else { parsedDataset = Promise.resolve(rdfParser(dataset)); } _context7.next = 15; return parsedDataset; case 15: parsedDataset = _context7.sent; // back-compat with old parsers that produced legacy dataset format if (!Array.isArray(parsedDataset)) { parsedDataset = NQuads.legacyDatasetToQuads(parsedDataset); } return _context7.abrupt('return', _fromRDF(parsedDataset, options)); case 18: case 'end': return _context7.stop(); } } }, _callee7, this); })); return function (_x17, _x18) { return _ref7.apply(this, arguments); }; }()); /** * Outputs the RDF dataset found in the given JSON-LD object. * * @param input the JSON-LD input. * @param [options] the options to use: * [base] the base IRI to use. * [expandContext] a context to expand with. * [format] the format to use to output a string: * 'application/n-quads' for N-Quads. * [produceGeneralizedRdf] true to output generalized RDF, false * to produce only standard RDF (default: false). * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, dataset)] called once the operation completes. * * @return a Promise that resolves to the RDF dataset. */ jsonld.toRDF = util.callbackify(function () { var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(input, options) { var expanded, dataset, _args8 = arguments; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!(_args8.length < 1)) { _context8.next = 2; break; } throw new TypeError('Could not convert to RDF, too few arguments.'); case 2: // set default options options = _setDefaults(options, { base: _isString(input) ? input : '' }); // TODO: support toRDF custom map? // expand input _context8.next = 5; return jsonld.expand(input, options); case 5: expanded = _context8.sent; // output RDF dataset dataset = _toRDF(expanded, options); if (!options.format) { _context8.next = 13; break; } if (!(options.format === 'application/n-quads' || options.format === 'application/nquads')) { _context8.next = 12; break; } _context8.next = 11; return NQuads.serialize(dataset); case 11: return _context8.abrupt('return', _context8.sent); case 12: throw new JsonLdError('Unknown output format.', 'jsonld.UnknownFormat', { format: options.format }); case 13: return _context8.abrupt('return', dataset); case 14: case 'end': return _context8.stop(); } } }, _callee8, this); })); return function (_x19, _x20) { return _ref8.apply(this, arguments); }; }()); /** * **Experimental** * * Recursively flattens the nodes in the given JSON-LD input into a merged * map of node ID => node. All graphs will be merged into the default graph. * * @param input the JSON-LD input. * @param [options] the options to use: * [base] the base IRI to use. * [expandContext] a context to expand with. * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, nodeMap)] called once the operation completes. * * @return a Promise that resolves to the merged node map. */ jsonld.createNodeMap = util.callbackify(function () { var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(input, options) { var expanded, _args9 = arguments; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: if (!(_args9.length < 1)) { _context9.next = 2; break; } throw new TypeError('Could not create node map, too few arguments.'); case 2: // set default options options = _setDefaults(options, { base: _isString(input) ? input : '' }); // expand input expanded = jsonld.expand(input, options); return _context9.abrupt('return', _createMergedNodeMap(expanded, options)); case 5: case 'end': return _context9.stop(); } } }, _callee9, this); })); return function (_x21, _x22) { return _ref9.apply(this, arguments); }; }()); /** * **Experimental** * * Merges two or more JSON-LD documents into a single flattened document. * * @param docs the JSON-LD documents to merge together. * @param ctx the context to use to compact the merged result, or null. * @param [options] the options to use: * [base] the base IRI to use. * [expandContext] a context to expand with. * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. * [mergeNodes] true to merge properties for nodes with the same ID, * false to ignore new properties for nodes with the same ID once * the ID has been defined; note that this may not prevent merging * new properties where a node is in the `object` position * (default: true). * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, merged)] called once the operation completes. * * @return a Promise that resolves to the merged output. */ jsonld.merge = util.callbackify(function () { var _ref10 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(docs, ctx, options) { var expanded, mergeNodes, issuer, graphs, i, doc, _graphs, graphName, _nodeMap, nodeMap, key, defaultGraph, flattened, keys, ki, node, compacted, _args10 = arguments; return regeneratorRuntime.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: if (!(_args10.length < 1)) { _context10.next = 2; break; } throw new TypeError('Could not merge, too few arguments.'); case 2: if (_isArray(docs)) { _context10.next = 4; break; } throw new TypeError('Could not merge, "docs" must be an array.'); case 4: if (typeof ctx === 'function') { ctx = null; } else { ctx = ctx || null; } // set default options options = _setDefaults(options, {}); // expand all documents _context10.next = 8; return Promise.all(docs.map(function (doc) { var opts = Object.assign({}, options); return jsonld.expand(doc, opts); })); case 8: expanded = _context10.sent; mergeNodes = true; if ('mergeNodes' in options) { mergeNodes = options.mergeNodes; } issuer = options.issuer || new IdentifierIssuer('_:b'); graphs = { '@default': {} }; i = 0; case 14: if (!(i < expanded.length)) { _context10.next = 33; break; } // uniquely relabel blank nodes doc = util.relabelBlankNodes(expanded[i], { issuer: new IdentifierIssuer('_:b' + i + '-') }); // add nodes to the shared node map graphs if merging nodes, to a // separate graph set if not _graphs = mergeNodes || i === 0 ? graphs : { '@default': {} }; _createNodeMap(doc, _graphs, '@default', issuer); if (!(_graphs !== graphs)) { _context10.next = 30; break; } _context10.t0 = regeneratorRuntime.keys(_graphs); case 20: if ((_context10.t1 = _context10.t0()).done) { _context10.next = 30; break; } graphName = _context10.t1.value; _nodeMap = _graphs[graphName]; if (graphName in graphs) { _context10.next = 26; break; } graphs[graphName] = _nodeMap; return _context10.abrupt('continue', 20); case 26: nodeMap = graphs[graphName]; for (key in _nodeMap) { if (!(key in nodeMap)) { nodeMap[key] = _nodeMap[key]; } } _context10.next = 20; break; case 30: ++i; _context10.next = 14; break; case 33: // add all non-default graphs to default graph defaultGraph = _mergeNodeMaps(graphs); // produce flattened output flattened = []; keys = Object.keys(defaultGraph).sort(); for (ki = 0; ki < keys.length; ++ki) { node = defaultGraph[keys[ki]]; // only add full subjects to top-level if (!_isSubjectReference(node)) { flattened.push(node); } } if (!(ctx === null)) { _context10.next = 39; break; } return _context10.abrupt('return', flattened); case 39: // compact result (force @graph option to true, skip expansion) options.graph = true; options.skipExpansion = true; compacted = jsonld.compact(flattened, ctx, options); return _context10.abrupt('return', compacted); case 43: case 'end': return _context10.stop(); } } }, _callee10, this); })); return function (_x23, _x24, _x25) { return _ref10.apply(this, arguments); }; }()); /** * The default document loader for external documents. If the environment * is node.js, a callback-continuation-style document loader is used; otherwise, * a promises-style document loader is used. * * @param url the URL to load. * @param callback(err, remoteDoc) called once the operation completes, * if using a non-promises API. * * @return a promise, if using a promises API. */ Object.defineProperty(jsonld, 'documentLoader', { get: function get() { return jsonld._documentLoader; }, set: function set(v) { return jsonld._documentLoader = util.normalizeDocumentLoader(v); } }); // default document loader not implemented jsonld.documentLoader = function () { var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(url) { return regeneratorRuntime.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: throw new JsonLdError('Could not retrieve a JSON-LD document from the URL. URL ' + 'dereferencing not implemented.', 'jsonld.LoadDocumentError', { code: 'loading document failed', url: url }); case 1: case 'end': return _context11.stop(); } } }, _callee11, _this); })); return function (_x26) { return _ref11.apply(this, arguments); }; }(); /** * Deprecated default document loader. Do not use or override. */ jsonld.loadDocument = util.callbackify(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12() { var _args12 = arguments; return regeneratorRuntime.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: return _context12.abrupt('return', jsonld.documentLoader.apply(null, _args12)); case 1: case 'end': return _context12.stop(); } } }, _callee12, this); }))); /** * Gets a remote JSON-LD document using the default document loader or * one given in the passed options. * * @param url the URL to fetch. * @param [options] the options to use: * [documentLoader] the document loader to use. * @param [callback(err, remoteDoc)] called once the operation completes. * * @return a Promise that resolves to the retrieved remote document. */ jsonld.get = util.callbackify(function () { var _ref13 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(url, options) { var load, remoteDoc; return regeneratorRuntime.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: load = void 0; if (typeof options.documentLoader === 'function') { load = util.normalizeDocumentLoader(options.documentLoader); } else { load = jsonld.documentLoader; } _context13.next = 4; return load(url); case 4: remoteDoc = _context13.sent; _context13.prev = 5; if (remoteDoc.document) { _context13.next = 8; break; } throw new JsonLdError('No remote document found at the given URL.', 'jsonld.NullRemoteDocument'); case 8: if (_isString(remoteDoc.document)) { remoteDoc.document = JSON.parse(remoteDoc.document); } _context13.next = 14; break; case 11: _context13.prev = 11; _context13.t0 = _context13['catch'](5); throw new JsonLdError('Could not retrieve a JSON-LD document from the URL.', 'jsonld.LoadDocumentError', { code: 'loading document failed', cause: _context13.t0, remoteDoc: remoteDoc }); case 14: return _context13.abrupt('return', remoteDoc); case 15: case 'end': return _context13.stop(); } } }, _callee13, this, [[5, 11]]); })); return function (_x27, _x28) { return _ref13.apply(this, arguments); }; }()); /** * Processes a local context, resolving any URLs as necessary, and returns a * new active context in its callback. * * @param activeCtx the current active context. * @param localCtx the local context to process. * @param [options] the options to use: * [documentLoader(url, callback(err, remoteDoc))] the document loader. * @param [callback(err, activeCtx)] called once the operation completes. * * @return a Promise that resolves to the new active context. */ jsonld.processContext = util.callbackify(function () { var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(activeCtx, localCtx, options) { var ctx; return regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: // set default options options = _setDefaults(options, { base: '' }); // return initial context early for null context if (!(localCtx === null)) { _context14.next = 3; break; } return _context14.abrupt('return', _getInitialContext(options)); case 3: // get URLs in localCtx localCtx = util.clone(localCtx); if (!(_isObject(localCtx) && '@context' in localCtx)) { localCtx = { '@context': localCtx }; } _context14.next = 7; return _getAllContexts(localCtx, options); case 7: ctx = _context14.sent; return _context14.abrupt('return', _processContext({ activeCtx: activeCtx, localCtx: ctx, options: options })); case 9: case 'end': return _context14.stop(); } } }, _callee14, this); })); return function (_x29, _x30, _x31) { return _ref14.apply(this, arguments); }; }()); // backwards compatibility jsonld.getContextValue = __webpack_require__(15).getContextValue; /** * Document loaders. */ jsonld.documentLoaders = {}; jsonld.documentLoaders.node = __webpack_require__(136); jsonld.documentLoaders.xhr = __webpack_require__(137); /** * Assigns the default document loader for external document URLs to a built-in * default. Supported types currently include: 'xhr' and 'node'. * * @param type the type to set. * @param [params] the parameters required to use the document loader. */ jsonld.useDocumentLoader = function (type) { if (!(type in jsonld.documentLoaders)) { throw new JsonLdError('Unknown document loader type: "' + type + '"', 'jsonld.UnknownDocumentLoader', { type: type }); } // set document loader jsonld.documentLoader = jsonld.documentLoaders[type].apply(jsonld, Array.prototype.slice.call(arguments, 1)); }; /** Registered RDF dataset parsers hashed by content-type. */ var _rdfParsers = {}; /** * Registers an RDF dataset parser by content-type, for use with * jsonld.fromRDF. An RDF dataset parser will always be given two parameters, * a string of input and a callback. An RDF dataset parser can be synchronous * or asynchronous. * * If the parser function returns undefined or null then it will be assumed to * be asynchronous w/a continuation-passing style and the callback parameter * given to the parser MUST be invoked. * * If it returns a Promise, then it will be assumed to be asynchronous, but the * callback parameter MUST NOT be invoked. It should instead be ignored. * * If it returns an RDF dataset, it will be assumed to be synchronous and the * callback parameter MUST NOT be invoked. It should instead be ignored. * * @param contentType the content-type for the parser. * @param parser(input, callback(err, dataset)) the parser function (takes a * string as a parameter and either returns null/undefined and uses * the given callback, returns a Promise, or returns an RDF dataset). */ jsonld.registerRDFParser = function (contentType, parser) { _rdfParsers[contentType] = parser; }; /** * Unregisters an RDF dataset parser by content-type. * * @param contentType the content-type for the parser. */ jsonld.unregisterRDFParser = function (contentType) { delete _rdfParsers[contentType]; }; // register the N-Quads RDF parser jsonld.registerRDFParser('application/n-quads', NQuads.parse); jsonld.registerRDFParser('application/nquads', NQuads.parse); // register the RDFa API RDF parser jsonld.registerRDFParser('rdfa-api', Rdfa.parse); /* URL API */ jsonld.url = __webpack_require__(25); /* Utility API */ jsonld.util = util; // backwards compatibility Object.assign(jsonld, util); // reexpose API as jsonld.promises for backwards compatability jsonld.promises = jsonld; // backwards compatibility jsonld.RequestQueue = __webpack_require__(50); /* WebIDL API */ jsonld.JsonLdProcessor = __webpack_require__(138)(jsonld); // setup browser global JsonLdProcessor if (_browser && typeof global.JsonLdProcessor === 'undefined') { Object.defineProperty(global, 'JsonLdProcessor', { writable: true, enumerable: false, configurable: true, value: jsonld.JsonLdProcessor }); } // set platform-specific defaults/APIs if (_nodejs) { // use node document loader by default jsonld.useDocumentLoader('node'); } else if (typeof XMLHttpRequest !== 'undefined') { // use xhr document loader by default jsonld.useDocumentLoader('xhr'); } function _setDefaults(options, _ref15) { var _ref15$documentLoader = _ref15.documentLoader, documentLoader = _ref15$documentLoader === undefined ? jsonld.documentLoader : _ref15$documentLoader, defaults = _objectWithoutProperties(_ref15, ['documentLoader']); if (typeof options === 'function') { options = {}; } options = options || {}; return Object.assign({}, { documentLoader: documentLoader }, defaults, options); } // end of jsonld API `wrapper` factory return jsonld; }; // external APIs: // used to generate a new jsonld API instance var factory = function factory() { return wrapper(function () { return factory(); }); }; if (!_nodejs && "function" === 'function' && __webpack_require__(139)) { // export AMD API !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { // now that module is defined, wrap main jsonld API instance wrapper(factory); return factory; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { // wrap the main jsonld API instance wrapper(factory); if ("function" === 'function' && typeof module !== 'undefined' && module.exports) { // export CommonJS/nodejs API module.exports = factory; } if (_browser) { // export simple browser API if (typeof jsonld === 'undefined') { jsonld = jsonldjs = factory; } else { jsonldjs = factory; } } } return factory; })(); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(67))) /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var util = __webpack_require__(14); module.exports = function () { function AsyncAlgorithm() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$maxCallStackDept = _ref.maxCallStackDepth, maxCallStackDepth = _ref$maxCallStackDept === undefined ? 500 : _ref$maxCallStackDept, _ref$maxTotalCallStac = _ref.maxTotalCallStackDepth, maxTotalCallStackDepth = _ref$maxTotalCallStac === undefined ? 0xFFFFFFFF : _ref$maxTotalCallStac, _ref$timeSlice = _ref.timeSlice, timeSlice = _ref$timeSlice === undefined ? 10 : _ref$timeSlice; _classCallCheck(this, AsyncAlgorithm); this.schedule = {}; this.schedule.MAX_DEPTH = maxCallStackDepth; this.schedule.MAX_TOTAL_DEPTH = maxTotalCallStackDepth; this.schedule.depth = 0; this.schedule.totalDepth = 0; this.schedule.timeSlice = timeSlice; } // do some work in a time slice, but in serial _createClass(AsyncAlgorithm, [{ key: 'doWork', value: function doWork(fn, callback) { var schedule = this.schedule; if (schedule.totalDepth >= schedule.MAX_TOTAL_DEPTH) { return callback(new Error('Maximum total call stack depth exceeded; canonicalization aborting.')); } (function work() { if (schedule.depth === schedule.MAX_DEPTH) { // stack too deep, run on next tick schedule.depth = 0; schedule.running = false; return util.nextTick(work); } // if not yet running, force run var now = Date.now(); if (!schedule.running) { schedule.start = Date.now(); schedule.deadline = schedule.start + schedule.timeSlice; } // TODO: should also include an estimate of expectedWorkTime if (now < schedule.deadline) { schedule.running = true; schedule.depth++; schedule.totalDepth++; return fn(function (err, result) { schedule.depth--; schedule.totalDepth--; callback(err, result); }); } // not enough time left in this slice, run after letting browser // do some other things schedule.depth = 0; schedule.running = false; util.setImmediate(work); })(); } // asynchronously loop }, { key: 'forEach', value: function forEach(iterable, fn, callback) { var self = this; var _iterator2 = void 0; var idx = 0; var length = void 0; if (Array.isArray(iterable)) { length = iterable.length; _iterator2 = function iterator() { if (idx === length) { return false; } _iterator2.value = iterable[idx++]; _iterator2.key = idx; return true; }; } else { var keys = Object.keys(iterable); length = keys.length; _iterator2 = function _iterator() { if (idx === length) { return false; } _iterator2.key = keys[idx++]; _iterator2.value = iterable[_iterator2.key]; return true; }; } (function iterate(err) { if (err) { return callback(err); } if (_iterator2()) { return self.doWork(function () { return fn(_iterator2.value, _iterator2.key, iterate); }); } callback(); })(); } // asynchronous waterfall }, { key: 'waterfall', value: function waterfall(fns, callback) { var self = this; self.forEach(fns, function (fn, idx, callback) { return self.doWork(fn, callback); }, callback); } // asynchronous while }, { key: 'whilst', value: function whilst(condition, fn, callback) { var self = this; (function loop(err) { if (err) { return callback(err); } if (!condition()) { return callback(); } self.doWork(fn, loop); })(); } }]); return AsyncAlgorithm; }(); /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { /** * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ var forge = __webpack_require__(23); __webpack_require__(47); __webpack_require__(70); var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; forge.md.sha1 = forge.md.algorithms.sha1 = sha1; /** * Creates a SHA-1 message digest object. * * @return a message digest object. */ sha1.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // SHA-1 state contains five 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(80); // message digest object var md = { algorithm: 'sha1', blockLength: 64, digestLength: 20, // 56-bit length of message so far (does not including padding) messageLength: 0, // true message length fullMessageLength: null, // size of message length in bytes messageLengthSize: 8 }; /** * Starts the digest. * * @return this digest object. */ md.start = function() { // up to 56-bit message length for convenience md.messageLength = 0; // full message length (set md.messageLength64 for backwards-compatibility) md.fullMessageLength = md.messageLength64 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _state = { h0: 0x67452301, h1: 0xEFCDAB89, h2: 0x98BADCFE, h3: 0x10325476, h4: 0xC3D2E1F0 }; return md; }; // start digest automatically for first time md.start(); /** * Updates the digest with the given message input. The given input can * treated as raw input (no encoding will be applied) or an encoding of * 'utf8' maybe given to encode the input using UTF-8. * * @param msg the message input to update with. * @param encoding the encoding to use (default: 'raw', other: 'utf8'). * * @return this digest object. */ md.update = function(msg, encoding) { if(encoding === 'utf8') { msg = forge.util.encodeUtf8(msg); } // update message length var len = msg.length; md.messageLength += len; len = [(len / 0x100000000) >>> 0, len >>> 0]; for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { md.fullMessageLength[i] += len[1]; len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; len[0] = ((len[1] / 0x100000000) >>> 0); } // add bytes to input buffer _input.putBytes(msg); // process bytes _update(_state, _w, _input); // compact input buffer every 2K or if empty if(_input.read > 2048 || _input.length() === 0) { _input.compact(); } return md; }; /** * Produces the digest. * * @return a byte buffer containing the digest value. */ md.digest = function() { /* Note: Here we copy the remaining bytes in the input buffer and add the appropriate SHA-1 padding. Then we do the final update on a copy of the state so that if the user wants to get intermediate digests they can do so. */ /* Determine the number of bytes that must be added to the message to ensure its length is congruent to 448 mod 512. In other words, the data to be digested must be a multiple of 512 bits (or 128 bytes). This data includes the message, some padding, and the length of the message. Since the length of the message will be encoded as 8 bytes (64 bits), that means that the last segment of the data must have 56 bytes (448 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 448 mod 512 because 512 - 128 = 448. In order to fill up the message length it must be filled with padding that begins with 1 bit followed by all 0 bits. Padding must *always* be present, so if the message length is already congruent to 448 mod 512, then 512 padding bits must be added. */ var finalBlock = forge.util.createBuffer(); finalBlock.putBytes(_input.bytes()); // compute remaining size to be digested (include message length size) var remaining = ( md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize); // add padding for overflow blockSize - overflow // _padding starts with 1 byte with first bit is set (byte value 128), then // there may be up to (blockSize - 1) other pad bytes var overflow = remaining & (md.blockLength - 1); finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); // serialize message length in bits in big-endian order; since length // is stored in bytes we multiply by 8 and add carry from next int var next, carry; var bits = md.fullMessageLength[0] * 8; for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { next = md.fullMessageLength[i + 1] * 8; carry = (next / 0x100000000) >>> 0; bits += carry; finalBlock.putInt32(bits >>> 0); bits = next >>> 0; } finalBlock.putInt32(bits); var s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3, h4: _state.h4 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); return rval; }; return md; }; // sha-1 padding bytes not initialized yet var _padding = null; var _initialized = false; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // now initialized _initialized = true; } /** * Updates a SHA-1 state with the given byte buffer. * * @param s the SHA-1 state to update. * @param w the array to use to store words. * @param bytes the byte buffer to update with. */ function _update(s, w, bytes) { // consume 512 bit (64 byte) chunks var t, a, b, c, d, e, f, i; var len = bytes.length(); while(len >= 64) { // the w array will be populated with sixteen 32-bit big-endian words // and then extended into 80 32-bit words according to SHA-1 algorithm // and for 32-79 using Max Locktyukhin's optimization // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; e = s.h4; // round 1 for(i = 0; i < 16; ++i) { t = bytes.getInt32(); w[i] = t; f = d ^ (b & (c ^ d)); t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } for(; i < 20; ++i) { t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); t = (t << 1) | (t >>> 31); w[i] = t; f = d ^ (b & (c ^ d)); t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 2 for(; i < 32; ++i) { t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); t = (t << 1) | (t >>> 31); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } for(; i < 40; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 3 for(; i < 60; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = (b & c) | (d & (b ^ c)); t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // round 4 for(; i < 80; ++i) { t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); t = (t << 2) | (t >>> 30); w[i] = t; f = b ^ c ^ d; t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; e = d; d = c; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug c = ((b << 30) | (b >>> 2)) >>> 0; b = a; a = t; } // update hash state s.h0 = (s.h0 + a) | 0; s.h1 = (s.h1 + b) | 0; s.h2 = (s.h2 + c) | 0; s.h3 = (s.h3 + d) | 0; s.h4 = (s.h4 + e) | 0; len -= 64; } } /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { /** * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. * * See FIPS 180-2 for details. * * @author Dave Longley * * Copyright (c) 2010-2015 Digital Bazaar, Inc. */ var forge = __webpack_require__(23); __webpack_require__(47); __webpack_require__(70); var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; forge.md.sha256 = forge.md.algorithms.sha256 = sha256; /** * Creates a SHA-256 message digest object. * * @return a message digest object. */ sha256.create = function() { // do initialization as necessary if(!_initialized) { _init(); } // SHA-256 state contains eight 32-bit integers var _state = null; // input buffer var _input = forge.util.createBuffer(); // used for word storage var _w = new Array(64); // message digest object var md = { algorithm: 'sha256', blockLength: 64, digestLength: 32, // 56-bit length of message so far (does not including padding) messageLength: 0, // true message length fullMessageLength: null, // size of message length in bytes messageLengthSize: 8 }; /** * Starts the digest. * * @return this digest object. */ md.start = function() { // up to 56-bit message length for convenience md.messageLength = 0; // full message length (set md.messageLength64 for backwards-compatibility) md.fullMessageLength = md.messageLength64 = []; var int32s = md.messageLengthSize / 4; for(var i = 0; i < int32s; ++i) { md.fullMessageLength.push(0); } _input = forge.util.createBuffer(); _state = { h0: 0x6A09E667, h1: 0xBB67AE85, h2: 0x3C6EF372, h3: 0xA54FF53A, h4: 0x510E527F, h5: 0x9B05688C, h6: 0x1F83D9AB, h7: 0x5BE0CD19 }; return md; }; // start digest automatically for first time md.start(); /** * Updates the digest with the given message input. The given input can * treated as raw input (no encoding will be applied) or an encoding of * 'utf8' maybe given to encode the input using UTF-8. * * @param msg the message input to update with. * @param encoding the encoding to use (default: 'raw', other: 'utf8'). * * @return this digest object. */ md.update = function(msg, encoding) { if(encoding === 'utf8') { msg = forge.util.encodeUtf8(msg); } // update message length var len = msg.length; md.messageLength += len; len = [(len / 0x100000000) >>> 0, len >>> 0]; for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { md.fullMessageLength[i] += len[1]; len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; len[0] = ((len[1] / 0x100000000) >>> 0); } // add bytes to input buffer _input.putBytes(msg); // process bytes _update(_state, _w, _input); // compact input buffer every 2K or if empty if(_input.read > 2048 || _input.length() === 0) { _input.compact(); } return md; }; /** * Produces the digest. * * @return a byte buffer containing the digest value. */ md.digest = function() { /* Note: Here we copy the remaining bytes in the input buffer and add the appropriate SHA-256 padding. Then we do the final update on a copy of the state so that if the user wants to get intermediate digests they can do so. */ /* Determine the number of bytes that must be added to the message to ensure its length is congruent to 448 mod 512. In other words, the data to be digested must be a multiple of 512 bits (or 128 bytes). This data includes the message, some padding, and the length of the message. Since the length of the message will be encoded as 8 bytes (64 bits), that means that the last segment of the data must have 56 bytes (448 bits) of message and padding. Therefore, the length of the message plus the padding must be congruent to 448 mod 512 because 512 - 128 = 448. In order to fill up the message length it must be filled with padding that begins with 1 bit followed by all 0 bits. Padding must *always* be present, so if the message length is already congruent to 448 mod 512, then 512 padding bits must be added. */ var finalBlock = forge.util.createBuffer(); finalBlock.putBytes(_input.bytes()); // compute remaining size to be digested (include message length size) var remaining = ( md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize); // add padding for overflow blockSize - overflow // _padding starts with 1 byte with first bit is set (byte value 128), then // there may be up to (blockSize - 1) other pad bytes var overflow = remaining & (md.blockLength - 1); finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); // serialize message length in bits in big-endian order; since length // is stored in bytes we multiply by 8 and add carry from next int var next, carry; var bits = md.fullMessageLength[0] * 8; for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { next = md.fullMessageLength[i + 1] * 8; carry = (next / 0x100000000) >>> 0; bits += carry; finalBlock.putInt32(bits >>> 0); bits = next >>> 0; } finalBlock.putInt32(bits); var s2 = { h0: _state.h0, h1: _state.h1, h2: _state.h2, h3: _state.h3, h4: _state.h4, h5: _state.h5, h6: _state.h6, h7: _state.h7 }; _update(s2, _w, finalBlock); var rval = forge.util.createBuffer(); rval.putInt32(s2.h0); rval.putInt32(s2.h1); rval.putInt32(s2.h2); rval.putInt32(s2.h3); rval.putInt32(s2.h4); rval.putInt32(s2.h5); rval.putInt32(s2.h6); rval.putInt32(s2.h7); return rval; }; return md; }; // sha-256 padding bytes not initialized yet var _padding = null; var _initialized = false; // table of constants var _k = null; /** * Initializes the constant tables. */ function _init() { // create padding _padding = String.fromCharCode(128); _padding += forge.util.fillString(String.fromCharCode(0x00), 64); // create K table for SHA-256 _k = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; // now initialized _initialized = true; } /** * Updates a SHA-256 state with the given byte buffer. * * @param s the SHA-256 state to update. * @param w the array to use to store words. * @param bytes the byte buffer to update with. */ function _update(s, w, bytes) { // consume 512 bit (64 byte) chunks var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; var len = bytes.length(); while(len >= 64) { // the w array will be populated with sixteen 32-bit big-endian words // and then extended into 64 32-bit words according to SHA-256 for(i = 0; i < 16; ++i) { w[i] = bytes.getInt32(); } for(; i < 64; ++i) { // XOR word 2 words ago rot right 17, rot right 19, shft right 10 t1 = w[i - 2]; t1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); // XOR word 15 words ago rot right 7, rot right 18, shft right 3 t2 = w[i - 15]; t2 = ((t2 >>> 7) | (t2 << 25)) ^ ((t2 >>> 18) | (t2 << 14)) ^ (t2 >>> 3); // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; } // initialize hash value for this chunk a = s.h0; b = s.h1; c = s.h2; d = s.h3; e = s.h4; f = s.h5; g = s.h6; h = s.h7; // round function for(i = 0; i < 64; ++i) { // Sum1(e) s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); // Ch(e, f, g) (optimized the same way as SHA-1) ch = g ^ (e & (f ^ g)); // Sum0(a) s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); // Maj(a, b, c) (optimized the same way as SHA-1) maj = (a & b) | (c & (a ^ b)); // main algorithm t1 = h + s1 + ch + _k[i] + w[i]; t2 = s0 + maj; h = g; g = f; f = e; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug // can't truncate with `| 0` e = (d + t1) >>> 0; d = c; c = b; b = a; // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug // can't truncate with `| 0` a = (t1 + t2) >>> 0; } // update hash state s.h0 = (s.h0 + a) | 0; s.h1 = (s.h1 + b) | 0; s.h2 = (s.h2 + c) | 0; s.h3 = (s.h3 + d) | 0; s.h4 = (s.h4 + e) | 0; s.h5 = (s.h5 + f) | 0; s.h6 = (s.h6 + g) | 0; s.h7 = (s.h7 + h) | 0; len -= 64; } } /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(122); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(123); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(67))) /***/ }), /* 122 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } /***/ }), /* 123 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016-2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var URDNA2015 = __webpack_require__(68); var util = __webpack_require__(14); module.exports = function (_URDNA) { _inherits(URDNA2012, _URDNA); function URDNA2012(options) { _classCallCheck(this, URDNA2012); var _this = _possibleConstructorReturn(this, (URDNA2012.__proto__ || Object.getPrototypeOf(URDNA2012)).call(this, options)); _this.name = 'URGNA2012'; _this.hashAlgorithm = 'sha1'; return _this; } // helper for modifying component during Hash First Degree Quads _createClass(URDNA2012, [{ key: 'modifyFirstDegreeComponent', value: function modifyFirstDegreeComponent(id, component, key) { if (component.termType !== 'BlankNode') { return component; } component = util.clone(component); if (key === 'name') { component.value = '_:g'; } else { component.value = component.value === id ? '_:a' : '_:z'; } return component; } // helper for getting a related predicate }, { key: 'getRelatedPredicate', value: function getRelatedPredicate(quad) { return quad.predicate.value; } // helper for creating hash to related blank nodes map }, { key: 'createHashToRelated', value: function createHashToRelated(id, issuer, callback) { var self = this; // 1) Create a hash to related blank nodes map for storing hashes that // identify related blank nodes. var hashToRelated = {}; // 2) Get a reference, quads, to the list of quads in the blank node to // quads map for the key identifier. var quads = self.blankNodeInfo[id].quads; // 3) For each quad in quads: self.forEach(quads, function (quad, idx, callback) { // 3.1) If the quad's subject is a blank node that does not match // identifier, set hash to the result of the Hash Related Blank Node // algorithm, passing the blank node identifier for subject as related, // quad, path identifier issuer as issuer, and p as position. var position = void 0; var related = void 0; if (quad.subject.termType === 'BlankNode' && quad.subject.value !== id) { related = quad.subject.value; position = 'p'; } else if (quad.object.termType === 'BlankNode' && quad.object.value !== id) { // 3.2) Otherwise, if quad's object is a blank node that does not match // identifier, to the result of the Hash Related Blank Node algorithm, // passing the blank node identifier for object as related, quad, path // identifier issuer as issuer, and r as position. related = quad.object.value; position = 'r'; } else { // 3.3) Otherwise, continue to the next quad. return callback(); } // 3.4) Add a mapping of hash to the blank node identifier for the // component that matched (subject or object) to hash to related blank // nodes map, adding an entry as necessary. self.hashRelatedBlankNode(related, quad, issuer, position, function (err, hash) { if (err) { return callback(err); } if (hash in hashToRelated) { hashToRelated[hash].push(related); } else { hashToRelated[hash] = [related]; } callback(); }); }, function (err) { return callback(err, hashToRelated); }); } }]); return URDNA2012; }(URDNA2015); /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2016 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var URDNA2015Sync = __webpack_require__(72); var util = __webpack_require__(14); module.exports = function (_URDNA2015Sync) { _inherits(URDNA2012Sync, _URDNA2015Sync); function URDNA2012Sync() { _classCallCheck(this, URDNA2012Sync); var _this = _possibleConstructorReturn(this, (URDNA2012Sync.__proto__ || Object.getPrototypeOf(URDNA2012Sync)).call(this)); _this.name = 'URGNA2012'; _this.hashAlgorithm = 'sha1'; return _this; } // helper for modifying component during Hash First Degree Quads _createClass(URDNA2012Sync, [{ key: 'modifyFirstDegreeComponent', value: function modifyFirstDegreeComponent(id, component, key) { if (component.termType !== 'BlankNode') { return component; } component = util.clone(component); if (key === 'name') { component.value = '_:g'; } else { component.value = component.value === id ? '_:a' : '_:z'; } return component; } // helper for getting a related predicate }, { key: 'getRelatedPredicate', value: function getRelatedPredicate(quad) { return quad.predicate.value; } // helper for creating hash to related blank nodes map }, { key: 'createHashToRelated', value: function createHashToRelated(id, issuer) { var self = this; // 1) Create a hash to related blank nodes map for storing hashes that // identify related blank nodes. var hashToRelated = {}; // 2) Get a reference, quads, to the list of quads in the blank node to // quads map for the key identifier. var quads = self.blankNodeInfo[id].quads; // 3) For each quad in quads: for (var i = 0; i < quads.length; ++i) { // 3.1) If the quad's subject is a blank node that does not match // identifier, set hash to the result of the Hash Related Blank Node // algorithm, passing the blank node identifier for subject as related, // quad, path identifier issuer as issuer, and p as position. var quad = quads[i]; var position = void 0; var related = void 0; if (quad.subject.termType === 'BlankNode' && quad.subject.value !== id) { related = quad.subject.value; position = 'p'; } else if (quad.object.termType === 'BlankNode' && quad.object.value !== id) { // 3.2) Otherwise, if quad's object is a blank node that does not match // identifier, to the result of the Hash Related Blank Node algorithm, // passing the blank node identifier for object as related, quad, path // identifier issuer as issuer, and r as position. related = quad.object.value; position = 'r'; } else { // 3.3) Otherwise, continue to the next quad. continue; } // 3.4) Add a mapping of hash to the blank node identifier for the // component that matched (subject or object) to hash to related blank // nodes map, adding an entry as necessary. var hash = self.hashRelatedBlankNode(related, quad, issuer, position); if (hash in hashToRelated) { hashToRelated[hash].push(related); } else { hashToRelated[hash] = [related]; } } return hashToRelated; } }]); return URDNA2012Sync; }(URDNA2015Sync); /***/ }), /* 126 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ // TODO: move `NQuads` to its own package module.exports = __webpack_require__(45).NQuads; /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ /* global Node, XMLSerializer */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __webpack_require__(24), RDF_LANGSTRING = _require.RDF_LANGSTRING, RDF_PLAIN_LITERAL = _require.RDF_PLAIN_LITERAL, RDF_OBJECT = _require.RDF_OBJECT, RDF_XML_LITERAL = _require.RDF_XML_LITERAL, XSD_STRING = _require.XSD_STRING; var _Node = void 0; if (typeof Node !== 'undefined') { _Node = Node; } else { _Node = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12 }; } module.exports = function () { function Rdfa() { _classCallCheck(this, Rdfa); } _createClass(Rdfa, [{ key: 'parse', /** * Parses the RDF dataset found via the data object from the RDFa API. * * @param data the RDFa API data object. * * @return the RDF dataset. */ value: function parse(data) { var dataset = {}; dataset['@default'] = []; var subjects = data.getSubjects(); for (var si = 0; si < subjects.length; ++si) { var subject = subjects[si]; if (subject === null) { continue; } // get all related triples var triples = data.getSubjectTriples(subject); if (triples === null) { continue; } var predicates = triples.predicates; for (var predicate in predicates) { // iterate over objects var objects = predicates[predicate].objects; for (var oi = 0; oi < objects.length; ++oi) { var object = objects[oi]; // create RDF triple var triple = {}; // add subject if (subject.indexOf('_:') === 0) { triple.subject = { type: 'blank node', value: subject }; } else { triple.subject = { type: 'IRI', value: subject }; } // add predicate if (predicate.indexOf('_:') === 0) { triple.predicate = { type: 'blank node', value: predicate }; } else { triple.predicate = { type: 'IRI', value: predicate }; } // serialize XML literal var value = object.value; if (object.type === RDF_XML_LITERAL) { // initialize XMLSerializer var _XMLSerializer = getXMLSerializerClass(); var serializer = new _XMLSerializer(); value = ''; for (var x = 0; x < object.value.length; x++) { if (object.value[x].nodeType === _Node.ELEMENT_NODE) { value += serializer.serializeToString(object.value[x]); } else if (object.value[x].nodeType === _Node.TEXT_NODE) { value += object.value[x].nodeValue; } } } // add object triple.object = {}; // object is an IRI if (object.type === RDF_OBJECT) { if (object.value.indexOf('_:') === 0) { triple.object.type = 'blank node'; } else { triple.object.type = 'IRI'; } } else { // object is a literal triple.object.type = 'literal'; if (object.type === RDF_PLAIN_LITERAL) { if (object.language) { triple.object.datatype = RDF_LANGSTRING; triple.object.language = object.language; } else { triple.object.datatype = XSD_STRING; } } else { triple.object.datatype = object.type; } } triple.object.value = value; // add triple to dataset in default graph dataset['@default'].push(triple); } } } return dataset; } }]); return Rdfa; }(); function getXMLSerializerClass() { if (typeof XMLSerializer === 'undefined') { return __webpack_require__(49).XMLSerializer; } return XMLSerializer; } /***/ }), /* 129 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var JsonLdError = __webpack_require__(6); var _require = __webpack_require__(4), _isArray = _require.isArray, _isObject = _require.isObject, _isString = _require.isString; var _require2 = __webpack_require__(5), _isList = _require2.isList, _isValue = _require2.isValue; var _require3 = __webpack_require__(15), _expandIri = _require3.expandIri, _getContextValue = _require3.getContextValue, _isKeyword = _require3.isKeyword, _processContext = _require3.process; var _require4 = __webpack_require__(25), _isAbsoluteIri = _require4.isAbsolute; var _require5 = __webpack_require__(2), _addValue = _require5.addValue, _validateTypeValue = _require5.validateTypeValue; var api = {}; module.exports = api; /** * Recursively expands an element using the given context. Any context in * the element will be removed. All context URLs must have been retrieved * before calling this method. * * @param activeCtx the context to use. * @param activeProperty the property for the element, null for none. * @param element the element to expand. * @param options the expansion options. * @param insideList true if the element is a list, false if not. * @param expansionMap(info) a function that can be used to custom map * unmappable values (or to throw an error when they are detected); * if this function returns `undefined` then the default behavior * will be used. * * @return a Promise that resolves to the expanded value. */ api.expand = function (_ref) { var activeCtx = _ref.activeCtx, _ref$activeProperty = _ref.activeProperty, activeProperty = _ref$activeProperty === undefined ? null : _ref$activeProperty, element = _ref.element, _ref$options = _ref.options, options = _ref$options === undefined ? {} : _ref$options, _ref$insideList = _ref.insideList, insideList = _ref$insideList === undefined ? false : _ref$insideList, _ref$expansionMap = _ref.expansionMap, expansionMap = _ref$expansionMap === undefined ? function () { return undefined; } : _ref$expansionMap; // nothing to expand if (element === null || element === undefined) { return null; } if (!_isArray(element) && !_isObject(element)) { // drop free-floating scalars that are not in lists unless custom mapped if (!insideList && (activeProperty === null || _expandIri(activeCtx, activeProperty, { vocab: true }) === '@graph')) { // TODO: use `await` to support async var mapped = expansionMap({ unmappedValue: element, activeCtx: activeCtx, activeProperty: activeProperty, options: options, insideList: insideList }); if (mapped === undefined) { return null; } return mapped; } // expand element according to value expansion rules return _expandValue({ activeCtx: activeCtx, activeProperty: activeProperty, value: element }); } // recursively expand array if (_isArray(element)) { var _rval = []; var container = _getContextValue(activeCtx, activeProperty, '@container') || []; insideList = insideList || container.includes('@list'); for (var i = 0; i < element.length; ++i) { // expand element var e = api.expand({ activeCtx: activeCtx, activeProperty: activeProperty, element: element[i], options: options, expansionMap: expansionMap }); if (insideList && (_isArray(e) || _isList(e))) { // lists of lists are illegal throw new JsonLdError('Invalid JSON-LD syntax; lists of lists are not permitted.', 'jsonld.SyntaxError', { code: 'list of lists' }); } if (e === null) { // TODO: add `await` for async support e = expansionMap({ unmappedValue: element[i], activeCtx: activeCtx, activeProperty: activeProperty, parent: element, index: i, options: options, expandedParent: _rval, insideList: insideList }); if (e === undefined) { continue; } } if (_isArray(e)) { _rval = _rval.concat(e); } else { _rval.push(e); } } return _rval; } // recursively expand object: // if element has a context, process it if ('@context' in element) { activeCtx = _processContext({ activeCtx: activeCtx, localCtx: element['@context'], options: options }); } // expand the active property var expandedActiveProperty = _expandIri(activeCtx, activeProperty, { vocab: true }); var rval = {}; var keys = Object.keys(element).sort(); for (var ki = 0; ki < keys.length; ++ki) { var key = keys[ki]; var value = element[key]; var expandedValue = void 0; // skip @context if (key === '@context') { continue; } // expand property var expandedProperty = _expandIri(activeCtx, key, { vocab: true }); // drop non-absolute IRI keys that aren't keywords unless custom mapped if (expandedProperty === null || !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) { // TODO: use `await` to support async expandedProperty = expansionMap({ unmappedProperty: key, activeCtx: activeCtx, activeProperty: activeProperty, parent: element, options: options, insideList: insideList, value: value, expandedParent: rval }); if (expandedProperty === undefined) { continue; } } if (_isKeyword(expandedProperty)) { if (expandedActiveProperty === '@reverse') { throw new JsonLdError('Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' + 'property.', 'jsonld.SyntaxError', { code: 'invalid reverse property map', value: value }); } if (expandedProperty in rval) { throw new JsonLdError('Invalid JSON-LD syntax; colliding keywords detected.', 'jsonld.SyntaxError', { code: 'colliding keywords', keyword: expandedProperty }); } } // syntax error if @id is not a string if (expandedProperty === '@id' && !_isString(value)) { if (!options.isFrame) { throw new JsonLdError('Invalid JSON-LD syntax; "@id" value must a string.', 'jsonld.SyntaxError', { code: 'invalid @id value', value: value }); } if (!_isObject(value)) { throw new JsonLdError('Invalid JSON-LD syntax; "@id" value must be a string or an ' + 'object.', 'jsonld.SyntaxError', { code: 'invalid @id value', value: value }); } } if (expandedProperty === '@type') { _validateTypeValue(value); } // @graph must be an array or an object if (expandedProperty === '@graph' && !(_isObject(value) || _isArray(value))) { throw new JsonLdError('Invalid JSON-LD syntax; "@graph" value must not be an ' + 'object or an array.', 'jsonld.SyntaxError', { code: 'invalid @graph value', value: value }); } // @value must not be an object or an array if (expandedProperty === '@value' && (_isObject(value) || _isArray(value))) { throw new JsonLdError('Invalid JSON-LD syntax; "@value" value must not be an ' + 'object or an array.', 'jsonld.SyntaxError', { code: 'invalid value object value', value: value }); } // @language must be a string if (expandedProperty === '@language') { if (value === null) { // drop null @language values, they expand as if they didn't exist continue; } if (!_isString(value)) { throw new JsonLdError('Invalid JSON-LD syntax; "@language" value must be a string.', 'jsonld.SyntaxError', { code: 'invalid language-tagged string', value: value }); } // ensure language value is lowercase value = value.toLowerCase(); } // @index must be a string if (expandedProperty === '@index') { if (!_isString(value)) { throw new JsonLdError('Invalid JSON-LD syntax; "@index" value must be a string.', 'jsonld.SyntaxError', { code: 'invalid @index value', value: value }); } } // @reverse must be an object if (expandedProperty === '@reverse') { if (!_isObject(value)) { throw new JsonLdError('Invalid JSON-LD syntax; "@reverse" value must be an object.', 'jsonld.SyntaxError', { code: 'invalid @reverse value', value: value }); } expandedValue = api.expand({ activeCtx: activeCtx, activeProperty: '@reverse', element: value, options: options, expansionMap: expansionMap }); // properties double-reversed if ('@reverse' in expandedValue) { for (var property in expandedValue['@reverse']) { _addValue(rval, property, expandedValue['@reverse'][property], { propertyIsArray: true }); } } // FIXME: can this be merged with code below to simplify? // merge in all reversed properties var reverseMap = rval['@reverse'] || null; for (var _property in expandedValue) { if (_property === '@reverse') { continue; } if (reverseMap === null) { reverseMap = rval['@reverse'] = {}; } _addValue(reverseMap, _property, [], { propertyIsArray: true }); var items = expandedValue[_property]; for (var ii = 0; ii < items.length; ++ii) { var item = items[ii]; if (_isValue(item) || _isList(item)) { throw new JsonLdError('Invalid JSON-LD syntax; "@reverse" value must not be a ' + '@value or an @list.', 'jsonld.SyntaxError', { code: 'invalid reverse property value', value: expandedValue }); } _addValue(reverseMap, _property, item, { propertyIsArray: true }); } } continue; } var _container = _getContextValue(activeCtx, key, '@container') || []; if (_container.includes('@language') && _isObject(value)) { // handle language map container (skip if value is not an object) expandedValue = _expandLanguageMap(value); } else if (_container.includes('@index') && _isObject(value)) { // handle index container (skip if value is not an object) expandedValue = _expandIndexMap({ activeCtx: activeCtx, options: options, activeProperty: key, value: value, expansionMap: expansionMap }); } else { // recurse into @list or @set var isList = expandedProperty === '@list'; if (isList || expandedProperty === '@set') { var nextActiveProperty = activeProperty; if (isList && expandedActiveProperty === '@graph') { nextActiveProperty = null; } expandedValue = api.expand({ activeCtx: activeCtx, activeProperty: nextActiveProperty, element: value, options: options, insideList: isList, expansionMap: expansionMap }); if (isList && _isList(expandedValue)) { throw new JsonLdError('Invalid JSON-LD syntax; lists of lists are not permitted.', 'jsonld.SyntaxError', { code: 'list of lists' }); } } else { // recursively expand value with key as new active property expandedValue = api.expand({ activeCtx: activeCtx, activeProperty: key, element: value, options: options, insideList: false, expansionMap: expansionMap }); } } // drop null values if property is not @value if (expandedValue === null && expandedProperty !== '@value') { // TODO: use `await` to support async expandedValue = expansionMap({ unmappedValue: value, expandedProperty: expandedProperty, activeCtx: activeCtx, activeProperty: activeProperty, parent: element, options: options, insideList: insideList, key: key, expandedParent: rval }); if (expandedValue === undefined) { continue; } } // convert expanded value to @list if container specifies it if (expandedProperty !== '@list' && !_isList(expandedValue) && _container.includes('@list')) { // ensure expanded value is an array expandedValue = _isArray(expandedValue) ? expandedValue : [expandedValue]; expandedValue = { '@list': expandedValue }; } // convert expanded value to @graph if container specifies it if (_container.includes('@graph')) { // ensure expanded value is an array expandedValue = [].concat(expandedValue); expandedValue = { '@graph': expandedValue }; } // FIXME: can this be merged with code above to simplify? // merge in reverse properties if (activeCtx.mappings[key] && activeCtx.mappings[key].reverse) { var _reverseMap = rval['@reverse'] = rval['@reverse'] || {}; if (!_isArray(expandedValue)) { expandedValue = [expandedValue]; } for (var _ii = 0; _ii < expandedValue.length; ++_ii) { var _item = expandedValue[_ii]; if (_isValue(_item) || _isList(_item)) { throw new JsonLdError('Invalid JSON-LD syntax; "@reverse" value must not be a ' + '@value or an @list.', 'jsonld.SyntaxError', { code: 'invalid reverse property value', value: expandedValue }); } _addValue(_reverseMap, expandedProperty, _item, { propertyIsArray: true }); } continue; } // add value for property // use an array except for certain keywords var useArray = !['@index', '@id', '@type', '@value', '@language'].includes(expandedProperty); _addValue(rval, expandedProperty, expandedValue, { propertyIsArray: useArray }); } // get property count on expanded output keys = Object.keys(rval); var count = keys.length; if ('@value' in rval) { // @value must only have @language or @type if ('@type' in rval && '@language' in rval) { throw new JsonLdError('Invalid JSON-LD syntax; an element containing "@value" may not ' + 'contain both "@type" and "@language".', 'jsonld.SyntaxError', { code: 'invalid value object', element: rval }); } var validCount = count - 1; if ('@type' in rval) { validCount -= 1; } if ('@index' in rval) { validCount -= 1; } if ('@language' in rval) { validCount -= 1; } if (validCount !== 0) { throw new JsonLdError('Invalid JSON-LD syntax; an element containing "@value" may only ' + 'have an "@index" property and at most one other property ' + 'which can be "@type" or "@language".', 'jsonld.SyntaxError', { code: 'invalid value object', element: rval }); } // drop null @values unless custom mapped if (rval['@value'] === null) { // TODO: use `await` to support async var _mapped = expansionMap({ unmappedValue: rval, activeCtx: activeCtx, activeProperty: activeProperty, element: element, options: options, insideList: insideList }); if (_mapped !== undefined) { rval = _mapped; } else { rval = null; } } else if ('@language' in rval && !_isString(rval['@value'])) { // if @language is present, @value must be a string throw new JsonLdError('Invalid JSON-LD syntax; only strings may be language-tagged.', 'jsonld.SyntaxError', { code: 'invalid language-tagged value', element: rval }); } else if ('@type' in rval && (!_isAbsoluteIri(rval['@type']) || rval['@type'].indexOf('_:') === 0)) { throw new JsonLdError('Invalid JSON-LD syntax; an element containing "@value" and "@type" ' + 'must have an absolute IRI for the value of "@type".', 'jsonld.SyntaxError', { code: 'invalid typed value', element: rval }); } } else if ('@type' in rval && !_isArray(rval['@type'])) { // convert @type to an array rval['@type'] = [rval['@type']]; } else if ('@set' in rval || '@list' in rval) { // handle @set and @list if (count > 1 && !(count === 2 && '@index' in rval)) { throw new JsonLdError('Invalid JSON-LD syntax; if an element has the property "@set" ' + 'or "@list", then it can have at most one other property that is ' + '"@index".', 'jsonld.SyntaxError', { code: 'invalid set or list object', element: rval }); } // optimize away @set if ('@set' in rval) { rval = rval['@set']; keys = Object.keys(rval); count = keys.length; } } else if (count === 1 && '@language' in rval) { // drop objects with only @language unless custom mapped // TODO: use `await` to support async var _mapped2 = expansionMap(rval, { unmappedValue: rval, activeCtx: activeCtx, activeProperty: activeProperty, element: element, options: options, insideList: insideList }); if (_mapped2 !== undefined) { rval = _mapped2; } else { rval = null; } } // drop certain top-level objects that do not occur in lists, unless custom // mapped if (_isObject(rval) && !options.keepFreeFloatingNodes && !insideList && (activeProperty === null || expandedActiveProperty === '@graph')) { // drop empty object, top-level @value/@list, or object with only @id if (count === 0 || '@value' in rval || '@list' in rval || count === 1 && '@id' in rval) { // TODO: use `await` to support async var _mapped3 = expansionMap({ unmappedValue: rval, activeCtx: activeCtx, activeProperty: activeProperty, element: element, options: options, insideList: insideList }); if (_mapped3 !== undefined) { rval = _mapped3; } else { rval = null; } } } return rval; }; /** * Expands the given value by using the coercion and keyword rules in the * given context. * * @param activeCtx the active context to use. * @param activeProperty the active property the value is associated with. * @param value the value to expand. * * @return the expanded value. */ function _expandValue(_ref2) { var activeCtx = _ref2.activeCtx, activeProperty = _ref2.activeProperty, value = _ref2.value; // nothing to expand if (value === null || value === undefined) { return null; } // special-case expand @id and @type (skips '@id' expansion) var expandedProperty = _expandIri(activeCtx, activeProperty, { vocab: true }); if (expandedProperty === '@id') { return _expandIri(activeCtx, value, { base: true }); } else if (expandedProperty === '@type') { return _expandIri(activeCtx, value, { vocab: true, base: true }); } // get type definition from context var type = _getContextValue(activeCtx, activeProperty, '@type'); // do @id expansion (automatic for @graph) if ((type === '@id' || expandedProperty === '@graph') && _isString(value)) { return { '@id': _expandIri(activeCtx, value, { base: true }) }; } // do @id expansion w/vocab if (type === '@vocab' && _isString(value)) { return { '@id': _expandIri(activeCtx, value, { vocab: true, base: true }) }; } // do not expand keyword values if (_isKeyword(expandedProperty)) { return value; } var rval = {}; if (type && !['@id', '@vocab'].includes(type)) { // other type rval['@type'] = type; } else if (_isString(value)) { // check for language tagging for strings var language = _getContextValue(activeCtx, activeProperty, '@language'); if (language !== null) { rval['@language'] = language; } } // do conversion of values that aren't basic JSON types to strings if (!['boolean', 'number', 'string'].includes(typeof value === 'undefined' ? 'undefined' : _typeof(value))) { value = value.toString(); } rval['@value'] = value; return rval; } /** * Expands a language map. * * @param languageMap the language map to expand. * * @return the expanded language map. */ function _expandLanguageMap(languageMap) { var rval = []; var keys = Object.keys(languageMap).sort(); for (var ki = 0; ki < keys.length; ++ki) { var key = keys[ki]; var val = languageMap[key]; if (!_isArray(val)) { val = [val]; } for (var vi = 0; vi < val.length; ++vi) { var item = val[vi]; if (item === null) { // null values are allowed (8.5) but ignored (3.1) continue; } if (!_isString(item)) { throw new JsonLdError('Invalid JSON-LD syntax; language map values must be strings.', 'jsonld.SyntaxError', { code: 'invalid language map value', languageMap: languageMap }); } rval.push({ '@value': item, '@language': key.toLowerCase() }); } } return rval; } function _expandIndexMap(_ref3) { var activeCtx = _ref3.activeCtx, options = _ref3.options, activeProperty = _ref3.activeProperty, value = _ref3.value, expansionMap = _ref3.expansionMap; var rval = []; var keys = Object.keys(value).sort(); for (var ki = 0; ki < keys.length; ++ki) { var key = keys[ki]; var val = value[key]; if (!_isArray(val)) { val = [val]; } val = api.expand({ activeCtx: activeCtx, activeProperty: activeProperty, element: val, options: options, insideList: false, expansionMap: expansionMap }); for (var vi = 0; vi < val.length; ++vi) { var item = val[vi]; if (!('@index' in item)) { item['@index'] = key; } rval.push(item); } } return rval; } /***/ }), /* 130 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __webpack_require__(2), clone = _require.clone; module.exports = function () { /** * Creates an active context cache. * * @param size the maximum size of the cache. */ function ActiveContextCache() { var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; _classCallCheck(this, ActiveContextCache); this.order = []; this.cache = {}; this.size = size; } _createClass(ActiveContextCache, [{ key: 'get', value: function get(activeCtx, localCtx) { var key1 = JSON.stringify(activeCtx); var key2 = JSON.stringify(localCtx); var level1 = this.cache[key1]; if (level1 && key2 in level1) { return level1[key2]; } return null; } }, { key: 'set', value: function set(activeCtx, localCtx, result) { if (this.order.length === this.size) { var entry = this.order.shift(); delete this.cache[entry.activeCtx][entry.localCtx]; } var key1 = JSON.stringify(activeCtx); var key2 = JSON.stringify(localCtx); this.order.push({ activeCtx: key1, localCtx: key2 }); if (!(key1 in this.cache)) { this.cache[key1] = {}; } this.cache[key1][key2] = clone(result); } }]); return ActiveContextCache; }(); /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _require = __webpack_require__(5), _isSubjectReference = _require.isSubjectReference; var _require2 = __webpack_require__(33), _createMergedNodeMap = _require2.createMergedNodeMap; var api = {}; module.exports = api; /** * Performs JSON-LD flattening. * * @param input the expanded JSON-LD to flatten. * * @return the flattened output. */ api.flatten = function (input) { var defaultGraph = _createMergedNodeMap(input); // produce flattened output var flattened = []; var keys = Object.keys(defaultGraph).sort(); for (var ki = 0; ki < keys.length; ++ki) { var node = defaultGraph[keys[ki]]; // only add full subjects to top-level if (!_isSubjectReference(node)) { flattened.push(node); } } return flattened; }; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _require = __webpack_require__(15), isKeyword = _require.isKeyword; var graphTypes = __webpack_require__(5); var types = __webpack_require__(4); var util = __webpack_require__(2); var JsonLdError = __webpack_require__(6); var _require2 = __webpack_require__(33), _createNodeMap = _require2.createNodeMap; var api = {}; module.exports = api; /** * Performs JSON-LD `merged` framing. * * @param input the expanded JSON-LD to frame. * @param frame the expanded JSON-LD frame to use. * @param options the framing options. * * @return the framed output. */ api.frameMerged = function (input, frame, options) { // create framing state var state = { options: options, graphs: { '@default': {}, '@merged': {} }, subjectStack: [], link: {} }; // produce a map of all graphs and name each bnode // FIXME: currently uses subjects from @merged graph only var issuer = new util.IdentifierIssuer('_:b'); _createNodeMap(input, state.graphs, '@merged', issuer); state.subjects = state.graphs['@merged']; // frame the subjects var framed = []; api.frame(state, Object.keys(state.subjects).sort(), frame, framed); return framed; }; /** * Frames subjects according to the given frame. * * @param state the current framing state. * @param subjects the subjects to filter. * @param frame the frame. * @param parent the parent subject or top-level array. * @param property the parent property, initialized to null. */ api.frame = function (state, subjects, frame, parent) { var property = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; // validate the frame _validateFrame(frame); frame = frame[0]; // get flags for current frame var options = state.options; var flags = { embed: _getFrameFlag(frame, options, 'embed'), explicit: _getFrameFlag(frame, options, 'explicit'), requireAll: _getFrameFlag(frame, options, 'requireAll') }; // filter out subjects that match the frame var matches = _filterSubjects(state, subjects, frame, flags); // add matches to output var ids = Object.keys(matches).sort(); for (var idx = 0; idx < ids.length; ++idx) { var id = ids[idx]; var subject = matches[id]; if (flags.embed === '@link' && id in state.link) { // TODO: may want to also match an existing linked subject against // the current frame ... so different frames could produce different // subjects that are only shared in-memory when the frames are the same // add existing linked subject _addFrameOutput(parent, property, state.link[id]); continue; } /* Note: In order to treat each top-level match as a compartmentalized result, clear the unique embedded subjects map when the property is null, which only occurs at the top-level. */ if (property === null) { state.uniqueEmbeds = {}; } // start output for subject var output = {}; output['@id'] = id; state.link[id] = output; // if embed is @never or if a circular reference would be created by an // embed, the subject cannot be embedded, just add the reference; // note that a circular reference won't occur when the embed flag is // `@link` as the above check will short-circuit before reaching this point if (flags.embed === '@never' || _createsCircularReference(subject, state.subjectStack)) { _addFrameOutput(parent, property, output); continue; } // if only the last match should be embedded if (flags.embed === '@last') { // remove any existing embed if (id in state.uniqueEmbeds) { _removeEmbed(state, id); } state.uniqueEmbeds[id] = { parent: parent, property: property }; } // push matching subject onto stack to enable circular embed checks state.subjectStack.push(subject); // iterate over subject properties var props = Object.keys(subject).sort(); for (var i = 0; i < props.length; i++) { var prop = props[i]; // copy keywords to output if (isKeyword(prop)) { output[prop] = util.clone(subject[prop]); continue; } // explicit is on and property isn't in the frame, skip processing if (flags.explicit && !(prop in frame)) { continue; } // add objects var objects = subject[prop]; for (var oi = 0; oi < objects.length; ++oi) { var o = objects[oi]; // recurse into list if (graphTypes.isList(o)) { // add empty list var list = { '@list': [] }; _addFrameOutput(output, prop, list); // add list objects var src = o['@list']; for (var n in src) { o = src[n]; if (graphTypes.isSubjectReference(o)) { var subframe = prop in frame ? frame[prop][0]['@list'] : _createImplicitFrame(flags); // recurse into subject reference api.frame(state, [o['@id']], subframe, list, '@list'); } else { // include other values automatically _addFrameOutput(list, '@list', util.clone(o)); } } continue; } if (graphTypes.isSubjectReference(o)) { // recurse into subject reference var _subframe = prop in frame ? frame[prop] : _createImplicitFrame(flags); api.frame(state, [o['@id']], _subframe, output, prop); } else { // include other values automatically _addFrameOutput(output, prop, util.clone(o)); } } } // handle defaults props = Object.keys(frame).sort(); for (var _i = 0; _i < props.length; ++_i) { var _prop = props[_i]; // skip keywords if (isKeyword(_prop)) { continue; } // if omit default is off, then include default values for properties // that appear in the next frame but are not in the matching subject var next = frame[_prop][0]; var omitDefaultOn = _getFrameFlag(next, options, 'omitDefault'); if (!omitDefaultOn && !(_prop in output)) { var preserve = '@null'; if ('@default' in next) { preserve = util.clone(next['@default']); } if (!types.isArray(preserve)) { preserve = [preserve]; } output[_prop] = [{ '@preserve': preserve }]; } } // add output to parent _addFrameOutput(parent, property, output); // pop matching subject from circular ref-checking stack state.subjectStack.pop(); } }; /** * Creates an implicit frame when recursing through subject matches. If * a frame doesn't have an explicit frame for a particular property, then * a wildcard child frame will be created that uses the same flags that the * parent frame used. * * @param flags the current framing flags. * * @return the implicit frame. */ function _createImplicitFrame(flags) { var frame = {}; for (var key in flags) { if (flags[key] !== undefined) { frame['@' + key] = [flags[key]]; } } return [frame]; } /** * Checks the current subject stack to see if embedding the given subject * would cause a circular reference. * * @param subjectToEmbed the subject to embed. * @param subjectStack the current stack of subjects. * * @return true if a circular reference would be created, false if not. */ function _createsCircularReference(subjectToEmbed, subjectStack) { for (var i = subjectStack.length - 1; i >= 0; --i) { if (subjectStack[i]['@id'] === subjectToEmbed['@id']) { return true; } } return false; } /** * Gets the frame flag value for the given flag name. * * @param frame the frame. * @param options the framing options. * @param name the flag name. * * @return the flag value. */ function _getFrameFlag(frame, options, name) { var flag = '@' + name; var rval = flag in frame ? frame[flag][0] : options[name]; if (name === 'embed') { // default is "@last" // backwards-compatibility support for "embed" maps: // true => "@last" // false => "@never" if (rval === true) { rval = '@last'; } else if (rval === false) { rval = '@never'; } else if (rval !== '@always' && rval !== '@never' && rval !== '@link') { rval = '@last'; } } return rval; } /** * Validates a JSON-LD frame, throwing an exception if the frame is invalid. * * @param frame the frame to validate. */ function _validateFrame(frame) { if (!types.isArray(frame) || frame.length !== 1 || !types.isObject(frame[0])) { throw new JsonLdError('Invalid JSON-LD syntax; a JSON-LD frame must be a single object.', 'jsonld.SyntaxError', { frame: frame }); } } /** * Returns a map of all of the subjects that match a parsed frame. * * @param state the current framing state. * @param subjects the set of subjects to filter. * @param frame the parsed frame. * @param flags the frame flags. * * @return all of the matched subjects. */ function _filterSubjects(state, subjects, frame, flags) { // filter subjects in @id order var rval = {}; for (var i = 0; i < subjects.length; ++i) { var id = subjects[i]; var subject = state.subjects[id]; if (_filterSubject(subject, frame, flags)) { rval[id] = subject; } } return rval; } /** * Returns true if the given subject matches the given frame. * * @param subject the subject to check. * @param frame the frame to check. * @param flags the frame flags. * * @return true if the subject matches, false if not. */ function _filterSubject(subject, frame, flags) { // check @type (object value means 'any' type, fall through to ducktyping) if ('@type' in frame && !(frame['@type'].length === 1 && types.isObject(frame['@type'][0]))) { var nodeTypes = frame['@type']; for (var i = 0; i < nodeTypes.length; ++i) { // any matching @type is a match if (util.hasValue(subject, '@type', nodeTypes[i])) { return true; } } return false; } // check ducktype var wildcard = true; var matchesSome = false; for (var key in frame) { if (isKeyword(key)) { // skip non-@id and non-@type if (key !== '@id' && key !== '@type') { continue; } wildcard = false; // check @id for a specific @id value if (key === '@id' && types.isString(frame[key])) { if (subject[key] !== frame[key]) { return false; } matchesSome = true; continue; } } wildcard = false; if (key in subject) { // frame[key] === [] means do not match if property is present if (types.isArray(frame[key]) && frame[key].length === 0 && subject[key] !== undefined) { return false; } matchesSome = true; continue; } // all properties must match to be a duck unless a @default is specified var hasDefault = types.isArray(frame[key]) && types.isObject(frame[key][0]) && '@default' in frame[key][0]; if (flags.requireAll && !hasDefault) { return false; } } // return true if wildcard or subject matches some properties return wildcard || matchesSome; } /** * Removes an existing embed. * * @param state the current framing state. * @param id the @id of the embed to remove. */ function _removeEmbed(state, id) { // get existing embed var embeds = state.uniqueEmbeds; var embed = embeds[id]; var parent = embed.parent; var property = embed.property; // create reference to replace embed var subject = { '@id': id }; // remove existing embed if (types.isArray(parent)) { // replace subject with reference for (var i = 0; i < parent.length; ++i) { if (util.compareValues(parent[i], subject)) { parent[i] = subject; break; } } } else { // replace subject with reference var useArray = types.isArray(parent[property]); util.removeValue(parent, property, subject, { propertyIsArray: useArray }); util.addValue(parent, property, subject, { propertyIsArray: useArray }); } // recursively remove dependent dangling embeds var removeDependents = function removeDependents(id) { // get embed keys as a separate array to enable deleting keys in map var ids = Object.keys(embeds); for (var _i2 = 0; _i2 < ids.length; ++_i2) { var next = ids[_i2]; if (next in embeds && types.isObject(embeds[next].parent) && embeds[next].parent['@id'] === id) { delete embeds[next]; removeDependents(next); } } }; removeDependents(id); } /** * Adds framing output to the given parent. * * @param parent the parent to add to. * @param property the parent property. * @param output the output to add. */ function _addFrameOutput(parent, property, output) { if (types.isObject(parent)) { util.addValue(parent, property, output, { propertyIsArray: true }); } else { parent.push(output); } } /***/ }), /* 133 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var graphTypes = __webpack_require__(5); var types = __webpack_require__(4); var util = __webpack_require__(2); // constants var _require = __webpack_require__(24), RDF = _require.RDF, RDF_LIST = _require.RDF_LIST, RDF_FIRST = _require.RDF_FIRST, RDF_REST = _require.RDF_REST, RDF_NIL = _require.RDF_NIL, RDF_TYPE = _require.RDF_TYPE, RDF_PLAIN_LITERAL = _require.RDF_PLAIN_LITERAL, RDF_XML_LITERAL = _require.RDF_XML_LITERAL, RDF_OBJECT = _require.RDF_OBJECT, RDF_LANGSTRING = _require.RDF_LANGSTRING, XSD = _require.XSD, XSD_BOOLEAN = _require.XSD_BOOLEAN, XSD_DOUBLE = _require.XSD_DOUBLE, XSD_INTEGER = _require.XSD_INTEGER, XSD_STRING = _require.XSD_STRING; var api = {}; module.exports = api; /** * Converts an RDF dataset to JSON-LD. * * @param dataset the RDF dataset. * @param options the RDF serialization options. * * @return a Promise that resolves to the JSON-LD output. */ api.fromRDF = function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(dataset, _ref) { var _ref$useRdfType = _ref.useRdfType, useRdfType = _ref$useRdfType === undefined ? false : _ref$useRdfType, _ref$useNativeTypes = _ref.useNativeTypes, useNativeTypes = _ref$useNativeTypes === undefined ? false : _ref$useNativeTypes; var defaultGraph, graphMap, referencedOnce, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, quad, name, nodeMap, s, p, o, node, objectIsNode, value, object, graphObject, nil, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, usage, property, head, list, listNodes, nodeKeyCount, _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, listNode, result, subjects, _iteratorNormalCompletion4, _didIteratorError4, _iteratorError4, _iterator4, _step4, subject, _node, graph, _graphObject, graphSubjects, _iteratorNormalCompletion5, _didIteratorError5, _iteratorError5, _iterator5, _step5, graphSubject, _node2; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: defaultGraph = {}; graphMap = { '@default': defaultGraph }; referencedOnce = {}; _iteratorNormalCompletion = true; _didIteratorError = false; _iteratorError = undefined; _context.prev = 6; _iterator = dataset[Symbol.iterator](); case 8: if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { _context.next = 30; break; } quad = _step.value; // TODO: change 'name' to 'graph' name = quad.graph.termType === 'DefaultGraph' ? '@default' : quad.graph.value; if (!(name in graphMap)) { graphMap[name] = {}; } if (name !== '@default' && !(name in defaultGraph)) { defaultGraph[name] = { '@id': name }; } nodeMap = graphMap[name]; // get subject, predicate, object s = quad.subject.value; p = quad.predicate.value; o = quad.object; if (!(s in nodeMap)) { nodeMap[s] = { '@id': s }; } node = nodeMap[s]; objectIsNode = o.termType.endsWith('Node'); if (objectIsNode && !(o.value in nodeMap)) { nodeMap[o.value] = { '@id': o.value }; } if (!(p === RDF_TYPE && !useRdfType && objectIsNode)) { _context.next = 24; break; } util.addValue(node, '@type', o.value, { propertyIsArray: true }); return _context.abrupt('continue', 27); case 24: value = _RDFToObject(o, useNativeTypes); util.addValue(node, p, value, { propertyIsArray: true }); // object may be an RDF list/partial list node but we can't know easily // until all triples are read if (objectIsNode) { if (o.value === RDF_NIL) { // track rdf:nil uniquely per graph object = nodeMap[o.value]; if (!('usages' in object)) { object.usages = []; } object.usages.push({ node: node, property: p, value: value }); } else if (o.value in referencedOnce) { // object referenced more than once referencedOnce[o.value] = false; } else { // keep track of single reference referencedOnce[o.value] = { node: node, property: p, value: value }; } } case 27: _iteratorNormalCompletion = true; _context.next = 8; break; case 30: _context.next = 36; break; case 32: _context.prev = 32; _context.t0 = _context['catch'](6); _didIteratorError = true; _iteratorError = _context.t0; case 36: _context.prev = 36; _context.prev = 37; if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } case 39: _context.prev = 39; if (!_didIteratorError) { _context.next = 42; break; } throw _iteratorError; case 42: return _context.finish(39); case 43: return _context.finish(36); case 44: _context.t1 = regeneratorRuntime.keys(graphMap); case 45: if ((_context.t2 = _context.t1()).done) { _context.next = 125; break; } name = _context.t2.value; graphObject = graphMap[name]; // no @lists to be converted, continue if (RDF_NIL in graphObject) { _context.next = 50; break; } return _context.abrupt('continue', 45); case 50: // iterate backwards through each RDF list nil = graphObject[RDF_NIL]; if (nil.usages) { _context.next = 53; break; } return _context.abrupt('continue', 45); case 53: _iteratorNormalCompletion2 = true; _didIteratorError2 = false; _iteratorError2 = undefined; _context.prev = 56; _iterator2 = nil.usages[Symbol.iterator](); case 58: if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) { _context.next = 108; break; } usage = _step2.value; node = usage.node; property = usage.property; head = usage.value; list = []; listNodes = []; // ensure node is a well-formed list node; it must: // 1. Be referenced only once. // 2. Have an array for rdf:first that has 1 item. // 3. Have an array for rdf:rest that has 1 item. // 4. Have no keys other than: @id, rdf:first, rdf:rest, and, // optionally, @type where the value is rdf:List. nodeKeyCount = Object.keys(node).length; case 66: if (!(property === RDF_REST && types.isObject(referencedOnce[node['@id']]) && types.isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 && types.isArray(node[RDF_REST]) && node[RDF_REST].length === 1 && (nodeKeyCount === 3 || nodeKeyCount === 4 && types.isArray(node['@type']) && node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) { _context.next = 78; break; } list.push(node[RDF_FIRST][0]); listNodes.push(node['@id']); // get next node, moving backwards through list usage = referencedOnce[node['@id']]; node = usage.node; property = usage.property; head = usage.value; nodeKeyCount = Object.keys(node).length; // if node is not a blank node, then list head found if (graphTypes.isBlankNode(node)) { _context.next = 76; break; } return _context.abrupt('break', 78); case 76: _context.next = 66; break; case 78: if (!(property === RDF_FIRST)) { _context.next = 84; break; } if (!(node['@id'] === RDF_NIL)) { _context.next = 81; break; } return _context.abrupt('continue', 105); case 81: // preserve list head head = graphObject[head['@id']][RDF_REST][0]; list.pop(); listNodes.pop(); case 84: // transform list into @list object delete head['@id']; head['@list'] = list.reverse(); _iteratorNormalCompletion3 = true; _didIteratorError3 = false; _iteratorError3 = undefined; _context.prev = 89; for (_iterator3 = listNodes[Symbol.iterator](); !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { listNode = _step3.value; delete graphObject[listNode]; } _context.next = 97; break; case 93: _context.prev = 93; _context.t3 = _context['catch'](89); _didIteratorError3 = true; _iteratorError3 = _context.t3; case 97: _context.prev = 97; _context.prev = 98; if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } case 100: _context.prev = 100; if (!_didIteratorError3) { _context.next = 103; break; } throw _iteratorError3; case 103: return _context.finish(100); case 104: return _context.finish(97); case 105: _iteratorNormalCompletion2 = true; _context.next = 58; break; case 108: _context.next = 114; break; case 110: _context.prev = 110; _context.t4 = _context['catch'](56); _didIteratorError2 = true; _iteratorError2 = _context.t4; case 114: _context.prev = 114; _context.prev = 115; if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } case 117: _context.prev = 117; if (!_didIteratorError2) { _context.next = 120; break; } throw _iteratorError2; case 120: return _context.finish(117); case 121: return _context.finish(114); case 122: delete nil.usages; _context.next = 45; break; case 125: result = []; subjects = Object.keys(defaultGraph).sort(); _iteratorNormalCompletion4 = true; _didIteratorError4 = false; _iteratorError4 = undefined; _context.prev = 130; _iterator4 = subjects[Symbol.iterator](); case 132: if (_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done) { _context.next = 162; break; } subject = _step4.value; _node = defaultGraph[subject]; if (!(subject in graphMap)) { _context.next = 158; break; } graph = _node['@graph'] = []; _graphObject = graphMap[subject]; graphSubjects = Object.keys(_graphObject).sort(); _iteratorNormalCompletion5 = true; _didIteratorError5 = false; _iteratorError5 = undefined; _context.prev = 142; for (_iterator5 = graphSubjects[Symbol.iterator](); !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { graphSubject = _step5.value; _node2 = _graphObject[graphSubject]; // only add full subjects to top-level if (!graphTypes.isSubjectReference(_node2)) { graph.push(_node2); } } _context.next = 150; break; case 146: _context.prev = 146; _context.t5 = _context['catch'](142); _didIteratorError5 = true; _iteratorError5 = _context.t5; case 150: _context.prev = 150; _context.prev = 151; if (!_iteratorNormalCompletion5 && _iterator5.return) { _iterator5.return(); } case 153: _context.prev = 153; if (!_didIteratorError5) { _context.next = 156; break; } throw _iteratorError5; case 156: return _context.finish(153); case 157: return _context.finish(150); case 158: // only add full subjects to top-level if (!graphTypes.isSubjectReference(_node)) { result.push(_node); } case 159: _iteratorNormalCompletion4 = true; _context.next = 132; break; case 162: _context.next = 168; break; case 164: _context.prev = 164; _context.t6 = _context['catch'](130); _didIteratorError4 = true; _iteratorError4 = _context.t6; case 168: _context.prev = 168; _context.prev = 169; if (!_iteratorNormalCompletion4 && _iterator4.return) { _iterator4.return(); } case 171: _context.prev = 171; if (!_didIteratorError4) { _context.next = 174; break; } throw _iteratorError4; case 174: return _context.finish(171); case 175: return _context.finish(168); case 176: return _context.abrupt('return', result); case 177: case 'end': return _context.stop(); } } }, _callee, undefined, [[6, 32, 36, 44], [37,, 39, 43], [56, 110, 114, 122], [89, 93, 97, 105], [98,, 100, 104], [115,, 117, 121], [130, 164, 168, 176], [142, 146, 150, 158], [151,, 153, 157], [169,, 171, 175]]); })); return function (_x, _x2) { return _ref2.apply(this, arguments); }; }(); /** * Converts an RDF triple object to a JSON-LD object. * * @param o the RDF triple object to convert. * @param useNativeTypes true to output native types, false not to. * * @return the JSON-LD object. */ function _RDFToObject(o, useNativeTypes) { // convert NamedNode/BlankNode object to JSON-LD if (o.termType.endsWith('Node')) { return { '@id': o.value }; } // convert literal to JSON-LD var rval = { '@value': o.value }; // add language if (o.language) { rval['@language'] = o.language; } else { var type = o.datatype.value; if (!type) { type = XSD_STRING; } // use native types for certain xsd types if (useNativeTypes) { if (type === XSD_BOOLEAN) { if (rval['@value'] === 'true') { rval['@value'] = true; } else if (rval['@value'] === 'false') { rval['@value'] = false; } } else if (types.isNumeric(rval['@value'])) { if (type === XSD_INTEGER) { var i = parseInt(rval['@value'], 10); if (i.toFixed(0) === rval['@value']) { rval['@value'] = i; } } else if (type === XSD_DOUBLE) { rval['@value'] = parseFloat(rval['@value']); } } // do not add native type if (![XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING].includes(type)) { rval['@type'] = type; } } else if (type !== XSD_STRING) { rval['@type'] = type; } } return rval; } /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _require = __webpack_require__(33), createNodeMap = _require.createNodeMap; var _require2 = __webpack_require__(15), isKeyword = _require2.isKeyword; var graphTypes = __webpack_require__(5); var types = __webpack_require__(4); var util = __webpack_require__(2); var _require3 = __webpack_require__(24), RDF = _require3.RDF, RDF_LIST = _require3.RDF_LIST, RDF_FIRST = _require3.RDF_FIRST, RDF_REST = _require3.RDF_REST, RDF_NIL = _require3.RDF_NIL, RDF_TYPE = _require3.RDF_TYPE, RDF_PLAIN_LITERAL = _require3.RDF_PLAIN_LITERAL, RDF_XML_LITERAL = _require3.RDF_XML_LITERAL, RDF_OBJECT = _require3.RDF_OBJECT, RDF_LANGSTRING = _require3.RDF_LANGSTRING, XSD = _require3.XSD, XSD_BOOLEAN = _require3.XSD_BOOLEAN, XSD_DOUBLE = _require3.XSD_DOUBLE, XSD_INTEGER = _require3.XSD_INTEGER, XSD_STRING = _require3.XSD_STRING; var _require4 = __webpack_require__(25), _isAbsoluteIri = _require4.isAbsolute; var api = {}; module.exports = api; /** * Outputs an RDF dataset for the expanded JSON-LD input. * * @param input the expanded JSON-LD input. * @param options the RDF serialization options. * * @return the RDF dataset. */ api.toRDF = function (input, options) { // create node map for default graph (and any named graphs) var issuer = new util.IdentifierIssuer('_:b'); var nodeMap = { '@default': {} }; createNodeMap(input, nodeMap, '@default', issuer); var dataset = []; var graphNames = Object.keys(nodeMap).sort(); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = graphNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var graphName = _step.value; var graphTerm = void 0; if (graphName === '@default') { graphTerm = { termType: 'DefaultGraph', value: '' }; } else if (_isAbsoluteIri(graphName)) { if (graphName.startsWith('_:')) { graphTerm = { termType: 'BlankNode' }; } else { graphTerm = { termType: 'NamedNode' }; } graphTerm.value = graphName; } else { // skip relative IRIs (not valid RDF) continue; } _graphToRDF(dataset, nodeMap[graphName], graphTerm, issuer, options); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return dataset; }; /** * Adds RDF quads for a particular graph to the given dataset. * * @param dataset the dataset to append RDF quads to. * @param graph the graph to create RDF quads for. * @param graphTerm the graph term for each quad. * @param issuer a IdentifierIssuer for assigning blank node names. * @param options the RDF serialization options. * * @return the array of RDF triples for the given graph. */ function _graphToRDF(dataset, graph, graphTerm, issuer, options) { var ids = Object.keys(graph).sort(); for (var i = 0; i < ids.length; ++i) { var id = ids[i]; var node = graph[id]; var properties = Object.keys(node).sort(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = properties[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var property = _step2.value; var items = node[property]; if (property === '@type') { property = RDF_TYPE; } else if (isKeyword(property)) { continue; } var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = items[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var item = _step3.value; // RDF subject var subject = { termType: id.startsWith('_:') ? 'BlankNode' : 'NamedNode', value: id }; // skip relative IRI subjects (not valid RDF) if (!_isAbsoluteIri(id)) { continue; } // RDF predicate var predicate = { termType: property.startsWith('_:') ? 'BlankNode' : 'NamedNode', value: property }; // skip relative IRI predicates (not valid RDF) if (!_isAbsoluteIri(property)) { continue; } // skip blank node predicates unless producing generalized RDF if (predicate.termType === 'BlankNode' && !options.produceGeneralizedRdf) { continue; } // convert @list to triples if (graphTypes.isList(item)) { _listToRDF(item['@list'], issuer, subject, predicate, dataset, graphTerm); } else { // convert value or node object to triple var object = _objectToRDF(item); // skip null objects (they are relative IRIs) if (object) { dataset.push({ subject: subject, predicate: predicate, object: object, graph: graphTerm }); } } } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } } /** * Converts a @list value into linked list of blank node RDF quads * (an RDF collection). * * @param list the @list value. * @param issuer a IdentifierIssuer for assigning blank node names. * @param subject the subject for the head of the list. * @param predicate the predicate for the head of the list. * @param dataset the array of quads to append to. * @param graphTerm the graph term for each quad. */ function _listToRDF(list, issuer, subject, predicate, dataset, graphTerm) { var first = { termType: 'NamedNode', value: RDF_FIRST }; var rest = { termType: 'NamedNode', value: RDF_REST }; var nil = { termType: 'NamedNode', value: RDF_NIL }; var _iteratorNormalCompletion4 = true; var _didIteratorError4 = false; var _iteratorError4 = undefined; try { for (var _iterator4 = list[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { var item = _step4.value; var blankNode = { termType: 'BlankNode', value: issuer.getId() }; dataset.push({ subject: subject, predicate: predicate, object: blankNode, graph: graphTerm }); subject = blankNode; predicate = first; var object = _objectToRDF(item); // skip null objects (they are relative IRIs) if (object) { dataset.push({ subject: subject, predicate: predicate, object: object, graph: graphTerm }); } predicate = rest; } } catch (err) { _didIteratorError4 = true; _iteratorError4 = err; } finally { try { if (!_iteratorNormalCompletion4 && _iterator4.return) { _iterator4.return(); } } finally { if (_didIteratorError4) { throw _iteratorError4; } } } dataset.push({ subject: subject, predicate: predicate, object: nil, graph: graphTerm }); } /** * Converts a JSON-LD value object to an RDF literal or a JSON-LD string or * node object to an RDF resource. * * @param item the JSON-LD value or node object. * * @return the RDF literal or RDF resource. */ function _objectToRDF(item) { var object = {}; // convert value object to RDF if (graphTypes.isValue(item)) { object.termType = 'Literal'; object.value = undefined; object.datatype = { termType: 'NamedNode' }; var value = item['@value']; var datatype = item['@type'] || null; // convert to XSD datatypes as appropriate if (types.isBoolean(value)) { object.value = value.toString(); object.datatype.value = datatype || XSD_BOOLEAN; } else if (types.isDouble(value) || datatype === XSD_DOUBLE) { if (!types.isDouble(value)) { value = parseFloat(value); } // canonical double representation object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E'); object.datatype.value = datatype || XSD_DOUBLE; } else if (types.isNumber(value)) { object.value = value.toFixed(0); object.datatype.value = datatype || XSD_INTEGER; } else if ('@language' in item) { object.value = value; object.datatype.value = datatype || RDF_LANGSTRING; object.language = item['@language']; } else { object.value = value; object.datatype.value = datatype || XSD_STRING; } } else { // convert string/node object to RDF var id = types.isObject(item) ? item['@id'] : item; object.termType = id.startsWith('_:') ? 'BlankNode' : 'NamedNode'; object.value = id; } // skip relative IRIs, not valid RDF if (object.termType === 'NamedNode' && !_isAbsoluteIri(object.value)) { return null; } return object; } /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var JsonLdError = __webpack_require__(6); var _require = __webpack_require__(4), _isArray = _require.isArray, _isObject = _require.isObject, _isString = _require.isString; var _require2 = __webpack_require__(5), _isList = _require2.isList, _isValue = _require2.isValue, _isSimpleGraph = _require2.isSimpleGraph, _isSubjectReference = _require2.isSubjectReference; var _require3 = __webpack_require__(15), _expandIri = _require3.expandIri, _getContextValue = _require3.getContextValue, _isKeyword = _require3.isKeyword; var _require4 = __webpack_require__(25), _removeBase = _require4.removeBase; var _require5 = __webpack_require__(2), _addValue = _require5.addValue, _compareShortestLeast = _require5.compareShortestLeast; var api = {}; module.exports = api; /** * Recursively compacts an element using the given active context. All values * must be in expanded form before this method is called. * * @param activeCtx the active context to use. * @param activeProperty the compacted property associated with the element * to compact, null for none. * @param element the element to compact. * @param options the compaction options. * @param compactionMap the compaction map to use. * * @return the compacted value. */ api.compact = function (_ref) { var activeCtx = _ref.activeCtx, _ref$activeProperty = _ref.activeProperty, activeProperty = _ref$activeProperty === undefined ? null : _ref$activeProperty, element = _ref.element, _ref$options = _ref.options, options = _ref$options === undefined ? {} : _ref$options, _ref$compactionMap = _ref.compactionMap, compactionMap = _ref$compactionMap === undefined ? function () { return undefined; } : _ref$compactionMap; // recursively compact array if (_isArray(element)) { var rval = []; for (var i = 0; i < element.length; ++i) { // compact, dropping any null values unless custom mapped var compacted = api.compact({ activeCtx: activeCtx, activeProperty: activeProperty, element: element[i], options: options, compactionMap: compactionMap }); if (compacted === null) { // TODO: use `await` to support async compacted = compactionMap({ unmappedValue: element[i], activeCtx: activeCtx, activeProperty: activeProperty, parent: element, index: i, options: options }); if (compacted === undefined) { continue; } } rval.push(compacted); } if (options.compactArrays && rval.length === 1) { // use single element if no container is specified var container = _getContextValue(activeCtx, activeProperty, '@container') || []; if (container.length === 0) { rval = rval[0]; } } return rval; } // recursively compact object if (_isObject(element)) { if (options.link && '@id' in element && element['@id'] in options.link) { // check for a linked element to reuse var linked = options.link[element['@id']]; for (var _i = 0; _i < linked.length; ++_i) { if (linked[_i].expanded === element) { return linked[_i].compacted; } } } // do value compaction on @values and subject references if (_isValue(element) || _isSubjectReference(element)) { var _rval2 = api.compactValue({ activeCtx: activeCtx, activeProperty: activeProperty, value: element }); if (options.link && _isSubjectReference(element)) { // store linked element if (!(element['@id'] in options.link)) { options.link[element['@id']] = []; } options.link[element['@id']].push({ expanded: element, compacted: _rval2 }); } return _rval2; } // FIXME: avoid misuse of active property as an expanded property? var insideReverse = activeProperty === '@reverse'; var _rval = {}; if (options.link && '@id' in element) { // store linked element if (!(element['@id'] in options.link)) { options.link[element['@id']] = []; } options.link[element['@id']].push({ expanded: element, compacted: _rval }); } // process element keys in order var keys = Object.keys(element).sort(); for (var ki = 0; ki < keys.length; ++ki) { var expandedProperty = keys[ki]; var expandedValue = element[expandedProperty]; // compact @id and @type(s) if (expandedProperty === '@id' || expandedProperty === '@type') { var compactedValue = void 0; // compact single @id if (_isString(expandedValue)) { compactedValue = api.compactIri({ activeCtx: activeCtx, iri: expandedValue, relativeTo: { vocab: expandedProperty === '@type' } }); } else { // expanded value must be a @type array compactedValue = []; for (var vi = 0; vi < expandedValue.length; ++vi) { compactedValue.push(api.compactIri({ activeCtx: activeCtx, iri: expandedValue[vi], relativeTo: { vocab: true } })); } } // use keyword alias and add value var alias = api.compactIri({ activeCtx: activeCtx, iri: expandedProperty, relativeTo: { vocab: true } }); var isArray = _isArray(compactedValue) && expandedValue.length === 0; _addValue(_rval, alias, compactedValue, { propertyIsArray: isArray }); continue; } // handle @reverse if (expandedProperty === '@reverse') { // recursively compact expanded value var _compactedValue = api.compact({ activeCtx: activeCtx, activeProperty: '@reverse', element: expandedValue, options: options, compactionMap: compactionMap }); // handle double-reversed properties for (var compactedProperty in _compactedValue) { if (activeCtx.mappings[compactedProperty] && activeCtx.mappings[compactedProperty].reverse) { var value = _compactedValue[compactedProperty]; var _container = _getContextValue(activeCtx, compactedProperty, '@container') || []; var useArray = _container.includes('@set') || !options.compactArrays; _addValue(_rval, compactedProperty, value, { propertyIsArray: useArray }); delete _compactedValue[compactedProperty]; } } if (Object.keys(_compactedValue).length > 0) { // use keyword alias and add value var _alias = api.compactIri({ activeCtx: activeCtx, iri: expandedProperty, relativeTo: { vocab: true } }); _addValue(_rval, _alias, _compactedValue); } continue; } // handle @index property if (expandedProperty === '@index') { // drop @index if inside an @index container var _container2 = _getContextValue(activeCtx, activeProperty, '@container') || []; if (_container2.includes('@index')) { continue; } // use keyword alias and add value var _alias2 = api.compactIri({ activeCtx: activeCtx, iri: expandedProperty, relativeTo: { vocab: true } }); _addValue(_rval, _alias2, expandedValue); continue; } // skip array processing for keywords that aren't @graph or @list if (expandedProperty !== '@graph' && expandedProperty !== '@list' && _isKeyword(expandedProperty)) { // use keyword alias and add value as is var _alias3 = api.compactIri({ activeCtx: activeCtx, iri: expandedProperty, relativeTo: { vocab: true } }); _addValue(_rval, _alias3, expandedValue); continue; } // Note: expanded value must be an array due to expansion algorithm. if (!_isArray(expandedValue)) { throw new JsonLdError('JSON-LD expansion error; expanded value must be an array.', 'jsonld.SyntaxError'); } // preserve empty arrays if (expandedValue.length === 0) { var itemActiveProperty = api.compactIri({ activeCtx: activeCtx, iri: expandedProperty, value: expandedValue, relativeTo: { vocab: true }, reverse: insideReverse }); _addValue(_rval, itemActiveProperty, expandedValue, { propertyIsArray: true }); } // recusively process array values for (var _vi = 0; _vi < expandedValue.length; ++_vi) { var expandedItem = expandedValue[_vi]; // compact property and get container type var _itemActiveProperty = api.compactIri({ activeCtx: activeCtx, iri: expandedProperty, value: expandedItem, relativeTo: { vocab: true }, reverse: insideReverse }); var _container3 = _getContextValue(activeCtx, _itemActiveProperty, '@container') || []; // get simple @graph or @list value if appropriate var isSimpleGraph = _isSimpleGraph(expandedItem); var isList = _isList(expandedItem); var inner = void 0; if (isList) { inner = expandedItem['@list']; } else if (isSimpleGraph) { inner = expandedItem['@graph']; } // recursively compact expanded item var compactedItem = api.compact({ activeCtx: activeCtx, activeProperty: _itemActiveProperty, element: isList || isSimpleGraph ? inner : expandedItem, options: options, compactionMap: compactionMap }); // handle @list if (isList) { // ensure @list value is an array if (!_isArray(compactedItem)) { compactedItem = [compactedItem]; } if (!_container3.includes('@list')) { // wrap using @list alias compactedItem = _defineProperty({}, api.compactIri({ activeCtx: activeCtx, iri: '@list', relativeTo: { vocab: true } }), compactedItem); // include @index from expanded @list, if any if ('@index' in expandedItem) { compactedItem[api.compactIri({ activeCtx: activeCtx, iri: '@index', relativeTo: { vocab: true } })] = expandedItem['@index']; } } else if (_itemActiveProperty in _rval) { // can't use @list container for more than 1 list throw new JsonLdError('JSON-LD compact error; property has a "@list" @container ' + 'rule but there is more than a single @list that matches ' + 'the compacted term in the document. Compaction might mix ' + 'unwanted items into the list.', 'jsonld.SyntaxError', { code: 'compaction to list of lists' }); } } // handle simple @graph if (isSimpleGraph && !_container3.includes('@graph')) { // wrap using @graph alias compactedItem = _defineProperty({}, api.compactIri({ activeCtx: activeCtx, iri: '@graph', relativeTo: { vocab: true } }), compactedItem); // include @index from expanded @graph, if any if ('@index' in expandedItem) { compactedItem[api.compactIri({ activeCtx: activeCtx, iri: '@index', relativeTo: { vocab: true } })] = expandedItem['@index']; } } // handle language and index maps if (_container3.includes('@language') || _container3.includes('@index')) { // get or create the map object var mapObject = void 0; if (_itemActiveProperty in _rval) { mapObject = _rval[_itemActiveProperty]; } else { _rval[_itemActiveProperty] = mapObject = {}; } // if container is a language map, simplify compacted value to // a simple string if (_container3.includes('@language') && _isValue(compactedItem)) { compactedItem = compactedItem['@value']; } // add compact value to map object using key from expanded value // based on the container type var c = _container3.includes('@language') ? '@language' : '@index'; _addValue(mapObject, expandedItem[c], compactedItem); } else { // use an array if: compactArrays flag is false, // @container is @set or @list , value is an empty // array, or key is @graph var _isArray2 = !options.compactArrays || _container3.includes('@set') || _container3.includes('@list') || _isArray(compactedItem) && compactedItem.length === 0 || expandedProperty === '@list' || expandedProperty === '@graph'; // add compact value _addValue(_rval, _itemActiveProperty, compactedItem, { propertyIsArray: _isArray2 }); } } } return _rval; } // only primitives remain which are already compact return element; }; /** * Compacts an IRI or keyword into a term or prefix if it can be. If the * IRI has an associated value it may be passed. * * @param activeCtx the active context to use. * @param iri the IRI to compact. * @param value the value to check or null. * @param relativeTo options for how to compact IRIs: * vocab: true to split after @vocab, false not to. * @param reverse true if a reverse property is being compacted, false if not. * * @return the compacted term, prefix, keyword alias, or the original IRI. */ api.compactIri = function (_ref2) { var activeCtx = _ref2.activeCtx, iri = _ref2.iri, _ref2$value = _ref2.value, value = _ref2$value === undefined ? null : _ref2$value, _ref2$relativeTo = _ref2.relativeTo, relativeTo = _ref2$relativeTo === undefined ? { vocab: false } : _ref2$relativeTo, _ref2$reverse = _ref2.reverse, reverse = _ref2$reverse === undefined ? false : _ref2$reverse; // can't compact null if (iri === null) { return iri; } var inverseCtx = activeCtx.getInverse(); // if term is a keyword, it may be compacted to a simple alias if (_isKeyword(iri) && iri in inverseCtx && '@none' in inverseCtx[iri] && '@type' in inverseCtx[iri]['@none'] && '@none' in inverseCtx[iri]['@none']['@type']) { return inverseCtx[iri]['@none']['@type']['@none']; } // use inverse context to pick a term if iri is relative to vocab if (relativeTo.vocab && iri in inverseCtx) { var defaultLanguage = activeCtx['@language'] || '@none'; // prefer @index if available in value var containers = []; if (_isObject(value) && '@index' in value) { containers.push('@index'); } // prefer `['@graph', '@set']` and then `@graph` if value is a simple graph // TODO: support `@graphId`? if (_isSimpleGraph(value)) { containers.push('@graph@set'); containers.push('@graph'); } // defaults for term selection based on type/language var typeOrLanguage = '@language'; var typeOrLanguageValue = '@null'; if (reverse) { typeOrLanguage = '@type'; typeOrLanguageValue = '@reverse'; containers.push('@set'); } else if (_isList(value)) { // choose the most specific term that works for all elements in @list // only select @list containers if @index is NOT in value if (!('@index' in value)) { containers.push('@list'); } var list = value['@list']; if (list.length === 0) { // any empty list can be matched against any term that uses the // @list container regardless of @type or @language typeOrLanguage = '@any'; typeOrLanguageValue = '@none'; } else { var commonLanguage = list.length === 0 ? defaultLanguage : null; var commonType = null; for (var i = 0; i < list.length; ++i) { var item = list[i]; var itemLanguage = '@none'; var itemType = '@none'; if (_isValue(item)) { if ('@language' in item) { itemLanguage = item['@language']; } else if ('@type' in item) { itemType = item['@type']; } else { // plain literal itemLanguage = '@null'; } } else { itemType = '@id'; } if (commonLanguage === null) { commonLanguage = itemLanguage; } else if (itemLanguage !== commonLanguage && _isValue(item)) { commonLanguage = '@none'; } if (commonType === null) { commonType = itemType; } else if (itemType !== commonType) { commonType = '@none'; } // there are different languages and types in the list, so choose // the most generic term, no need to keep iterating the list if (commonLanguage === '@none' && commonType === '@none') { break; } } commonLanguage = commonLanguage || '@none'; commonType = commonType || '@none'; if (commonType !== '@none') { typeOrLanguage = '@type'; typeOrLanguageValue = commonType; } else { typeOrLanguageValue = commonLanguage; } } } else { if (_isValue(value)) { if ('@language' in value && !('@index' in value)) { containers.push('@language'); typeOrLanguageValue = value['@language']; } else if ('@type' in value) { typeOrLanguage = '@type'; typeOrLanguageValue = value['@type']; } } else { typeOrLanguage = '@type'; typeOrLanguageValue = '@id'; } containers.push('@set'); } // do term selection containers.push('@none'); var term = _selectTerm(activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue); if (term !== null) { return term; } } // no term match, use @vocab if available if (relativeTo.vocab) { if ('@vocab' in activeCtx) { // determine if vocab is a prefix of the iri var vocab = activeCtx['@vocab']; if (iri.indexOf(vocab) === 0 && iri !== vocab) { // use suffix as relative iri if it is not a term in the active context var suffix = iri.substr(vocab.length); if (!(suffix in activeCtx.mappings)) { return suffix; } } } } // no term or @vocab match, check for possible CURIEs var choice = null; // TODO: make FastCurieMap a class with a method to do this lookup var partialMatches = []; var iriMap = activeCtx.fastCurieMap; // check for partial matches of against `iri`, which means look until // iri.length - 1, not full length var maxPartialLength = iri.length - 1; for (var _i2 = 0; _i2 < maxPartialLength && iri[_i2] in iriMap; ++_i2) { iriMap = iriMap[iri[_i2]]; if ('' in iriMap) { partialMatches.push(iriMap[''][0]); } } // check partial matches in reverse order to prefer longest ones first for (var _i3 = partialMatches.length - 1; _i3 >= 0; --_i3) { var entry = partialMatches[_i3]; var terms = entry.terms; for (var ti = 0; ti < terms.length; ++ti) { // a CURIE is usable if: // 1. it has no mapping, OR // 2. value is null, which means we're not compacting an @value, AND // the mapping matches the IRI var curie = terms[ti] + ':' + iri.substr(entry.iri.length); var isUsableCurie = !(curie in activeCtx.mappings) || value === null && activeCtx.mappings[curie]['@id'] === iri; // select curie if it is shorter or the same length but lexicographically // less than the current choice if (isUsableCurie && (choice === null || _compareShortestLeast(curie, choice) < 0)) { choice = curie; } } } // return chosen curie if (choice !== null) { return choice; } // compact IRI relative to base if (!relativeTo.vocab) { return _removeBase(activeCtx['@base'], iri); } // return IRI as is return iri; }; /** * Performs value compaction on an object with '@value' or '@id' as the only * property. * * @param activeCtx the active context. * @param activeProperty the active property that points to the value. * @param value the value to compact. * * @return the compaction result. */ api.compactValue = function (_ref3) { var activeCtx = _ref3.activeCtx, activeProperty = _ref3.activeProperty, value = _ref3.value; // value is a @value if (_isValue(value)) { // get context rules var _type = _getContextValue(activeCtx, activeProperty, '@type'); var language = _getContextValue(activeCtx, activeProperty, '@language'); var container = _getContextValue(activeCtx, activeProperty, '@container') || []; // whether or not the value has an @index that must be preserved var preserveIndex = '@index' in value && !container.includes('@index'); // if there's no @index to preserve ... if (!preserveIndex) { // matching @type or @language specified in context, compact value if (value['@type'] === _type || value['@language'] === language) { return value['@value']; } } // return just the value of @value if all are true: // 1. @value is the only key or @index isn't being preserved // 2. there is no default language or @value is not a string or // the key has a mapping with a null @language var keyCount = Object.keys(value).length; var isValueOnlyKey = keyCount === 1 || keyCount === 2 && '@index' in value && !preserveIndex; var hasDefaultLanguage = '@language' in activeCtx; var isValueString = _isString(value['@value']); var hasNullMapping = activeCtx.mappings[activeProperty] && activeCtx.mappings[activeProperty]['@language'] === null; if (isValueOnlyKey && (!hasDefaultLanguage || !isValueString || hasNullMapping)) { return value['@value']; } var rval = {}; // preserve @index if (preserveIndex) { rval[api.compactIri({ activeCtx: activeCtx, iri: '@index', relativeTo: { vocab: true } })] = value['@index']; } if ('@type' in value) { // compact @type IRI rval[api.compactIri({ activeCtx: activeCtx, iri: '@type', relativeTo: { vocab: true } })] = api.compactIri({ activeCtx: activeCtx, iri: value['@type'], relativeTo: { vocab: true } }); } else if ('@language' in value) { // alias @language rval[api.compactIri({ activeCtx: activeCtx, iri: '@language', relativeTo: { vocab: true } })] = value['@language']; } // alias @value rval[api.compactIri({ activeCtx: activeCtx, iri: '@value', relativeTo: { vocab: true } })] = value['@value']; return rval; } // value is a subject reference var expandedProperty = _expandIri(activeCtx, activeProperty, { vocab: true }); var type = _getContextValue(activeCtx, activeProperty, '@type'); var compacted = api.compactIri({ activeCtx: activeCtx, iri: value['@id'], relativeTo: { vocab: type === '@vocab' } }); // compact to scalar if (type === '@id' || type === '@vocab' || expandedProperty === '@graph') { return compacted; } return _defineProperty({}, api.compactIri({ activeCtx: activeCtx, iri: '@id', relativeTo: { vocab: true } }), compacted); }; /** * Removes the @preserve keywords as the last step of the compaction * algorithm when it is running on framed output. * * @param ctx the active context used to compact the input. * @param input the framed, compacted output. * @param options the compaction options used. * * @return the resulting output. */ api.removePreserve = function (ctx, input, options) { // recurse through arrays if (_isArray(input)) { var output = []; for (var i = 0; i < input.length; ++i) { var result = api.removePreserve(ctx, input[i], options); // drop nulls from arrays if (result !== null) { output.push(result); } } input = output; } else if (_isObject(input)) { // remove @preserve if ('@preserve' in input) { if (input['@preserve'] === '@null') { return null; } return input['@preserve']; } // skip @values if (_isValue(input)) { return input; } // recurse through @lists if (_isList(input)) { input['@list'] = api.removePreserve(ctx, input['@list'], options); return input; } // handle in-memory linked nodes var idAlias = api.compactIri({ activeCtx: ctx, iri: '@id', relativeTo: { vocab: true } }); if (idAlias in input) { var id = input[idAlias]; if (id in options.link) { var idx = options.link[id].indexOf(input); if (idx !== -1) { // already visited return options.link[id][idx]; } // prevent circular visitation options.link[id].push(input); } else { // prevent circular visitation options.link[id] = [input]; } } // recurse through properties for (var prop in input) { var _result = api.removePreserve(ctx, input[prop], options); var container = _getContextValue(ctx, prop, '@container') || []; if (options.compactArrays && _isArray(_result) && _result.length === 1 && container.length === 0) { _result = _result[0]; } input[prop] = _result; } } return input; }; /** * Picks the preferred compaction term from the given inverse context entry. * * @param activeCtx the active context. * @param iri the IRI to pick the term for. * @param value the value to pick the term for. * @param containers the preferred containers. * @param typeOrLanguage either '@type' or '@language'. * @param typeOrLanguageValue the preferred value for '@type' or '@language'. * * @return the preferred term. */ function _selectTerm(activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) { if (typeOrLanguageValue === null) { typeOrLanguageValue = '@null'; } // preferences for the value of @type or @language var prefs = []; // determine prefs for @id based on whether or not value compacts to a term if ((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') && _isSubjectReference(value)) { // prefer @reverse first if (typeOrLanguageValue === '@reverse') { prefs.push('@reverse'); } // try to compact value to a term var term = api.compactIri({ activeCtx: activeCtx, iri: value['@id'], relativeTo: { vocab: true } }); if (term in activeCtx.mappings && activeCtx.mappings[term] && activeCtx.mappings[term]['@id'] === value['@id']) { // prefer @vocab prefs.push.apply(prefs, ['@vocab', '@id']); } else { // prefer @id prefs.push.apply(prefs, ['@id', '@vocab']); } } else { prefs.push(typeOrLanguageValue); } prefs.push('@none'); var containerMap = activeCtx.inverse[iri]; for (var ci = 0; ci < containers.length; ++ci) { // if container not available in the map, continue var container = containers[ci]; if (!(container in containerMap)) { continue; } var typeOrLanguageValueMap = containerMap[container][typeOrLanguage]; for (var pi = 0; pi < prefs.length; ++pi) { // if type/language option not available in the map, continue var pref = prefs[pi]; if (!(pref in typeOrLanguageValueMap)) { continue; } // select term return typeOrLanguageValueMap[pref]; } } return null; } /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var _require = __webpack_require__(2), parseLinkHeader = _require.parseLinkHeader, buildHeaders = _require.buildHeaders; var _require2 = __webpack_require__(24), LINK_HEADER_REL = _require2.LINK_HEADER_REL; var JsonLdError = __webpack_require__(6); var RequestQueue = __webpack_require__(50); /** * Creates a built-in node document loader. * * @param options the options to use: * secure: require all URLs to use HTTPS. * strictSSL: true to require SSL certificates to be valid, * false not to (default: true). * maxRedirects: the maximum number of redirects to permit, none by * default. * request: the object which will make the request, default is * provided by `https://www.npmjs.com/package/request`. * headers: an object (map) of headers which will be passed as request * headers for the requested document. Accept is not allowed. * * @return the node document loader. */ module.exports = function () { var loadDocument = function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url, redirects) { var doc, result, _result, res, body, statusText, linkHeader; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0)) { _context.next = 2; break; } throw new JsonLdError('URL could not be dereferenced; only "http" and "https" URLs are ' + 'supported.', 'jsonld.InvalidUrl', { code: 'loading document failed', url: url }); case 2: if (!(secure && url.indexOf('https') !== 0)) { _context.next = 4; break; } throw new JsonLdError('URL could not be dereferenced; secure mode is enabled and ' + 'the URL\'s scheme is not "https".', 'jsonld.InvalidUrl', { code: 'loading document failed', url: url }); case 4: // TODO: disable cache until HTTP caching implemented doc = null; //cache.get(url); if (!(doc !== null)) { _context.next = 7; break; } return _context.abrupt('return', doc); case 7: result = void 0; _context.prev = 8; _context.next = 11; return _request(request, { url: url, headers: headers, strictSSL: strictSSL, followRedirect: false }); case 11: result = _context.sent; _context.next = 17; break; case 14: _context.prev = 14; _context.t0 = _context['catch'](8); throw new JsonLdError('URL could not be dereferenced, an error occurred.', 'jsonld.LoadDocumentError', { code: 'loading document failed', url: url, cause: _context.t0 }); case 17: _result = result, res = _result.res, body = _result.body; doc = { contextUrl: null, documentUrl: url, document: body || null }; // handle error statusText = http.STATUS_CODES[res.statusCode]; if (!(res.statusCode >= 400)) { _context.next = 22; break; } throw new JsonLdError('URL could not be dereferenced: ' + statusText, 'jsonld.InvalidUrl', { code: 'loading document failed', url: url, httpStatusCode: res.statusCode }); case 22: if (!(res.headers.link && res.headers['content-type'] !== 'application/ld+json')) { _context.next = 27; break; } // only 1 related link header permitted linkHeader = parseLinkHeader(res.headers.link)[LINK_HEADER_REL]; if (!Array.isArray(linkHeader)) { _context.next = 26; break; } throw new JsonLdError('URL could not be dereferenced, it has more than one associated ' + 'HTTP Link Header.', 'jsonld.InvalidUrl', { code: 'multiple context link headers', url: url }); case 26: if (linkHeader) { doc.contextUrl = linkHeader.target; } case 27: if (!(res.statusCode >= 300 && res.statusCode < 400 && res.headers.location)) { _context.next = 34; break; } if (!(redirects.length === maxRedirects)) { _context.next = 30; break; } throw new JsonLdError('URL could not be dereferenced; there were too many redirects.', 'jsonld.TooManyRedirects', { code: 'loading document failed', url: url, httpStatusCode: res.statusCode, redirects: redirects }); case 30: if (!(redirects.indexOf(url) !== -1)) { _context.next = 32; break; } throw new JsonLdError('URL could not be dereferenced; infinite redirection was detected.', 'jsonld.InfiniteRedirectDetected', { code: 'recursive context inclusion', url: url, httpStatusCode: res.statusCode, redirects: redirects }); case 32: redirects.push(url); return _context.abrupt('return', loadDocument(res.headers.location, redirects)); case 34: // cache for each redirected URL redirects.push(url); // TODO: disable cache until HTTP caching implemented /*for(let i = 0; i < redirects.length; ++i) { cache.set( redirects[i], {contextUrl: null, documentUrl: redirects[i], document: body}); }*/ return _context.abrupt('return', doc); case 36: case 'end': return _context.stop(); } } }, _callee, this, [[8, 14]]); })); return function loadDocument(_x2, _x3) { return _ref2.apply(this, arguments); }; }(); var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { strictSSL: true, maxRedirects: -1, headers: {} }, secure = _ref.secure, _ref$strictSSL = _ref.strictSSL, strictSSL = _ref$strictSSL === undefined ? true : _ref$strictSSL, _ref$maxRedirects = _ref.maxRedirects, maxRedirects = _ref$maxRedirects === undefined ? -1 : _ref$maxRedirects, request = _ref.request, _ref$headers = _ref.headers, headers = _ref$headers === undefined ? {} : _ref$headers; headers = buildHeaders(headers); // TODO: use `r2` request = request || __webpack_require__(49); var http = __webpack_require__(49); // TODO: disable cache until HTTP caching implemented //const cache = new DocumentCache(); var queue = new RequestQueue(); return queue.wrapLoader(function (url) { return loadDocument(url, []); }); }; function _request(request, options) { return new Promise(function (resolve, reject) { request(options, function (err, res, body) { if (err) { reject(err); } else { resolve({ res: res, body: body }); } }); }); } /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } var _require = __webpack_require__(2), parseLinkHeader = _require.parseLinkHeader, buildHeaders = _require.buildHeaders; var _require2 = __webpack_require__(24), LINK_HEADER_REL = _require2.LINK_HEADER_REL; var JsonLdError = __webpack_require__(6); var RequestQueue = __webpack_require__(50); var REGEX_LINK_HEADER = /(^|(\r\n))link:/i; /** * Creates a built-in XMLHttpRequest document loader. * * @param options the options to use: * secure: require all URLs to use HTTPS. * headers: an object (map) of headers which will be passed as request * headers for the requested document. Accept is not allowed. * [xhr]: the XMLHttpRequest API to use. * * @return the XMLHttpRequest document loader. */ module.exports = function () { var loader = function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) { var req, doc, contentType, linkHeader; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0)) { _context.next = 2; break; } throw new JsonLdError('URL could not be dereferenced; only "http" and "https" URLs are ' + 'supported.', 'jsonld.InvalidUrl', { code: 'loading document failed', url: url }); case 2: if (!(secure && url.indexOf('https') !== 0)) { _context.next = 4; break; } throw new JsonLdError('URL could not be dereferenced; secure mode is enabled and ' + 'the URL\'s scheme is not "https".', 'jsonld.InvalidUrl', { code: 'loading document failed', url: url }); case 4: req = void 0; _context.prev = 5; _context.next = 8; return _get(xhr, url, headers); case 8: req = _context.sent; _context.next = 14; break; case 11: _context.prev = 11; _context.t0 = _context['catch'](5); throw new JsonLdError('URL could not be dereferenced, an error occurred.', 'jsonld.LoadDocumentError', { code: 'loading document failed', url: url, cause: _context.t0 }); case 14: if (!(req.status >= 400)) { _context.next = 16; break; } throw new JsonLdError('URL could not be dereferenced: ' + req.statusText, 'jsonld.LoadDocumentError', { code: 'loading document failed', url: url, httpStatusCode: req.status }); case 16: doc = { contextUrl: null, documentUrl: url, document: req.response }; // handle Link Header (avoid unsafe header warning by existence testing) contentType = req.getResponseHeader('Content-Type'); linkHeader = void 0; if (REGEX_LINK_HEADER.test(req.getAllResponseHeaders())) { linkHeader = req.getResponseHeader('Link'); } if (!(linkHeader && contentType !== 'application/ld+json')) { _context.next = 25; break; } // only 1 related link header permitted linkHeader = parseLinkHeader(linkHeader)[LINK_HEADER_REL]; if (!Array.isArray(linkHeader)) { _context.next = 24; break; } throw new JsonLdError('URL could not be dereferenced, it has more than one ' + 'associated HTTP Link Header.', 'jsonld.InvalidUrl', { code: 'multiple context link headers', url: url }); case 24: if (linkHeader) { doc.contextUrl = linkHeader.target; } case 25: return _context.abrupt('return', doc); case 26: case 'end': return _context.stop(); } } }, _callee, this, [[5, 11]]); })); return function loader(_x2) { return _ref2.apply(this, arguments); }; }(); var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { headers: {} }, secure = _ref.secure, _ref$headers = _ref.headers, headers = _ref$headers === undefined ? {} : _ref$headers, xhr = _ref.xhr; headers = buildHeaders(headers); var queue = new RequestQueue(); return queue.wrapLoader(loader); }; function _get(xhr, url, headers) { xhr = xhr || XMLHttpRequest; var req = new xhr(); return new Promise(function (resolve, reject) { req.onload = function () { return resolve(req); }; req.onerror = function (err) { return reject(err); }; req.open('GET', url, true); for (var k in headers) { req.setRequestHeader(k, headers[k]); } req.send(); }); } /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = function (jsonld) { var JsonLdProcessor = function () { function JsonLdProcessor() { _classCallCheck(this, JsonLdProcessor); } _createClass(JsonLdProcessor, [{ key: 'toString', value: function toString() { return '[object JsonLdProcessor]'; } }]); return JsonLdProcessor; }(); Object.defineProperty(JsonLdProcessor, 'prototype', { writable: false, enumerable: false }); Object.defineProperty(JsonLdProcessor.prototype, 'constructor', { writable: true, enumerable: false, configurable: true, value: JsonLdProcessor }); // The Web IDL test harness will check the number of parameters defined in // the functions below. The number of parameters must exactly match the // required (non-optional) parameters of the JsonLdProcessor interface as // defined here: // https://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface JsonLdProcessor.compact = function (input, ctx) { if (arguments.length < 2) { return Promise.reject(new TypeError('Could not compact, too few arguments.')); } return jsonld.compact(input, ctx); }; JsonLdProcessor.expand = function (input) { if (arguments.length < 1) { return Promise.reject(new TypeError('Could not expand, too few arguments.')); } return jsonld.expand(input); }; JsonLdProcessor.flatten = function (input) { if (arguments.length < 1) { return Promise.reject(new TypeError('Could not flatten, too few arguments.')); } return jsonld.flatten(input); }; return JsonLdProcessor; }; /***/ }), /* 139 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }) /******/ ]); });
/** * @ngdoc model * @name BackOfficeTreeDisplay * @function * * @description * Represents a JS version of BackOfficeTreeDisplay object */ var BackOfficeTreeDisplay = function() { var self = this; self.routeId = ''; self.parentRouteId = ''; self.title = ''; self.icon = ''; self.routePath = ''; self.sortOrder = 0; }; angular.module('merchello.models').constant('BackOfficeTreeDisplay', BackOfficeTreeDisplay);
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; module.exports = require('./src/dom/Drag');
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the ParameterGroupingPostOptionalParameters class. * @constructor * Additional parameters for the ParameterGrouping_postOptional operation. * * @member {string} [customHeader] * * @member {number} [query] Query parameter with default. Default value: 30 . * */ function ParameterGroupingPostOptionalParameters() { } /** * Defines the metadata of ParameterGroupingPostOptionalParameters * * @returns {object} metadata of ParameterGroupingPostOptionalParameters * */ ParameterGroupingPostOptionalParameters.prototype.mapper = function () { return { required: false, type: { name: 'Composite', className: 'ParameterGroupingPostOptionalParameters', modelProperties: { customHeader: { required: false, type: { name: 'String' } }, query: { required: false, defaultValue: 30, type: { name: 'Number' } } } } }; }; module.exports = ParameterGroupingPostOptionalParameters;
import Ember from 'ember-metal/core'; import {set} from 'ember-metal/property_set'; import run from 'ember-metal/run_loop'; import {observer as emberObserver} from 'ember-metal/mixin'; import {listenersFor} from 'ember-metal/events'; import ArrayProxy from 'ember-runtime/system/array_proxy'; import SortableMixin from 'ember-runtime/mixins/sortable'; import EmberObject from 'ember-runtime/system/object'; import ArrayController, { arrayControllerDeprecation } from 'ember-runtime/controllers/array_controller'; var unsortedArray, sortedArrayController; QUnit.module('Ember.Sortable'); QUnit.module('Ember.Sortable with content', { setup() { run(function() { var array = [{ id: 1, name: 'Scumbag Dale' }, { id: 2, name: 'Scumbag Katz' }, { id: 3, name: 'Scumbag Bryn' }]; unsortedArray = Ember.A(Ember.A(array).copy()); sortedArrayController = ArrayProxy.extend(SortableMixin).create({ content: unsortedArray }); }); }, teardown() { run(function() { sortedArrayController.set('content', null); sortedArrayController.destroy(); }); } }); QUnit.test('if you do not specify `sortProperties` sortable have no effect', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(0).name, 'Scumbag Dale', 'array is in it natural order'); unsortedArray.pushObject({ id: 4, name: 'Scumbag Chavard' }); equal(sortedArrayController.get('length'), 4, 'array has 4 items'); equal(sortedArrayController.objectAt(3).name, 'Scumbag Chavard', 'a new object was inserted in the natural order'); sortedArrayController.set('sortProperties', []); unsortedArray.pushObject({ id: 5, name: 'Scumbag Jackson' }); equal(sortedArrayController.get('length'), 5, 'array has 5 items'); equal(sortedArrayController.objectAt(4).name, 'Scumbag Jackson', 'a new object was inserted in the natural order with empty array as sortProperties'); }); QUnit.test('you can change sorted properties', function() { sortedArrayController.set('sortProperties', ['id']); equal(sortedArrayController.objectAt(0).name, 'Scumbag Dale', 'array is sorted by id'); equal(sortedArrayController.get('length'), 3, 'array has 3 items'); sortedArrayController.set('sortAscending', false); equal(sortedArrayController.objectAt(0).name, 'Scumbag Bryn', 'array is sorted by id in DESC order'); equal(sortedArrayController.objectAt(2).name, 'Scumbag Dale', 'array is sorted by id in DESC order'); equal(sortedArrayController.get('length'), 3, 'array has 3 items'); sortedArrayController.set('sortProperties', ['name']); equal(sortedArrayController.objectAt(0).name, 'Scumbag Katz', 'array is sorted by name in DESC order'); equal(sortedArrayController.get('length'), 3, 'array has 3 items'); }); QUnit.test('changing sort order triggers observers', function() { var observer; var changeCount = 0; observer = EmberObject.extend({ arrangedDidChange: emberObserver('array.[]', function() { changeCount++; }) }).create({ array: sortedArrayController }); equal(changeCount, 0, 'precond - changeCount starts at 0'); sortedArrayController.set('sortProperties', ['id']); equal(changeCount, 1, 'setting sortProperties increments changeCount'); sortedArrayController.set('sortAscending', false); equal(changeCount, 2, 'changing sortAscending increments changeCount'); sortedArrayController.set('sortAscending', true); equal(changeCount, 3, 'changing sortAscending again increments changeCount'); run(function() { observer.destroy(); }); }); QUnit.test('changing sortProperties and sortAscending with setProperties, sortProperties appearing first', function() { sortedArrayController.set('sortProperties', ['name']); sortedArrayController.set('sortAscending', false); equal(sortedArrayController.objectAt(0).name, 'Scumbag Katz', 'array is sorted by name in DESC order'); equal(sortedArrayController.objectAt(2).name, 'Scumbag Bryn', 'array is sorted by name in DESC order'); sortedArrayController.setProperties({ sortProperties: ['id'], sortAscending: true }); equal(sortedArrayController.objectAt(0).id, 1, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).id, 3, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); sortedArrayController.setProperties({ sortProperties: ['name'], sortAscending: false }); equal(sortedArrayController.objectAt(0).name, 'Scumbag Katz', 'array is sorted by name in DESC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).name, 'Scumbag Bryn', 'array is sorted by name in DESC order after setting sortAscending and sortProperties'); sortedArrayController.setProperties({ sortProperties: ['id'], sortAscending: false }); equal(sortedArrayController.objectAt(0).id, 3, 'array is sorted by id in DESC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).id, 1, 'array is sorted by id in DESC order after setting sortAscending and sortProperties'); sortedArrayController.setProperties({ sortProperties: ['id'], sortAscending: true }); equal(sortedArrayController.objectAt(0).id, 1, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).id, 3, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); }); QUnit.test('changing sortProperties and sortAscending with setProperties, sortAscending appearing first', function() { sortedArrayController.set('sortProperties', ['name']); sortedArrayController.set('sortAscending', false); equal(sortedArrayController.objectAt(0).name, 'Scumbag Katz', 'array is sorted by name in DESC order'); equal(sortedArrayController.objectAt(2).name, 'Scumbag Bryn', 'array is sorted by name in DESC order'); sortedArrayController.setProperties({ sortAscending: true, sortProperties: ['id'] }); equal(sortedArrayController.objectAt(0).id, 1, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).id, 3, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); sortedArrayController.setProperties({ sortAscending: false, sortProperties: ['name'] }); equal(sortedArrayController.objectAt(0).name, 'Scumbag Katz', 'array is sorted by name in DESC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).name, 'Scumbag Bryn', 'array is sorted by name in DESC order after setting sortAscending and sortProperties'); sortedArrayController.setProperties({ sortAscending: false, sortProperties: ['id'] }); equal(sortedArrayController.objectAt(0).id, 3, 'array is sorted by id in DESC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).id, 1, 'array is sorted by id in DESC order after setting sortAscending and sortProperties'); sortedArrayController.setProperties({ sortAscending: true, sortProperties: ['id'] }); equal(sortedArrayController.objectAt(0).id, 1, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); equal(sortedArrayController.objectAt(2).id, 3, 'array is sorted by id in ASC order after setting sortAscending and sortProperties'); }); QUnit.module('Ember.Sortable with content and sortProperties', { setup() { run(function() { var array = [{ id: 1, name: 'Scumbag Dale' }, { id: 2, name: 'Scumbag Katz' }, { id: 3, name: 'Scumbag Bryn' }]; unsortedArray = Ember.A(Ember.A(array).copy()); expectDeprecation(arrayControllerDeprecation); sortedArrayController = ArrayController.create({ content: unsortedArray, sortProperties: ['name'] }); }); }, teardown() { run(function() { sortedArrayController.destroy(); }); } }); QUnit.test('sortable object will expose associated content in the right order', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(0).name, 'Scumbag Bryn', 'array is sorted by name'); }); QUnit.test('you can add objects in sorted order', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); unsortedArray.pushObject({ id: 4, name: 'Scumbag Chavard' }); equal(sortedArrayController.get('length'), 4, 'array has 4 items'); equal(sortedArrayController.objectAt(1).name, 'Scumbag Chavard', 'a new object added to content was inserted according to given constraint'); sortedArrayController.addObject({ id: 5, name: 'Scumbag Fucs' }); equal(sortedArrayController.get('length'), 5, 'array has 5 items'); equal(sortedArrayController.objectAt(3).name, 'Scumbag Fucs', 'a new object added to controller was inserted according to given constraint'); }); QUnit.test('you can push objects in sorted order', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); unsortedArray.pushObject({ id: 4, name: 'Scumbag Chavard' }); equal(sortedArrayController.get('length'), 4, 'array has 4 items'); equal(sortedArrayController.objectAt(1).name, 'Scumbag Chavard', 'a new object added to content was inserted according to given constraint'); sortedArrayController.pushObject({ id: 5, name: 'Scumbag Fucs' }); equal(sortedArrayController.get('length'), 5, 'array has 5 items'); equal(sortedArrayController.objectAt(3).name, 'Scumbag Fucs', 'a new object added to controller was inserted according to given constraint'); }); QUnit.test('you can unshift objects in sorted order', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); unsortedArray.unshiftObject({ id: 4, name: 'Scumbag Chavard' }); equal(sortedArrayController.get('length'), 4, 'array has 4 items'); equal(sortedArrayController.objectAt(1).name, 'Scumbag Chavard', 'a new object added to content was inserted according to given constraint'); sortedArrayController.addObject({ id: 5, name: 'Scumbag Fucs' }); equal(sortedArrayController.get('length'), 5, 'array has 5 items'); equal(sortedArrayController.objectAt(3).name, 'Scumbag Fucs', 'a new object added to controller was inserted according to given constraint'); }); QUnit.test('addObject does not insert duplicates', function() { var sortedArrayProxy; var obj = {}; sortedArrayProxy = ArrayProxy.extend(SortableMixin).create({ content: Ember.A([obj]) }); equal(sortedArrayProxy.get('length'), 1, 'array has 1 item'); sortedArrayProxy.addObject(obj); equal(sortedArrayProxy.get('length'), 1, 'array still has 1 item'); }); QUnit.test('you can change a sort property and the content will rearrange', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(0).name, 'Scumbag Bryn', 'bryn is first'); set(sortedArrayController.objectAt(0), 'name', 'Scumbag Fucs'); equal(sortedArrayController.objectAt(0).name, 'Scumbag Dale', 'dale is first now'); equal(sortedArrayController.objectAt(1).name, 'Scumbag Fucs', 'foucs is second'); }); QUnit.test('you can change the position of the middle item', function() { equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(1).name, 'Scumbag Dale', 'Dale is second'); set(sortedArrayController.objectAt(1), 'name', 'Alice'); // Change Dale to Alice equal(sortedArrayController.objectAt(0).name, 'Alice', 'Alice (previously Dale) is first now'); }); QUnit.test('don\'t remove and insert if position didn\'t change', function() { var insertItemSortedCalled = false; sortedArrayController.reopen({ insertItemSorted(item) { insertItemSortedCalled = true; this._super(item); } }); sortedArrayController.set('sortProperties', ['name']); set(sortedArrayController.objectAt(0), 'name', 'Scumbag Brynjolfsson'); ok(!insertItemSortedCalled, 'insertItemSorted should not have been called'); }); QUnit.test('sortProperties observers removed on content removal', function() { var removedObject = unsortedArray.objectAt(2); equal(listenersFor(removedObject, 'name:change').length, 1, 'Before removal, there should be one listener for sortProperty change.'); unsortedArray.replace(2, 1, []); equal(listenersFor(removedObject, 'name:change').length, 0, 'After removal, there should be no listeners for sortProperty change.'); }); QUnit.module('Ember.Sortable with sortProperties', { setup() { run(function() { expectDeprecation(arrayControllerDeprecation); sortedArrayController = ArrayController.create({ sortProperties: ['name'] }); var array = [{ id: 1, name: 'Scumbag Dale' }, { id: 2, name: 'Scumbag Katz' }, { id: 3, name: 'Scumbag Bryn' }]; unsortedArray = Ember.A(Ember.A(array).copy()); }); }, teardown() { run(function() { sortedArrayController.destroy(); }); } }); QUnit.test('you can set content later and it will be sorted', function() { equal(sortedArrayController.get('length'), 0, 'array has 0 items'); run(function() { sortedArrayController.set('content', unsortedArray); }); equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(0).name, 'Scumbag Bryn', 'array is sorted by name'); }); QUnit.module('Ember.Sortable with sortFunction and sortProperties', { setup() { run(function() { expectDeprecation(arrayControllerDeprecation); sortedArrayController = ArrayController.create({ sortProperties: ['name'], sortFunction(v, w) { var lowerV = v.toLowerCase(); var lowerW = w.toLowerCase(); if (lowerV < lowerW) { return -1; } if (lowerV > lowerW) { return 1; } return 0; } }); var array = [{ id: 1, name: 'Scumbag Dale' }, { id: 2, name: 'Scumbag Katz' }, { id: 3, name: 'Scumbag bryn' }]; unsortedArray = Ember.A(Ember.A(array).copy()); }); }, teardown() { run(function() { sortedArrayController.destroy(); }); } }); QUnit.test('you can sort with custom sorting function', function() { equal(sortedArrayController.get('length'), 0, 'array has 0 items'); run(function() { sortedArrayController.set('content', unsortedArray); }); equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(0).name, 'Scumbag bryn', 'array is sorted by custom sort'); }); QUnit.test('Ember.Sortable with sortFunction on ArrayProxy should work like ArrayController', function() { run(function() { sortedArrayController = ArrayProxy.extend(SortableMixin).create({ sortProperties: ['name'], sortFunction(v, w) { var lowerV = v.toLowerCase(); var lowerW = w.toLowerCase(); if (lowerV < lowerW) { return -1; } if (lowerV > lowerW) { return 1; } return 0; } }); var array = [{ id: 1, name: 'Scumbag Dale' }, { id: 2, name: 'Scumbag Katz' }, { id: 3, name: 'Scumbag Bryn' }]; unsortedArray = Ember.A(Ember.A(array).copy()); }); equal(sortedArrayController.get('length'), 0, 'array has 0 items'); run(function() { sortedArrayController.set('content', unsortedArray); }); equal(sortedArrayController.get('length'), 3, 'array has 3 items'); equal(sortedArrayController.objectAt(0).name, 'Scumbag Bryn', 'array is sorted by name'); });
import "rxjs"; import "rxjs/operators"; const __globalThis = "undefined" !== typeof globalThis && globalThis; const __window = "undefined" !== typeof window && window; const __self = "undefined" !== typeof self && "undefined" !== typeof WorkerGlobalScope && self instanceof WorkerGlobalScope && self; const __global = "undefined" !== typeof global && global; const _global = __globalThis || __global || __window || __self; if (ngDevMode) _global.$localize = _global.$localize || function() { throw new Error("It looks like your application or one of its dependencies is using i18n.\n" + "Angular 9 introduced a global `$localize()` function that needs to be loaded.\n" + "Please run `ng add @angular/localize` from the Angular CLI.\n" + "(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.\n" + "For server-side rendering applications add the import to your `main.server.ts` file.)"); };
import { typeOf } from '../../lib/type-of'; import EmberObject from '../../lib/system/object'; import { window } from '@ember/-internals/browser-environment'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'Ember Type Checking', class extends AbstractTestCase { ['@test Ember.typeOf'](assert) { let MockedDate = function() {}; MockedDate.prototype = new Date(); let mockedDate = new MockedDate(); let date = new Date(); let error = new Error('boum'); let object = { a: 'b' }; let a = null; let arr = [1, 2, 3]; let obj = {}; let instance = EmberObject.create({ method() {} }); assert.equal(typeOf(), 'undefined', 'undefined'); assert.equal(typeOf(null), 'null', 'null'); assert.equal(typeOf('Cyril'), 'string', 'Cyril'); assert.equal(typeOf(101), 'number', '101'); assert.equal(typeOf(true), 'boolean', 'true'); assert.equal(typeOf([1, 2, 90]), 'array', '[1,2,90]'); assert.equal(typeOf(/abc/), 'regexp', '/abc/'); assert.equal(typeOf(date), 'date', 'new Date()'); assert.equal(typeOf(mockedDate), 'date', 'mocked date'); assert.equal(typeOf(error), 'error', 'error'); assert.equal(typeOf(object), 'object', 'object'); assert.equal(typeOf(undefined), 'undefined', 'item of type undefined'); assert.equal(typeOf(a), 'null', 'item of type null'); assert.equal(typeOf(arr), 'array', 'item of type array'); assert.equal(typeOf(obj), 'object', 'item of type object'); assert.equal(typeOf(instance), 'instance', 'item of type instance'); assert.equal(typeOf(instance.method), 'function', 'item of type function'); assert.equal(typeOf(EmberObject.extend()), 'class', 'item of type class'); assert.equal(typeOf(new Error()), 'error', 'item of type error'); } ['@test Ember.typeOf(fileList)'](assert) { if (window && typeof window.FileList === 'function') { let fileListElement = document.createElement('input'); fileListElement.type = 'file'; let fileList = fileListElement.files; assert.equal(typeOf(fileList), 'filelist', 'item of type filelist'); } else { assert.ok(true, 'FileList is not present on window'); } } } );
function makeData() { "use strict"; } function run(svg, data, Plottable) { "use strict"; d3.csv("/quicktests/overlaying/data/cities.csv").get(function(error, rows) { data = rows; var ds = new Plottable.Dataset(data); var csRange = []; for(var i = 0; i < 30; i++){ var c = "#" + Math.floor(Math.random() * 16777215).toString(16); csRange.push(c); } var cs = new Plottable.Scales.Color(); cs.range(csRange); var xScale = new Plottable.Scales.Linear().domain([-110, -90]); var yScale = new Plottable.Scales.Linear().domain([25, 40]); var xAxis = new Plottable.Axes.Numeric(xScale, "bottom"); var yAxis = new Plottable.Axes.Numeric(yScale, "left"); var plot = new Plottable.Plots.Scatter(xScale, yScale); plot.addDataset(ds); plot.x(function(d){ return d.lng; }, xScale) .y(function(d){ return d.lat; }, yScale) .attr("fill", function(d){ return d.state; }, cs); var table = new Plottable.Components.Table([[yAxis, plot], [null, xAxis]]); table.renderTo(svg); }); }
/*! * remark (http://getbootstrapadmin.com/remark) * Copyright 2016 amazingsurge * Licensed under the Themeforest Standard Licenses */ $.components.register("asRange", { mode: "default", defaults: { tip: false, scale: false } });
const Channel = require('./Channel'); const Role = require('./Role'); const PermissionOverwrites = require('./PermissionOverwrites'); const EvaluatedPermissions = require('./EvaluatedPermissions'); const Constants = require('../util/Constants'); const Collection = require('../util/Collection'); /** * Represents a guild channel (i.e. text channels and voice channels) * @extends {Channel} */ class GuildChannel extends Channel { constructor(guild, data) { super(guild.client, data); /** * The guild the channel is in * @type {Guild} */ this.guild = guild; } setup(data) { super.setup(data); /** * The name of the guild channel * @type {string} */ this.name = data.name; /** * The position of the channel in the list. * @type {number} */ this.position = data.position; /** * A map of permission overwrites in this channel for roles and users. * @type {Collection<string, PermissionOverwrites>} */ this.permissionOverwrites = new Collection(); if (data.permission_overwrites) { for (const overwrite of data.permission_overwrites) { this.permissionOverwrites.set(overwrite.id, new PermissionOverwrites(this, overwrite)); } } } /** * Gets the overall set of permissions for a user in this channel, taking into account roles and permission * overwrites. * @param {GuildMemberResolvable} member The user that you want to obtain the overall permissions for * @returns {?EvaluatedPermissions} */ permissionsFor(member) { member = this.client.resolver.resolveGuildMember(this.guild, member); if (!member) return null; if (member.id === this.guild.ownerID) return new EvaluatedPermissions(member, Constants.ALL_PERMISSIONS); let permissions = 0; const roles = member.roles; for (const role of roles.values()) permissions |= role.permissions; const overwrites = this.overwritesFor(member, true, roles); for (const overwrite of overwrites.role.concat(overwrites.member)) { permissions &= ~overwrite.deny; permissions |= overwrite.allow; } const admin = Boolean(permissions & Constants.PermissionFlags.ADMINISTRATOR); if (admin) permissions = Constants.ALL_PERMISSIONS; return new EvaluatedPermissions(member, permissions); } overwritesFor(member, verified = false, roles = null) { if (!verified) member = this.client.resolver.resolveGuildMember(this.guild, member); if (!member) return []; roles = roles || member.roles; const roleOverwrites = []; const memberOverwrites = []; for (const overwrite of this.permissionOverwrites.values()) { if (overwrite.id === member.id) { memberOverwrites.push(overwrite); } else if (roles.has(overwrite.id)) { roleOverwrites.push(overwrite); } } return { role: roleOverwrites, member: memberOverwrites, }; } /** * An object mapping permission flags to `true` (enabled) or `false` (disabled) * ```js * { * 'SEND_MESSAGES': true, * 'ATTACH_FILES': false, * } * ``` * @typedef {Object} PermissionOverwriteOptions */ /** * Overwrites the permissions for a user or role in this channel. * @param {RoleResolvable|UserResolvable} userOrRole The user or role to update * @param {PermissionOverwriteOptions} options The configuration for the update * @returns {Promise} * @example * // overwrite permissions for a message author * message.channel.overwritePermissions(message.author, { * SEND_MESSAGES: false * }) * .then(() => console.log('Done!')) * .catch(console.error); */ overwritePermissions(userOrRole, options) { const payload = { allow: 0, deny: 0, }; if (userOrRole instanceof Role) { payload.type = 'role'; } else if (this.guild.roles.has(userOrRole)) { userOrRole = this.guild.roles.get(userOrRole); payload.type = 'role'; } else { userOrRole = this.client.resolver.resolveUser(userOrRole); payload.type = 'member'; if (!userOrRole) return Promise.reject(new TypeError('Supplied parameter was neither a User nor a Role.')); } payload.id = userOrRole.id; const prevOverwrite = this.permissionOverwrites.get(userOrRole.id); if (prevOverwrite) { payload.allow = prevOverwrite.allow; payload.deny = prevOverwrite.deny; } for (const perm in options) { if (options[perm] === true) { payload.allow |= Constants.PermissionFlags[perm] || 0; payload.deny &= ~(Constants.PermissionFlags[perm] || 0); } else if (options[perm] === false) { payload.allow &= ~(Constants.PermissionFlags[perm] || 0); payload.deny |= Constants.PermissionFlags[perm] || 0; } else if (options[perm] === null) { payload.allow &= ~(Constants.PermissionFlags[perm] || 0); payload.deny &= ~(Constants.PermissionFlags[perm] || 0); } } return this.client.rest.methods.setChannelOverwrite(this, payload); } /** * The data for a guild channel * @typedef {Object} ChannelData * @property {string} [name] The name of the channel * @property {number} [position] The position of the channel * @property {string} [topic] The topic of the text channel * @property {number} [bitrate] The bitrate of the voice channel * @property {number} [userLimit] The user limit of the channel */ /** * Edits the channel * @param {ChannelData} data The new data for the channel * @returns {Promise<GuildChannel>} * @example * // edit a channel * channel.edit({name: 'new-channel'}) * .then(c => console.log(`Edited channel ${c}`)) * .catch(console.error); */ edit(data) { return this.client.rest.methods.updateChannel(this, data); } /** * Set a new name for the guild channel * @param {string} name The new name for the guild channel * @returns {Promise<GuildChannel>} * @example * // set a new channel name * channel.setName('not_general') * .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`)) * .catch(console.error); */ setName(name) { return this.edit({ name }); } /** * Set a new position for the guild channel * @param {number} position The new position for the guild channel * @returns {Promise<GuildChannel>} * @example * // set a new channel position * channel.setPosition(2) * .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`)) * .catch(console.error); */ setPosition(position) { return this.client.rest.methods.updateChannel(this, { position }); } /** * Set a new topic for the guild channel * @param {string} topic The new topic for the guild channel * @returns {Promise<GuildChannel>} * @example * // set a new channel topic * channel.setTopic('needs more rate limiting') * .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`)) * .catch(console.error); */ setTopic(topic) { return this.client.rest.methods.updateChannel(this, { topic }); } /** * Options given when creating a guild channel invite * @typedef {Object} InviteOptions * @property {boolean} [temporary=false] Whether the invite should kick users after 24hrs if they are not given a role * @property {number} [maxAge=0] Time in seconds the invite expires in * @property {number} [maxUses=0] Maximum amount of uses for this invite */ /** * Create an invite to this guild channel * @param {InviteOptions} [options={}] The options for the invite * @returns {Promise<Invite>} */ createInvite(options = {}) { return this.client.rest.methods.createChannelInvite(this, options); } /** * Clone this channel * @param {string} [name=this.name] Optional name for the new channel, otherwise it has the name of this channel * @param {boolean} [withPermissions=true] Whether to clone the channel with this channel's permission overwrites * @returns {Promise<GuildChannel>} */ clone(name = this.name, withPermissions = true) { return this.guild.createChannel(name, this.type, withPermissions ? this.permissionOverwrites : []); } /** * Checks if this channel has the same type, topic, position, name, overwrites and ID as another channel. * In most cases, a simple `channel.id === channel2.id` will do, and is much faster too. * @param {GuildChannel} channel Channel to compare with * @returns {boolean} */ equals(channel) { let equal = channel && this.id === channel.id && this.type === channel.type && this.topic === channel.topic && this.position === channel.position && this.name === channel.name; if (equal) { if (this.permissionOverwrites && channel.permissionOverwrites) { equal = this.permissionOverwrites.equals(channel.permissionOverwrites); } else { equal = !this.permissionOverwrites && !channel.permissionOverwrites; } } return equal; } /** * When concatenated with a string, this automatically returns the channel's mention instead of the Channel object. * @returns {string} * @example * // Outputs: Hello from #general * console.log(`Hello from ${channel}`); * @example * // Outputs: Hello from #general * console.log('Hello from ' + channel); */ toString() { return `<#${this.id}>`; } } module.exports = GuildChannel;
/* * Metadata response has `zoomMin`/`zoomMax` properties, that currently (in most cases) are constant: `1`/`21`. * But in fact, imagery for 'Aerial*' and (deprecated) 'Road' sets may be absent at high zoom levels, * depending on location. * This addon is intended to find and apply *real* maximum available zoom (for current location) on layer add. * Ref: https://stackoverflow.com/questions/12788245/bing-maps-determine-max-zoom-level-for-static-aerial-map-with-rest-imagery-api * * @option applyMaxNativeZoom: Boolean|String = 'auto' * Determines whether `applyMaxNativeZoom` method will be called on layer add. * 'auto' means that option will be active for 'Aerial*' and 'Road' imagery sets * (but only if `maxNativeZoom` is not explicitely provided in options). * * @option applyMaxNativeZoom_validityRadius: Number = 10000000 * Limits validity of 'measured' max zoom to specified radius. * Metadata requests are asynchronous, so when result is ready actual map position can be already changed. * if distance between old and new locations is longer than defined by this option, * then maxNativeZoom will be recalculated for new position. * * @method applyMaxNativeZoom(latlng: LatLng): this * Try to find maximum available zoom (for current location), and apply it as `maxNativeZoom`. * There is no official way, so use heuristic: check `vintageStart` in metadata response. * Currently method makes sense for 'Aerial*' and 'Road' imagery sets only. * * @event maxNativeZoomApplied: Event * Fired when applyMaxNativeZoom method succeed. * Extends event object with these properties: value, oldValue, latlng. */ L.BingLayer.mergeOptions({ applyMaxNativeZoom: 'auto', applyMaxNativeZoom_validityRadius: 10000000 }); L.BingLayer.addInitHook(function () { var options = this.options; if (options.applyMaxNativeZoom === 'auto' && !options.maxNativeZoom) { options.applyMaxNativeZoom = options.imagerySet === 'Road' || options.imagerySet.substring(0,6) === 'Aerial'; } if (options.applyMaxNativeZoom) { this.on('add',function () { this.applyMaxNativeZoom(this._map.getCenter()); }); } }); L.BingLayer.include({ applyMaxNativeZoom: function (latlng) { var options = this.options; // https://docs.microsoft.com/en-us/bingmaps/rest-services/imagery/get-imagery-metadata#basic-metadata-url var request = this._makeApiUrl('Imagery/BasicMetadata', L.Util.template('{imagerySet}/{centerPoint}', { imagerySet: options.imagerySet, centerPoint: L.Util.template('{lat},{lng}', latlng) })); var zoomOffset = options.zoomOffset || 0; // detectRetina sideeffects on maxZoom / maxNativeZoom this._findVintage(request, options.maxZoom + zoomOffset, function (zoom) { if (!zoom || !this._map) { return; } var newLatlng = this._map.getCenter(); var validityRadius = this.options.applyMaxNativeZoom_validityRadius; if (newLatlng.distanceTo(latlng) > validityRadius) { this.applyMaxNativeZoom(newLatlng); return; } zoom -= zoomOffset; var oldValue = options.maxNativeZoom || options.maxZoom; options.maxNativeZoom = zoom; var mapZoom = this._map.getZoom(); if (zoom<oldValue && zoom<mapZoom || zoom>oldValue && mapZoom>oldValue) { this._resetView(); } this.fire('maxNativeZoomApplied',{ latlng: latlng, value: zoom, oldValue: oldValue }); }); return this; }, _findVintage: function (request, zoomLevel, callback, context) { // there is no official way, so use heuristic: check `vintageStart` in metadata response this.callRestService(request + '&zoomLevel='+zoomLevel, function (meta) { if (meta.resourceSets[0].resources[0].vintageStart || zoomLevel === 0) { return callback.call(context || this, zoomLevel); } this._findVintage(request, zoomLevel-1, callback, context); }); } });
/** * Perform a jQuery selector action on the table's TR elements (from the tbody) and * return the resulting jQuery object. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select TR elements that meet the current filter * criterion ("applied") or all TR elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the TR elements in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {object} jQuery object, filtered by the given selector. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Highlight every second row * oTable.$('tr:odd').css('backgroundColor', 'blue'); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to rows with 'Webkit' in them, add a background colour and then * // remove the filter, thus highlighting the 'Webkit' rows only. * oTable.fnFilter('Webkit'); * oTable.$('tr', {"filter": "applied"}).css('backgroundColor', 'blue'); * oTable.fnFilter(''); * } ); */ this.$ = function ( sSelector, oOpts ) { var i, iLen, a = [], tr; var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var aoData = oSettings.aoData; var aiDisplay = oSettings.aiDisplay; var aiDisplayMaster = oSettings.aiDisplayMaster; if ( !oOpts ) { oOpts = {}; } oOpts = $.extend( {}, { "filter": "none", // applied "order": "current", // "original" "page": "all" // current }, oOpts ); // Current page implies that order=current and fitler=applied, since it is fairly // senseless otherwise if ( oOpts.page == 'current' ) { for ( i=oSettings._iDisplayStart, iLen=oSettings.fnDisplayEnd() ; i<iLen ; i++ ) { tr = aoData[ aiDisplay[i] ].nTr; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "current" && oOpts.filter == "none" ) { for ( i=0, iLen=aiDisplayMaster.length ; i<iLen ; i++ ) { tr = aoData[ aiDisplayMaster[i] ].nTr; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "current" && oOpts.filter == "applied" ) { for ( i=0, iLen=aiDisplay.length ; i<iLen ; i++ ) { tr = aoData[ aiDisplay[i] ].nTr; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "original" && oOpts.filter == "none" ) { for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { tr = aoData[ i ].nTr ; if ( tr ) { a.push( tr ); } } } else if ( oOpts.order == "original" && oOpts.filter == "applied" ) { for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { tr = aoData[ i ].nTr; if ( $.inArray( i, aiDisplay ) !== -1 && tr ) { a.push( tr ); } } } else { _fnLog( oSettings, 1, "Unknown selection options" ); } /* We need to filter on the TR elements and also 'find' in their descendants * to make the selector act like it would in a full table - so we need * to build both results and then combine them together */ var jqA = $(a); var jqTRs = jqA.filter( sSelector ); var jqDescendants = jqA.find( sSelector ); return $( [].concat($.makeArray(jqTRs), $.makeArray(jqDescendants)) ); }; /** * Almost identical to $ in operation, but in this case returns the data for the matched * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes * rather than any decendents, so the data can be obtained for the row/cell. If matching * rows are found, the data returned is the original data array/object that was used to * create the row (or a generated array if from a DOM source). * * This method is often useful incombination with $ where both functions are given the * same parameters and the array indexes will match identically. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select elements that meet the current filter * criterion ("applied") or all elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the data in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {array} Data for the matched elements. If any elements, as a result of the * selector, were not TR, TD or TH elements in the DataTable, they will have a null * entry in the array. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the data from the first row in the table * var data = oTable._('tr:first'); * * // Do something useful with the data * alert( "First cell is: "+data[0] ); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to 'Webkit' and get all data for * oTable.fnFilter('Webkit'); * var data = oTable._('tr', {"filter": "applied"}); * * // Do something with the data * alert( data.length+" rows matched the filter" ); * } ); */ this._ = function ( sSelector, oOpts ) { var aOut = []; var i, iLen, iIndex; var aTrs = this.$( sSelector, oOpts ); for ( i=0, iLen=aTrs.length ; i<iLen ; i++ ) { aOut.push( this.fnGetData(aTrs[i]) ); } return aOut; }; /** * Add a single new row or multiple rows of data to the table. Please note * that this is suitable for client-side processing only - if you are using * server-side processing (i.e. "bServerSide": true), then to add data, you * must add it to the data source, i.e. the server-side, through an Ajax call. * @param {array|object} mData The data to be added to the table. This can be: * <ul> * <li>1D array of data - add a single row with the data provided</li> * <li>2D array of arrays - add multiple rows in a single call</li> * <li>object - data object when using <i>mDataProp</i></li> * <li>array of objects - multiple data objects when using <i>mDataProp</i></li> * </ul> * @param {bool} [bRedraw=true] redraw the table or not * @returns {array} An array of integers, representing the list of indexes in * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to * the table. * @dtopt API * * @example * // Global var for counter * var giCount = 2; * * $(document).ready(function() { * $('#example').dataTable(); * } ); * * function fnClickAddRow() { * $('#example').dataTable().fnAddData( [ * giCount+".1", * giCount+".2", * giCount+".3", * giCount+".4" ] * ); * * giCount++; * } */ this.fnAddData = function( mData, bRedraw ) { if ( mData.length === 0 ) { return []; } var aiReturn = []; var iTest; /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); /* Check if we want to add multiple rows or not */ if ( typeof mData[0] === "object" && mData[0] !== null ) { for ( var i=0 ; i<mData.length ; i++ ) { iTest = _fnAddData( oSettings, mData[i] ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } } else { iTest = _fnAddData( oSettings, mData ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); if ( bRedraw === undefined || bRedraw ) { _fnReDraw( oSettings ); } return aiReturn; }; /** * This function will make DataTables recalculate the column sizes, based on the data * contained in the table and the sizes applied to the columns (in the DOM, CSS or * through the sWidth parameter). This can be useful when the width of the table's * parent element changes (for example a window resize). * @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false * } ); * * $(window).bind('resize', function () { * oTable.fnAdjustColumnSizing(); * } ); * } ); */ this.fnAdjustColumnSizing = function ( bRedraw ) { var oSettings = _fnSettingsFromNode(this[DataTable.ext.iApiIndex]); _fnAdjustColumnSizing( oSettings ); if ( bRedraw === undefined || bRedraw ) { this.fnDraw( false ); } else if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */ this.oApi._fnScrollDraw(oSettings); } }; /** * Quickly and simply clear a table * @param {bool} [bRedraw=true] redraw the table or not * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...) * oTable.fnClearTable(); * } ); */ this.fnClearTable = function( bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); _fnClearTable( oSettings ); if ( bRedraw === undefined || bRedraw ) { _fnDraw( oSettings ); } }; /** * The exact opposite of 'opening' a row, this function will close any rows which * are currently 'open'. * @param {node} nTr the table row to 'close' * @returns {int} 0 on success, or 1 if failed (can't find the row) * @dtopt API * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnClose = function( nTr ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ ) { if ( oSettings.aoOpenRows[i].nParent == nTr ) { var nTrParent = oSettings.aoOpenRows[i].nTr.parentNode; if ( nTrParent ) { /* Remove it if it is currently on display */ nTrParent.removeChild( oSettings.aoOpenRows[i].nTr ); } oSettings.aoOpenRows.splice( i, 1 ); return 0; } } return 1; }; /** * Remove a row for the table * @param {mixed} mTarget The index of the row from aoData to be deleted, or * the TR element you want to delete * @param {function|null} [fnCallBack] Callback function * @param {bool} [bRedraw=true] Redraw the table or not * @returns {array} The row that was deleted * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately remove the first row * oTable.fnDeleteRow( 0 ); * } ); */ this.fnDeleteRow = function( mTarget, fnCallBack, bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var i, iLen, iAODataIndex; iAODataIndex = (typeof mTarget === 'object') ? _fnNodeToDataIndex(oSettings, mTarget) : mTarget; /* Return the data array from this row */ var oData = oSettings.aoData.splice( iAODataIndex, 1 ); /* Update the _DT_RowIndex parameter */ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { oSettings.aoData[i].nTr._DT_RowIndex = i; } } /* Remove the target row from the search array */ var iDisplayIndex = $.inArray( iAODataIndex, oSettings.aiDisplay ); oSettings.asDataSearch.splice( iDisplayIndex, 1 ); /* Delete from the display arrays */ _fnDeleteIndex( oSettings.aiDisplayMaster, iAODataIndex ); _fnDeleteIndex( oSettings.aiDisplay, iAODataIndex ); /* If there is a user callback function - call it */ if ( typeof fnCallBack === "function" ) { fnCallBack.call( this, oSettings, oData ); } /* Check for an 'overflow' they case for displaying the table */ if ( oSettings._iDisplayStart >= oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart -= oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( bRedraw === undefined || bRedraw ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } return oData; }; /** * Restore the table to it's original state in the DOM by removing all of DataTables * enhancements, alterations to the DOM structure of the table and event listeners. * @param {boolean} [bRemove=false] Completely remove the table from the DOM * @dtopt API * * @example * $(document).ready(function() { * // This example is fairly pointless in reality, but shows how fnDestroy can be used * var oTable = $('#example').dataTable(); * oTable.fnDestroy(); * } ); */ this.fnDestroy = function ( bRemove ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var nOrig = oSettings.nTableWrapper.parentNode; var nBody = oSettings.nTBody; var i, iLen; bRemove = (bRemove===undefined) ? false : true; /* Flag to note that the table is currently being destroyed - no action should be taken */ oSettings.bDestroying = true; /* Fire off the destroy callbacks for plug-ins etc */ _fnCallbackFire( oSettings, "aoDestroyCallback", "destroy", [oSettings] ); /* Restore hidden columns */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].bVisible === false ) { this.fnSetColumnVis( i, true ); } } /* Blitz all DT events */ $(oSettings.nTableWrapper).find('*').andSelf().unbind('.DT'); /* If there is an 'empty' indicator row, remove it */ $('tbody>tr>td.'+oSettings.oClasses.sRowEmpty, oSettings.nTable).parent().remove(); /* When scrolling we had to break the table up - restore it */ if ( oSettings.nTable != oSettings.nTHead.parentNode ) { $(oSettings.nTable).children('thead').remove(); oSettings.nTable.appendChild( oSettings.nTHead ); } if ( oSettings.nTFoot && oSettings.nTable != oSettings.nTFoot.parentNode ) { $(oSettings.nTable).children('tfoot').remove(); oSettings.nTable.appendChild( oSettings.nTFoot ); } /* Remove the DataTables generated nodes, events and classes */ oSettings.nTable.parentNode.removeChild( oSettings.nTable ); $(oSettings.nTableWrapper).remove(); oSettings.aaSorting = []; oSettings.aaSortingFixed = []; _fnSortingClasses( oSettings ); $(_fnGetTrNodes( oSettings )).removeClass( oSettings.asStripeClasses.join(' ') ); $('th, td', oSettings.nTHead).removeClass( [ oSettings.oClasses.sSortable, oSettings.oClasses.sSortableAsc, oSettings.oClasses.sSortableDesc, oSettings.oClasses.sSortableNone ].join(' ') ); if ( oSettings.bJUI ) { $('th span.'+oSettings.oClasses.sSortIcon + ', td span.'+oSettings.oClasses.sSortIcon, oSettings.nTHead).remove(); $('th, td', oSettings.nTHead).each( function () { var jqWrapper = $('div.'+oSettings.oClasses.sSortJUIWrapper, this); var kids = jqWrapper.contents(); $(this).append( kids ); jqWrapper.remove(); } ); } /* Add the TR elements back into the table in their original order */ if ( !bRemove && oSettings.nTableReinsertBefore ) { nOrig.insertBefore( oSettings.nTable, oSettings.nTableReinsertBefore ); } else if ( !bRemove ) { nOrig.appendChild( oSettings.nTable ); } for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { nBody.appendChild( oSettings.aoData[i].nTr ); } } /* Restore the width of the original table */ if ( oSettings.oFeatures.bAutoWidth === true ) { oSettings.nTable.style.width = _fnStringToCss(oSettings.sDestroyWidth); } /* If the were originally odd/even type classes - then we add them back here. Note * this is not fool proof (for example if not all rows as odd/even classes - but * it's a good effort without getting carried away */ $(nBody).children('tr:even').addClass( oSettings.asDestroyStripes[0] ); $(nBody).children('tr:odd').addClass( oSettings.asDestroyStripes[1] ); /* Remove the settings object from the settings array */ for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ ) { if ( DataTable.settings[i] == oSettings ) { DataTable.settings.splice( i, 1 ); } } /* End it all */ oSettings = null; }; /** * Redraw the table * @param {bool} [bComplete=true] Re-filter and resort (if enabled) the table before the draw. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Re-draw the table - you wouldn't want to do it here, but it's an example :-) * oTable.fnDraw(); * } ); */ this.fnDraw = function( bComplete ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( bComplete === false ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } else { _fnReDraw( oSettings ); } }; /** * Filter the input based on data * @param {string} sInput String to filter the table on * @param {int|null} [iColumn] Column to limit filtering to * @param {bool} [bRegex=false] Treat as regular expression or not * @param {bool} [bSmart=true] Perform smart filtering or not * @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es) * @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false) * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sometime later - filter... * oTable.fnFilter( 'test string' ); * } ); */ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( !oSettings.oFeatures.bFilter ) { return; } if ( bRegex === undefined || bRegex === null ) { bRegex = false; } if ( bSmart === undefined || bSmart === null ) { bSmart = true; } if ( bShowGlobal === undefined || bShowGlobal === null ) { bShowGlobal = true; } if ( bCaseInsensitive === undefined || bCaseInsensitive === null ) { bCaseInsensitive = true; } if ( iColumn === undefined || iColumn === null ) { /* Global filter */ _fnFilterComplete( oSettings, { "sSearch":sInput+"", "bRegex": bRegex, "bSmart": bSmart, "bCaseInsensitive": bCaseInsensitive }, 1 ); if ( bShowGlobal && oSettings.aanFeatures.f ) { var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $(n[i]._DT_Input).val( sInput ); } } } else { /* Single column filter */ $.extend( oSettings.aoPreSearchCols[ iColumn ], { "sSearch": sInput+"", "bRegex": bRegex, "bSmart": bSmart, "bCaseInsensitive": bCaseInsensitive } ); _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } }; /** * Get the data for the whole table, an individual row or an individual cell based on the * provided parameters. * @param {int|node} [mRow] A TR row node, TD/TH cell node or an integer. If given as * a TR node then the data source for the whole row will be returned. If given as a * TD/TH cell node then iCol will be automatically calculated and the data for the * cell returned. If given as an integer, then this is treated as the aoData internal * data index for the row (see fnGetPosition) and the data for that row used. * @param {int} [iCol] Optional column index that you want the data of. * @returns {array|object|string} If mRow is undefined, then the data for all rows is * returned. If mRow is defined, just data for that row, and is iCol is * defined, only data for the designated cell is returned. * @dtopt API * * @example * // Row data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('tr').click( function () { * var data = oTable.fnGetData( this ); * // ... do something with the array / object of data for the row * } ); * } ); * * @example * // Individual cell data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('td').click( function () { * var sData = oTable.fnGetData( this ); * alert( 'The cell clicked on had the value of '+sData ); * } ); * } ); */ this.fnGetData = function( mRow, iCol ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( mRow !== undefined ) { var iRow = mRow; if ( typeof mRow === 'object' ) { var sNode = mRow.nodeName.toLowerCase(); if (sNode === "tr" ) { iRow = _fnNodeToDataIndex(oSettings, mRow); } else if ( sNode === "td" ) { iRow = _fnNodeToDataIndex(oSettings, mRow.parentNode); iCol = _fnNodeToColumnIndex( oSettings, iRow, mRow ); } } if ( iCol !== undefined ) { return _fnGetCellData( oSettings, iRow, iCol, '' ); } return (oSettings.aoData[iRow]!==undefined) ? oSettings.aoData[iRow]._aData : null; } return _fnGetDataMaster( oSettings ); }; /** * Get an array of the TR nodes that are used in the table's body. Note that you will * typically want to use the '$' API method in preference to this as it is more * flexible. * @param {int} [iRow] Optional row index for the TR element you want * @returns {array|node} If iRow is undefined, returns an array of all TR elements * in the table's body, or iRow is defined, just the TR element requested. * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the nodes from the table * var nNodes = oTable.fnGetNodes( ); * } ); */ this.fnGetNodes = function( iRow ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); if ( iRow !== undefined ) { return (oSettings.aoData[iRow]!==undefined) ? oSettings.aoData[iRow].nTr : null; } return _fnGetTrNodes( oSettings ); }; /** * Get the array indexes of a particular cell from it's DOM element * and column index including hidden columns * @param {node} nNode this can either be a TR, TD or TH in the table's body * @returns {int} If nNode is given as a TR, then a single index is returned, or * if given as a cell, an array of [row index, column index (visible)] is given. * @dtopt API * * @example * $(document).ready(function() { * $('#example tbody td').click( function () { * // Get the position of the current data from the node * var aPos = oTable.fnGetPosition( this ); * * // Get the data array for this row * var aData = oTable.fnGetData( aPos[0] ); * * // Update the data array and return the value * aData[ aPos[1] ] = 'clicked'; * this.innerHTML = 'clicked'; * } ); * * // Init DataTables * oTable = $('#example').dataTable(); * } ); */ this.fnGetPosition = function( nNode ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var sNodeName = nNode.nodeName.toUpperCase(); if ( sNodeName == "TR" ) { return _fnNodeToDataIndex(oSettings, nNode); } else if ( sNodeName == "TD" || sNodeName == "TH" ) { var iDataIndex = _fnNodeToDataIndex( oSettings, nNode.parentNode ); var iColumnIndex = _fnNodeToColumnIndex( oSettings, iDataIndex, nNode ); return [ iDataIndex, _fnColumnIndexToVisible(oSettings, iColumnIndex ), iColumnIndex ]; } return null; }; /** * Check to see if a row is 'open' or not. * @param {node} nTr the table row to check * @returns {boolean} true if the row is currently open, false otherwise * @dtopt API * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnIsOpen = function( nTr ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var aoOpenRows = oSettings.aoOpenRows; for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ ) { if ( oSettings.aoOpenRows[i].nParent == nTr ) { return true; } } return false; }; /** * This function will place a new row directly after a row which is currently * on display on the page, with the HTML contents that is passed into the * function. This can be used, for example, to ask for confirmation that a * particular record should be deleted. * @param {node} nTr The table row to 'open' * @param {string|node|jQuery} mHtml The HTML to put into the row * @param {string} sClass Class to give the new TD cell * @returns {node} The row opened. Note that if the table row passed in as the * first parameter, is not found in the table, this method will silently * return. * @dtopt API * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnOpen = function( nTr, mHtml, sClass ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); /* Check that the row given is in the table */ var nTableRows = _fnGetTrNodes( oSettings ); if ( $.inArray(nTr, nTableRows) === -1 ) { return; } /* the old open one if there is one */ this.fnClose( nTr ); var nNewRow = document.createElement("tr"); var nNewCell = document.createElement("td"); nNewRow.appendChild( nNewCell ); nNewCell.className = sClass; nNewCell.colSpan = _fnVisbleColumns( oSettings ); if (typeof mHtml === "string") { nNewCell.innerHTML = mHtml; } else { $(nNewCell).html( mHtml ); } /* If the nTr isn't on the page at the moment - then we don't insert at the moment */ var nTrs = $('tr', oSettings.nTBody); if ( $.inArray(nTr, nTrs) != -1 ) { $(nNewRow).insertAfter(nTr); } oSettings.aoOpenRows.push( { "nTr": nNewRow, "nParent": nTr } ); return nNewRow; }; /** * Change the pagination - provides the internal logic for pagination in a simple API * function. With this function you can have a DataTables table go to the next, * previous, first or last pages. * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last" * or page number to jump to (integer), note that page 0 is the first page. * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnPageChange( 'next' ); * } ); */ this.fnPageChange = function ( mAction, bRedraw ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); _fnPageChange( oSettings, mAction ); _fnCalculateEnd( oSettings ); if ( bRedraw === undefined || bRedraw ) { _fnDraw( oSettings ); } }; /** * Show a particular column * @param {int} iCol The column whose display should be changed * @param {bool} bShow Show (true) or hide (false) the column * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Hide the second column after initialisation * oTable.fnSetColumnVis( 1, false ); * } ); */ this.fnSetColumnVis = function ( iCol, bShow, bRedraw ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var i, iLen; var aoColumns = oSettings.aoColumns; var aoData = oSettings.aoData; var nTd, bAppend, iBefore; /* No point in doing anything if we are requesting what is already true */ if ( aoColumns[iCol].bVisible == bShow ) { return; } /* Show the column */ if ( bShow ) { var iInsert = 0; for ( i=0 ; i<iCol ; i++ ) { if ( aoColumns[i].bVisible ) { iInsert++; } } /* Need to decide if we should use appendChild or insertBefore */ bAppend = (iInsert >= _fnVisbleColumns( oSettings )); /* Which coloumn should we be inserting before? */ if ( !bAppend ) { for ( i=iCol ; i<aoColumns.length ; i++ ) { if ( aoColumns[i].bVisible ) { iBefore = i; break; } } } for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { if ( bAppend ) { aoData[i].nTr.appendChild( aoData[i]._anHidden[iCol] ); } else { aoData[i].nTr.insertBefore( aoData[i]._anHidden[iCol], _fnGetTdNodes( oSettings, i )[iBefore] ); } } } } else { /* Remove a column from display */ for ( i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { nTd = _fnGetTdNodes( oSettings, i )[iCol]; aoData[i]._anHidden[iCol] = nTd; nTd.parentNode.removeChild( nTd ); } } } /* Clear to set the visible flag */ aoColumns[iCol].bVisible = bShow; /* Redraw the header and footer based on the new column visibility */ _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* If there are any 'open' rows, then we need to alter the colspan for this col change */ for ( i=0, iLen=oSettings.aoOpenRows.length ; i<iLen ; i++ ) { oSettings.aoOpenRows[i].nTr.colSpan = _fnVisbleColumns( oSettings ); } /* Do a redraw incase anything depending on the table columns needs it * (built-in: scrolling) */ if ( bRedraw === undefined || bRedraw ) { _fnAdjustColumnSizing( oSettings ); _fnDraw( oSettings ); } _fnSaveState( oSettings ); }; /** * Get the settings for a particular table for external manipulation * @returns {object} DataTables settings object. See * {@link DataTable.models.oSettings} * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * var oSettings = oTable.fnSettings(); * * // Show an example parameter from the settings * alert( oSettings._iDisplayStart ); * } ); */ this.fnSettings = function() { return _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); }; /** * Sort the table by a particular column * @param {int} iCol the data index to sort on. Note that this will not match the * 'display index' if you have hidden data entries * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort immediately with columns 0 and 1 * oTable.fnSort( [ [0,'asc'], [1,'asc'] ] ); * } ); */ this.fnSort = function( aaSort ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); oSettings.aaSorting = aaSort; _fnSort( oSettings ); }; /** * Attach a sort listener to an element for a given column * @param {node} nNode the element to attach the sort listener to * @param {int} iColumn the column that a click on this node will sort on * @param {function} [fnCallback] callback function when sort is run * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort on column 1, when 'sorter' is clicked on * oTable.fnSortListener( document.getElementById('sorter'), 1 ); * } ); */ this.fnSortListener = function( nNode, iColumn, fnCallback ) { _fnSortAttachListener( _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ), nNode, iColumn, fnCallback ); }; /** * Update a table cell or row - this method will accept either a single value to * update the cell with, an array of values with one element for each column or * an object in the same format as the original data source. The function is * self-referencing in order to make the multi column updates easier. * @param {object|array|string} mData Data to update the cell/row with * @param {node|int} mRow TR element you want to update or the aoData index * @param {int} [iColumn] The column to update (not used of mData is an array or object) * @param {bool} [bRedraw=true] Redraw the table or not * @param {bool} [bAction=true] Perform predraw actions or not * @returns {int} 0 on success, 1 on error * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], 1, 0 ); // Row * } ); */ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction ) { var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ); var i, iLen, sDisplay; var iRow = (typeof mRow === 'object') ? _fnNodeToDataIndex(oSettings, mRow) : mRow; if ( oSettings.__fnUpdateDeep === undefined && $.isArray(mData) && typeof mData === 'object' ) { /* Array update - update the whole row */ oSettings.aoData[iRow]._aData = mData.slice(); /* Flag to the function that we are recursing */ oSettings.__fnUpdateDeep = true; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } oSettings.__fnUpdateDeep = undefined; } else if ( oSettings.__fnUpdateDeep === undefined && mData !== null && typeof mData === 'object' ) { /* Object update - update the whole row - assume the developer gets the object right */ oSettings.aoData[iRow]._aData = $.extend( true, {}, mData ); oSettings.__fnUpdateDeep = true; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } oSettings.__fnUpdateDeep = undefined; } else { /* Individual cell update */ _fnSetCellData( oSettings, iRow, iColumn, mData ); sDisplay = _fnGetCellData( oSettings, iRow, iColumn, 'display' ); var oCol = oSettings.aoColumns[iColumn]; if ( oCol.fnRender !== null ) { sDisplay = _fnRender( oSettings, iRow, iColumn ); if ( oCol.bUseRendered ) { _fnSetCellData( oSettings, iRow, iColumn, sDisplay ); } } if ( oSettings.aoData[iRow].nTr !== null ) { /* Do the actual HTML update */ _fnGetTdNodes( oSettings, iRow )[iColumn].innerHTML = sDisplay; } } /* Modify the search index for this row (strictly this is likely not needed, since fnReDraw * will rebuild the search array - however, the redraw might be disabled by the user) */ var iDisplayIndex = $.inArray( iRow, oSettings.aiDisplay ); oSettings.asDataSearch[iDisplayIndex] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, iRow, 'filter' ) ); /* Perform pre-draw actions */ if ( bAction === undefined || bAction ) { _fnAdjustColumnSizing( oSettings ); } /* Redraw the table */ if ( bRedraw === undefined || bRedraw ) { _fnReDraw( oSettings ); } return 0; }; /** * Provide a common method for plug-ins to check the version of DataTables being used, in order * to ensure compatibility. * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the * formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to the required * version, or false if this version of DataTales is not suitable * @method * @dtopt API * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * alert( oTable.fnVersionCheck( '1.9.0' ) ); * } ); */ this.fnVersionCheck = DataTable.ext.fnVersionCheck;
; (function() { window.require(["ace/mode/text"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
/* @flow */ // These util functions are split into its own file because Rollup cannot drop // makeMap() due to potential side effects, so these variables end up // bloating the web builds. import { makeMap } from 'shared/util' export const isReservedTag = makeMap( 'template,script,style,element,content,slot,link,meta,svg,view,' + 'a,div,img,image,text,span,input,switch,textarea,spinner,select,' + 'slider,slider-neighbor,indicator,canvas,' + 'list,cell,header,loading,loading-indicator,refresh,scrollable,scroller,' + 'video,web,embed,tabbar,tabheader,datepicker,timepicker,marquee,countdown', true ) // Elements that you can, intentionally, leave open (and which close themselves) // more flexible than web export const canBeLeftOpenTag = makeMap( 'web,spinner,switch,video,textarea,canvas,' + 'indicator,marquee,countdown', true ) export const isRuntimeComponent = makeMap( 'richtext,transition,transition-group', true ) export const isUnaryTag = makeMap( 'embed,img,image,input,link,meta', true ) export function mustUseProp (tag: string, type: ?string, name: string): boolean { return false } export function getTagNamespace (tag?: string): string | void { } export function isUnknownElement (tag?: string): boolean { return false } export function query (el: string | Element, document: Object) { // document is injected by weex factory wrapper const placeholder = document.createComment('root') placeholder.hasAttribute = placeholder.removeAttribute = function () {} // hack for patch document.documentElement.appendChild(placeholder) return placeholder }
var progressInstance = ( <Progress> <Progress now={65} label="Male" amStyle="success" key={1} /> <Progress now={15} label="Female" amStyle="warning" key={2} /> <Progress now={20} label="Other" amStyle="danger" key={3} /> </Progress> ); React.render(progressInstance, mountNode);
///import editor.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js ///import core/dom/Range.js /** * @class UM.dom.Selection Selection类 */ (function () { function getBoundaryInformation( range, start ) { var getIndex = domUtils.getNodeIndex; range = range.duplicate(); range.collapse( start ); var parent = range.parentElement(); //如果节点里没有子节点,直接退出 if ( !parent.hasChildNodes() ) { return {container:parent, offset:0}; } var siblings = parent.children, child, testRange = range.duplicate(), startIndex = 0, endIndex = siblings.length - 1, index = -1, distance; while ( startIndex <= endIndex ) { index = Math.floor( (startIndex + endIndex) / 2 ); child = siblings[index]; testRange.moveToElementText( child ); var position = testRange.compareEndPoints( 'StartToStart', range ); if ( position > 0 ) { endIndex = index - 1; } else if ( position < 0 ) { startIndex = index + 1; } else { //trace:1043 return {container:parent, offset:getIndex( child )}; } } if ( index == -1 ) { testRange.moveToElementText( parent ); testRange.setEndPoint( 'StartToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; siblings = parent.childNodes; if ( !distance ) { child = siblings[siblings.length - 1]; return {container:child, offset:child.nodeValue.length}; } var i = siblings.length; while ( distance > 0 ){ distance -= siblings[ --i ].nodeValue.length; } return {container:siblings[i], offset:-distance}; } testRange.collapse( position > 0 ); testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; if ( !distance ) { return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ? {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} : {container:child, offset:position > 0 ? 0 : child.childNodes.length} } while ( distance > 0 ) { try { var pre = child; child = child[position > 0 ? 'previousSibling' : 'nextSibling']; distance -= child.nodeValue.length; } catch ( e ) { return {container:parent, offset:getIndex( pre )}; } } return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance} } /** * 将ieRange转换为Range对象 * @param {Range} ieRange ieRange对象 * @param {Range} range Range对象 * @return {Range} range 返回转换后的Range对象 */ function transformIERangeToRange( ieRange, range ) { if ( ieRange.item ) { range.selectNode( ieRange.item( 0 ) ); } else { var bi = getBoundaryInformation( ieRange, true ); range.setStart( bi.container, bi.offset ); if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) { bi = getBoundaryInformation( ieRange, false ); range.setEnd( bi.container, bi.offset ); } } return range; } /** * 获得ieRange * @param {Selection} sel Selection对象 * @return {ieRange} 得到ieRange */ function _getIERange( sel,txtRange ) { var ieRange; //ie下有可能报错 try { ieRange = sel.getNative(txtRange).createRange(); } catch ( e ) { return null; } var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement(); if ( ( el.ownerDocument || el ) === sel.document ) { return ieRange; } return null; } var Selection = dom.Selection = function ( doc,body ) { var me = this; me.document = doc; me.body = body; if ( browser.ie9below ) { $( body).on('beforedeactivate', function () { me._bakIERange = me.getIERange(); } ).on('activate', function () { try { var ieNativRng = _getIERange( me ); if ( (!ieNativRng || !me.rangeInBody(ieNativRng)) && me._bakIERange ) { me._bakIERange.select(); } } catch ( ex ) { } me._bakIERange = null; } ); } }; Selection.prototype = { hasNativeRange : function(){ var rng; if(!browser.ie || browser.ie9above){ var nativeSel = this.getNative(); if(!nativeSel.rangeCount){ return false; } rng = nativeSel.getRangeAt(0); }else{ rng = _getIERange(this); } return this.rangeInBody(rng); }, /** * 获取原生seleciton对象 * @public * @function * @name UM.dom.Selection.getNative * @return {Selection} 获得selection对象 */ getNative:function (txtRange) { var doc = this.document; try { return !doc ? null : browser.ie9below || txtRange? doc.selection : domUtils.getWindow( doc ).getSelection(); } catch ( e ) { return null; } }, /** * 获得ieRange * @public * @function * @name UM.dom.Selection.getIERange * @return {ieRange} 返回ie原生的Range */ getIERange:function (txtRange) { var ieRange = _getIERange( this,txtRange ); if ( !ieRange || !this.rangeInBody(ieRange,txtRange)) { if ( this._bakIERange ) { return this._bakIERange; } } return ieRange; }, rangeInBody : function(rng,txtRange){ var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer; return node === this.body || domUtils.inDoc(node,this.body); }, /** * 缓存当前选区的range和选区的开始节点 * @public * @function * @name UM.dom.Selection.cache */ cache:function () { this.clear(); this._cachedRange = this.getRange(); this._cachedStartElement = this.getStart(); this._cachedStartElementPath = this.getStartElementPath(); }, getStartElementPath:function () { if ( this._cachedStartElementPath ) { return this._cachedStartElementPath; } var start = this.getStart(); if ( start ) { return domUtils.findParents( start, true, null, true ) } return []; }, /** * 清空缓存 * @public * @function * @name UM.dom.Selection.clear */ clear:function () { this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null; }, /** * 编辑器是否得到了选区 */ isFocus:function () { return this.hasNativeRange() }, /** * 获取选区对应的Range * @public * @function * @name UM.dom.Selection.getRange * @returns {UM.dom.Range} 得到Range对象 */ getRange:function () { var me = this; function optimze( range ) { var child = me.body.firstChild, collapsed = range.collapsed; while ( child && child.firstChild ) { range.setStart( child, 0 ); child = child.firstChild; } if ( !range.startContainer ) { range.setStart( me.body, 0 ) } if ( collapsed ) { range.collapse( true ); } } if ( me._cachedRange != null ) { return this._cachedRange; } var range = new dom.Range( me.document,me.body ); if ( browser.ie9below ) { var nativeRange = me.getIERange(); if ( nativeRange && this.rangeInBody(nativeRange)) { try{ transformIERangeToRange( nativeRange, range ); }catch(e){ optimze( range ); } } else { optimze( range ); } } else { var sel = me.getNative(); if ( sel && sel.rangeCount && me.rangeInBody(sel.getRangeAt( 0 ))) { var firstRange = sel.getRangeAt( 0 ); var lastRange = sel.getRangeAt( sel.rangeCount - 1 ); range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset ); if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) { optimze( range ); } } else { //trace:1734 有可能已经不在dom树上了,标识的节点 if ( this._bakRange && (this._bakRange.startContainer === this.body || domUtils.inDoc( this._bakRange.startContainer, this.body )) ){ return this._bakRange; } optimze( range ); } } return this._bakRange = range; }, /** * 获取开始元素,用于状态反射 * @public * @function * @name UM.dom.Selection.getStart * @return {Element} 获得开始元素 */ getStart:function () { if ( this._cachedStartElement ) { return this._cachedStartElement; } var range = browser.ie9below ? this.getIERange() : this.getRange(), tmpRange, start, tmp, parent; if ( browser.ie9below ) { if ( !range ) { //todo 给第一个值可能会有问题 return this.document.body.firstChild; } //control元素 if ( range.item ){ return range.item( 0 ); } tmpRange = range.duplicate(); //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 ); tmpRange.collapse( 1 ); start = tmpRange.parentElement(); parent = tmp = range.parentElement(); while ( tmp = tmp.parentNode ) { if ( tmp == start ) { start = parent; break; } } } else { start = range.startContainer; if ( start.nodeType == 1 && start.hasChildNodes() ){ start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )]; } if ( start.nodeType == 3 ){ return start.parentNode; } } return start; }, /** * 得到选区中的文本 * @public * @function * @name UM.dom.Selection.getText * @return {String} 选区中包含的文本 */ getText:function () { var nativeSel, nativeRange; if ( this.isFocus() && (nativeSel = this.getNative()) ) { nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 ); return browser.ie9below ? nativeRange.text : nativeRange.toString(); } return ''; } }; })();
app.controller('mainCtrl', function($scope) { });
/* jshint -W084 */ angular.module('angular-login.mock', ['ngMockE2E']) .factory('delayHTTP', function ($q, $timeout) { return { request: function (request) { var delayedResponse = $q.defer(); $timeout(function () { delayedResponse.resolve(request); }, 700); return delayedResponse.promise; }, response: function (response) { var deferResponse = $q.defer(); if (response.config.timeout && response.config.timeout.then) { response.config.timeout.then(function () { deferResponse.reject(); }); } else { deferResponse.resolve(response); } return $timeout(function () { deferResponse.resolve(response); return deferResponse.promise; }); } }; }) // delay HTTP .config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push('delayHTTP'); }]) .constant('loginExampleData', { version: '0.2.0' }) .run(function ($httpBackend, $log, loginExampleData) { var userStorage = angular.fromJson(localStorage.getItem('userStorage')), emailStorage = angular.fromJson(localStorage.getItem('emailStorage')), tokenStorage = angular.fromJson(localStorage.getItem('tokenStorage')) || {}, loginExample = angular.fromJson(localStorage.getItem('loginExample')); // Check and corrects old localStorage values, backward-compatibility! if (!loginExample || loginExample.version !== loginExampleData.version) { userStorage = null; tokenStorage = {}; localStorage.setItem('loginExample', angular.toJson(loginExampleData)); } if (userStorage === null || emailStorage === null) { userStorage = { 'johnm': { name: 'John', username: 'johnm', password: 'hello', email: 'john.dott@myemail.com', userRole: userRoles.user, tokens: [] }, 'sandrab': { name: 'Sandra', username: 'sandrab', password: 'world', email: 'bitter.s@provider.com', userRole: userRoles.admin, tokens: [] } }; emailStorage = { 'john.dott@myemail.com': 'johnm', 'bitter.s@provider.com': 'sandrab' }; localStorage.setItem('userStorage', angular.toJson(userStorage)); localStorage.setItem('emailStorage', angular.toJson(emailStorage)); } /** * Generates random Token */ var randomUUID = function () { var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var randomToken = ''; for (var i = 0; i < 36; i++) { if (i === 8 || i === 13 || i === 18 || i === 23) { randomToken += ''; continue; } var randomPoz = Math.floor(Math.random() * charSet.length); randomToken += charSet.substring(randomPoz, randomPoz + 1); } return randomToken; }; // fakeLogin $httpBackend.when('POST', '/login').respond(function (method, url, data, headers) { var postData = angular.fromJson(data), user = userStorage[postData.username], newToken, tokenObj; $log.info(method, '->', url); if (angular.isDefined(user) && user.password === postData.password) { newToken = randomUUID(); user.tokens.push(newToken); tokenStorage[newToken] = postData.username; localStorage.setItem('userStorage', angular.toJson(userStorage)); localStorage.setItem('tokenStorage', angular.toJson(tokenStorage)); return [200, { name: user.name, userRole: user.userRole, token: newToken }, {}]; } else { return [401, 'wrong combination username/password', {}]; } }); // fakeLogout $httpBackend.when('GET', '/logout').respond(function (method, url, data, headers) { var queryToken, userTokens; $log.info(method, '->', url); if (queryToken = headers['X-Token']) { if (angular.isDefined(tokenStorage[queryToken])) { userTokens = userStorage[tokenStorage[queryToken]].tokens; // Update userStorage AND tokenStorage userTokens.splice(userTokens.indexOf(queryToken)); delete tokenStorage[queryToken]; localStorage.setItem('userStorage', angular.toJson(userStorage)); localStorage.setItem('tokenStorage', angular.toJson(tokenStorage)); return [200, {}, {}]; } else { return [401, 'auth token invalid or expired', {}]; } } else { return [401, 'auth token invalid or expired', {}]; } }); // fakeUser $httpBackend.when('GET', '/user').respond(function (method, url, data, headers) { var queryToken, userObject; $log.info(method, '->', url); // if is present in a registered users array. if (queryToken = headers['X-Token']) { if (angular.isDefined(tokenStorage[queryToken])) { userObject = userStorage[tokenStorage[queryToken]]; return [200, { token: queryToken, name: userObject.name, userRole: userObject.userRole }, {}]; } else { return [401, 'auth token invalid or expired', {}]; } } else { return [401, 'auth token invalid or expired', {}]; } }); // fakeRegister $httpBackend.when('POST', '/user').respond(function (method, url, data, headers) { var postData = angular.fromJson(data), newUser, errors = []; $log.info(method, '->', url); if (angular.isDefined(userStorage[postData.username])) { errors.push({ field: 'username', name: 'used' }); } if (angular.isDefined(emailStorage[postData.email])) { errors.push({ field: 'email', name: 'used' }); } if (errors.length) { return [409, { valid: false, errors: errors }, {}]; } else { newUser = angular.extend(postData, { userRole: userRoles[postData.role], tokens: [] }); delete newUser.role; userStorage[newUser.username] = newUser; emailStorage[newUser.email] = newUser.username; localStorage.setItem('userStorage', angular.toJson(userStorage)); localStorage.setItem('emailStorage', angular.toJson(emailStorage)); return [201, { valid: true, creationDate: Date.now() }, {}]; } }); });
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import { EventEmitter } from 'events'; import ActorClient from 'utils/ActorClient'; import DialogStore from 'stores/DialogStore' import { register, waitFor } from 'dispatcher/ActorAppDispatcher'; import { ActionTypes, AsyncActionStates } from 'constants/ActorAppConstants'; const CHANGE_EVENT = 'change'; let _integrationToken = null; class GroupStore extends EventEmitter { getGroup(gid) { return ActorClient.getGroup(gid); } getIntegrationToken() { return _integrationToken; } emitChange() { this.emit(CHANGE_EVENT); } addChangeListener(callback) { this.on(CHANGE_EVENT, callback); } removeChangeListener(callback) { this.removeListener(CHANGE_EVENT, callback); } } let GroupStoreInstance = new GroupStore(); GroupStoreInstance.dispatchToken = register(action => { switch (action.type) { case ActionTypes.LEFT_GROUP: GroupStoreInstance.emitChange(); break; case ActionTypes.GET_INTEGRATION_TOKEN: waitFor([DialogStore.dispatchToken]); GroupStoreInstance.emitChange(); break; case ActionTypes.GET_INTEGRATION_TOKEN_SUCCESS: _integrationToken = action.response; GroupStoreInstance.emitChange(); break; case ActionTypes.GET_INTEGRATION_TOKEN_ERROR: _integrationToken = null; GroupStoreInstance.emitChange(); break; } }); export default GroupStoreInstance;
/** @license React v16.6.1 * react-dom-unstable-native-dependencies.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react-dom'), require('react')) : typeof define === 'function' && define.amd ? define(['react-dom', 'react'], factory) : (global.ReactDOMUnstableNativeDependencies = factory(global.ReactDOM,global.React)); }(this, (function (ReactDOM,React) { 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function () {}; { validateFormat = function (format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error = void 0; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } // Relying on the `invariant()` implementation lets us // preserve the format and params in the www builds. { // In DEV mode, we swap out invokeGuardedCallback for a special version // that plays more nicely with the browser's DevTools. The idea is to preserve // "Pause on exceptions" behavior. Because React wraps all user-provided // functions in invokeGuardedCallback, and the production version of // invokeGuardedCallback uses a try-catch, all user exceptions are treated // like caught exceptions, and the DevTools won't pause unless the developer // takes the extra step of enabling pause on caught exceptions. This is // untintuitive, though, because even though React has caught the error, from // the developer's perspective, the error is uncaught. // // To preserve the expected "Pause on exceptions" behavior, we don't use a // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake // DOM node, and call the user-provided callback from inside an event handler // for that fake event. If the callback throws, the error is "captured" using // a global event handler. But because the error happens in a different // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); } } /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. * * In production, this is implemented using a try-catch. The reason we don't * use a try-catch directly is so that we can swap out a different * implementation in DEV mode. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. * TODO: See if caughtError and rethrowError can be unified. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warningWithoutStack = function () {}; { warningWithoutStack = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument'); } if (args.length > 8) { // Check before the condition to catch violations early. throw new Error('warningWithoutStack() currently supports at most 8 arguments.'); } if (condition) { return; } if (typeof console !== 'undefined') { var argsWithFormat = args.map(function (item) { return '' + item; }); argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 Function.prototype.apply.call(console.error, console, argsWithFormat); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); throw new Error(message); } catch (x) {} }; } var warningWithoutStack$1 = warningWithoutStack; var getFiberCurrentPropsFromNode$1 = null; var getInstanceFromNode$1 = null; var getNodeFromInstance$1 = null; function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) { getFiberCurrentPropsFromNode$1 = getFiberCurrentPropsFromNodeImpl; getInstanceFromNode$1 = getInstanceFromNodeImpl; getNodeFromInstance$1 = getNodeFromInstanceImpl; { !(getNodeFromInstance$1 && getInstanceFromNode$1) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } } var validateEventDispatches = void 0; { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Standard/simple iteration through an event's collected dispatches. */ /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : void 0; event.currentTarget = dispatchListener ? getNodeFromInstance$1(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } // Before we know whether it is function or class // Root of a host tree. Could be nested inside another node. // A subtree. Could be an entry point to a different renderer. var HostComponent = 5; function getParent(inst) { do { inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); if (inst) { return inst; } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { var depthA = 0; for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } instA = getParent(instA); instB = getParent(instB); } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } instB = getParent(instB); } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { return getParent(inst); } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = getParent(inst); } var i = void 0; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ /** * Ordered list of injected plugins. */ /** * Mapping from event name to dispatch config */ /** * Mapping from registration name to plugin module */ /** * Mapping from registration name to event name */ /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in true. * @type {Object} */ // Trust the developer to only use possibleRegistrationNames in true /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). * @param {function} cb Callback invoked with each element or a collection. * @param {?} [scope] Scope used as `this` in a callback. */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ /** * Methods for injecting dependencies. */ /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ function getListener(inst, registrationName) { var listener = void 0; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon var stateNode = inst.stateNode; if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } var props = getFiberCurrentPropsFromNode$1(stateNode); if (!props) { // Work in progress. return null; } listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } !(!listener || typeof listener === 'function') ? invariant(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0; return listener; } /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing even a * single one. */ /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { { !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0; } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? getParentInstance(targetInst) : null; traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var _assign = ReactInternals.assign; /* eslint valid-typeof: 0 */ var EVENT_POOL_SIZE = 10; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: function () { return null; }, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; function functionThatReturnsTrue() { return true; } function functionThatReturnsFalse() { return false; } /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; delete this.isDefaultPrevented; delete this.isPropagationStopped; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } this.isPropagationStopped = functionThatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { event.returnValue = false; } this.isDefaultPrevented = functionThatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = functionThatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = functionThatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: functionThatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } } this.dispatchConfig = null; this._targetInst = null; this.nativeEvent = null; this.isDefaultPrevented = functionThatReturnsFalse; this.isPropagationStopped = functionThatReturnsFalse; this._dispatchListeners = null; this._dispatchInstances = null; { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse)); Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {})); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {})); } } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. */ SyntheticEvent.extend = function (Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); function Class() { return Super.apply(this, arguments); } _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.extend = Super.extend; addEventPoolingTo(Class); return Class; }; addEventPoolingTo(SyntheticEvent); /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {String} propName * @param {?object} getVal * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; !warningCondition ? warningWithoutStack$1(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { var EventConstructor = this; if (EventConstructor.eventPool.length) { var instance = EventConstructor.eventPool.pop(); EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst); return instance; } return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst); } function releasePooledEvent(event) { var EventConstructor = this; !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0; event.destructor(); if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { EventConstructor.eventPool.push(event); } } function addEventPoolingTo(EventConstructor) { EventConstructor.eventPool = []; EventConstructor.getPooled = getPooledEvent; EventConstructor.release = releasePooledEvent; } /** * `touchHistory` isn't actually on the native event, but putting it in the * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ var ResponderSyntheticEvent = SyntheticEvent.extend({ touchHistory: function (nativeEvent) { return null; // Actually doesn't even look at the native event. } }); // Note: ideally these would be imported from DOMTopLevelEventTypes, // but our build system currently doesn't let us do that from a fork. var TOP_TOUCH_START = 'touchstart'; var TOP_TOUCH_MOVE = 'touchmove'; var TOP_TOUCH_END = 'touchend'; var TOP_TOUCH_CANCEL = 'touchcancel'; var TOP_SCROLL = 'scroll'; var TOP_SELECTION_CHANGE = 'selectionchange'; var TOP_MOUSE_DOWN = 'mousedown'; var TOP_MOUSE_MOVE = 'mousemove'; var TOP_MOUSE_UP = 'mouseup'; function isStartish(topLevelType) { return topLevelType === TOP_TOUCH_START || topLevelType === TOP_MOUSE_DOWN; } function isMoveish(topLevelType) { return topLevelType === TOP_TOUCH_MOVE || topLevelType === TOP_MOUSE_MOVE; } function isEndish(topLevelType) { return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL || topLevelType === TOP_MOUSE_UP; } var startDependencies = [TOP_TOUCH_START, TOP_MOUSE_DOWN]; var moveDependencies = [TOP_TOUCH_MOVE, TOP_MOUSE_MOVE]; var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_MOUSE_UP]; /** * Tracks the position and time of each active touch by `touch.identifier`. We * should typically only see IDs in the range of 1-20 because IDs get recycled * when touches end and start again. */ var MAX_TOUCH_BANK = 20; var touchBank = []; var touchHistory = { touchBank: touchBank, numberActiveTouches: 0, // If there is only one active touch, we remember its location. This prevents // us having to loop through all of the touches all the time in the most // common case. indexOfSingleActiveTouch: -1, mostRecentTimeStamp: 0 }; function timestampForTouch(touch) { // The legacy internal implementation provides "timeStamp", which has been // renamed to "timestamp". Let both work for now while we iron it out // TODO (evv): rename timeStamp to timestamp in internal code return touch.timeStamp || touch.timestamp; } /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ function createTouchRecord(touch) { return { touchActive: true, startPageX: touch.pageX, startPageY: touch.pageY, startTimeStamp: timestampForTouch(touch), currentPageX: touch.pageX, currentPageY: touch.pageY, currentTimeStamp: timestampForTouch(touch), previousPageX: touch.pageX, previousPageY: touch.pageY, previousTimeStamp: timestampForTouch(touch) }; } function resetTouchRecord(touchRecord, touch) { touchRecord.touchActive = true; touchRecord.startPageX = touch.pageX; touchRecord.startPageY = touch.pageY; touchRecord.startTimeStamp = timestampForTouch(touch); touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchRecord.previousPageX = touch.pageX; touchRecord.previousPageY = touch.pageY; touchRecord.previousTimeStamp = timestampForTouch(touch); } function getTouchIdentifier(_ref) { var identifier = _ref.identifier; !(identifier != null) ? invariant(false, 'Touch object is missing identifier.') : void 0; { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1(false, 'Touch identifier %s is greater than maximum supported %s which causes ' + 'performance issues backfilling array locations for all of the indices.', identifier, MAX_TOUCH_BANK) : void 0; } return identifier; } function recordTouchStart(touch) { var identifier = getTouchIdentifier(touch); var touchRecord = touchBank[identifier]; if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; touchRecord.previousPageY = touchRecord.currentPageY; touchRecord.previousTimeStamp = touchRecord.currentTimeStamp; touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } else { console.error('Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank()); } } function recordTouchEnd(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; touchRecord.previousPageY = touchRecord.currentPageY; touchRecord.previousTimeStamp = touchRecord.currentTimeStamp; touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } else { console.error('Cannot record touch end without a touch start.\n' + 'Touch End: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank()); } } function printTouch(touch) { return JSON.stringify({ identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY, timestamp: timestampForTouch(touch) }); } function printTouchBank() { var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); if (touchBank.length > MAX_TOUCH_BANK) { printed += ' (original size: ' + touchBank.length + ')'; } return printed; } var ResponderTouchHistoryStore = { recordTouchTrack: function (topLevelType, nativeEvent) { if (isMoveish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchMove); } else if (isStartish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; } } else if (isEndish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; if (touchHistory.numberActiveTouches === 1) { for (var i = 0; i < touchBank.length; i++) { var touchTrackToCheck = touchBank[i]; if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } { var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; !(activeRecord != null && activeRecord.touchActive) ? warningWithoutStack$1(false, 'Cannot find single active touch.') : void 0; } } } }, touchHistory: touchHistory }; /** * Accumulates items that must not be null or undefined. * * This is used to conserve memory by avoiding array allocations. * * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { !(next != null) ? invariant(false, 'accumulate(...): Accumulated items must be not be null or undefined.') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { return current.concat(next); } if (Array.isArray(next)) { return [current].concat(next); } return [current, next]; } /** * Instance of element that should respond to touch/move types of interactions, * as indicated explicitly by relevant callbacks. */ var responderInst = null; /** * Count of current touches. A textInput should become responder iff the * selection changes while there is a touch on the screen. */ var trackedTouchCount = 0; var changeResponder = function (nextResponderInst, blockHostResponder) { var oldResponderInst = responderInst; responderInst = nextResponderInst; if (ResponderEventPlugin.GlobalResponderHandler !== null) { ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder); } }; var eventTypes = { /** * On a `touchStart`/`mouseDown`, is it desired that this element become the * responder? */ startShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onStartShouldSetResponder', captured: 'onStartShouldSetResponderCapture' }, dependencies: startDependencies }, /** * On a `scroll`, is it desired that this element become the responder? This * is usually not needed, but should be used to retroactively infer that a * `touchStart` had occurred during momentum scroll. During a momentum scroll, * a touch start will be immediately followed by a scroll event if the view is * currently scrolling. * * TODO: This shouldn't bubble. */ scrollShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onScrollShouldSetResponder', captured: 'onScrollShouldSetResponderCapture' }, dependencies: [TOP_SCROLL] }, /** * On text selection change, should this element become the responder? This * is needed for text inputs or other views with native selection, so the * JS view can claim the responder. * * TODO: This shouldn't bubble. */ selectionChangeShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onSelectionChangeShouldSetResponder', captured: 'onSelectionChangeShouldSetResponderCapture' }, dependencies: [TOP_SELECTION_CHANGE] }, /** * On a `touchMove`/`mouseMove`, is it desired that this element become the * responder? */ moveShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onMoveShouldSetResponder', captured: 'onMoveShouldSetResponderCapture' }, dependencies: moveDependencies }, /** * Direct responder events dispatched directly to responder. Do not bubble. */ responderStart: { registrationName: 'onResponderStart', dependencies: startDependencies }, responderMove: { registrationName: 'onResponderMove', dependencies: moveDependencies }, responderEnd: { registrationName: 'onResponderEnd', dependencies: endDependencies }, responderRelease: { registrationName: 'onResponderRelease', dependencies: endDependencies }, responderTerminationRequest: { registrationName: 'onResponderTerminationRequest', dependencies: [] }, responderGrant: { registrationName: 'onResponderGrant', dependencies: [] }, responderReject: { registrationName: 'onResponderReject', dependencies: [] }, responderTerminate: { registrationName: 'onResponderTerminate', dependencies: [] } }; /** * * Responder System: * ---------------- * * - A global, solitary "interaction lock" on a view. * - If a node becomes the responder, it should convey visual feedback * immediately to indicate so, either by highlighting or moving accordingly. * - To be the responder means, that touches are exclusively important to that * responder view, and no other view. * - While touches are still occurring, the responder lock can be transferred to * a new view, but only to increasingly "higher" views (meaning ancestors of * the current responder). * * Responder being granted: * ------------------------ * * - Touch starts, moves, and scrolls can cause an ID to become the responder. * - We capture/bubble `startShouldSetResponder`/`moveShouldSetResponder` to * the "appropriate place". * - If nothing is currently the responder, the "appropriate place" is the * initiating event's `targetID`. * - If something *is* already the responder, the "appropriate place" is the * first common ancestor of the event target and the current `responderInst`. * - Some negotiation happens: See the timing diagram below. * - Scrolled views automatically become responder. The reasoning is that a * platform scroll view that isn't built on top of the responder system has * began scrolling, and the active responder must now be notified that the * interaction is no longer locked to it - the system has taken over. * * - Responder being released: * As soon as no more touches that *started* inside of descendants of the * *current* responderInst, an `onResponderRelease` event is dispatched to the * current responder, and the responder lock is released. * * TODO: * - on "end", a callback hook for `onResponderEndShouldRemainResponder` that * determines if the responder lock should remain. * - If a view shouldn't "remain" the responder, any active touches should by * default be considered "dead" and do not influence future negotiations or * bubble paths. It should be as if those touches do not exist. * -- For multitouch: Usually a translate-z will choose to "remain" responder * after one out of many touches ended. For translate-y, usually the view * doesn't wish to "remain" responder after one of many touches end. * - Consider building this on top of a `stopPropagation` model similar to * `W3C` events. * - Ensure that `onResponderTerminate` is called on touch cancels, whether or * not `onResponderTerminationRequest` returns `true` or `false`. * */ /* Negotiation Performed +-----------------------+ / \ Process low level events to + Current Responder + wantsResponderID determine who to perform negot-| (if any exists at all) | iation/transition | Otherwise just pass through| -------------------------------+----------------------------+------------------+ Bubble to find first ID | | to return true:wantsResponderID| | | | +-------------+ | | | onTouchStart| | | +------+------+ none | | | return| | +-----------v-------------+true| +------------------------+ | |onStartShouldSetResponder|----->|onResponderStart (cur) |<-----------+ +-----------+-------------+ | +------------------------+ | | | | | +--------+-------+ | returned true for| false:REJECT +-------->|onResponderReject | wantsResponderID | | | +----------------+ | (now attempt | +------------------+-----+ | | handoff) | | onResponder | | +------------------->| TerminationRequest| | | +------------------+-----+ | | | | +----------------+ | true:GRANT +-------->|onResponderGrant| | | +--------+-------+ | +------------------------+ | | | | onResponderTerminate |<-----------+ | +------------------+-----+ | | | | +----------------+ | +-------->|onResponderStart| | | +----------------+ Bubble to find first ID | | to return true:wantsResponderID| | | | +-------------+ | | | onTouchMove | | | +------+------+ none | | | return| | +-----------v-------------+true| +------------------------+ | |onMoveShouldSetResponder |----->|onResponderMove (cur) |<-----------+ +-----------+-------------+ | +------------------------+ | | | | | +--------+-------+ | returned true for| false:REJECT +-------->|onResponderRejec| | wantsResponderID | | | +----------------+ | (now attempt | +------------------+-----+ | | handoff) | | onResponder | | +------------------->| TerminationRequest| | | +------------------+-----+ | | | | +----------------+ | true:GRANT +-------->|onResponderGrant| | | +--------+-------+ | +------------------------+ | | | | onResponderTerminate |<-----------+ | +------------------+-----+ | | | | +----------------+ | +-------->|onResponderMove | | | +----------------+ | | | | Some active touch started| | inside current responder | +------------------------+ | +------------------------->| onResponderEnd | | | | +------------------------+ | +---+---------+ | | | onTouchEnd | | | +---+---------+ | | | | +------------------------+ | +------------------------->| onResponderEnd | | No active touches started| +-----------+------------+ | inside current responder | | | | v | | +------------------------+ | | | onResponderRelease | | | +------------------------+ | | | + + */ /** * A note about event ordering in the `EventPluginHub`. * * Suppose plugins are injected in the following order: * * `[R, S, C]` * * To help illustrate the example, assume `S` is `SimpleEventPlugin` (for * `onClick` etc) and `R` is `ResponderEventPlugin`. * * "Deferred-Dispatched Events": * * - The current event plugin system will traverse the list of injected plugins, * in order, and extract events by collecting the plugin's return value of * `extractEvents()`. * - These events that are returned from `extractEvents` are "deferred * dispatched events". * - When returned from `extractEvents`, deferred-dispatched events contain an * "accumulation" of deferred dispatches. * - These deferred dispatches are accumulated/collected before they are * returned, but processed at a later time by the `EventPluginHub` (hence the * name deferred). * * In the process of returning their deferred-dispatched events, event plugins * themselves can dispatch events on-demand without returning them from * `extractEvents`. Plugins might want to do this, so that they can use event * dispatching as a tool that helps them decide which events should be extracted * in the first place. * * "On-Demand-Dispatched Events": * * - On-demand-dispatched events are not returned from `extractEvents`. * - On-demand-dispatched events are dispatched during the process of returning * the deferred-dispatched events. * - They should not have side effects. * - They should be avoided, and/or eventually be replaced with another * abstraction that allows event plugins to perform multiple "rounds" of event * extraction. * * Therefore, the sequence of event dispatches becomes: * * - `R`s on-demand events (if any) (dispatched by `R` on-demand) * - `S`s on-demand events (if any) (dispatched by `S` on-demand) * - `C`s on-demand events (if any) (dispatched by `C` on-demand) * - `R`s extracted events (if any) (dispatched by `EventPluginHub`) * - `S`s extracted events (if any) (dispatched by `EventPluginHub`) * - `C`s extracted events (if any) (dispatched by `EventPluginHub`) * * In the case of `ResponderEventPlugin`: If the `startShouldSetResponder` * on-demand dispatch returns `true` (and some other details are satisfied) the * `onResponderGrant` deferred dispatched event is returned from * `extractEvents`. The sequence of dispatch executions in this case * will appear as follows: * * - `startShouldSetResponder` (`ResponderEventPlugin` dispatches on-demand) * - `touchStartCapture` (`EventPluginHub` dispatches as usual) * - `touchStart` (`EventPluginHub` dispatches as usual) * - `responderGrant/Reject` (`EventPluginHub` dispatches as usual) */ function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder. var bubbleShouldSetFrom = !responderInst ? targetInst : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target // (deepest ID) if it happens to be the current responder. The reasoning: // It's strange to get an `onMoveShouldSetResponder` when you're *already* // the responder. var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst; var shouldSetEvent = ResponderSyntheticEvent.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; if (skipOverBubbleShouldSetFrom) { accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent); } else { accumulateTwoPhaseDispatches(shouldSetEvent); } var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent); if (!shouldSetEvent.isPersistent()) { shouldSetEvent.constructor.release(shouldSetEvent); } if (!wantsResponderInst || wantsResponderInst === responderInst) { return null; } var extracted = void 0; var grantEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget); grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; accumulateDirectDispatches(grantEvent); var blockHostResponder = executeDirectDispatch(grantEvent) === true; if (responderInst) { var terminationRequestEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget); terminationRequestEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; accumulateDirectDispatches(terminationRequestEvent); var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent); if (!terminationRequestEvent.isPersistent()) { terminationRequestEvent.constructor.release(terminationRequestEvent); } if (shouldSwitch) { var terminateEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget); terminateEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; accumulateDirectDispatches(terminateEvent); extracted = accumulate(extracted, [grantEvent, terminateEvent]); changeResponder(wantsResponderInst, blockHostResponder); } else { var rejectEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget); rejectEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; accumulateDirectDispatches(rejectEvent); extracted = accumulate(extracted, rejectEvent); } } else { extracted = accumulate(extracted, grantEvent); changeResponder(wantsResponderInst, blockHostResponder); } return extracted; } /** * A transfer is a negotiation between a currently set responder and the next * element to claim responder status. Any start event could trigger a transfer * of responderInst. Any move event could trigger a transfer. * * @param {string} topLevelType Record from `BrowserEventConstants`. * @return {boolean} True if a transfer of responder could possibly occur. */ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { return topLevelInst && ( // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && topLevelType === TOP_SELECTION_CHANGE || isStartish(topLevelType) || isMoveish(topLevelType)); } /** * Returns whether or not this touch end event makes it such that there are no * longer any touches that started inside of the current `responderInst`. * * @param {NativeEvent} nativeEvent Native touch end event. * @return {boolean} Whether or not this touch end event ends the responder. */ function noResponderTouches(nativeEvent) { var touches = nativeEvent.touches; if (!touches || touches.length === 0) { return true; } for (var i = 0; i < touches.length; i++) { var activeTouch = touches[i]; var target = activeTouch.target; if (target !== null && target !== undefined && target !== 0) { // Is the original touch location inside of the current responder? var targetInst = getInstanceFromNode$1(target); if (isAncestor(responderInst, targetInst)) { return false; } } } return true; } var ResponderEventPlugin = { /* For unit testing only */ _getResponder: function () { return responderInst; }, eventTypes: eventTypes, /** * We must be resilient to `targetInst` being `null` on `touchMove` or * `touchEnd`. On certain platforms, this means that a native scroll has * assumed control and the original touch targets are destroyed. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (isStartish(topLevelType)) { trackedTouchCount += 1; } else if (isEndish(topLevelType)) { if (trackedTouchCount >= 0) { trackedTouchCount -= 1; } else { console.error('Ended a touch event which was not counted in `trackedTouchCount`.'); return null; } } ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null; // Responder may or may not have transferred on a new touch start/move. // Regardless, whoever is the responder after any potential transfer, we // direct all touch start/move/ends to them in the form of // `onResponderMove/Start/End`. These will be called for *every* additional // finger that move/start/end, dispatched directly to whoever is the // current responder at that moment, until the responder is "released". // // These multiple individual change touch events are are always bookended // by `onResponderGrant`, and one of // (`onResponderRelease/onResponderTerminate`). var isResponderTouchStart = responderInst && isStartish(topLevelType); var isResponderTouchMove = responderInst && isMoveish(topLevelType); var isResponderTouchEnd = responderInst && isEndish(topLevelType); var incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null; if (incrementalTouch) { var gesture = ResponderSyntheticEvent.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget); gesture.touchHistory = ResponderTouchHistoryStore.touchHistory; accumulateDirectDispatches(gesture); extracted = accumulate(extracted, gesture); } var isResponderTerminate = responderInst && topLevelType === TOP_TOUCH_CANCEL; var isResponderRelease = responderInst && !isResponderTerminate && isEndish(topLevelType) && noResponderTouches(nativeEvent); var finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null; if (finalTouch) { var finalEvent = ResponderSyntheticEvent.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget); finalEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; accumulateDirectDispatches(finalEvent); extracted = accumulate(extracted, finalEvent); changeResponder(null); } return extracted; }, GlobalResponderHandler: null, injection: { /** * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler * Object that handles any change in responder. Use this to inject * integration with an existing touch handling system etc. */ injectGlobalResponderHandler: function (GlobalResponderHandler) { ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler; } } }; // Inject react-dom's ComponentTree into this module. // Keep in sync with ReactDOM.js and ReactTestUtils.js: var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events; var getInstanceFromNode = _ReactDOM$__SECRET_IN[0]; var getNodeFromInstance = _ReactDOM$__SECRET_IN[1]; var getFiberCurrentPropsFromNode = _ReactDOM$__SECRET_IN[2]; var injectEventPluginsByName = _ReactDOM$__SECRET_IN[3]; setComponentTree(getFiberCurrentPropsFromNode, getInstanceFromNode, getNodeFromInstance); var ReactDOMUnstableNativeDependencies = Object.freeze({ ResponderEventPlugin: ResponderEventPlugin, ResponderTouchHistoryStore: ResponderTouchHistoryStore, injectEventPluginsByName: injectEventPluginsByName }); var unstableNativeDependencies = ReactDOMUnstableNativeDependencies; return unstableNativeDependencies; })));
/**! * MixItUp v3.0.0 * A high-performance, dependency-free library for animated filtering, sorting and more * Build 47693865-4fa6-4558-8a21-d91e4c4dd7c8 * * @copyright Copyright 2014-2016 KunkaLabs Limited. * @author KunkaLabs Limited. * @link https://www.kunkalabs.com/mixitup/ * * @license Commercial use requires a commercial license. * https://www.kunkalabs.com/mixitup/licenses/ * * Non-commercial use permitted under same terms as CC BY-NC 3.0 license. * http://creativecommons.org/licenses/by-nc/3.0/ */ (function(window) { 'use strict'; var mixitup = null, h = null, jq = null; (function() { var VENDORS = ['webkit', 'moz', 'o', 'ms'], canary = window.document.createElement('div'), i = -1; // window.requestAnimationFrame for (i = 0; i < VENDORS.length && !window.requestAnimationFrame; i++) { window.requestAnimationFrame = window[VENDORS[i] + 'RequestAnimationFrame']; } // Element.nextElementSibling if (typeof canary.nextElementSibling === 'undefined') { Object.defineProperty(window.Element.prototype, 'nextElementSibling', { get: function() { var el = this.nextSibling; while (el) { if (el.nodeType === 1) { return el; } el = el.nextSibling; } return null; } }); } // Element.matches (function(ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.machesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.oMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { return Array.prototype.indexOf.call(this.parentElement.querySelectorAll(selector), this) > -1; }; })(window.Element.prototype); // Object.keys // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = false, dontEnums = [], dontEnumsLength = -1; hasDontEnumBug = !({ toString: null }) .propertyIsEnumerable('toString'); dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; dontEnumsLength = dontEnums.length; return function(obj) { var result = [], prop = '', i = -1; if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Array.isArray // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } // Object.create // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create if (typeof Object.create !== 'function') { Object.create = (function(undefined) { var Temp = function() {}; return function (prototype, propertiesObject) { if (prototype !== Object(prototype) && prototype !== null) { throw TypeError('Argument must be an object, or null'); } Temp.prototype = prototype || {}; var result = new Temp(); Temp.prototype = null; if (propertiesObject !== undefined) { Object.defineProperties(result, propertiesObject); } if (prototype === null) { /* jshint ignore:start */ result.__proto__ = null; /* jshint ignore:end */ } return result; }; })(); } // String.prototyoe.trim if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; } // Array.prototype.indexOf // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement) { var n, k, t, len; if (this === null) { throw new TypeError(); } t = Object(this); len = t.length >>> 0; if (len === 0) { return -1; } n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n !== Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Function.prototype.bind // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { var aArgs, self, FNOP, fBound; if (typeof this !== 'function') { throw new TypeError(); } aArgs = Array.prototype.slice.call(arguments, 1); self = this; FNOP = function() {}; fBound = function() { return self.apply(this instanceof FNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { FNOP.prototype = this.prototype; } fBound.prototype = new FNOP(); return fBound; }; } // Element.prototype.dispatchEvent if (!window.Element.prototype.dispatchEvent) { window.Element.prototype.dispatchEvent = function(event) { try { return this.fireEvent('on' + event.type, event); } catch (err) {} }; } })(); /** * The `mixitup()` "factory" function creates and returns individual instances * of MixItUp, known as "mixers", on which API methods can be called. * * When loading MixItUp via a script tag, the factory function is accessed * via the global variable `mixitup`. When using a module loading * system (e.g. ES2015, CommonJS, RequireJS), the factory function is * exported into your module when you require the MixItUp library. * * @example * mixitup(container [,config] [,foreignDoc]) * * @example <caption>Example 1: Creating a mixer instance with an element reference</caption> * var containerEl = document.querySelector('.container'); * * var mixer = mixitup(containerEl); * * @example <caption>Example 2: Creating a mixer instance with a selector string</caption> * var mixer = mixitup('.container'); * * @example <caption>Example 3: Passing a configuration object</caption> * var mixer = mixitup(containerEl, { * animation: { * effects: 'fade scale(0.5)' * } * }); * * @example <caption>Example 4: Passing an iframe reference</caption> * var mixer = mixitup(containerEl, config, foreignDocument); * * @global * @namespace * @public * @kind function * @since 3.0.0 * @param {(Element|string)} container * A DOM element or selector string representing the container(s) on which to instantiate MixItUp. * @param {object} [config] * An optional "configuration object" used to customize the behavior of the MixItUp instance. * @param {object} [foreignDoc] * An optional reference to a `document`, which can be used to control a MixItUp instance in an iframe. * @return {mixitup.Mixer} * A "mixer" object holding the MixItUp instance. */ mixitup = function(container, config, foreignDoc) { var el = null, returnCollection = false, instance = null, facade = null, doc = null, output = null, instances = [], id = '', elements = [], i = -1; doc = foreignDoc || window.document; if (returnCollection = arguments[3]) { // A non-documented 4th paramater enabling control of multiple instances returnCollection = typeof returnCollection === 'boolean'; } if (typeof container === 'string') { elements = doc.querySelectorAll(container); } else if (container && typeof container === 'object' && h.isElement(container, doc)) { elements = [container]; } else if (container && typeof container === 'object' && container.length) { // Although not documented, the container may also be an array-like list of // elements such as a NodeList or jQuery collection, is returnCollection is true elements = container; } else { throw new Error(mixitup.messages.errorFactoryInvalidContainer()); } if (elements.length < 1) { throw new Error(mixitup.messages.errorFactoryContainerNotFound()); } for (i = 0; el = elements[i]; i++) { if (i > 0 && !returnCollection) break; if (!el.id) { id = 'MixItUp' + h.randomHex(); el.id = id; } else { id = el.id; } if (mixitup.instances[id] instanceof mixitup.Mixer) { instance = mixitup.instances[id]; if (!config || (config && config.debug && config.debug.showWarnings !== false)) { console.warn(mixitup.messages.warningFactoryPreexistingInstance()); } } else { instance = new mixitup.Mixer(); instance.attach(el, doc, id, config); mixitup.instances[id] = instance; } facade = new mixitup.Facade(instance); if (config && config.debug && config.debug.enable) { instances.push(instance); } else { instances.push(facade); } } if (returnCollection) { output = new mixitup.Collection(instances); } else { // Return the first instance regardless output = instances[0]; } return output; }; /** * The `.use()` static method is used to extend the functionality of mixitup with compatible * extensions and libraries in an environment with modular scoping e.g. ES2015, CommonJS, or RequireJS. * * You need only call the `.use()` function once per project, per extension, as module loaders * will cache a single reference to MixItUp inclusive of all changes made. * * @example * mixitup.use(extension) * * @example <caption>Example 1: Extending MixItUp with the Pagination Extension</caption> * * import mixitup from 'mixitup'; * import mixitupPagination from 'mixitup-pagination'; * * mixitup.use(mixitupPagination); * * // All mixers created by the factory function in all modules will now * // have pagination functionality * * var mixer = mixitup('.container'); * * @example <caption>Example 2: Activating the legacy jQuery API</caption> * * import mixitup from 'mixitup'; * import $ from 'jquery'; * * mixitup.use($); * * // MixItUp can now be used as a jQuery plugin, as per the v2 API * * $('.container').mixitup(); * * @public * @name use * @memberof mixitup * @kind function * @static * @since 3.0.0 * @param {*} extension A reference to the extension or library to be used. * @return {void} */ mixitup.use = function(extension) { // Call the extension's factory function, passing // the mixitup factory as a paramater if (typeof extension === 'function' && extension.TYPE === 'mixitup-extension') { // Mixitup extension if (typeof mixitup.extensions[extension.NAME] === 'undefined') { extension(mixitup); mixitup.extensions[extension.NAME] = extension; } } else if (extension.fn && extension.fn.jquery) { // jQuery mixitup.libraries.$ = extension; // Register MixItUp as a jQuery plugin to allow v2 API mixitup.registerJqPlugin(extension); } }; /** * @private * @static * @since 3.0.0 * @param {jQuery} $ * @return {void} */ mixitup.registerJqPlugin = function($) { $.fn.mixItUp = function() { var method = arguments[0], config = arguments[1], args = Array.prototype.slice.call(arguments, 1), outputs = [], chain = []; chain = this.each(function() { var instance = null, output = null; if (method && typeof method === 'string') { // jQuery-UI method syntax instance = mixitup.instances[this.id]; output = instance[method].apply(instance, args); if (typeof output !== 'undefined' && output !== null && typeof output.then !== 'function') outputs.push(output); } else { mixitup(this, config); } }); if (outputs.length) { return outputs.length > 1 ? outputs : outputs[0]; } else { return chain; } }; }; mixitup.instances = {}; mixitup.extensions = {}; mixitup.libraries = {}; /** * @private */ h = { /** * @private * @param {HTMLElement} el * @param {string} cls * @return {boolean} */ hasClass: function(el, cls) { return !!el.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }, /** * @private * @param {HTMLElement} el * @param {string} cls * @return {void} */ addClass: function(el, cls) { if (!this.hasClass(el, cls)) el.className += el.className ? ' ' + cls : cls; }, /** * @private * @param {HTMLElement} el * @param {string} cls * @return {void} */ removeClass: function(el, cls) { if (this.hasClass(el, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); el.className = el.className.replace(reg, ' ').trim(); } }, /** * Merges the properties of the source object onto the * target object. Alters the target object. * * @private * @param {object} destination * @param {object} source * @param {boolean} [deep=false] * @param {boolean} [handleErrors=false] * @return {void} */ extend: function(destination, source, deep, handleErrors) { var sourceKeys = [], key = '', i = -1; deep = deep || false; handleErrors = handleErrors || false; try { if (Array.isArray(source)) { for (i = 0; i < source.length; i++) { sourceKeys.push(i); } } else if (source) { sourceKeys = Object.keys(source); } for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (!deep || typeof source[key] !== 'object' || this.isElement(source[key])) { // All non-object properties, or all properties if shallow extend destination[key] = source[key]; } else if (Array.isArray(source[key])) { // Arrays if (!destination[key]) { destination[key] = []; } this.extend(destination[key], source[key], deep, handleErrors); } else { // Objects if (!destination[key]) { destination[key] = {}; } this.extend(destination[key], source[key], deep, handleErrors); } } } catch(err) { if (handleErrors) { this.handleExtendError(err, destination); } else { throw err; } } return destination; }, /** * @private * @param {Error} err * @param {object} destination * @return {void} */ handleExtendError: function(err, destination) { var re = /property "?(\w*)"?[,:] object/i, matches = null, erroneous = '', message = '', suggestion = '', probableMatch = '', key = '', mostMatchingChars = -1, i = -1; if (err instanceof TypeError && (matches = re.exec(err.message))) { erroneous = matches[1]; for (key in destination) { i = 0; while (i < erroneous.length && erroneous.charAt(i) === key.charAt(i)) { i++; } if (i > mostMatchingChars) { mostMatchingChars = i; probableMatch = key; } } if (mostMatchingChars > 1) { suggestion = mixitup.messages.errorConfigInvalidPropertySuggestion({ probableMatch: probableMatch }); } message = mixitup.messages.errorConfigInvalidProperty({ erroneous: erroneous, suggestion: suggestion }); throw new TypeError(message); } throw err; }, /** * @private * @param {string} str * @return {function} */ template: function(str) { var re = /\${([\w]*)}/g, dynamics = {}, matches = null; while ((matches = re.exec(str))) { dynamics[matches[1]] = new RegExp('\\${' + matches[1] + '}', 'g'); } return function(data) { var key = '', output = str; data = data || {}; for (key in dynamics) { output = output.replace(dynamics[key], typeof data[key] !== 'undefined' ? data[key] : ''); } return output; }; }, /** * @private * @param {HTMLElement} el * @param {string} type * @param {function} fn * @param {boolean} useCapture * @return {void} */ on: function(el, type, fn, useCapture) { if (!el) return; if (el.addEventListener) { el.addEventListener(type, fn, useCapture); } else if (el.attachEvent) { el['e' + type + fn] = fn; el[type + fn] = function() { el['e' + type + fn](window.event); }; el.attachEvent('on' + type, el[type + fn]); } }, /** * @private * @param {HTMLElement} el * @param {string} type * @param {function} fn * @return {void} */ off: function(el, type, fn) { if (!el) return; if (el.removeEventListener) { el.removeEventListener(type, fn, false); } else if (el.detachEvent) { el.detachEvent('on' + type, el[type + fn]); el[type + fn] = null; } }, /** * @private * @param {string} eventType * @param {object} detail * @param {Document} [doc] * @return {CustomEvent} */ getCustomEvent: function(eventType, detail, doc) { var event = null; doc = doc || window.document; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventType, { detail: detail, bubbles: true, cancelable: true }); } else if (typeof doc.createEvent === 'function') { event = doc.createEvent('CustomEvent'); event.initCustomEvent(eventType, true, true, detail); } else { event = doc.createEventObject(), event.type = eventType; event.returnValue = false; event.cancelBubble = false; event.detail = detail; } return event; }, /** * @private * @param {Event} e * @return {Event} */ getOriginalEvent: function(e) { if (e.touches && e.touches.length) { return e.touches[0]; } else if (e.changedTouches && e.changedTouches.length) { return e.changedTouches[0]; } else { return e; } }, /** * @private * @param {HTMLElement} el * @param {string} selector * @return {Number} */ index: function(el, selector) { var i = 0; while ((el = el.previousElementSibling) !== null) { if (!selector || el.matches(selector)) { ++i; } } return i; }, /** * Converts a dash or snake-case string to camel case. * * @private * @param {string} str * @param {boolean} [isPascal] * @return {string} */ camelCase: function(str) { return str.toLowerCase().replace(/([_-][a-z])/g, function($1) { return $1.toUpperCase().replace(/[_-]/, ''); }); }, /** * Converts a dash or snake-case string to pascal case. * * @private * @param {string} str * @param {boolean} [isPascal] * @return {string} */ pascalCase: function(str) { return (str = this.camelCase(str)).charAt(0).toUpperCase() + str.slice(1); }, /** * Converts a camel or pascal-case string to dash case. * * @private * @param {string} str * @return {string} */ dashCase: function(str) { return str.replace(/([A-Z])/g, '-$1').replace(/^-/, '').toLowerCase(); }, /** * @private * @param {HTMLElement} el * @param {HTMLHtmlElement} [doc] * @return {boolean} */ isElement: function(el, doc) { doc = doc || window.document; if ( window.HTMLElement && el instanceof window.HTMLElement ) { return true; } else if ( doc.defaultView && doc.defaultView.HTMLElement && el instanceof doc.defaultView.HTMLElement ) { return true; } else { return ( el !== null && el.nodeType === 1 && typeof el.nodeName === 'string' ); } }, /** * @private * @param {string} htmlString * @param {HTMLHtmlElement} [doc] * @return {DocumentFragment} */ createElement: function(htmlString, doc) { var frag = null, temp = null; doc = doc || window.document; frag = doc.createDocumentFragment(); temp = doc.createElement('div'); temp.innerHTML = htmlString; while (temp.firstChild) { frag.appendChild(temp.firstChild); } return frag; }, /** * @private * @param {Node} node * @return {void} */ removeWhitespace: function(node) { var deleting; while (node && node.nodeName === '#text') { deleting = node; node = node.previousSibling; deleting.parentElement && deleting.parentElement.removeChild(deleting); } }, /** * @private * @param {Array<*>} a * @param {Array<*>} b * @return {boolean} */ isEqualArray: function(a, b) { var i = a.length; if (i !== b.length) return false; while (i--) { if (a[i] !== b[i]) return false; } return true; }, /** * @private * @param {object} a * @param {object} b * @return {boolean} */ deepEquals: function(a, b) { var key; if (typeof a === 'object' && a && typeof b === 'object' && b) { if (Object.keys(a).length !== Object.keys(b).length) return false; for (key in a) { if (!b.hasOwnProperty(key) || !this.deepEquals(a[key], b[key])) return false; } } else if (a !== b) { return false; } return true; }, /** * @private * @param {Array<*>} oldArray * @return {Array<*>} */ arrayShuffle: function(oldArray) { var newArray = oldArray.slice(), len = newArray.length, i = len, p = -1, t = []; while (i--) { p = ~~(Math.random() * len); t = newArray[i]; newArray[i] = newArray[p]; newArray[p] = t; } return newArray; }, /** * @private * @param {object} list */ arrayFromList: function(list) { var output, i; try { return Array.prototype.slice.call(list); } catch(err) { output = []; for (i = 0; i < list.length; i++) { output.push(list[i]); } return output; } }, /** * @private * @param {function} func * @param {Number} wait * @param {boolean} immediate * @return {function} */ debounce: function(func, wait, immediate) { var timeout; return function() { var self = this, args = arguments, callNow = immediate && !timeout, later = null; later = function() { timeout = null; if (!immediate) { func.apply(self, args); } }; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(self, args); }; }, /** * @private * @param {HTMLElement} element * @return {object} */ position: function(element) { var xPosition = 0, yPosition = 0, offsetParent = element; while (element) { xPosition -= element.scrollLeft; yPosition -= element.scrollTop; if (element === offsetParent) { xPosition += element.offsetLeft; yPosition += element.offsetTop; offsetParent = element.offsetParent; } element = element.parentElement; } return { x: xPosition, y: yPosition }; }, /** * @private * @param {object} node1 * @param {object} node2 * @return {Number} */ getHypotenuse: function(node1, node2) { var distanceX = node1.x - node2.x, distanceY = node1.y - node2.y; distanceX = distanceX < 0 ? distanceX * -1 : distanceX, distanceY = distanceY < 0 ? distanceY * -1 : distanceY; return Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2)); }, /** * Calcuates the area of intersection between two rectangles and expresses it as * a ratio in comparison to the area of the first rectangle. * * @private * @param {Rect} box1 * @param {Rect} box2 * @return {number} */ getIntersectionRatio: function(box1, box2) { var controlArea = box1.width * box1.height, intersectionX = -1, intersectionY = -1, intersectionArea = -1, ratio = -1; intersectionX = Math.max(0, Math.min(box1.left + box1.width, box2.left + box2.width) - Math.max(box1.left, box2.left)); intersectionY = Math.max(0, Math.min(box1.top + box1.height, box2.top + box2.height) - Math.max(box1.top, box2.top)); intersectionArea = intersectionY * intersectionX; ratio = intersectionArea / controlArea; return ratio; }, /** * @private * @param {object} el * @param {string} selector * @param {boolean} [includeSelf] * @param {HTMLHtmlElement} [doc] * @return {Element|null} */ closestParent: function(el, selector, includeSelf, doc) { var parent = el.parentNode; doc = doc || window.document; if (includeSelf && el.matches(selector)) { return el; } while (parent && parent != doc.body) { if (parent.matches && parent.matches(selector)) { return parent; } else if (parent.parentNode) { parent = parent.parentNode; } else { return null; } } return null; }, /** * @private * @param {HTMLElement} el * @param {string} selector * @param {HTMLHtmlElement} [doc] * @return {NodeList} */ children: function(el, selector, doc) { var children = [], tempId = ''; doc = doc || window.doc; if (el) { if (!el.id) { tempId = 'Temp' + this.randomHexKey(); el.id = tempId; } children = doc.querySelectorAll('#' + el.id + ' > ' + selector); if (tempId) { el.removeAttribute('id'); } } return children; }, /** * Creates a clone of a provided array, with any empty strings removed. * * @private * @param {Array<*>} originalArray * @return {Array<*>} */ clean: function(originalArray) { var cleanArray = [], i = -1; for (i = 0; i < originalArray.length; i++) { if (originalArray[i] !== '') { cleanArray.push(originalArray[i]); } } return cleanArray; }, /** * Abstracts an ES6 promise into a q-like deferred interface for storage and deferred resolution. * * @private * @param {object} libraries * @return {h.Deferred} */ defer: function(libraries) { var deferred = null, promiseWrapper = null, $ = null; promiseWrapper = new this.Deferred(); if (mixitup.features.has.promises) { // ES6 native promise or polyfill promiseWrapper.promise = new Promise(function(resolve, reject) { promiseWrapper.resolve = resolve; promiseWrapper.reject = reject; }); } else if (($ = (window.jQuery || libraries.$)) && typeof $.Deferred === 'function') { // jQuery deferred = $.Deferred(); promiseWrapper.promise = deferred.promise(); promiseWrapper.resolve = deferred.resolve; promiseWrapper.reject = deferred.reject; } else if (window.console) { // No implementation console.warn(mixitup.messages.warningNoPromiseImplementation()); } return promiseWrapper; }, /** * @private * @param {Array<Promise>} tasks * @param {object} libraries * @return {Promise<Array>} */ all: function(tasks, libraries) { var $ = null; if (mixitup.features.has.promises) { return Promise.all(tasks); } else if (($ = (window.jQuery || libraries.$)) && typeof $.when === 'function') { return $.when.apply($, tasks) .done(function() { // jQuery when returns spread arguments rather than an array or resolutions return arguments; }); } // No implementation if (window.console) { console.warn(mixitup.messages.warningNoPromiseImplementation()); } return []; }, /** * @private * @param {HTMLElement} el * @param {string} property * @param {Array<string>} vendors * @return {string} */ getPrefix: function(el, property, vendors) { var i = -1, prefix = ''; if (h.dashCase(property) in el.style) return ''; for (i = 0; prefix = vendors[i]; i++) { if (prefix + property in el.style) { return prefix.toLowerCase(); } } return 'unsupported'; }, /** * @private * @return {string} */ randomHex: function() { return ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6).toUpperCase(); }, /** * @private * @param {HTMLDocument} [doc] * @return {object} */ getDocumentState: function(doc) { doc = typeof doc.body === 'object' ? doc : window.document; return { scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, docHeight: doc.documentElement.scrollHeight }; }, /** * @private * @param {object} obj * @param {function} fn * @return {function} */ bind: function(obj, fn) { return function() { return fn.apply(obj, arguments); }; }, /** * @private * @param {HTMLElement} el * @return {boolean} */ isVisible: function(el) { var styles = null; if (el.offsetParent) return true; styles = window.getComputedStyle(el); if ( styles.position === 'fixed' && styles.visibility !== 'hidden' && styles.opacity !== '0' ) { // Fixed elements report no offsetParent, // but may still be invisible return true; } return false; }, /** * @private * @param {object} obj */ seal: function(obj) { if (typeof Object.seal === 'function') { Object.seal(obj); } }, /** * @private * @param {object} obj */ freeze: function(obj) { if (typeof Object.freeze === 'function') { Object.freeze(obj); } }, /** * @private * @param {string} control * @param {string} specimen * @return {boolean} */ compareVersions: function(control, specimen) { var controlParts = control.split('.'), specimenParts = specimen.split('.'), controlPart = -1, specimenPart = -1, i = -1; for (i = 0; i < controlParts.length; i++) { controlPart = parseInt(controlParts[i]); specimenPart = parseInt(specimenParts[i] || 0); if (specimenPart < controlPart) { return false; } else if (specimenPart > controlPart) { return true; } } return true; }, /** * @private * @constructor */ Deferred: function() { this.promise = null; this.resolve = null; this.reject = null; this.id = h.randomHex(); }, /** * @private * @param {object} obj * @return {boolean} */ isEmptyObject: function(obj) { var key = ''; if (typeof Object.keys === 'function') { return Object.keys(obj).length === 0; } for (key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; }, /** * @param {mixitup.Config.ClassNames} classNames * @param {string} elementName * @param {string} [modifier] * @return {string} */ getClassname: function(classNames, elementName, modifier) { var classname = ''; classname += classNames.block; if (classname.length) { classname += classNames.delineatorElement; } classname += classNames['element' + this.pascalCase(elementName)]; if (!modifier) return classname; if (classname.length) { classname += classNames.delineatorModifier; } classname += modifier; return classname; }, /** * Returns the value of a property on a given object via its string key. * * @param {object} obj * @param {string} stringKey * @return {*} value */ getProperty: function(obj, stringKey) { var parts = stringKey.split('.'), returnCurrent = null, current = '', i = 0; if (!stringKey) { return obj; } returnCurrent = function(obj) { if (!obj) { return null; } else { return obj[current]; } }; while (i < parts.length) { current = parts[i]; obj = returnCurrent(obj); i++; } if (typeof obj !== 'undefined') { return obj; } else { return null; } } }; mixitup.h = h; /** * The Base class adds instance methods to all other extensible MixItUp classes, * enabling the calling of any registered hooks. * * @constructor * @namespace * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Base = function() {}; mixitup.Base.prototype = { constructor: mixitup.Base, /** * Calls any registered hooks for the provided action. * * @memberof mixitup.Base * @private * @instance * @since 2.0.0 * @param {string} actionName * @param {Array<*>} args * @return {void} */ callActions: function(actionName, args) { var self = this, hooks = self.constructor.actions[actionName], extensionName = ''; if (!hooks || h.isEmptyObject(hooks)) return; for (extensionName in hooks) { hooks[extensionName].apply(self, args); } }, /** * Calls any registered hooks for the provided filter. * * @memberof mixitup.Base * @private * @instance * @since 2.0.0 * @param {string} filterName * @param {*} input * @param {Array<*>} args * @return {*} */ callFilters: function(filterName, input, args) { var self = this, hooks = self.constructor.filters[filterName], output = input, extensionName = ''; if (!hooks || h.isEmptyObject(hooks)) return output; args = args || []; for (extensionName in hooks) { args = h.arrayFromList(args); args.unshift(output); output = hooks[extensionName].apply(self, args); } return output; } }; /** * The BaseStatic class holds a set of static methods which are then added to all other * extensible MixItUp classes as a means of integrating extensions via the addition of new * methods and/or actions and hooks. * * @constructor * @namespace * @memberof mixitup * @private * @since 3.0.0 */ mixitup.BaseStatic = function() { this.actions = {}; this.filters = {}; /** * Performs a shallow extend on the class's prototype, adding one or more new members to * the class in a single operation. * * @memberof mixitup.BaseStatic * @public * @static * @since 2.1.0 * @param {object} extension * @return {void} */ this.extend = function(extension) { h.extend(this.prototype, extension); }; /** * Registers a function to be called on the action hook of the provided name. * * @memberof mixitup.BaseStatic * @public * @static * @since 2.1.0 * @param {string} hookName * @param {string} extensionName * @param {function} func * @return {void} */ this.registerAction = function(hookName, extensionName, func) { (this.actions[hookName] = this.actions[hookName] || {})[extensionName] = func; }; /** * Registers a function to be called on the filter of the provided name. * * @memberof mixitup.BaseStatic * @public * @static * @since 2.1.0 * @param {string} hookName * @param {string} extensionName * @param {function} func * @return {void} */ this.registerFilter = function(hookName, extensionName, func) { (this.filters[hookName] = this.filters[hookName] || {})[extensionName] = func; }; }; /** * The `mixitup.Features` class performs all feature and CSS prefix detection * neccessary for MixItUp to function correctly, as well as storing various * string and array constants. All feature decection is on evaluation of the * library and stored in a singleton instance for use by other internal classes. * * @constructor * @namespace * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Features = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.boxSizingPrefix = ''; this.transformPrefix = ''; this.transitionPrefix = ''; this.boxSizingPrefix = ''; this.transformProp = ''; this.transformRule = ''; this.transitionProp = ''; this.perspectiveProp = ''; this.perspectiveOriginProp = ''; this.has = new mixitup.Has(); this.canary = null; this.BOX_SIZING_PROP = 'boxSizing'; this.TRANSITION_PROP = 'transition'; this.TRANSFORM_PROP = 'transform'; this.PERSPECTIVE_PROP = 'perspective'; this.PERSPECTIVE_ORIGIN_PROP = 'perspectiveOrigin'; this.VENDORS = ['Webkit', 'moz', 'O', 'ms']; this.TWEENABLE = [ 'opacity', 'width', 'height', 'marginRight', 'marginBottom', 'x', 'y', 'scale', 'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ' ]; this.callActions('afterConstruct'); }; mixitup.BaseStatic.call(mixitup.Features); mixitup.Features.prototype = Object.create(mixitup.Base.prototype); h.extend(mixitup.Features.prototype, /** @lends mixitup.Features */ { constructor: mixitup.Features, /** * @private * @return {void} */ init: function() { var self = this; self.callActions('beforeInit', arguments); self.canary = document.createElement('div'); self.setPrefixes(); self.runTests(); self.callActions('beforeInit', arguments); }, /** * @private * @return {void} */ runTests: function() { var self = this; self.callActions('beforeRunTests', arguments); self.has.promises = typeof window.Promise === 'function'; self.has.transitions = self.transitionPrefix !== 'unsupported'; self.callActions('afterRunTests', arguments); h.freeze(self.has); }, /** * @private * @return {void} */ setPrefixes: function() { var self = this; self.callActions('beforeSetPrefixes', arguments); self.transitionPrefix = h.getPrefix(self.canary, 'Transition', self.VENDORS); self.transformPrefix = h.getPrefix(self.canary, 'Transform', self.VENDORS); self.boxSizingPrefix = h.getPrefix(self.canary, 'BoxSizing', self.VENDORS); self.boxSizingProp = self.boxSizingPrefix ? self.boxSizingPrefix + h.pascalCase(self.BOX_SIZING_PROP) : self.BOX_SIZING_PROP; self.transitionProp = self.transitionPrefix ? self.transitionPrefix + h.pascalCase(self.TRANSITION_PROP) : self.TRANSITION_PROP; self.transformProp = self.transformPrefix ? self.transformPrefix + h.pascalCase(self.TRANSFORM_PROP) : self.TRANSFORM_PROP; self.transformRule = self.transformPrefix ? '-' + self.transformPrefix + '-' + self.TRANSFORM_PROP : self.TRANSFORM_PROP; self.perspectiveProp = self.transformPrefix ? self.transformPrefix + h.pascalCase(self.PERSPECTIVE_PROP) : self.PERSPECTIVE_PROP; self.perspectiveOriginProp = self.transformPrefix ? self.transformPrefix + h.pascalCase(self.PERSPECTIVE_ORIGIN_PROP) : self.PERSPECTIVE_ORIGIN_PROP; self.callActions('afterSetPrefixes', arguments); } }); /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Has = function() { this.transitions = false; this.promises = false; h.seal(this); }; // Assign a singleton instance to `mixitup.features` and initialise: mixitup.features = new mixitup.Features(); mixitup.features.init(); /** * A group of properties defining the mixer's animation and effects settings. * * @constructor * @memberof mixitup.Config * @name animation * @namespace * @public * @since 2.0.0 */ mixitup.ConfigAnimation = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A boolean dictating whether or not animation should be enabled for the MixItUp instance. * If `false`, all operations will occur instantly and syncronously, although callback * functions and any returned promises will still be fulfilled. * * @example <caption>Example: Create a mixer with all animations disabled</caption> * var mixer = mixitup(containerEl, { * animation: { * enable: false * } * }); * * @name enable * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default true */ this.enable = true; /** * A string of one or more space-seperated properties to which transitions will be * applied for all filtering animations. * * Properties can be listed any order or combination, although they will be applied in a specific * predefined order to produce consistent results. * * To learn more about available effects, experiment with our <a href="https://www.kunkalabs.com/mixitup/"> * sandbox demo</a> and try out the "Export config" button in the Animation options drop down. * * @example <caption>Example: Apply "fade" and "translateZ" effects to all animations</caption> * // As targets are filtered in and out, they will fade between * // opacity 1 and 0 and transform between translateZ(-100px) and * // translateZ(0). * * var mixer = mixitup(containerEl, { * animation: { * effects: 'fade translateZ(-100px)' * } * }); * * @name effects * @memberof mixitup.Config.animation * @instance * @type {string} * @default 'fade scale' */ this.effects = 'fade scale'; /** * A string of one or more space-seperated effects to be applied only to filter-in * animations, overriding `config.animation.effects` if set. * * @example <caption>Example: Apply downwards vertical translate to targets being filtered in</caption> * * var mixer = mixitup(containerEl, { * animation: { * effectsIn: 'fade translateY(-100%)' * } * }); * * @name effectsIn * @memberof mixitup.Config.animation * @instance * @type {string} * @default '' */ this.effectsIn = ''; /** * A string of one or more space-seperated effects to be applied only to filter-out * animations, overriding `config.animation.effects` if set. * * @example <caption>Example: Apply upwards vertical translate to targets being filtered out</caption> * * var mixer = mixitup(containerEl, { * animation: { * effectsOut: 'fade translateY(-100%)' * } * }); * * @name effectsOut * @memberof mixitup.Config.animation * @instance * @type {string} * @default '' */ this.effectsOut = ''; /** * An integer dictating the duration of all MixItUp animations in milliseconds, not * including any additional delay apllied via the `'stagger'` effect. * * @example <caption>Example: Apply an animation duration of 200ms to all mixitup animations</caption> * * var mixer = mixitup(containerEl, { * animation: { * duration: 200 * } * }); * * @name duration * @memberof mixitup.Config.animation * @instance * @type {number} * @default 600 */ this.duration = 600; /** * A valid CSS3 transition-timing function or shorthand. For a full list of accepted * values, visit <a href="http://easings.net" target="_blank">easings.net</a>. * * @example <caption>Example 1: Apply "ease-in-out" easing to all animations</caption> * * var mixer = mixitup(containerEl, { * animation: { * easing: 'ease-in-out' * } * }); * * @example <caption>Example 2: Apply a custom "cubic-bezier" easing function to all animations</caption> * var mixer = mixitup(containerEl, { * animation: { * easing: 'cubic-bezier(0.645, 0.045, 0.355, 1)' * } * }); * * @name easing * @memberof mixitup.Config.animation * @instance * @type {string} * @default 'ease' */ this.easing = 'ease'; /** * A boolean dictating whether or not to apply perspective to the MixItUp container * during animations. By default, perspective is always applied and creates the * illusion of three-dimensional space for effects such as `translateZ`, `rotateX`, * and `rotateY`. * * You may wish to disable this and define your own perspective settings via CSS. * * @example <caption>Example: Prevent perspective from being applied to any 3D transforms</caption> * var mixer = mixitup(containerEl, { * animation: { * applyPerspective: false * } * }); * * @name applyPerspective * @memberof mixitup.Config.animation * @instance * @type {bolean} * @default true */ this.applyPerspective = true; /** * The perspective distance value to be applied to the container during animations, * affecting any 3D-transform-based effects. * * @example <caption>Example: Set a perspective distance of 2000px</caption> * var mixer = mixitup(containerEl, { * animation: { * effects: 'rotateY(-25deg)', * perspectiveDistance: '2000px' * } * }); * * @name perspectiveDistance * @memberof mixitup.Config.animation * @instance * @type {string} * @default '3000px' */ this.perspectiveDistance = '3000px'; /** * The perspective-origin value to be applied to the container during animations, * affecting any 3D-transform-based effects. * * @example <caption>Example: Set a perspective origin in the top-right of the container</caption> * var mixer = mixitup(containerEl, { * animation: { * effects: 'transateZ(-200px)', * perspectiveOrigin: '100% 0' * } * }); * * @name perspectiveOrigin * @memberof mixitup.Config.animation * @instance * @type {string} * @default '50% 50%' */ this.perspectiveOrigin = '50% 50%'; /** * A boolean dictating whether or not to enable the queuing of operations. * * If `true` (default), and a control is clicked or an API call is made while another * operation is progress, the operation will go into the queue and will be automatically exectuted * when the previous operaitons is finished. * * If `false`, any requested operations will be ignored, and the `onMixBusy` callback and `mixBusy` * event will be fired. If `debug.showWarnings` is enabled, a console warning will also occur. * * @example <caption>Example: Disable queuing</caption> * var mixer = mixitup(containerEl, { * animation: { * queue: false * } * }); * * @name queue * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default true */ this.queue = true; /** * An integer dictacting the maximum number of operations allowed in the queue at * any time, when queuing is enabled. * * @example <caption>Example: Allow a maximum of 5 operations in the queue at any time</caption> * var mixer = mixitup(containerEl, { * animation: { * queueLimit: 5 * } * }); * * @name queueLimit * @memberof mixitup.Config.animation * @instance * @type {number} * @default 3 */ this.queueLimit = 3; /** * A boolean dictating whether or not to transition the height and width of the * container as elements are filtered in and out. If disabled, the container height * will change abruptly. * * It may be desirable to disable this on mobile devices as the CSS `height` and * `width` properties do not receive GPU-acceleration and can therefore cause stuttering. * * @example <caption>Example 1: Disable the transitioning of the container height and/or width</caption> * var mixer = mixitup(containerEl, { * animation: { * animateResizeContainer: false * } * }); * * @example <caption>Example 2: Disable the transitioning of the container height and/or width for mobile devices only</caption> * var mixer = mixitup(containerEl, { * animation: { * animateResizeContainer: myFeatureTests.isMobile ? false : true * } * }); * * @name animateResizeContainer * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default true */ this.animateResizeContainer = true; /** * A boolean dictating whether or not to transition the height and width of target * elements as they change throughout the course of an animation. * * This is often a must for flex-box grid layouts where the size of target elements may change * depending on final their position in relation to their siblings, or for `.changeLayout()` * operations where the size of targets change between layouts. * * NB: This feature requires additional calculations and manipulation to non-hardware-accelerated * properties which may adversely affect performance on slower devices, and is therefore * disabled by default. * * @example <caption>Example: Enable the transitioning of target widths and heights</caption> * var mixer = mixitup(containerEl, { * animation: { * animateResizeTargets: true * } * }); * * @name animateResizeTargets * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default false */ this.animateResizeTargets = false; /** * A custom function used to manipulate the order in which the stagger delay is * incremented when using the ‘stagger’ effect. * * When using the 'stagger' effect, the delay applied to each target element is incremented * based on its index. You may create a custom function to manipulate the order in which the * delay is incremented and create engaging non-linear stagger effects. * * The function receives the index of the target element as a parameter, and must * return an integer which serves as the multiplier for the stagger delay. * * @example <caption>Example 1: Stagger target elements by column in a 3-column grid</caption> * var mixer = mixitup(containerEl, { * animation: { * effects: 'fade stagger(100ms)', * staggerSequence: function(i) { * return i % 3; * } * } * }); * * @example <caption>Example 2: Using an algorithm to produce a more complex sequence</caption> * var mixer = mixitup(containerEl, { * animation: { * effects: 'fade stagger(100ms)', * staggerSequence: function(i) { * return (2*i) - (5*((i/3) - ((1/3) * (i%3)))); * } * } * }); * * @name staggerSequence * @memberof mixitup.Config.animation * @instance * @type {function} * @default null */ this.staggerSequence = null; /** * A boolean dictating whether or not to reverse the direction of `translate` * and `rotate` transforms for elements being filtered out. * * It can be used to create carousel-like animations where elements enter and exit * from opposite directions. If enabled, the effect `translateX(-100%)` for elements * being filtered in would become `translateX(100%)` for targets being filtered out. * * This functionality can also be achieved by providing seperate effects * strings for `config.animation.effectsIn` and `config.animation.effectsOut`. * * @example <caption>Example: Reverse the desired direction on any translate/rotate effect for targets being filtered out</caption> * // Elements being filtered in will be translated from '100%' to '0' while * // elements being filtered out will be translated from 0 to '-100%' * * var mixer = mixitup(containerEl, { * animation: { * effects: 'fade translateX(100%)', * reverseOut: true, * nudge: false // Disable nudging to create a carousel-like effect * } * }); * * @name reverseOut * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default false */ this.reverseOut = false; /** * A boolean dictating whether or not to "nudge" the animation path of targets * when they are being filtered in and out simulatenously. * * This has been the default behavior of MixItUp since version 1, but it * may be desirable to disable this effect when filtering directly from * one exclusive set of targets to a different exclusive set of targets, * to create a carousel-like effect, or a generally more subtle animation. * * @example <caption>Example: Disable the "nudging" of targets being filtered in and out simulatenously</caption> * * var mixer = mixitup(containerEl, { * animation: { * nudge: false * } * }); * * @name nudge * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default true */ this.nudge = true; /** * A boolean dictating whether or not to clamp the height of the container while MixItUp's * geometry tests are carried out before an operation. * * To prevent scroll-bar flicker, clamping is turned on by default. But in the case where the * height of the container might affect its vertical positioning in the viewport * (e.g. a vertically-centered container), this should be turned off to ensure accurate * test results and a smooth animation. * * @example <caption>Example: Disable container height-clamping</caption> * * var mixer = mixitup(containerEl, { * animation: { * clampHeight: false * } * }); * * @name clampHeight * @memberof mixitup.Config.animation * @instance * @type {boolean} * @default true */ this.clampHeight = true; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigAnimation); mixitup.ConfigAnimation.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigAnimation.prototype.constructor = mixitup.ConfigAnimation; /** * A group of optional callback functions to be invoked at various * points within the lifecycle of a mixer operation. * * Each function is analogous to an event of the same name triggered from the * container element, and is invoked immediately after it. * * All callback functions receive the current `state` object as their first * argument, as well as other more specific arguments described below. * * @constructor * @memberof mixitup.Config * @name callbacks * @namespace * @public * @since 2.0.0 */ mixitup.ConfigCallbacks = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A callback function invoked immediately after any MixItUp operation is requested * and before animations have begun. * * A second `futureState` argument is passed to the function which represents the final * state of the mixer once the requested operation has completed. * * @example <caption>Example: Adding an `onMixStart` callback function</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixStart: function(state, futureState) { * console.log('Starting operation...'); * } * } * }); * * @name onMixStart * @memberof mixitup.Config.callbacks * @instance * @type {function} * @default null */ this.onMixStart = null; /** * A callback function invoked when a MixItUp operation is requested while another * operation is in progress, and the animation queue is full, or queueing * is disabled. * * @example <caption>Example: Adding an `onMixBusy` callback function</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixBusy: function(state) { * console.log('Mixer busy'); * } * } * }); * * @name onMixBusy * @memberof mixitup.Config.callbacks * @instance * @type {function} * @default null */ this.onMixBusy = null; /** * A callback function invoked after any MixItUp operation has completed, and the * state has been updated. * * @example <caption>Example: Adding an `onMixEnd` callback function</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixEnd: function(state) { * console.log('Operation complete'); * } * } * }); * * @name onMixEnd * @memberof mixitup.Config.callbacks * @instance * @type {function} * @default null */ this.onMixEnd = null; /** * A callback function invoked whenever an operation "fails", i.e. no targets * could be found matching the requested filter. * * @example <caption>Example: Adding an `onMixFail` callback function</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixFail: function(state) { * console.log('No items could be found matching the requested filter'); * } * } * }); * * @name onMixFail * @memberof mixitup.Config.callbacks * @instance * @type {function} * @default null */ this.onMixFail = null; /** * A callback function invoked whenever a MixItUp control is clicked, and before its * respective operation is requested. * * The clicked element is assigned to the `this` keyword within the function. The original * click event is passed to the function as the second argument, which can be useful if * using `<a>` tags as controls where the default behavior needs to be prevented. * * Returning `false` from the callback will prevent the control click from triggering * an operation. * * @example <caption>Example 1: Adding an `onMixClick` callback function</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixClick: function(state, originalEvent) { * console.log('The control "' + this.innerText + '" was clicked'); * } * } * }); * * @example <caption>Example 2: Using `onMixClick` to manipulate the original click event</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixClick: function(state, originalEvent) { * // Prevent original click event from bubbling up: * originalEvent.stopPropagation(); * * // Prevent default behavior of clicked element: * originalEvent.preventDefault(); * } * } * }); * * @example <caption>Example 3: Using `onMixClick` to conditionally cancel operations</caption> * var mixer = mixitup(containerEl, { * callbacks: { * onMixClick: function(state, originalEvent) { * // Perform some conditional check: * * if (myApp.isLoading) { * // By returning false, we can prevent the control click from triggering an operation. * * return false; * } * } * } * }); * * @name onMixClick * @memberof mixitup.Config.callbacks * @instance * @type {function} * @default null */ this.onMixClick = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigCallbacks); mixitup.ConfigCallbacks.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigCallbacks.prototype.constructor = mixitup.ConfigCallbacks; /** * A group of properties relating to clickable control elements. * * @constructor * @memberof mixitup.Config * @name controls * @namespace * @public * @since 2.0.0 */ mixitup.ConfigControls = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A boolean dictating whether or not controls should be enabled for the mixer instance. * * If `true` (default behavior), MixItUp will search the DOM for any clickable elements with * `data-filter`, `data-sort` or `data-toggle` attributes, and bind them for click events. * * If `false`, no click handlers will be bound, and all functionality must therefore be performed * via the mixer's API methods. * * If you do not intend to use the default controls, setting this property to `false` will * marginally improve the startup time of your mixer instance, and will also prevent any other active * mixer instances in the DOM which are bound to controls from controlling the instance. * * @example <caption>Example: Disabling controls</caption> * var mixer = mixitup(containerEl, { * controls: { * enable: false * } * }); * * // With the default controls disabled, we can only control * // the mixer via its API methods, e.g.: * * mixer.filter('.cat-1'); * * @name enable * @memberof mixitup.Config.controls * @instance * @type {boolean} * @default true */ this.enable = true; /** * A boolean dictating whether or not to use event delegation when binding click events * to the default controls. * * If `false` (default behavior), each control button in the DOM will be found and * individually bound when a mixer is instantiated, with their corresponding actions * cached for performance. * * If `true`, a single click handler will be applied to the `window` (or container element - see * `config.controls.scope`), and any click events triggered by elements with `data-filter`, * `data-sort` or `data-toggle` attributes present will be handled as they propagate upwards. * * If you require a user interface where control buttons may be added, removed, or changed during the * lifetime of a mixer, `controls.live` should be set to `true`. There is a marginal but unavoidable * performance deficit when using live controls, as the value of each control button must be read * from the DOM in real time once the click event has propagated. * * @example <caption>Example: Setting live controls</caption> * var mixer = mixitup(containerEl, { * controls: { * live: true * } * }); * * // Control buttons can now be added, remove and changed without breaking * // the mixer's UI * * @name live * @memberof mixitup.Config.controls * @instance * @type {boolean} * @default true */ this.live = false; /** * A string dictating the "scope" to use when binding or querying the default controls. The available * values are `'global'` or `'local'`. * * When set to `'global'` (default behavior), MixItUp will query the entire document for control buttons * to bind, or delegate click events from (see `config.controls.live`). * * When set to `'local'`, MixItUp will only query (or bind click events to) its own container element. * This may be desireable if you require multiple active mixer instances within the same document, with * controls that would otherwise intefere with each other if scoped globally. * * Conversely, if you wish to control multiple instances with a single UI, you would create one * set of controls and keep the controls scope of each mixer set to `global`. * * @example <caption>Example: Setting 'local' scoped controls</caption> * var mixerOne = mixitup(containerOne, { * controls: { * scope: 'local' * } * }); * * var mixerTwo = mixitup(containerTwo, { * controls: { * scope: 'local' * } * }); * * // Both mixers can now exist within the same document with * // isolated controls placed within their container elements. * * @name scope * @memberof mixitup.Config.controls * @instance * @type {string} * @default 'global' */ this.scope = 'global'; // enum: ['local' ,'global'] /** * A string dictating the type of logic to apply when concatenating the filter selectors of * active toggle buttons (i.e. any clickable element with a `data-toggle` attribute). * * If set to `'or'` (default behavior), selectors will be concatenated together as * a comma-seperated list. For example: * * `'.cat-1, .cat-2'` (shows any elements matching `'.cat-1'` OR `'.cat-2'`) * * If set to `'and'`, selectors will be directly concatenated together. For example: * * `'.cat-1.cat-2'` (shows any elements which match both `'.cat-1'` AND `'.cat-2'`) * * @example <caption>Example: Setting "and" toggle logic</caption> * var mixer = mixitup(containerEl, { * controls: { * toggleLogic: 'and' * } * }); * * @name toggleLogic * @memberof mixitup.Config.controls * @instance * @type {string} * @default 'or' */ this.toggleLogic = 'or'; // enum: ['or', 'and'] /** * A string dictating the filter behavior when all toggles are inactive. * * When set to `'all'` (default behavior), *all* targets will be shown by default * when no toggles are active, or at the moment all active toggles are toggled off. * * When set to `'none'`, no targets will be shown by default when no toggles are * active, or at the moment all active toggles are toggled off. * * @example <caption>Example 1: Setting the default toggle behavior to `'all'`</caption> * var mixer = mixitup(containerEl, { * controls: { * toggleDefault: 'all' * } * }); * * mixer.toggleOn('.cat-2') * .then(function() { * // Deactivate all active toggles * * return mixer.toggleOff('.cat-2') * }) * .then(function(state) { * console.log(state.activeFilter.selector); // 'all' * console.log(state.totalShow); // 12 * }); * * @example <caption>Example 2: Setting the default toggle behavior to `'none'`</caption> * var mixer = mixitup(containerEl, { * controls: { * toggleDefault: 'none' * } * }); * * mixer.toggleOn('.cat-2') * .then(function() { * // Deactivate all active toggles * * return mixer.toggleOff('.cat-2') * }) * .then(function(state) { * console.log(state.activeFilter.selector); // 'none' * console.log(state.totalShow); // 0 * }); * * @name toggleDefault * @memberof mixitup.Config.controls * @instance * @type {string} * @default 'all' */ this.toggleDefault = 'all'; // enum: ['all', 'none'] this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigControls); mixitup.ConfigControls.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigControls.prototype.constructor = mixitup.ConfigControls; /** * A group of properties defining the output and structure of class names programmatically * added to controls and containers to reflect the state of the mixer. * * Most commonly, class names are added to controls by MixItUp to indicate that * the control is active so that it can be styled accordingly - `'mixitup-control-active'` by default. * * Using a "BEM" like structure, each classname is broken into the three parts: * a block namespace (`'mixitup'`), an element name (e.g. `'control'`), and an optional modifier * name (e.g. `'active'`) reflecting the state of the element. * * By default, each part of the classname is concatenated together using single hyphens as * delineators, but this can be easily customised to match the naming convention and style of * your project. * * @constructor * @memberof mixitup.Config * @name classNames * @namespace * @public * @since 3.0.0 */ mixitup.ConfigClassNames = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * The "block" portion, or top-level namespace added to the start of any class names created by MixItUp. * * @example <caption>Example 1: changing the `config.classNames.block` value</caption> * var mixer = mixitup(containerEl, { * classNames: { * block: 'portfolio' * } * }); * * // Active control output: "portfolio-control-active" * * @example <caption>Example 2: Removing `config.classNames.block`</caption> * var mixer = mixitup(containerEl, { * classNames: { * block: '' * } * }); * * // Active control output: "control-active" * * @name block * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'mixitup' */ this.block = 'mixitup'; /** * The "element" portion of the class name added to container. * * @name elementContainer * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'container' */ this.elementContainer = 'container'; /** * The "element" portion of the class name added to filter controls. * * By default, all filter, sort, multimix and toggle controls take the same element value of `'control'`, but * each type's element value can be individually overwritten to match the unique classNames of your controls as needed. * * @example <caption>Example 1: changing the `config.classNames.elementFilter` value</caption> * var mixer = mixitup(containerEl, { * classNames: { * elementFilter: 'filter' * } * }); * * // Active filter output: "mixitup-filter-active" * * @example <caption>Example 2: changing the `config.classNames.block` and `config.classNames.elementFilter` values</caption> * var mixer = mixitup(containerEl, { * classNames: { * block: 'portfolio', * elementFilter: 'filter' * } * }); * * // Active filter output: "portfolio-filter-active" * * @name elementFilter * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'control' */ this.elementFilter = 'control'; /** * The "element" portion of the class name added to sort controls. * * By default, all filter, sort, multimix and toggle controls take the same element value of `'control'`, but * each type's element value can be individually overwritten to match the unique classNames of your controls as needed. * * @example <caption>Example 1: changing the `config.classNames.elementSort` value</caption> * var mixer = mixitup(containerEl, { * classNames: { * elementSort: 'sort' * } * }); * * // Active sort output: "mixitup-sort-active" * * @example <caption>Example 2: changing the `config.classNames.block` and `config.classNames.elementSort` values</caption> * var mixer = mixitup(containerEl, { * classNames: { * block: 'portfolio', * elementSort: 'sort' * } * }); * * // Active sort output: "portfolio-sort-active" * * @name elementSort * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'control' */ this.elementSort = 'control'; /** * The "element" portion of the class name added to multimix controls. * * By default, all filter, sort, multimix and toggle controls take the same element value of `'control'`, but * each type's element value can be individually overwritten to match the unique classNames of your controls as needed. * * @example <caption>Example 1: changing the `config.classNames.elementMultimix` value</caption> * var mixer = mixitup(containerEl, { * classNames: { * elementMultimix: 'multimix' * } * }); * * // Active multimix output: "mixitup-multimix-active" * * @example <caption>Example 2: changing the `config.classNames.block` and `config.classNames.elementMultimix` values</caption> * var mixer = mixitup(containerEl, { * classNames: { * block: 'portfolio', * elementSort: 'multimix' * } * }); * * // Active multimix output: "portfolio-multimix-active" * * @name elementMultimix * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'control' */ this.elementMultimix = 'control'; /** * The "element" portion of the class name added to toggle controls. * * By default, all filter, sort, multimix and toggle controls take the same element value of `'control'`, but * each type's element value can be individually overwritten to match the unique classNames of your controls as needed. * * @example <caption>Example 1: changing the `config.classNames.elementToggle` value</caption> * var mixer = mixitup(containerEl, { * classNames: { * elementToggle: 'toggle' * } * }); * * // Active toggle output: "mixitup-toggle-active" * * @example <caption>Example 2: changing the `config.classNames.block` and `config.classNames.elementToggle` values</caption> * var mixer = mixitup(containerEl, { * classNames: { * block: 'portfolio', * elementToggle: 'toggle' * } * }); * * // Active toggle output: "portfolio-toggle-active" * * @name elementToggle * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'control' */ this.elementToggle = 'control'; /** * The "modifier" portion of the class name added to active controls. * @name modifierActive * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'active' */ this.modifierActive = 'active'; /** * The "modifier" portion of the class name added to disabled controls. * * @name modifierDisabled * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'disabled' */ this.modifierDisabled = 'disabled'; /** * The "modifier" portion of the class name added to the container when in a "failed" state. * * @name modifierFailed * @memberof mixitup.Config.classNames * @instance * @type {string} * @default 'failed' */ this.modifierFailed = 'failed'; /** * The delineator used between the "block" and "element" portions of any class name added by MixItUp. * * If the block portion is ommited by setting it to an empty string, no delineator will be added. * * @example <caption>Example: changing the delineator to match BEM convention</caption> * var mixer = mixitup(containerEl, { * classNames: { * delineatorElement: '__' * } * }); * * // example active control output: "mixitup__control-active" * * @name delineatorElement * @memberof mixitup.Config.classNames * @instance * @type {string} * @default '-' */ this.delineatorElement = '-'; /** * The delineator used between the "element" and "modifier" portions of any class name added by MixItUp. * * If the element portion is ommited by setting it to an empty string, no delineator will be added. * * @example <caption>Example: changing both delineators to match BEM convention</caption> * var mixer = mixitup(containerEl, { * classNames: { * delineatorElement: '__' * delineatorModifier: '--' * } * }); * * // Active control output: "mixitup__control--active" * * @name delineatorModifier * @memberof mixitup.Config.classNames * @instance * @type {string} * @default '-' */ this.delineatorModifier = '-'; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigClassNames); mixitup.ConfigClassNames.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigClassNames.prototype.constructor = mixitup.ConfigClassNames; /** * A group of properties relating to MixItUp's dataset API. * * @constructor * @memberof mixitup.Config * @name data * @namespace * @public * @since 3.0.0 */ mixitup.ConfigData = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A string specifying the name of the key containing your data model's unique * identifier (UID). To use the dataset API, a UID key must be specified and * be present and unique on all objects in the dataset you provide to MixItUp. * * For example, if your dataset is made up of MongoDB documents, the UID * key would be `'id'` or `'_id'`. * * @example <caption>Example: Setting the UID to `'id'`</caption> * var mixer = mixitup(containerEl, { * data: { * uidKey: 'id' * } * }); * * @name uidKey * @memberof mixitup.Config.data * @instance * @type {string} * @default '' */ this.uidKey = ''; /** * A boolean dictating whether or not MixItUp should "dirty check" each object in * your dataset for changes whenever `.dataset()` is called, and re-render any targets * for which a change is found. * * Depending on the complexity of your data model, dirty checking can be expensive * and is therefore disabled by default. * * NB: For changes to be detected, a new immutable instance of the edited model must be * provided to mixitup, rather than manipulating properties on the existing instance. * If your changes are a result of a DB write and read, you will most likely be calling * `.dataset()` with a clean set of objects each time, so this will not be an issue. * * @example <caption>Example: Enabling dirty checking</caption> * * var myDataset = [ * { * id: 0, * title: "Blog Post Title 0" * ... * }, * { * id: 1, * title: "Blog Post Title 1" * ... * } * ]; * * // Instantiate a mixer with a pre-loaded dataset, and a target renderer * // function defined * * var mixer = mixitup(containerEl, { * data: { * uidKey: 'id', * dirtyCheck: true * }, * load: { * dataset: myDataset * }, * render: { * target: function() { ... } * } * }); * * // For illustration, we will clone and edit the second object in the dataset. * // NB: this would typically be done server-side in response to a DB update, * and then re-queried via an API. * * myDataset[1] = Object.assign({}, myDataset[1]); * * myDataset[1].title = 'Blog Post Title 11'; * * mixer.dataset(myDataset) * .then(function() { * // the target with ID "1", will be re-rendered reflecting its new title * }); * * @name dirtyCheck * @memberof mixitup.Config.data * @instance * @type {boolean} * @default false */ this.dirtyCheck = false; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigData); mixitup.ConfigData.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigData.prototype.constructor = mixitup.ConfigData; /** * A group of properties allowing the toggling of various debug features. * * @constructor * @memberof mixitup.Config * @name debug * @namespace * @public * @since 3.0.0 */ mixitup.ConfigDebug = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A boolean dictating whether or not the mixer instance returned by the * `mixitup()` factory function should expose private properties and methods. * * By default, mixer instances only expose their public API, but enabling * debug mode will give you access to various mixer internals which may aid * in debugging, or the authoring of extensions. * * @example <caption>Example: Enabling debug mode</caption> * * var mixer = mixitup(containerEl, { * debug: { * enable: true * } * }); * * // Private properties and methods will now be visible on the mixer instance: * * console.log(mixer); * * @name enable * @memberof mixitup.Config.debug * @instance * @type {boolean} * @default false */ this.enable = false; /** * A boolean dictating whether or not warnings should be shown when various * common gotchas occur. * * Warnings are intended to provide insights during development when something * occurs that is not a fatal, but may indicate an issue with your integration, * and are therefore turned on by default. However, you may wish to disable * them in production. * * @example <caption>Example 1: Disabling warnings</caption> * * var mixer = mixitup(containerEl, { * debug: { * showWarnings: false * } * }); * * @example <caption>Example 2: Disabling warnings based on environment</caption> * * var showWarnings = myAppConfig.environment === 'development' ? true : false; * * var mixer = mixitup(containerEl, { * debug: { * showWarnings: showWarnings * } * }); * * @name showWarnings * @memberof mixitup.Config.debug * @instance * @type {boolean} * @default true */ this.showWarnings = true; /** * Used for server-side testing only. * * @private * @name fauxAsync * @memberof mixitup.Config.debug * @instance * @type {boolean} * @default false */ this.fauxAsync = false; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigDebug); mixitup.ConfigDebug.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigDebug.prototype.constructor = mixitup.ConfigDebug; /** * A group of properties relating to the layout of the container. * * @constructor * @memberof mixitup.Config * @name layout * @namespace * @public * @since 3.0.0 */ mixitup.ConfigLayout = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A boolean dictating whether or not mixitup should query all descendants * of the container for targets, or only immediate children. * * By default, mixitup will query all descendants matching the * `selectors.target` selector when indexing targets upon instantiation. * This allows for targets to be nested inside a sub-container which is * useful when ring-fencing targets from locally scoped controls in your * markup (see `controls.scope`). * * However, if you are building a more complex UI requiring the nesting * of mixers within mixers, you will most likely want to limit targets to * immediate children of the container by setting this property to `false`. * * @example <caption>Example: Restricting targets to immediate children</caption> * * var mixer = mixitup(containerEl, { * layout: { * allowNestedTargets: false * } * }); * * @name allowNestedTargets * @memberof mixitup.Config.layout * @instance * @type {boolean} * @default true */ this.allowNestedTargets = true; /** * A string specifying an optional class name to apply to the container when in * its default state. * * By changing this class name or adding a class name to the container via the * `.changeLayout()` API method, the CSS layout of the container can be changed, * and MixItUp will attemp to gracefully animate the container and its targets * between states. * * @example <caption>Example 1: Specifying a container class name</caption> * * var mixer = mixitup(containerEl, { * layout: { * containerClassName: 'grid' * } * }); * * @example <caption>Example 2: Changing the default class name with `.changeLayout()`</caption> * * var mixer = mixitup(containerEl, { * layout: { * containerClassName: 'grid' * } * }); * * mixer.changeLayout('list') * .then(function(state) { * console.log(state.activeContainerClass); // "list" * }); * * @name containerClassName * @memberof mixitup.Config.layout * @instance * @type {string} * @default '' */ this.containerClassName = ''; /** * A reference to a non-target sibling element after which to insert targets * when there are no targets in the container. * * @example <caption>Example: Setting a `siblingBefore` reference element</caption> * * var addButton = containerEl.querySelector('button'); * * var mixer = mixitup(containerEl, { * layout: { * siblingBefore: addButton * } * }); * * @name siblingBefore * @memberof mixitup.Config.layout * @instance * @type {HTMLElement} * @default null */ this.siblingBefore = null; /** * A reference to a non-target sibling element before which to insert targets * when there are no targets in the container. * * @example <caption>Example: Setting an `siblingAfter` reference element</caption> * * var gap = containerEl.querySelector('.gap'); * * var mixer = mixitup(containerEl, { * layout: { * siblingAfter: gap * } * }); * * @name siblingAfter * @memberof mixitup.Config.layout * @instance * @type {HTMLElement} * @default null */ this.siblingAfter = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigLayout); mixitup.ConfigLayout.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigLayout.prototype.constructor = mixitup.ConfigLayout; /** * A group of properties defining the initial state of the mixer on load (instantiation). * * @constructor * @memberof mixitup.Config * @name load * @namespace * @public * @since 2.0.0 */ mixitup.ConfigLoad = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A string defining any filtering to be statically applied to the mixer on load. * As per the `.filter()` API, this can be any valid selector string, or the * values `'all'` or `'none'`. * * @example <caption>Example 1: Defining an initial filter selector to be applied on load</caption> * * // The mixer will show only those targets matching '.category-a' on load. * * var mixer = mixitup(containerEl, { * load: { * filter: '.category-a' * } * }); * * @example <caption>Example 2: Hiding all targets on load</caption> * * // The mixer will show hide all targets on load. * * var mixer = mixitup(containerEl, { * load: { * filter: 'none' * } * }); * * @name filter * @memberof mixitup.Config.load * @instance * @type {string} * @default 'all' */ this.filter = 'all'; /** * A string defining any sorting to be statically applied to the mixer on load. * As per the `.sort()` API, this should be a valid "sort string" made up of * an attribute to sort by (or `'default'`) followed by an optional sorting * order, or the value `'random'`; * * @example <caption>Example: Defining sorting to be applied on load</caption> * * // The mixer will sort the container by the value of the `data-published-date` * // attribute, in descending order. * * var mixer = mixitup(containerEl, { * load: { * sort: 'published-date:desc' * } * }); * * @name sort * @memberof mixitup.Config.load * @instance * @type {string} * @default 'default:asc' */ this.sort = 'default:asc'; /** * An array of objects representing the underlying data of any pre-rendered targets, * when using the `.dataset()` API. * * NB: If targets are pre-rendered when the mixer is instantiated, this must be set. * * @example <caption>Example: Defining the initial underyling dataset</caption> * * var myDataset = [ * { * id: 0, * title: "Blog Post Title 0", * ... * }, * { * id: 1, * title: "Blog Post Title 1", * ... * } * ]; * * var mixer = mixitup(containerEl, { * data: { * uidKey: 'id' * }, * load: { * dataset: myDataset * } * }); * * @name dataset * @memberof mixitup.Config.load * @instance * @type {Array.<object>} * @default null */ this.dataset = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigLoad); mixitup.ConfigLoad.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigLoad.prototype.constructor = mixitup.ConfigLoad; /** * A group of properties defining the selectors used to query elements within a mixitup container. * * @constructor * @memberof mixitup.Config * @name selectors * @namespace * @public * @since 3.0.0 */ mixitup.ConfigSelectors = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A selector string used to query and index target elements within the container. * * By default, the class selector `'.mix'` is used, but this can be changed to an * attribute or element selector to match the style of your project. * * @example <caption>Example 1: Changing the target selector</caption> * * var mixer = mixitup(containerEl, { * selectors: { * target: '.portfolio-item' * } * }); * * @example <caption>Example 2: Using an attribute selector as a target selector</caption> * * // The mixer will search for any children with the attribute `data-ref="mix"` * * var mixer = mixitup(containerEl, { * selectors: { * target: '[data-ref="mix"]' * } * }); * * @name target * @memberof mixitup.Config.selectors * @instance * @type {string} * @default '.mix' */ this.target = '.mix'; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigSelectors); mixitup.ConfigSelectors.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigSelectors.prototype.constructor = mixitup.ConfigSelectors; /** * A group of optional render functions for creating and updating elements. * * All render functions receive a data object, and should return a valid HTML string. * * @constructor * @memberof mixitup.Config * @name render * @namespace * @public * @since 3.0.0 */ mixitup.ConfigRender = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A function returning an HTML string representing a target element. * * The function is invoked as part of the `.dataset()` API, whenever a new item is added * to the dataset, or an item in the dataset changes (if `dataset.dirtyCheck` is enabled). * * The function receives the relevant dataset item as its first parameter. * * @example <caption>Example 1: Using string concatenation</caption> * * var mixer = mixitup(containerEl, { * render: { * target: function(item) { * return '&lt;div class="mix"&gt;' + * '&lt;h2&gt;' + item.title + '&lt;/h2&gt;' + * '&lt;/div&gt;'; * } * } * }); * * @example <caption>Example 2: Using an ES2015 template literal</caption> * * var mixer = mixitup(containerEl, { * render: { * target: function(item) { * return `&lt;div class="mix"&gt; * &lt;h2&gt;${item.title}&lt;/h2&gt; * &lt;/div&gt;`; * } * } * }); * * @example <caption>Example 3: Using a Handlebars template</caption> * * var targetTemplate = Handlebars.compile('&lt;div class="mix"&gt;&lt;h2&gt;{{title}}&lt;/h2&gt;&lt;/div&gt;'); * * var mixer = mixitup(containerEl, { * render: { * target: targetTemplate * } * }); * * @name target * @memberof mixitup.Config.render * @instance * @type {function} * @default 'null' */ this.target = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigRender); mixitup.ConfigRender.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigRender.prototype.constructor = mixitup.ConfigRender; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.ConfigTemplates = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ConfigTemplates); mixitup.ConfigTemplates.prototype = Object.create(mixitup.Base.prototype); mixitup.ConfigTemplates.prototype.constructor = mixitup.ConfigTemplates; /** * `mixitup.Config` is an interface used for customising the functionality of a * mixer instance. It is organised into several semantically distinct sub-objects, * each one pertaining to a particular aspect of MixItUp functionality. * * An object literal containing any or all of the available properies, * known as the "configuration object", can be passed as the second parameter to * the `mixitup` factory function when creating a mixer instance to customise its * functionality as needed. * * If no configuration object is passed, the mixer instance will take on the default * configuration values detailed below. * * @example <caption>Example 1: Creating and passing the configuration object</caption> * // Create a configuration object with desired values * * var config = { * animation: { * enable: false * }, * selectors: { * target: '.item' * } * }; * * // Pass the configuration object to the mixitup factory function * * var mixer = mixitup(containerEl, config); * * @example <caption>Example 2: Passing the configuration object inline</caption> * // Typically, the configuration object is passed inline for brevity. * * var mixer = mixitup(containerEl, { * controls: { * live: true, * toggleLogic: 'and' * } * }); * * * @constructor * @memberof mixitup * @namespace * @public * @since 2.0.0 */ mixitup.Config = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.animation = new mixitup.ConfigAnimation(); this.callbacks = new mixitup.ConfigCallbacks(); this.controls = new mixitup.ConfigControls(); this.classNames = new mixitup.ConfigClassNames(); this.data = new mixitup.ConfigData(); this.debug = new mixitup.ConfigDebug(); this.layout = new mixitup.ConfigLayout(); this.load = new mixitup.ConfigLoad(); this.selectors = new mixitup.ConfigSelectors(); this.render = new mixitup.ConfigRender(); this.templates = new mixitup.ConfigTemplates(); this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Config); mixitup.Config.prototype = Object.create(mixitup.Base.prototype); mixitup.Config.prototype.constructor = mixitup.Config; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.MixerDom = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.document = null; this.body = null; this.container = null; this.parent = null; this.targets = []; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.MixerDom); mixitup.MixerDom.prototype = Object.create(mixitup.Base.prototype); mixitup.MixerDom.prototype.constructor = mixitup.MixerDom; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.UiClassNames = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.base = ''; this.active = ''; this.disabled = ''; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.UiClassNames); mixitup.UiClassNames.prototype = Object.create(mixitup.Base.prototype); mixitup.UiClassNames.prototype.constructor = mixitup.UiClassNames; /** * An object into which all arbitrary arguments sent to '.dataset()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandDataset = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.dataset = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandDataset); mixitup.CommandDataset.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandDataset.prototype.constructor = mixitup.CommandDataset; /** * An object into which all arbitrary arguments sent to '.multimix()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandMultimix = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.filter = null; this.sort = null; this.insert = null; this.remove = null; this.changeLayout = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandMultimix); mixitup.CommandMultimix.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandMultimix.prototype.constructor = mixitup.CommandMultimix; /** * An object into which all arbitrary arguments sent to '.filter()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandFilter = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.selector = ''; this.collection = null; this.action = 'show'; // enum: ['show', 'hide'] this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandFilter); mixitup.CommandFilter.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandFilter.prototype.constructor = mixitup.CommandFilter; /** * An object into which all arbitrary arguments sent to '.sort()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandSort = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.sortString = ''; this.attribute = ''; this.order = 'asc'; this.collection = null; this.next = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandSort); mixitup.CommandSort.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandSort.prototype.constructor = mixitup.CommandSort; /** * An object into which all arbitrary arguments sent to '.insert()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandInsert = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.index = 0; this.collection = []; this.position = 'before'; // enum: ['before', 'after'] this.sibling = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandInsert); mixitup.CommandInsert.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandInsert.prototype.constructor = mixitup.CommandInsert; /** * An object into which all arbitrary arguments sent to '.remove()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandRemove = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.targets = []; this.collection = []; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandRemove); mixitup.CommandRemove.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandRemove.prototype.constructor = mixitup.CommandRemove; /** * An object into which all arbitrary arguments sent to '.changeLayout()' are mapped. * * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.CommandChangeLayout = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.containerClassName = ''; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.CommandChangeLayout); mixitup.CommandChangeLayout.prototype = Object.create(mixitup.Base.prototype); mixitup.CommandChangeLayout.prototype.constructor = mixitup.CommandChangeLayout; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 * @param {string} type * @param {string} selector * @param {boolean} [live] * @param {string} [parent] * An optional string representing the name of the mixer.dom property containing a reference to a parent element. */ mixitup.ControlDefinition = function(type, selector, live, parent) { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.type = type; this.selector = selector; this.live = live || false; this.parent = parent || ''; this.callActions('afterConstruct'); h.freeze(this); h.seal(this); }; mixitup.BaseStatic.call(mixitup.ControlDefinition); mixitup.ControlDefinition.prototype = Object.create(mixitup.Base.prototype); mixitup.ControlDefinition.prototype.constructor = mixitup.ControlDefinition; mixitup.controlDefinitions = []; mixitup.controlDefinitions.push(new mixitup.ControlDefinition('multimix', '[data-filter][data-sort]')); mixitup.controlDefinitions.push(new mixitup.ControlDefinition('filter', '[data-filter]')); mixitup.controlDefinitions.push(new mixitup.ControlDefinition('sort', '[data-sort]')); mixitup.controlDefinitions.push(new mixitup.ControlDefinition('toggle', '[data-toggle]')); /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Control = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.el = null; this.selector = ''; this.bound = []; this.pending = -1; this.type = ''; this.status = 'inactive'; // enum: ['inactive', 'active', 'disabled', 'live'] this.filter = ''; this.sort = ''; this.canDisable = false; this.handler = null; this.classNames = new mixitup.UiClassNames(); this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Control); mixitup.Control.prototype = Object.create(mixitup.Base.prototype); h.extend(mixitup.Control.prototype, /** @lends mixitup.Control */ { constructor: mixitup.Control, /** * @private * @param {HTMLElement} el * @param {string} type * @param {string} selector */ init: function(el, type, selector) { var self = this; this.callActions('beforeInit', arguments); self.el = el; self.type = type; self.selector = selector; if (self.selector) { self.status = 'live'; } else { self.canDisable = typeof self.el.disable === 'boolean'; switch (self.type) { case 'filter': self.filter = self.el.getAttribute('data-filter'); break; case 'toggle': self.filter = self.el.getAttribute('data-toggle'); break; case 'sort': self.sort = self.el.getAttribute('data-sort'); break; case 'multimix': self.filter = self.el.getAttribute('data-filter'); self.sort = self.el.getAttribute('data-sort'); break; } } self.bindClick(); mixitup.controls.push(self); this.callActions('afterInit', arguments); }, /** * @private * @param {mixitup.Mixer} mixer * @return {boolean} */ isBound: function(mixer) { var self = this, isBound = false; this.callActions('beforeIsBound', arguments); isBound = self.bound.indexOf(mixer) > -1; return self.callFilters('afterIsBound', isBound, arguments); }, /** * @private * @param {mixitup.Mixer} mixer * @return {void} */ addBinding: function(mixer) { var self = this; this.callActions('beforeAddBinding', arguments); if (!self.isBound()) { self.bound.push(mixer); } this.callActions('afterAddBinding', arguments); }, /** * @private * @param {mixitup.Mixer} mixer * @return {void} */ removeBinding: function(mixer) { var self = this, removeIndex = -1; this.callActions('beforeRemoveBinding', arguments); if ((removeIndex = self.bound.indexOf(mixer)) > -1) { self.bound.splice(removeIndex, 1); } if (self.bound.length < 1) { // No bindings exist, unbind event click handlers self.unbindClick(); // Remove from `mixitup.controls` list removeIndex = mixitup.controls.indexOf(self); mixitup.controls.splice(removeIndex, 1); if (self.status === 'active') { self.renderStatus(self.el, 'inactive'); } } this.callActions('afterRemoveBinding', arguments); }, /** * @private * @return {void} */ bindClick: function() { var self = this; this.callActions('beforeBindClick', arguments); self.handler = function(e) { self.handleClick(e); }; h.on(self.el, 'click', self.handler); this.callActions('afterBindClick', arguments); }, /** * @private * @return {void} */ unbindClick: function() { var self = this; this.callActions('beforeUnbindClick', arguments); h.off(self.el, 'click', self.handler); self.handler = null; this.callActions('afterUnbindClick', arguments); }, /** * @private * @param {MouseEvent} e * @return {void} */ handleClick: function(e) { var self = this, button = null, mixer = null, isActive = false, returnValue = void(0), command = {}, clone = null, commands = [], i = -1; this.callActions('beforeHandleClick', arguments); this.pending = 0; if (!self.selector) { button = self.el; } else { button = h.closestParent(e.target, self.selector, true, self.bound[0].dom.document); } if (!button) { self.callActions('afterHandleClick', arguments); return; } switch (self.type) { case 'filter': command.filter = self.filter || button.getAttribute('data-filter'); break; case 'sort': command.sort = self.sort || button.getAttribute('data-sort'); break; case 'multimix': command.filter = self.filter || button.getAttribute('data-filter'); command.sort = self.sort || button.getAttribute('data-sort'); break; case 'toggle': command.filter = self.filter || button.getAttribute('data-toggle'); if (self.status === 'live') { isActive = h.hasClass(button, self.classNames.active); } else { isActive = self.status === 'active'; } break; } for (i = 0; i < self.bound.length; i++) { // Create a clone of the command for each bound mixer instance clone = new mixitup.CommandMultimix(); h.extend(clone, command); commands.push(clone); } commands = self.callFilters('commandsHandleClick', commands, arguments); self.pending = self.bound.length; for (i = 0; mixer = self.bound[i]; i++) { command = commands[i]; if (!command) { // An extension may set a command null to indicate that the click should not be handled continue; } if (!mixer.lastClicked) { mixer.lastClicked = button; } mixitup.events.fire('mixClick', mixer.dom.container, { state: mixer.state, instance: mixer, originalEvent: e, control: mixer.lastClicked }, mixer.dom.document); if (typeof mixer.config.callbacks.onMixClick === 'function') { returnValue = mixer.config.callbacks.onMixClick.call(mixer.lastClicked, mixer.state, e, mixer); if (returnValue === false) { // User has returned `false` from the callback, so do not handle click continue; } } if (self.type === 'toggle') { isActive ? mixer.toggleOff(command.filter) : mixer.toggleOn(command.filter); } else { mixer.multimix(command); } } this.callActions('afterHandleClick', arguments); }, /** * @param {object} command * @param {Array<string>} toggleArray * @return {void} */ update: function(command, toggleArray) { var self = this, actions = new mixitup.CommandMultimix(); self.callActions('beforeUpdate', arguments); self.pending--; self.pending = Math.max(0, self.pending); if (self.pending > 0) return; if (self.status === 'live') { // Live control (status unknown) self.updateLive(command, toggleArray); } else { // Static control actions.sort = self.sort; actions.filter = self.filter; self.callFilters('actionsUpdate', actions, arguments); self.parseStatusChange(self.el, command, actions, toggleArray); } self.callActions('afterUpdate', arguments); }, /** * @param {mixitup.CommandMultimix} command * @param {Array<string>} toggleArray * @return {void} */ updateLive: function(command, toggleArray) { var self = this, controlButtons = null, actions = null, button = null, i = -1; self.callActions('beforeUpdateLive', arguments); if (!self.el) return; controlButtons = self.el.querySelectorAll(self.selector); for (i = 0; button = controlButtons[i]; i++) { actions = new mixitup.CommandMultimix(); switch (self.type) { case 'filter': actions.filter = button.getAttribute('data-filter'); break; case 'sort': actions.sort = button.getAttribute('data-sort'); break; case 'multimix': actions.filter = button.getAttribute('data-filter'); actions.sort = button.getAttribute('data-sort'); break; case 'toggle': actions.filter = button.getAttribute('data-toggle'); break; } actions = self.callFilters('actionsUpdateLive', actions, arguments); self.parseStatusChange(button, command, actions, toggleArray); } self.callActions('afterUpdateLive', arguments); }, /** * @param {HTMLElement} button * @param {mixitup.CommandMultimix} command * @param {mixitup.CommandMultimix} actions * @param {Array<string>} toggleArray * @return {void} */ parseStatusChange: function(button, command, actions, toggleArray) { var self = this, alias = '', toggle = '', i = -1; self.callActions('beforeParseStatusChange', arguments); switch (self.type) { case 'filter': if (command.filter === actions.filter) { self.renderStatus(button, 'active'); } else { self.renderStatus(button, 'inactive'); } break; case 'multimix': if (command.sort === actions.sort && command.filter === actions.filter) { self.renderStatus(button, 'active'); } else { self.renderStatus(button, 'inactive'); } break; case 'sort': if (command.sort.match(/:asc/g)) { alias = command.sort.replace(/:asc/g, ''); } if (command.sort === actions.sort || alias === actions.sort) { self.renderStatus(button, 'active'); } else { self.renderStatus(button, 'inactive'); } break; case 'toggle': if (toggleArray.length < 1) self.renderStatus(button, 'inactive'); if (command.filter === actions.filter) { self.renderStatus(button, 'active'); } for (i = 0; i < toggleArray.length; i++) { toggle = toggleArray[i]; if (toggle === actions.filter) { // Button matches one active toggle self.renderStatus(button, 'active'); break; } self.renderStatus(button, 'inactive'); } break; } self.callActions('afterParseStatusChange', arguments); }, /** * @param {HTMLElement} button * @param {string} status * @return {void} */ renderStatus: function(button, status) { var self = this; self.callActions('beforeRenderStatus', arguments); switch (status) { case 'active': h.addClass(button, self.classNames.active); h.removeClass(button, self.classNames.disabled); if (self.canDisable) self.el.disabled = false; break; case 'inactive': h.removeClass(button, self.classNames.active); h.removeClass(button, self.classNames.disabled); if (self.canDisable) self.el.disabled = false; break; case 'disabled': if (self.canDisable) self.el.disabled = true; h.addClass(button, self.classNames.disabled); h.removeClass(button, self.classNames.active); break; } if (self.status !== 'live') { // Update the control's status propery if not live self.status = status; } self.callActions('afterRenderStatus', arguments); } }); mixitup.controls = []; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.StyleData = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.x = 0; this.y = 0; this.top = 0; this.right = 0; this.bottom = 0; this.left = 0; this.width = 0; this.height = 0; this.marginRight = 0; this.marginBottom = 0; this.opacity = 0; this.scale = new mixitup.TransformData(); this.translateX = new mixitup.TransformData(); this.translateY = new mixitup.TransformData(); this.translateZ = new mixitup.TransformData(); this.rotateX = new mixitup.TransformData(); this.rotateY = new mixitup.TransformData(); this.rotateZ = new mixitup.TransformData(); this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.StyleData); mixitup.StyleData.prototype = Object.create(mixitup.Base.prototype); mixitup.StyleData.prototype.constructor = mixitup.StyleData; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.TransformData = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.value = 0; this.unit = ''; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.TransformData); mixitup.TransformData.prototype = Object.create(mixitup.Base.prototype); mixitup.TransformData.prototype.constructor = mixitup.TransformData; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.TransformDefaults = function() { mixitup.StyleData.apply(this); this.callActions('beforeConstruct'); this.scale.value = 0.01; this.scale.unit = ''; this.translateX.value = 20; this.translateX.unit = 'px'; this.translateY.value = 20; this.translateY.unit = 'px'; this.translateZ.value = 20; this.translateZ.unit = 'px'; this.rotateX.value = 90; this.rotateX.unit = 'deg'; this.rotateY.value = 90; this.rotateY.unit = 'deg'; this.rotateX.value = 90; this.rotateX.unit = 'deg'; this.rotateZ.value = 180; this.rotateZ.unit = 'deg'; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.TransformDefaults); mixitup.TransformDefaults.prototype = Object.create(mixitup.StyleData.prototype); mixitup.TransformDefaults.prototype.constructor = mixitup.TransformDefaults; /** * @private * @static * @since 3.0.0 * @type {mixitup.TransformDefaults} */ mixitup.transformDefaults = new mixitup.TransformDefaults(); /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.EventDetail = function() { this.state = null; this.futureState = null; this.instance = null; this.originalEvent = null; }; /** * The `mixitup.Events` class contains all custom events dispatched by MixItUp at various * points within the lifecycle of a mixer operation. * * Each event is analogous to the callback function of the same name defined in * the `callbacks` configuration object, and is triggered immediately before it. * * Events are always triggered from the container element on which MixItUp is instantiated * upon. * * As with any event, registered event handlers receive the event object as a parameter * which includes a `detail` property containting references to the current `state`, * the `mixer` instance, and other event-specific properties described below. * * @constructor * @namespace * @memberof mixitup * @public * @since 3.0.0 */ mixitup.Events = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * A custom event triggered immediately after any MixItUp operation is requested * and before animations have begun. * * The `mixStart` event also exposes a `futureState` property via the * `event.detail` object, which represents the final state of the mixer once * the requested operation has completed. * * @name mixStart * @memberof mixitup.Events * @static * @type {CustomEvent} */ this.mixStart = null; /** * A custom event triggered when a MixItUp operation is requested while another * operation is in progress, and the animation queue is full, or queueing * is disabled. * * @name mixBusy * @memberof mixitup.Events * @static * @type {CustomEvent} */ this.mixBusy = null; /** * A custom event triggered after any MixItUp operation has completed, and the * state has been updated. * * @name mixEnd * @memberof mixitup.Events * @static * @type {CustomEvent} */ this.mixEnd = null; /** * A custom event triggered whenever a filter operation "fails", i.e. no targets * could be found matching the requested filter. * * @name mixFail * @memberof mixitup.Events * @static * @type {CustomEvent} */ this.mixFail = null; /** * A custom event triggered whenever a MixItUp control is clicked, and before its * respective operation is requested. * * This event also exposes an `originalEvent` property via the `event.detail` * object, which holds a reference to the original click event. * * @name mixClick * @memberof mixitup.Events * @static * @type {CustomEvent} */ this.mixClick = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Events); mixitup.Events.prototype = Object.create(mixitup.Base.prototype); mixitup.Events.prototype.constructor = mixitup.Events; /** * @private * @param {string} eventType * @param {Element} el * @param {object} detail * @param {Document} [doc] */ mixitup.Events.prototype.fire = function(eventType, el, detail, doc) { var self = this, event = null, eventDetail = new mixitup.EventDetail(); self.callActions('beforeFire', arguments); if (typeof self[eventType] === 'undefined') { throw new Error('Event type "' + eventType + '" not found.'); } eventDetail.state = new mixitup.State(); h.extend(eventDetail.state, detail.state); if (detail.futureState) { eventDetail.futureState = new mixitup.State(); h.extend(eventDetail.futureState, detail.futureState); } eventDetail.instance = detail.instance; if (detail.originalEvent) { eventDetail.originalEvent = detail.originalEvent; } event = h.getCustomEvent(eventType, eventDetail, doc); self.callFilters('eventFire', event, arguments); el.dispatchEvent(event); }; // Asign a singleton instance to `mixitup.events`: mixitup.events = new mixitup.Events(); /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.QueueItem = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.args = []; this.instruction = null; this.triggerElement = null; this.deferred = null; this.isToggling = false; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.QueueItem); mixitup.QueueItem.prototype = Object.create(mixitup.Base.prototype); mixitup.QueueItem.prototype.constructor = mixitup.QueueItem; /** * The `mixitup.Mixer` class is used to hold discreet, user-configured * instances of MixItUp on a provided container element. * * Mixer instances are returned whenever the `mixitup()` factory function is called, * which expose a range of methods enabling API-based filtering, sorting, * insertion, removal and more. * * @constructor * @namespace * @memberof mixitup * @public * @since 3.0.0 */ mixitup.Mixer = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.config = new mixitup.Config(); this.id = ''; this.isBusy = false; this.isToggling = false; this.incPadding = true; this.controls = []; this.targets = []; this.origOrder = []; this.cache = {}; this.toggleArray = []; this.targetsMoved = 0; this.targetsImmovable = 0; this.targetsBound = 0; this.targetsDone = 0; this.staggerDuration = 0; this.effectsIn = null; this.effectsOut = null; this.transformIn = []; this.transformOut = []; this.queue = []; this.state = null; this.lastOperation = null; this.lastClicked = null; this.userCallback = null; this.userDeferred = null; this.dom = new mixitup.MixerDom(); this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Mixer); mixitup.Mixer.prototype = Object.create(mixitup.Base.prototype); h.extend(mixitup.Mixer.prototype, /** @lends mixitup.Mixer */ { constructor: mixitup.Mixer, /** * @private * @instance * @since 3.0.0 * @param {HTMLElement} container * @param {HTMLElement} document * @param {string} id * @param {object} [config] */ attach: function(container, document, id, config) { var self = this, target = null, i = -1; self.callActions('beforeAttach', arguments); self.id = id; if (config) { h.extend(self.config, config, true, true); } self.sanitizeConfig(); self.cacheDom(container, document); if (self.config.layout.containerClassName) { h.addClass(self.dom.container, self.config.layout.containerClassName); } if (!mixitup.features.has.transitions) { self.config.animation.enable = false; } if (typeof window.console === 'undefined') { self.config.debug.showWarnings = false; } if (self.config.load.dataset) { self.config.controls.enable = false; } self.indexTargets(); self.state = self.getInitialState(); for (i = 0; target = self.lastOperation.toHide[i]; i++) { target.hide(); } if (self.config.controls.enable) { self.initControls(); self.updateControls({ filter: self.state.activeFilter, sort: self.state.activeSort }); self.buildToggleArray(null, self.state); } self.parseEffects(); self.callActions('afterAttach', arguments); }, sanitizeConfig: function() { var self = this; self.callActions('beforeSanitizeConfig', arguments); // Sanitize enum/string config options self.config.controls.scope = self.config.controls.scope.toLowerCase().trim(); self.config.controls.toggleLogic = self.config.controls.toggleLogic.toLowerCase().trim(); self.config.controls.toggleDefault = self.config.controls.toggleDefault.toLowerCase().trim(); self.config.animation.effects = self.config.animation.effects.trim(); self.callActions('afterSanitizeConfig', arguments); }, /** * @private * @instance * @since 3.0.0 * @return {mixitup.State} */ getInitialState: function() { var self = this, state = new mixitup.State(), operation = new mixitup.Operation(); self.callActions('beforeGetInitialState', arguments); // Map initial values into a mock state object if (self.config.load.dataset) { // Dataset API if (!self.config.data.uidKey || typeof self.config.data.uidKey !== 'string') { throw new TypeError(mixitup.messages.errorConfigDataUidKeyNotSet()); } operation.startDataset = operation.newDataset = state.activeDataset = self.config.load.dataset.slice(); operation.show = self.targets.slice(); state = self.callFilters('stateGetInitialState', state, arguments); } else { // DOM API state.activeFilter = self.parseFilterArgs([self.config.load.filter]).command; state.activeSort = self.parseSortArgs([self.config.load.sort]).command; state.activeContainerClassName = self.config.layout.containerClassName; state.totalTargets = self.targets.length; state = self.callFilters('stateGetInitialState', state, arguments); if ( state.activeSort.collection || state.activeSort.attribute || state.activeSort.order === 'random' || state.activeSort.order === 'desc' ) { // Sorting on load operation.newSort = state.activeSort; self.sortOperation(operation); self.printSort(false, operation); self.targets = operation.newOrder; } else { operation.startOrder = operation.newOrder = self.targets; } operation.startFilter = operation.newFilter = state.activeFilter; operation.startSort = operation.newSort = state.activeSort; if (operation.newFilter.selector === 'all') { operation.newFilter.selector = self.config.selectors.target; } else if (operation.newFilter.selector === 'none') { operation.newFilter.selector = ''; } } operation = self.callFilters('operationGetInitialState', operation, [state]); self.lastOperation = operation; if (operation.newFilter) { self.filterOperation(operation); } state = self.buildState(operation); return state; }, /** * Caches references of DOM elements neccessary for the mixer's functionality. * * @private * @instance * @since 3.0.0 * @param {HTMLElement} el * @param {HTMLHtmlElement} document * @return {void} */ cacheDom: function(el, document) { var self = this; self.callActions('beforeCacheDom', arguments); self.dom.document = document; self.dom.body = self.dom.document.querySelector('body'); self.dom.container = el; self.dom.parent = el; self.callActions('afterCacheDom', arguments); }, /** * Indexes all child elements of the mixer matching the `selectors.target` * selector, instantiating a mixitup.Target for each one. * * @private * @instance * @since 3.0.0 * @return {void} */ indexTargets: function() { var self = this, target = null, el = null, dataset = null, i = -1; self.callActions('beforeIndexTargets', arguments); self.dom.targets = self.config.layout.allowNestedTargets ? self.dom.container.querySelectorAll(self.config.selectors.target) : h.children(self.dom.container, self.config.selectors.target, self.dom.document); self.dom.targets = h.arrayFromList(self.dom.targets); self.targets = []; if ((dataset = self.config.load.dataset) && dataset.length !== self.dom.targets.length) { throw new Error(mixitup.messages.errorDatasetPrerenderedMismatch()); } if (self.dom.targets.length) { for (i = 0; el = self.dom.targets[i]; i++) { target = new mixitup.Target(); target.init(el, self, dataset ? dataset[i] : void(0)); target.isInDom = true; self.targets.push(target); } self.dom.parent = self.dom.targets[0].parentElement === self.dom.container ? self.dom.container : self.dom.targets[0].parentElement; } self.origOrder = self.targets; self.callActions('afterIndexTargets', arguments); }, initControls: function() { var self = this, definition = '', controlElements = null, el = null, parent = null, delagator = null, control = null, i = -1, j = -1; self.callActions('beforeInitControls', arguments); switch (self.config.controls.scope) { case 'local': parent = self.dom.container; break; case 'global': parent = self.dom.document; break; default: throw new Error(mixitup.messages.errorConfigInvalidControlsScope()); } for (i = 0; definition = mixitup.controlDefinitions[i]; i++) { if (self.config.controls.live || definition.live) { if (definition.parent) { delagator = self.dom[definition.parent]; if (!delagator) continue; } else { delagator = parent; } control = self.getControl(delagator, definition.type, definition.selector); self.controls.push(control); } else { controlElements = parent.querySelectorAll(definition.selector); for (j = 0; el = controlElements[j]; j++) { control = self.getControl(el, definition.type, ''); if (!control) continue; self.controls.push(control); } } } self.callActions('afterInitControls', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {HTMLElement} el * @param {string} type * @param {string} selector * @return {mixitup.Control|null} */ getControl: function(el, type, selector) { var self = this, control = null, i = -1; self.callActions('beforeGetControl', arguments); if (!selector) { // Static controls only for (i = 0; control = mixitup.controls[i]; i++) { if (control.el === el && control.isBound(self)) { // Control already bound to this mixer (as another type). // NB: This prevents duplicate controls from being registered where a selector // might collide, eg: "[data-filter]" and "[data-filter][data-sort]" return self.callFilters('controlGetControl', null, arguments); } else if (control.el === el && control.type === type && control.selector === selector) { // Another mixer is already using this control, add this mixer as a binding control.addBinding(self); return self.callFilters('controlGetControl', control, arguments); } } } // Create new control control = new mixitup.Control(); control.init(el, type, selector); control.classNames.base = h.getClassname(self.config.classNames, type); control.classNames.active = h.getClassname(self.config.classNames, type, self.config.classNames.modifierActive); control.classNames.disabled = h.getClassname(self.config.classNames, type, self.config.classNames.modifierDisabled); // Add a reference to this mixer as a binding control.addBinding(self); return self.callFilters('controlGetControl', control, arguments); }, /** * Creates a compound selector by joining the `toggleArray` value as per the * defined toggle logic. * * @private * @instance * @since 3.0.0 * @return {string} */ getToggleSelector: function() { var self = this, delineator = self.config.controls.toggleLogic === 'or' ? ', ' : '', toggleSelector = ''; self.callActions('beforeGetToggleSelector', arguments); self.toggleArray = h.clean(self.toggleArray); toggleSelector = self.toggleArray.join(delineator); if (toggleSelector === '') { toggleSelector = self.config.controls.toggleDefault; } return self.callFilters('selectorGetToggleSelector', toggleSelector, arguments); }, /** * Breaks compound selector strings in an array of discreet selectors, * as per the active `controls.toggleLogic` configuration option. Accepts * either a dynamic command object, or a state object. * * @private * @instance * @since 2.0.0 * @param {object} [command] * @param {mixitup.State} [state] * @return {void} */ buildToggleArray: function(command, state) { var self = this, activeFilterSelector = ''; self.callActions('beforeBuildToggleArray', arguments); if (command && command.filter) { activeFilterSelector = command.filter.selector.replace(/\s/g, ''); } else if (state) { activeFilterSelector = state.activeFilter.selector.replace(/\s/g, ''); } else { return; } if (activeFilterSelector === self.config.selectors.target || activeFilterSelector === 'all') { activeFilterSelector = ''; } if (self.config.controls.toggleLogic === 'or') { self.toggleArray = activeFilterSelector.split(','); } else { self.toggleArray = self.splitCompoundSelector(activeFilterSelector); } self.toggleArray = h.clean(self.toggleArray); self.callActions('afterBuildToggleArray', arguments); }, /** * Takes a compound selector (e.g. `.cat-1.cat-2`, `[data-cat="1"][data-cat="2"]`) * and breaks into its individual selectors. * * @private * @instance * @since 3.0.0 * @param {string} compoundSelector * @return {string[]} */ splitCompoundSelector: function(compoundSelector) { // Break at a `.` or `[`, capturing the delineator var partials = compoundSelector.split(/([\.\[])/g), toggleArray = [], selector = '', i = -1; if (partials[0] === '') { partials.shift(); } for (i = 0; i < partials.length; i++) { if (i % 2 === 0) { selector = ''; } selector += partials[i]; if (i % 2 !== 0) { toggleArray.push(selector); } } return toggleArray; }, /** * Updates controls to their active/inactive state based on the command or * current state of the mixer. * * @private * @instance * @since 2.0.0 * @param {object} command * @return {void} */ updateControls: function(command) { var self = this, control = null, output = new mixitup.CommandMultimix(), i = -1; self.callActions('beforeUpdateControls', arguments); // Sanitise to defaults if (command.filter) { output.filter = command.filter.selector; } else { output.filter = self.state.activeFilter.selector; } if (command.sort) { output.sort = self.buildSortString(command.sort); } else { output.sort = self.buildSortString(self.state.activeSort); } if (output.filter === self.config.selectors.target) { output.filter = 'all'; } if (output.filter === '') { output.filter = 'none'; } h.freeze(output); for (i = 0; control = self.controls[i]; i++) { control.update(output, self.toggleArray); } self.callActions('afterUpdateControls', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {mixitup.CommandSort} command * @return {string} */ buildSortString: function(command) { var self = this; var output = ''; output += command.sortString; if (command.next) { output += ' ' + self.buildSortString(command.next); } return output; }, /** * @private * @instance * @since 3.0.0 * @param {object} command * @param {Operation} operation * @return {Promise.<mixitup.State>} */ insertTargets: function(command, operation) { var self = this, nextSibling = null, insertionIndex = -1, frag = null, target = null, el = null, i = -1; self.callActions('beforeInsertTargets', arguments); if (typeof command.index === 'undefined') command.index = 0; nextSibling = self.getNextSibling(command.index, command.sibling, command.position); frag = self.dom.document.createDocumentFragment(); if (nextSibling) { insertionIndex = h.index(nextSibling, self.config.selectors.target); } else { insertionIndex = self.targets.length; } if (command.collection) { for (i = 0; el = command.collection[i]; i++) { if (self.dom.targets.indexOf(el) > -1) { throw new Error(mixitup.messages.errorInsertPreexistingElement()); } // Ensure elements are hidden when they are added to the DOM, so they can // be animated in gracefully el.style.display = 'none'; frag.appendChild(el); frag.appendChild(self.dom.document.createTextNode(' ')); if (!h.isElement(el, self.dom.document) || !el.matches(self.config.selectors.target)) continue; target = new mixitup.Target(); target.init(el, self); target.isInDom = true; self.targets.splice(insertionIndex, 0, target); insertionIndex++; } self.dom.parent.insertBefore(frag, nextSibling); } // Since targets have been added, the original order must be updated operation.startOrder = self.origOrder = self.targets; self.callActions('afterInsertTargets', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {Number} [index] * @param {Element} [sibling] * @param {string} [position] * @return {Element} */ getNextSibling: function(index, sibling, position) { var self = this, element = null; index = Math.max(index, 0); if (sibling && position === 'before') { // Explicit sibling element = sibling; } else if (sibling && position === 'after') { // Explicit sibling element = sibling.nextElementSibling || null; } else if (self.targets.length > 0 && typeof index !== 'undefined') { // Index and targets exist element = (index < self.targets.length || !self.targets.length) ? self.targets[index].dom.el : self.targets[self.targets.length - 1].dom.el.nextElementSibling; } else if (self.targets.length === 0 && self.dom.parent.children.length > 0) { // No targets but other siblings if (self.config.layout.siblingAfter) { element = self.config.layout.siblingAfter; } else if (self.config.layout.siblingBefore) { element = self.config.layout.siblingBefore.nextElementSibling; } else { self.dom.parent.children[0]; } } else { element === null; } return self.callFilters('elementGetNextSibling', element, arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ filterOperation: function(operation) { var self = this, testResult = false, index = -1, action = '', target = null, i = -1; self.callActions('beforeFilterOperation', arguments); action = operation.newFilter.action; for (i = 0; target = operation.newOrder[i]; i++) { if (operation.newFilter.collection) { // show via collection testResult = operation.newFilter.collection.indexOf(target.dom.el) > -1; } else { // show via selector if (operation.newFilter.selector === '') { testResult = false; } else { testResult = target.dom.el.matches(operation.newFilter.selector); } } self.evaluateHideShow(testResult, target, action, operation); } if (operation.toRemove.length) { for (i = 0; target = operation.show[i]; i++) { if (operation.toRemove.indexOf(target) > -1) { // If any shown targets should be removed, move them into the toHide array operation.show.splice(i, 1); if ((index = operation.toShow.indexOf(target)) > -1) { operation.toShow.splice(index, 1); } operation.toHide.push(target); operation.hide.push(target); i--; } } } operation.matching = operation.show.slice(); if (operation.show.length === 0 && operation.newFilter.selector !== '' && self.targets.length !== 0) { operation.hasFailed = true; } self.callActions('afterFilterOperation', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {boolean} testResult * @param {Element} target * @param {string} action * @param {Operation} operation * @return {void} */ evaluateHideShow: function(testResult, target, action, operation) { var self = this; self.callActions('beforeEvaluateHideShow', arguments); if (testResult === true && action === 'show' || testResult === false && action === 'hide') { operation.show.push(target); !target.isShown && operation.toShow.push(target); } else { operation.hide.push(target); target.isShown && operation.toHide.push(target); } self.callActions('afterEvaluateHideShow', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ sortOperation: function(operation) { var self = this; self.callActions('beforeSortOperation', arguments); operation.startOrder = self.targets; if (operation.newSort.collection) { // Sort by collection operation.newOrder = operation.newSort.collection; } else if (operation.newSort.order === 'random') { // Sort random operation.newOrder = h.arrayShuffle(operation.startOrder); } else if (operation.newSort.attribute === '') { // Sort by default operation.newOrder = self.origOrder.slice(); if (operation.newSort.order === 'desc') { operation.newOrder.reverse(); } } else { // Sort by attribute operation.newOrder = operation.startOrder.slice(); operation.newOrder.sort(function(a, b) { return self.compare(a, b, operation.newSort); }); } if (h.isEqualArray(operation.newOrder, operation.startOrder)) { operation.willSort = false; } self.callActions('afterSortOperation', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {mixitup.Target} a * @param {mixitup.Target} b * @param {mixitup.CommandSort} command * @return {Number} */ compare: function(a, b, command) { var self = this, order = command.order, attrA = self.getAttributeValue(a, command.attribute), attrB = self.getAttributeValue(b, command.attribute); if (isNaN(attrA * 1) || isNaN(attrB * 1)) { attrA = attrA.toLowerCase(); attrB = attrB.toLowerCase(); } else { attrA = attrA * 1; attrB = attrB * 1; } if (attrA < attrB) { return order === 'asc' ? -1 : 1; } if (attrA > attrB) { return order === 'asc' ? 1 : -1; } if (attrA === attrB && command.next) { return self.compare(a, b, command.next); } return 0; }, /** * Reads the values of any data attributes present the provided target element * which match the current sort command. * * @private * @instance * @since 3.0.0 * @param {mixitup.Target} target * @param {string} [attribute] * @return {(String|Number)} */ getAttributeValue: function(target, attribute) { var self = this, value = ''; value = target.dom.el.getAttribute('data-' + attribute); if (value === null) { if (self.config.debug.showWarnings) { // Encourage users to assign values to all targets to avoid erroneous sorting // when types are mixed console.warn(mixitup.messages.warningInconsistentSortingAttributes({ attribute: 'data-' + attribute })); } } // If an attribute is not present, return 0 as a safety value return self.callFilters('valueGetAttributeValue', value || 0, arguments); }, /** * Inserts elements into the DOM in the appropriate * order using a document fragment for minimal * DOM thrashing * * @private * @instance * @since 2.0.0 * @param {boolean} isResetting * @param {Operation} operation * @return {void} */ printSort: function(isResetting, operation) { var self = this, startOrder = isResetting ? operation.newOrder : operation.startOrder, newOrder = isResetting ? operation.startOrder : operation.newOrder, nextSibling = startOrder.length ? startOrder[startOrder.length - 1].dom.el.nextElementSibling : null, frag = window.document.createDocumentFragment(), whitespace = null, target = null, el = null, i = -1; self.callActions('beforePrintSort', arguments); // Empty the container for (i = 0; target = startOrder[i]; i++) { el = target.dom.el; if (el.style.position === 'absolute') continue; h.removeWhitespace(el.previousSibling); el.parentElement.removeChild(el); } whitespace = nextSibling ? nextSibling.previousSibling : self.dom.parent.lastChild; if (whitespace && whitespace.nodeName === '#text') { h.removeWhitespace(whitespace); } for (i = 0; target = newOrder[i]; i++) { // Add targets into a document fragment el = target.dom.el; if (h.isElement(frag.lastChild)) { frag.appendChild(window.document.createTextNode(' ')); } frag.appendChild(el); } // Insert the document fragment into the container // before any other non-target elements if (self.dom.parent.firstChild && self.dom.parent.firstChild !== nextSibling) { frag.insertBefore(window.document.createTextNode(' '), frag.childNodes[0]); } if (nextSibling) { frag.appendChild(window.document.createTextNode(' ')); self.dom.parent.insertBefore(frag, nextSibling); } else { self.dom.parent.appendChild(frag); } self.callActions('afterPrintSort', arguments); }, /** * Parses user-defined sort strings (i.e. `default:asc`) into sort commands objects. * * @private * @instance * @since 3.0.0 * @param {string} sortString * @param {mixitup.CommandSort} command * @return {mixitup.CommandSort} */ parseSortString: function(sortString, command) { var self = this, rules = sortString.split(' '), current = command, rule = [], i = -1; // command.sortString = sortString; for (i = 0; i < rules.length; i++) { rule = rules[i].split(':'); current.sortString = rules[i]; current.attribute = h.dashCase(rule[0]); current.order = rule[1] || 'asc'; switch (current.attribute) { case 'default': // treat "default" as sorting by no attribute current.attribute = ''; break; case 'random': // treat "random" as an order not an attribute current.attribute = ''; current.order = 'random'; break; } if (!current.attribute || current.order === 'random') break; if (i < rules.length - 1) { // Embed reference to the next command current.next = new mixitup.CommandSort(); h.freeze(current); current = current.next; } } return self.callFilters('commandsParseSort', command, arguments); }, /** * Parses all effects out of the user-defined `animation.effects` string into * their respective properties and units. * * @private * @instance * @since 2.0.0 * @return {void} */ parseEffects: function() { var self = this, transformName = '', effectsIn = self.config.animation.effectsIn || self.config.animation.effects, effectsOut = self.config.animation.effectsOut || self.config.animation.effects; self.callActions('beforeParseEffects', arguments); self.effectsIn = new mixitup.StyleData(); self.effectsOut = new mixitup.StyleData(); self.transformIn = []; self.transformOut = []; self.effectsIn.opacity = self.effectsOut.opacity = 1; self.parseEffect('fade', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('fade', effectsOut, self.effectsOut, self.transformOut, true); for (transformName in mixitup.transformDefaults) { if (!(mixitup.transformDefaults[transformName] instanceof mixitup.TransformData)) { continue; } self.parseEffect(transformName, effectsIn, self.effectsIn, self.transformIn); self.parseEffect(transformName, effectsOut, self.effectsOut, self.transformOut, true); } self.parseEffect('stagger', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('stagger', effectsOut, self.effectsOut, self.transformOut, true); self.callActions('afterParseEffects', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {string} effectName * @param {string} effectString * @param {StyleData} effects * @param {String[]} transform * @param {boolean} [isOut] */ parseEffect: function(effectName, effectString, effects, transform, isOut) { var self = this, re = /\(([^)]+)\)/, propIndex = -1, str = '', match = [], val = '', units = ['%', 'px', 'em', 'rem', 'vh', 'vw', 'deg'], unit = '', i = -1; self.callActions('beforeParseEffect', arguments); if (typeof effectString !== 'string') { throw new TypeError(mixitup.messages.errorConfigInvalidAnimationEffects()); } if (effectString.indexOf(effectName) < 0) { // The effect is not present in the effects string if (effectName === 'stagger') { // Reset stagger to 0 self.staggerDuration = 0; } return; } // The effect is present propIndex = effectString.indexOf(effectName + '('); if (propIndex > -1) { // The effect has a user defined value in parentheses // Extract from the first parenthesis to the end of string str = effectString.substring(propIndex); // Match any number of characters between "(" and ")" match = re.exec(str); val = match[1]; } switch (effectName) { case 'fade': effects.opacity = val ? parseFloat(val) : 0; break; case 'stagger': self.staggerDuration = val ? parseFloat(val) : 100; // TODO: Currently stagger must be applied globally, but // if seperate values are specified for in/out, this should // be respected break; default: // All other effects are transforms following the same structure if (isOut && self.config.animation.reverseOut && effectName !== 'scale') { effects[effectName].value = (val ? parseFloat(val) : mixitup.transformDefaults[effectName].value) * -1; } else { effects[effectName].value = (val ? parseFloat(val) : mixitup.transformDefaults[effectName].value); } if (val) { for (i = 0; unit = units[i]; i++) { if (val.indexOf(unit) > -1) { effects[effectName].unit = unit; break; } } } else { effects[effectName].unit = mixitup.transformDefaults[effectName].unit; } transform.push( effectName + '(' + effects[effectName].value + effects[effectName].unit + ')' ); } self.callActions('afterParseEffect', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {State} */ buildState: function(operation) { var self = this, state = new mixitup.State(), target = null, i = -1; self.callActions('beforeBuildState', arguments); // Map target elements into state arrays. // the real target objects should never be exposed for (i = 0; target = self.targets[i]; i++) { if (!operation.toRemove.length || operation.toRemove.indexOf(target) < 0) { state.targets.push(target.dom.el); } } for (i = 0; target = operation.matching[i]; i++) { state.matching.push(target.dom.el); } for (i = 0; target = operation.show[i]; i++) { state.show.push(target.dom.el); } for (i = 0; target = operation.hide[i]; i++) { if (!operation.toRemove.length || operation.toRemove.indexOf(target) < 0) { state.hide.push(target.dom.el); } } state.id = self.id; state.container = self.dom.container; state.activeFilter = operation.newFilter; state.activeSort = operation.newSort; state.activeDataset = operation.newDataset; state.activeContainerClassName = operation.newContainerClassName; state.hasFailed = operation.hasFailed; state.totalTargets = self.targets.length; state.totalShow = operation.show.length; state.totalHide = operation.hide.length; state.totalMatching = operation.matching.length; state.triggerElement = operation.triggerElement; return self.callFilters('stateBuildState', state, arguments); }, /** * @private * @instance * @since 2.0.0 * @param {boolean} shouldAnimate * @param {Operation} operation * @return {void} */ goMix: function(shouldAnimate, operation) { var self = this, deferred = null; self.callActions('beforeGoMix', arguments); // If the animation duration is set to 0ms, // or no effects specified, // or the container is hidden // then abort animation if ( !self.config.animation.duration || !self.config.animation.effects || !h.isVisible(self.dom.container) ) { shouldAnimate = false; } if ( !operation.toShow.length && !operation.toHide.length && !operation.willSort && !operation.willChangeLayout ) { // If nothing to show or hide, and not sorting or // changing layout shouldAnimate = false; } if ( !operation.startState.show.length && !operation.show.length ) { // If nothing currently shown, nothing to show shouldAnimate = false; } mixitup.events.fire('mixStart', self.dom.container, { state: operation.startState, futureState: operation.newState, instance: self }, self.dom.document); if (typeof self.config.callbacks.onMixStart === 'function') { self.config.callbacks.onMixStart.call( self.dom.container, operation.startState, operation.newState, self ); } h.removeClass(self.dom.container, h.getClassname(self.config.classNames, 'container', self.config.classNames.modifierFailed)); if (!self.userDeferred) { // Queue empty, no pending operations deferred = self.userDeferred = h.defer(mixitup.libraries); } else { // Use existing deferred deferred = self.userDeferred; } self.isBusy = true; if (!shouldAnimate || !mixitup.features.has.transitions) { // Abort if (self.config.debug.fauxAsync) { setTimeout(function() { self.cleanUp(operation); }, self.config.animation.duration); } else { self.cleanUp(operation); } return self.callFilters('promiseGoMix', deferred.promise, arguments); } // If we should animate and the platform supports transitions, go for it if (window.pageYOffset !== operation.docState.scrollTop) { window.scrollTo(operation.docState.scrollLeft, operation.docState.scrollTop); } if (self.config.animation.applyPerspective) { self.dom.parent.style[mixitup.features.perspectiveProp] = self.config.animation.perspectiveDistance; self.dom.parent.style[mixitup.features.perspectiveOriginProp] = self.config.animation.perspectiveOrigin; } if (self.config.animation.animateResizeContainer || operation.startHeight === operation.newHeight) { self.dom.parent.style.height = operation.startHeight + 'px'; } if (self.config.animation.animateResizeContainer || operation.startWidth === operation.newWidth) { self.dom.parent.style.width = operation.startWidth + 'px'; } requestAnimationFrame(function() { self.moveTargets(operation); }); return self.callFilters('promiseGoMix', deferred.promise, arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ getStartMixData: function(operation) { var self = this, parentStyle = window.getComputedStyle(self.dom.parent), parentRect = self.dom.parent.getBoundingClientRect(), target = null, data = {}, i = -1, boxSizing = parentStyle[mixitup.features.boxSizingProp]; self.incPadding = (boxSizing === 'border-box'); self.callActions('beforeGetStartMixData', arguments); for (i = 0; target = operation.show[i]; i++) { data = target.getPosData(); operation.showPosData[i] = { startPosData: data }; } for (i = 0; target = operation.toHide[i]; i++) { data = target.getPosData(); operation.toHidePosData[i] = { startPosData: data }; } operation.startX = parentRect.left; operation.startY = parentRect.top; operation.startHeight = self.incPadding ? parentRect.height : parentRect.height - parseFloat(parentStyle.paddingTop) - parseFloat(parentStyle.paddingBottom) - parseFloat(parentStyle.borderTop) - parseFloat(parentStyle.borderBottom); operation.startWidth = self.incPadding ? parentRect.width : parentRect.width - parseFloat(parentStyle.paddingLeft) - parseFloat(parentStyle.paddingRight) - parseFloat(parentStyle.borderLeft) - parseFloat(parentStyle.borderRight); self.callActions('afterGetStartMixData', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ setInter: function(operation) { var self = this, target = null, i = -1; self.callActions('beforeSetInter', arguments); // Prevent scrollbar flicker on non-inertial scroll platforms by clamping height if (self.config.animation.clampHeight) { self.dom.parent.style.height = operation.startHeight; self.dom.parent.style.overflow = 'hidden'; } for (i = 0; target = operation.toShow[i]; i++) { target.show(); } if (operation.willChangeLayout) { h.removeClass(self.dom.container, operation.startContainerClassName); h.addClass(self.dom.container, operation.newContainerClassName); } self.callActions('afterSetInter', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ getInterMixData: function(operation) { var self = this, target = null, i = -1; self.callActions('beforeGetInterMixData', arguments); for (i = 0; target = operation.show[i]; i++) { operation.showPosData[i].interPosData = target.getPosData(); } for (i = 0; target = operation.toHide[i]; i++) { operation.toHidePosData[i].interPosData = target.getPosData(); } self.callActions('afterGetInterMixData', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ setFinal: function(operation) { var self = this, target = null, i = -1; self.callActions('beforeSetFinal', arguments); // Remove clamping if (self.config.animation.clampHeight) { self.dom.parent.style.height = self.dom.parent.style.overflow = ''; } operation.willSort && self.printSort(false, operation); for (i = 0; target = operation.toHide[i]; i++) { target.hide(); } self.callActions('afterSetFinal', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ getFinalMixData: function(operation) { var self = this, parentStyle = null, parentRect = self.dom.parent.getBoundingClientRect(), target = null, i = -1; if (!self.incPadding) { parentStyle = window.getComputedStyle(self.dom.parent); } self.callActions('beforeGetFinalMixData', arguments); for (i = 0; target = operation.show[i]; i++) { operation.showPosData[i].finalPosData = target.getPosData(); } for (i = 0; target = operation.toHide[i]; i++) { operation.toHidePosData[i].finalPosData = target.getPosData(); } operation.newX = parentRect.left; operation.newY = parentRect.top; operation.newHeight = self.incPadding ? parentRect.height : parentRect.height - parseFloat(parentStyle.paddingTop) - parseFloat(parentStyle.paddingBottom) - parseFloat(parentStyle.borderTop) - parseFloat(parentStyle.borderBottom); operation.newWidth = self.incPadding ? parentRect.width : parentRect.width - parseFloat(parentStyle.paddingLeft) - parseFloat(parentStyle.paddingRight) - parseFloat(parentStyle.borderLeft) - parseFloat(parentStyle.borderRight); if (operation.willSort) { self.printSort(true, operation); } for (i = 0; target = operation.toShow[i]; i++) { target.hide(); } for (i = 0; target = operation.toHide[i]; i++) { target.show(); } if (operation.willChangeLayout) { h.removeClass(self.dom.container, operation.newContainerClassName); h.addClass(self.dom.container, self.config.layout.containerClassName); } self.callActions('afterGetFinalMixData', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {Operation} operation */ getTweenData: function(operation) { var self = this, target = null, posData = null, effectNames = Object.getOwnPropertyNames(self.effectsIn), effectName = '', effect = null, widthChange = -1, heightChange = -1, i = -1, j = -1; self.callActions('beforeGetTweenData', arguments); for (i = 0; target = operation.show[i]; i++) { posData = operation.showPosData[i]; posData.posIn = new mixitup.StyleData(); posData.posOut = new mixitup.StyleData(); posData.tweenData = new mixitup.StyleData(); // Process x and y if (target.isShown) { posData.posIn.x = posData.startPosData.x - posData.interPosData.x; posData.posIn.y = posData.startPosData.y - posData.interPosData.y; } else { posData.posIn.x = posData.posIn.y = 0; } posData.posOut.x = posData.finalPosData.x - posData.interPosData.x; posData.posOut.y = posData.finalPosData.y - posData.interPosData.y; // Process opacity posData.posIn.opacity = target.isShown ? 1 : self.effectsIn.opacity; posData.posOut.opacity = 1; posData.tweenData.opacity = posData.posOut.opacity - posData.posIn.opacity; // Adjust x and y if not nudging if (!target.isShown && !self.config.animation.nudge) { posData.posIn.x = posData.posOut.x; posData.posIn.y = posData.posOut.y; } posData.tweenData.x = posData.posOut.x - posData.posIn.x; posData.tweenData.y = posData.posOut.y - posData.posIn.y; // Process width, height, and margins if (self.config.animation.animateResizeTargets) { posData.posIn.width = posData.startPosData.width; posData.posIn.height = posData.startPosData.height; // "||" Prevents width/height change from including 0 width/height if hiding or showing widthChange = (posData.startPosData.width || posData.finalPosData.width) - posData.interPosData.width; posData.posIn.marginRight = posData.startPosData.marginRight - widthChange; heightChange = (posData.startPosData.height || posData.finalPosData.height) - posData.interPosData.height; posData.posIn.marginBottom = posData.startPosData.marginBottom - heightChange; posData.posOut.width = posData.finalPosData.width; posData.posOut.height = posData.finalPosData.height; widthChange = (posData.finalPosData.width || posData.startPosData.width) - posData.interPosData.width; posData.posOut.marginRight = posData.finalPosData.marginRight - widthChange; heightChange = (posData.finalPosData.height || posData.startPosData.height) - posData.interPosData.height; posData.posOut.marginBottom = posData.finalPosData.marginBottom - heightChange; posData.tweenData.width = posData.posOut.width - posData.posIn.width; posData.tweenData.height = posData.posOut.height - posData.posIn.height; posData.tweenData.marginRight = posData.posOut.marginRight - posData.posIn.marginRight; posData.tweenData.marginBottom = posData.posOut.marginBottom - posData.posIn.marginBottom; } // Process transforms for (j = 0; effectName = effectNames[j]; j++) { effect = self.effectsIn[effectName]; if (!(effect instanceof mixitup.TransformData) || !effect.value) continue; posData.posIn[effectName].value = effect.value; posData.posOut[effectName].value = 0; posData.tweenData[effectName].value = posData.posOut[effectName].value - posData.posIn[effectName].value; posData.posIn[effectName].unit = posData.posOut[effectName].unit = posData.tweenData[effectName].unit = effect.unit; } } for (i = 0; target = operation.toHide[i]; i++) { posData = operation.toHidePosData[i]; posData.posIn = new mixitup.StyleData(); posData.posOut = new mixitup.StyleData(); posData.tweenData = new mixitup.StyleData(); // Process x and y posData.posIn.x = target.isShown ? posData.startPosData.x - posData.interPosData.x : 0; posData.posIn.y = target.isShown ? posData.startPosData.y - posData.interPosData.y : 0; posData.posOut.x = self.config.animation.nudge ? 0 : posData.posIn.x; posData.posOut.y = self.config.animation.nudge ? 0 : posData.posIn.y; posData.tweenData.x = posData.posOut.x - posData.posIn.x; posData.tweenData.y = posData.posOut.y - posData.posIn.y; // Process width, height, and margins if (self.config.animation.animateResizeTargets) { posData.posIn.width = posData.startPosData.width; posData.posIn.height = posData.startPosData.height; widthChange = posData.startPosData.width - posData.interPosData.width; posData.posIn.marginRight = posData.startPosData.marginRight - widthChange; heightChange = posData.startPosData.height - posData.interPosData.height; posData.posIn.marginBottom = posData.startPosData.marginBottom - heightChange; } // Process opacity posData.posIn.opacity = 1; posData.posOut.opacity = self.effectsOut.opacity; posData.tweenData.opacity = posData.posOut.opacity - posData.posIn.opacity; // Process transforms for (j = 0; effectName = effectNames[j]; j++) { effect = self.effectsOut[effectName]; if (!(effect instanceof mixitup.TransformData) || !effect.value) continue; posData.posIn[effectName].value = 0; posData.posOut[effectName].value = effect.value; posData.tweenData[effectName].value = posData.posOut[effectName].value - posData.posIn[effectName].value; posData.posIn[effectName].unit = posData.posOut[effectName].unit = posData.tweenData[effectName].unit = effect.unit; } } self.callActions('afterGetTweenData', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {Operation} operation * @return {void} */ moveTargets: function(operation) { var self = this, target = null, moveData = null, posData = null, statusChange = '', willTransition = false, staggerIndex = -1, i = -1, checkProgress = self.checkProgress.bind(self); self.callActions('beforeMoveTargets', arguments); // TODO: this is an extra loop in addition to the calcs // done in getOperation, could some of this be done there? for (i = 0; target = operation.show[i]; i++) { moveData = new mixitup.IMoveData(); posData = operation.showPosData[i]; statusChange = target.isShown ? 'none' : 'show'; willTransition = self.willTransition( statusChange, operation.hasEffect, posData.posIn, posData.posOut ); if (willTransition) { // Prevent non-transitioning targets from incrementing the staggerIndex staggerIndex++; } target.show(); moveData.posIn = posData.posIn; moveData.posOut = posData.posOut; moveData.statusChange = statusChange; moveData.staggerIndex = staggerIndex; moveData.operation = operation; moveData.callback = willTransition ? checkProgress : null; target.move(moveData); } for (i = 0; target = operation.toHide[i]; i++) { posData = operation.toHidePosData[i]; moveData = new mixitup.IMoveData(); statusChange = 'hide'; willTransition = self.willTransition(statusChange, posData.posIn, posData.posOut); moveData.posIn = posData.posIn; moveData.posOut = posData.posOut; moveData.statusChange = statusChange; moveData.staggerIndex = i; moveData.operation = operation; moveData.callback = willTransition ? checkProgress : null; target.move(moveData); } if (self.config.animation.animateResizeContainer) { self.dom.parent.style[mixitup.features.transitionProp] = 'height ' + self.config.animation.duration + 'ms ease, ' + 'width ' + self.config.animation.duration + 'ms ease '; requestAnimationFrame(function() { self.dom.parent.style.height = operation.newHeight + 'px'; self.dom.parent.style.width = operation.newWidth + 'px'; }); } if (operation.willChangeLayout) { h.removeClass(self.dom.container, self.config.layout.ContainerClassName); h.addClass(self.dom.container, operation.newContainerClassName); } self.callActions('afterMoveTargets', arguments); }, /** * @private * @instance * @return {boolean} */ hasEffect: function() { var self = this, EFFECTABLES = [ 'scale', 'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ' ], effectName = '', effect = null, result = false, value = -1, i = -1; if (self.effectsIn.opacity !== 1) { return self.callFilters('resultHasEffect', true, arguments); } for (i = 0; effectName = EFFECTABLES[i]; i++) { effect = self.effectsIn[effectName]; value = (typeof effect && effect.value !== 'undefined') ? effect.value : effect; if (value !== 0) { result = true; break; } } return self.callFilters('resultHasEffect', result, arguments); }, /** * Determines if a target element will transition in * some fasion and therefore requires binding of * transitionEnd * * @private * @instance * @since 3.0.0 * @param {string} statusChange * @param {boolean} hasEffect * @param {StyleData} posIn * @param {StyleData} posOut * @return {boolean} */ willTransition: function(statusChange, hasEffect, posIn, posOut) { var self = this, result = false; if (!h.isVisible(self.dom.container)) { // If the container is not visible, the transitionEnd // event will not occur and MixItUp will hang result = false; } else if ( (statusChange !== 'none' && hasEffect) || posIn.x !== posOut.x || posIn.y !== posOut.y ) { // If opacity and/or translate will change result = true; } else if (self.config.animation.animateResizeTargets) { // Check if width, height or margins will change result = ( posIn.width !== posOut.width || posIn.height !== posOut.height || posIn.marginRight !== posOut.marginRight || posIn.marginTop !== posOut.marginTop ); } else { result = false; } return self.callFilters('resultWillTransition', result, arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ checkProgress: function(operation) { var self = this; self.targetsDone++; if (self.targetsBound === self.targetsDone) { self.cleanUp(operation); } }, /** * @private * @instance * @since 2.0.0 * @param {Operation} operation * @return {void} */ cleanUp: function(operation) { var self = this, target = null, whitespaceBefore = null, whitespaceAfter = null, nextInQueue = null, i = -1; self.callActions('beforeCleanUp', arguments); self.targetsMoved = self.targetsImmovable = self.targetsBound = self.targetsDone = 0; for (i = 0; target = operation.show[i]; i++) { target.cleanUp(); target.show(); } for (i = 0; target = operation.toHide[i]; i++) { target.cleanUp(); target.hide(); } if (operation.willSort) { self.printSort(false, operation); self.targets = operation.newOrder; } // Remove any styles applied to the parent container self.dom.parent.style[mixitup.features.transitionProp] = self.dom.parent.style.height = self.dom.parent.style.width = self.dom.parent.style[mixitup.features.perspectiveProp] = self.dom.parent.style[mixitup.features.perspectiveOriginProp] = ''; if (operation.willChangeLayout) { h.removeClass(self.dom.container, operation.startContainerClassName); h.addClass(self.dom.container, operation.newContainerClassName); } if (operation.toRemove.length) { for (i = 0; target = self.targets[i]; i++) { if (operation.toRemove.indexOf(target) > -1) { if ( (whitespaceBefore = target.dom.el.previousSibling) && whitespaceBefore.nodeName === '#text' && (whitespaceAfter = target.dom.el.nextSibling) && whitespaceAfter.nodeName === '#text' ) { h.removeWhitespace(whitespaceBefore); } self.dom.parent.removeChild(target.dom.el); self.targets.splice(i, 1); target.isInDom = false; i--; } } // Since targets have been removed, the original order must be updated self.origOrder = self.targets; } self.state = operation.newState; self.lastOperation = operation; self.dom.targets = self.state.targets; // mixEnd mixitup.events.fire('mixEnd', self.dom.container, { state: self.state, instance: self }, self.dom.document); if (typeof self.config.callbacks.onMixEnd === 'function') { self.config.callbacks.onMixEnd.call(self.dom.container, self.state, self); } if (operation.hasFailed) { // mixFail mixitup.events.fire('mixFail', self.dom.container, { state: self.state, instance: self }, self.dom.document); if (typeof self.config.callbacks.onMixFail === 'function') { self.config.callbacks.onMixFail.call(self.dom.container, self.state, self); } h.addClass(self.dom.container, h.getClassname(self.config.classNames, 'container', self.config.classNames.modifierFailed)); } // User-defined callback function if (typeof self.userCallback === 'function') { self.userCallback.call(self.dom.container, self.state, self); } if (typeof self.userDeferred.resolve === 'function') { self.userDeferred.resolve(self.state); } self.userCallback = null; self.userDeferred = null; self.lastClicked = null; self.isToggling = false; self.isBusy = false; if (self.queue.length) { self.callActions('beforeReadQueueCleanUp', arguments); nextInQueue = self.queue.shift(); // Update non-public API properties stored in queue self.userDeferred = nextInQueue.deferred; self.isToggling = nextInQueue.isToggling; self.lastClicked = nextInQueue.triggerElement; if (nextInQueue.instruction.command instanceof mixitup.CommandMultimix) { self.multimix.apply(self, nextInQueue.args); } else { self.dataset.apply(self, nextInQueue.args); } } self.callActions('afterCleanUp', arguments); }, /** * @private * @instance * @since 2.0.0 * @param {Array<*>} args * @return {mixitup.UserInstruction} */ parseMultimixArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), arg = null, i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandMultimix(); for (i = 0; i < args.length; i++) { arg = args[i]; if (arg === null) continue; if (typeof arg === 'object') { h.extend(instruction.command, arg); } else if (typeof arg === 'boolean') { instruction.animate = arg; } else if (typeof arg === 'function') { instruction.callback = arg; } } // Coerce arbitrary command arguments into typed command objects if (instruction.command.insert && !(instruction.command.insert instanceof mixitup.CommandInsert)) { instruction.command.insert = self.parseInsertArgs([instruction.command.insert]).command; } if (instruction.command.remove && !(instruction.command.remove instanceof mixitup.CommandRemove)) { instruction.command.remove = self.parseRemoveArgs([instruction.command.remove]).command; } if (instruction.command.filter && !(instruction.command.filter instanceof mixitup.CommandFilter)) { instruction.command.filter = self.parseFilterArgs([instruction.command.filter]).command; } if (instruction.command.sort && !(instruction.command.sort instanceof mixitup.CommandSort)) { instruction.command.sort = self.parseSortArgs([instruction.command.sort]).command; } if (instruction.command.changeLayout && !(instruction.command.changeLayout instanceof mixitup.CommandChangeLayout)) { instruction.command.changeLayout = self.parseChangeLayoutArgs([instruction.command.changeLayout]).command; } instruction = self.callFilters('instructionParseMultimixArgs', instruction, arguments); h.freeze(instruction); return instruction; }, /** * @private * @instance * @since 2.0.0 * @param {Array<*>} args * @return {mixitup.UserInstruction} */ parseFilterArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), arg = null, i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandFilter(); for (i = 0; i < args.length; i++) { arg = args[i]; if (typeof arg === 'string') { // Selector instruction.command.selector = arg; } else if (arg === null) { instruction.command.collection = []; } else if (typeof arg === 'object' && h.isElement(arg, self.dom.document)) { // Single element instruction.command.collection = [arg]; } else if (typeof arg === 'object' && typeof arg.length !== 'undefined') { // Multiple elements in array, NodeList or jQuery collection instruction.command.collection = h.arrayFromList(arg); } else if (typeof arg === 'object') { // Filter command h.extend(instruction.command, arg); } else if (typeof arg === 'boolean') { instruction.animate = arg; } else if (typeof arg === 'function') { instruction.callback = arg; } } if (instruction.command.selector && instruction.command.collection) { throw new Error(mixitup.messages.errorFilterInvalidArguments()); } instruction = self.callFilters('instructionParseFilterArgs', instruction, arguments); h.freeze(instruction); return instruction; }, parseSortArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), arg = null, sortString = '', i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandSort(); for (i = 0; i < args.length; i++) { arg = args[i]; if (arg === null) continue; switch (typeof arg) { case 'string': // Sort string sortString = arg; break; case 'object': // Array of element references if (arg.length) { instruction.command.collection = h.arrayFromList(arg); } break; case 'boolean': instruction.animate = arg; break; case 'function': instruction.callback = arg; break; } } if (sortString) { instruction.command = self.parseSortString(sortString, instruction.command); } instruction = self.callFilters('instructionParseSortArgs', instruction, arguments); h.freeze(instruction); return instruction; }, /** * @private * @instance * @since 2.0.0 * @param {Array<*>} args * @return {mixitup.UserInstruction} */ parseInsertArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), arg = null, i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandInsert(); for (i = 0; i < args.length; i++) { arg = args[i]; if (arg === null) continue; if (typeof arg === 'number') { // Insert index instruction.command.index = arg; } else if (typeof arg === 'string' && ['before', 'after'].indexOf(arg) > -1) { // 'before'/'after' instruction.command.position = arg; } else if (typeof arg === 'string') { // Markup instruction.command.collection = h.arrayFromList(h.createElement(arg).childNodes); } else if (typeof arg === 'object' && h.isElement(arg, self.dom.document)) { // Single element !instruction.command.collection.length ? (instruction.command.collection = [arg]) : (instruction.command.sibling = arg); } else if (typeof arg === 'object' && arg.length) { // Multiple elements in array or jQuery collection !instruction.command.collection.length ? (instruction.command.collection = arg) : instruction.command.sibling = arg[0]; } else if (typeof arg === 'object' && arg.childNodes && arg.childNodes.length) { // Document fragment !instruction.command.collection.length ? instruction.command.collection = h.arrayFromList(arg.childNodes) : instruction.command.sibling = arg.childNodes[0]; } else if (typeof arg === 'object') { // Insert command h.extend(instruction.command, arg); } else if (typeof arg === 'boolean') { instruction.animate = arg; } else if (typeof arg === 'function') { instruction.callback = arg; } } if (instruction.command.index && instruction.command.sibling) { throw new Error(mixitup.messages.errorInsertInvalidArguments()); } if (!instruction.command.collection.length && self.config.debug.showWarnings) { console.warn(mixitup.messages.warningInsertNoElements()); } instruction = self.callFilters('instructionParseInsertArgs', instruction, arguments); h.freeze(instruction); return instruction; }, /** * @private * @instance * @since 3.0.0 * @param {Array<*>} args * @return {mixitup.UserInstruction} */ parseRemoveArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), target = null, arg = null, i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandRemove(); for (i = 0; i < args.length; i++) { arg = args[i]; if (arg === null) continue; switch (typeof arg) { case 'number': if (self.targets[arg]) { instruction.command.targets[0] = self.targets[arg]; } break; case 'string': instruction.command.collection = h.arrayFromList(self.dom.parent.querySelectorAll(arg)); break; case 'object': if (arg && arg.length) { instruction.command.collection = arg; } else if (h.isElement(arg, self.dom.document)) { instruction.command.collection = [arg]; } else { // Remove command h.extend(instruction.command, arg); } break; case 'boolean': instruction.animate = arg; break; case 'function': instruction.callback = arg; break; } } if (instruction.command.collection.length) { for (i = 0; target = self.targets[i]; i++) { if (instruction.command.collection.indexOf(target.dom.el) > -1) { instruction.command.targets.push(target); } } } if (!instruction.command.targets.length && self.config.debug.showWarnings) { console.warn(mixitup.messages.warningRemoveNoElements()); } h.freeze(instruction); return instruction; }, /** * @private * @instance * @since 3.0.0 * @param {Array<*>} args * @return {mixitup.UserInstruction} */ parseDatasetArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), arg = null, i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandDataset(); for (i = 0; i < args.length; i++) { arg = args[i]; if (arg === null) continue; switch (typeof arg) { case 'object': if (Array.isArray(arg) || typeof arg.length === 'number') { instruction.command.dataset = arg; } else { // Change layout command h.extend(instruction.command, arg); } break; case 'boolean': instruction.animate = arg; break; case 'function': instruction.callback = arg; break; } } h.freeze(instruction); return instruction; }, /** * @private * @instance * @since 3.0.0 * @param {Array<*>} args * @return {mixitup.UserInstruction} */ parseChangeLayoutArgs: function(args) { var self = this, instruction = new mixitup.UserInstruction(), arg = null, i = -1; instruction.animate = self.config.animation.enable; instruction.command = new mixitup.CommandChangeLayout(); for (i = 0; i < args.length; i++) { arg = args[i]; if (arg === null) continue; switch (typeof arg) { case 'string': instruction.command.containerClassName = arg; break; case 'object': // Change layout command h.extend(instruction.command, arg); break; case 'boolean': instruction.animate = arg; break; case 'function': instruction.callback = arg; break; } } h.freeze(instruction); return instruction; }, /** * @private * @instance * @since 3.0.0 * @param {mixitup.QueueItem} queueItem * @return {Promise.<mixitup.State>} */ queueMix: function(queueItem) { var self = this, deferred = null, toggleSelector = ''; self.callActions('beforeQueueMix', arguments); deferred = h.defer(mixitup.libraries); if (self.config.animation.queue && self.queue.length < self.config.animation.queueLimit) { queueItem.deferred = deferred; self.queue.push(queueItem); // Keep controls in sync with user interactions. Mixer will catch up as it drains the queue. if (self.config.controls.enable) { if (self.isToggling) { self.buildToggleArray(queueItem.instruction.command); toggleSelector = self.getToggleSelector(); self.updateControls({ filter: { selector: toggleSelector } }); } else { self.updateControls(queueItem.instruction.command); } } } else { if (self.config.debug.showWarnings) { console.warn(mixitup.messages.warningMultimixInstanceQueueFull()); } deferred.resolve(self.state); mixitup.events.fire('mixBusy', self.dom.container, { state: self.state, instance: self }, self.dom.document); if (typeof self.config.callbacks.onMixBusy === 'function') { self.config.callbacks.onMixBusy.call(self.dom.container, self.state, self); } } return self.callFilters('promiseQueueMix', deferred.promise, arguments); }, /** * @private * @instance * @since 3.0.0 * @param {Array.<object>} newDataset * @return {Operation} */ getDataOperation: function(newDataset) { var self = this, operation = new mixitup.Operation(), startDataset = []; operation = self.callFilters('operationUnmappedGetDataOperation', operation, arguments); if (self.dom.targets.length && !(startDataset = (self.state.activeDataset || [])).length) { throw new Error(mixitup.messages.errorDatasetNotSet()); } operation.id = h.randomHex(); operation.startState = self.state; operation.startOrder = self.targets; operation.startDataset = startDataset; operation.newDataset = newDataset.slice(); self.diffDatasets(operation); operation.newOrder = operation.show; if (self.config.animation.enable) { self.getStartMixData(operation); self.setInter(operation); operation.docState = h.getDocumentState(self.dom.document); self.getInterMixData(operation); self.setFinal(operation); self.getFinalMixData(operation); self.parseEffects(); operation.hasEffect = self.hasEffect(); self.getTweenData(operation); } self.targets = operation.show.slice(); operation.newState = self.buildState(operation); // NB: Targets to be removed must be included in `self.targets` for removal during clean up, // but are added after state is built so that state is accurate Array.prototype.push.apply(self.targets, operation.toRemove); operation = self.callFilters('operationMappedGetDataOperation', operation, arguments); return operation; }, /** * @private * @instance * @since 3.0.0 * @param {mixitup.Operation} operation * @return {void} */ diffDatasets: function(operation) { var self = this, persistantStartIds = [], persistantNewIds = [], data = null, target = null, el = null, frag = null, nextEl = null, uids = {}, id = '', i = 0; self.callActions('beforeDiffDatasets', arguments); for (i = 0; data = operation.newDataset[i]; i++) { if (typeof (id = data[self.config.data.uidKey]) === 'undefined' || id.toString().length < 1) { throw new TypeError(mixitup.messages.errorDatasetInvalidUidKey({ uidKey: self.config.data.uidKey })); } if (!uids[id]) { uids[id] = true; } else { throw new Error(mixitup.messages.errorDatasetDuplicateUid({ uid: id })); } if ((target = self.cache[id]) instanceof mixitup.Target) { // Already in cache if (self.config.data.dirtyCheck && !h.deepEquals(data, target.data)) { // change detected el = self.renderTarget(data); target.data = data; self.dom.parent.replaceChild(el, target.dom.el); target.dom.el = el; } el = target.dom.el; } else { // New target el = el = self.renderTarget(data); target = new mixitup.Target(); target.init(el, self, data); } if (!target.isInDom) { // Adding to DOM if (!frag) { // Open frag frag = self.dom.document.createDocumentFragment(); } if (frag.lastElementChild) { frag.appendChild(self.dom.document.createTextNode(' ')); } frag.appendChild(el); target.isInDom = true; operation.toShow.push(target); } else { // Already in DOM nextEl = target.dom.el.nextElementSibling; persistantNewIds.push(id); if (frag) { // Close and insert frag if (frag.lastElementChild) { frag.appendChild(self.dom.document.createTextNode(' ')); } self.dom.parent.insertBefore(frag, target.dom.el); frag = null; } } operation.show.push(target); } if (frag) { // Unclosed frag remaining nextEl = nextEl || self.config.layout.siblingAfter; if (nextEl) { frag.appendChild(self.dom.document.createTextNode(' ')); } self.dom.parent.insertBefore(frag, nextEl); } for (i = 0; data = operation.startDataset[i]; i++) { id = data[self.config.data.uidKey]; target = self.cache[id]; if (operation.show.indexOf(target) < 0) { // Previously shown but now absent operation.hide.push(target); operation.toHide.push(target); operation.toRemove.push(target); } else { persistantStartIds.push(id); } } if (!h.isEqualArray(persistantStartIds, persistantNewIds)) { operation.willSort = true; } self.callActions('afterDiffDatasets', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {object} data * @return {void} */ renderTarget: function(data) { var self = this, render = null, el = null, temp = document.createElement('div'), html = ''; self.callActions('beforeRenderTarget', arguments); if (typeof (render = self.config.render.target) !== 'function') { throw new TypeError(mixitup.messages.errorDatasetRendererNotSet()); } html = render(data); temp.innerHTML = html; el = temp.firstElementChild; return self.callFilters('elRenderTarget', el, arguments); }, /** * @private * @instance * @since 3.0.0 * @param {mixitup.CommandSort} sortCommandA * @param {mixitup.CommandSort} sortCommandB * @return {boolean} */ willSort: function(sortCommandA, sortCommandB) { var self = this, result = false; if ( sortCommandA.order === 'random' || sortCommandA.attribute !== sortCommandB.attribute || sortCommandA.order !== sortCommandB.order || sortCommandA.collection !== sortCommandB.collection || (sortCommandA.next === null && sortCommandB.next) || (sortCommandA.next && sortCommandB.next === null) ) { result = true; } else if (sortCommandA.next && sortCommandB.next) { result = self.willSort(sortCommandA.next, sortCommandB.next); } else { result = false; } return self.callFilters('resultWillSort', result, arguments); }, /** * A shorthand method for `.filter('all')`. Shows all targets in the container. * * @example * * .show() * * @example <caption>Example: Showing all targets</caption> * * mixer.show() * .then(function(state) { * console.log(state.totalShow === state.totalTargets); // true * }); * * @public * @instance * @since 3.0.0 * @return {Promise.<mixitup.State>} */ show: function() { var self = this; return self.filter('all'); }, /** * A shorthand method for `.filter('none')`. Hides all targets in the container. * * @example * * .hide() * * @example <caption>Example: Hiding all targets</caption> * * mixer.hide() * .then(function(state) { * console.log(state.totalShow === 0); // true * console.log(state.totalHide === state.totalTargets); // true * }); * * @public * @instance * @since 3.0.0 * @return {Promise.<mixitup.State>} */ hide: function() { var self = this; return self.filter('none'); }, /** * Returns a boolean indicating whether or not a MixItUp operation is * currently in progress. * * @example * * .isMixing() * * @example <caption>Example: Checking the status of a mixer</caption> * * mixer.sort('random', function() { * console.log(mixer.isMixing()) // false * }); * * console.log(mixer.isMixing()) // true * * @public * @instance * @since 2.0.0 * @return {boolean} */ isMixing: function() { var self = this; return self.isBusy; }, /** * Filters all targets in the container by a provided selector string, or the values `'all'` * or `'none'`. Only targets matching the selector will be shown. * * @example * * .filter(selector [, animate] [, callback]) * * @example <caption>Example 1: Filtering targets by a class selector</caption> * * mixer.filter('.category-a') * .then(function(state) { * console.log(state.totalShow === containerEl.querySelectorAll('.category-a').length); // true * }); * * @example <caption>Example 2: Filtering targets by an attribute selector</caption> * * mixer.filter('[data-category~="a"]') * .then(function(state) { * console.log(state.totalShow === containerEl.querySelectorAll('[data-category~="a"]').length); // true * }); * * @example <caption>Example 3: Filtering targets by a compound selector</caption> * * // Show only those targets with the classes 'category-a' AND 'category-b' * * mixer.filter('.category-a.category-c') * .then(function(state) { * console.log(state.totalShow === containerEl.querySelectorAll('.category-a.category-c').length); // true * }); * * @example <caption>Example 4: Filtering via an element collection</caption> * * var collection = Array.from(container.querySelectorAll('.mix')); * * console.log(collection.length); // 34 * * // Filter the collection manually using Array.prototype.filter * * var filtered = collection.filter(function(target) { * return parseInt(target.getAttribute('data-price')) > 10; * }); * * console.log(filtered.length); // 22 * * // Pass the filtered collection to MixItUp * * mixer.filter(filtered) * .then(function(state) { * console.log(state.activeFilter.collection.length === 22); // true * }); * * @public * @instance * @since 2.0.0 * @param {(string|HTMLElement|Array.<HTMLElement>)} selector * Any valid CSS selector (i.e. `'.category-a'`), or the values `'all'` or `'none'`. The filter method also accepts a reference to single target element or a collection of target elements to show. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ filter: function() { var self = this, instruction = self.parseFilterArgs(arguments); return self.multimix({ filter: instruction.command }, instruction.animate, instruction.callback); }, /** * Adds an additional selector to the currently active filter selector, concatenating * as per the logic defined in `controls.toggleLogic`. * * @example * * .toggleOn(selector [, animate] [, callback]) * * @example <caption>Example: Toggling on a filter selector</caption> * * console.log(mixer.getState().activeFilter.selector); // '.category-a' * * mixer.toggleOn('.category-b') * .then(function(state) { * console.log(state.activeFilter.selector); // '.category-a, .category-b' * }); * * @public * @instance * @since 3.0.0 * @param {string} selector * Any valid CSS selector (i.e. `'.category-a'`) * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ toggleOn: function() { var self = this, instruction = self.parseFilterArgs(arguments), selector = instruction.command.selector, toggleSelector = ''; self.isToggling = true; if (self.toggleArray.indexOf(selector) < 0) { self.toggleArray.push(selector); } toggleSelector = self.getToggleSelector(); return self.multimix({ filter: toggleSelector }, instruction.animate, instruction.callback); }, /** * Removes a selector from the active filter selector. * * @example * * .toggleOff(selector [, animate] [, callback]) * * @example <caption>Example: Toggling off a filter selector</caption> * * console.log(mixer.getState().activeFilter.selector); // '.category-a, .category-b' * * mixer.toggleOff('.category-b') * .then(function(state) { * console.log(state.activeFilter.selector); // '.category-a' * }); * * @public * @instance * @since 3.0.0 * @param {string} selector * Any valid CSS selector (i.e. `'.category-a'`) * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ toggleOff: function() { var self = this, instruction = self.parseFilterArgs(arguments), selector = instruction.command.selector, toggleSelector = ''; self.isToggling = true; self.toggleArray.splice(self.toggleArray.indexOf(selector), 1); toggleSelector = self.getToggleSelector(); return self.multimix({ filter: toggleSelector }, instruction.animate, instruction.callback); }, /** * Sorts all targets in the container according to a provided sort string. * * @example * * .sort(sortString [, animate] [, callback]) * * @example <caption>Example 1: Sorting by the default DOM order</caption> * * // Reverse the default order of the targets * * mixer.sort('default:desc') * .then(function(state) { * console.log(state.activeSort.attribute === 'default'); // true * console.log(state.activeSort.order === 'desc'); // true * }); * * @example <caption>Example 2: Sorting by a custom data-attribute</caption> * * // Sort the targets by the value of a `data-published-date` attribute * * mixer.sort('published-date:asc') * .then(function(state) { * console.log(state.activeSort.attribute === 'published-date'); // true * console.log(state.activeSort.order === 'asc'); // true * }); * * @example <caption>Example 3: Sorting by multiple attributes</caption> * * // Sort the targets by the value of a `data-published-date` attribute, then by `data-title` * * mixer.sort('published-date:desc data-title:asc') * .then(function(state) { * console.log(state.activeSort.attribute === 'published-date'); // true * console.log(state.activeSort.order === 'desc'); // true * * console.log(state.activeSort.next.attribute === 'title'); // true * console.log(state.activeSort.next.order === 'asc'); // true * }); * * @example <caption>Example 4: Sorting by random</caption> * * mixer.sort('random') * .then(function(state) { * console.log(state.activeSort.order === 'random') // true * }); * * @example <caption>Example 5: Sorting via an element collection</caption> * * var collection = Array.from(container.querySelectorAll('.mix')); * * // Swap the position of two elements in the collection: * * var temp = collection[1]; * * collection[1] = collection[0]; * collection[0] = temp; * * // Pass the sorted collection to MixItUp * * mixer.sort(collection) * .then(function(state) { * console.log(state.targets[0] === collection[0]); // true * }); * * @public * @instance * @since 2.0.0 * @param {(string|Array.<HTMLElement>)} sortString * A valid sort string (e.g. `'default'`, `'published-date:asc'`, or `'random'`). The sort method also accepts an array of all target elements in a user-defined order. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ sort: function() { var self = this, instruction = self.parseSortArgs(arguments); return self.multimix({ sort: instruction.command }, instruction.animate, instruction.callback); }, /** * Changes the layout of the container by adding, removing or updating a * layout-specific class name. If `animation.animateResizetargets` is * enabled, MixItUp will attempt to gracefully animate the width, height, * and position of targets between layout states. * * @example * * .changeLayout(containerClassName [, animate] [, callback]) * * @example <caption>Example 1: Adding a new class name to the container</caption> * * mixer.changeLayout('container-list') * .then(function(state) { * console.log(state.activeContainerClass === 'container-list'); // true * }); * * @example <caption>Example 2: Removing a previously added class name from the container</caption> * * mixer.changeLayout('') * .then(function(state) { * console.log(state.activeContainerClass === ''); // true * }); * * @public * @instance * @since 2.0.0 * @param {string} containerClassName * A layout-specific class name to add to the container. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ changeLayout: function() { var self = this, instruction = self.parseChangeLayoutArgs(arguments); return self.multimix({ changeLayout: instruction.command }, instruction.animate, instruction.callback); }, /** * Updates the contents and order of the container to reflect the provided dataset, * if the dataset API is in use. * * The dataset API is designed for use in API-driven JavaScript applications, and * can be used instead of DOM-based methods such as `.filter()`, `.sort()`, * `.insert()`, etc. When used, insertion, removal, sorting and pagination can be * achieved purely via changes to your data model, without the uglyness of having * to interact with or query the DOM directly. * * @example * * .dataset(dataset [, animate] [, callback]) * * @example <caption>Example 1: Rendering a dataset</caption> * * var myDataset = [ * {id: 1, ...}, * {id: 2, ...}, * {id: 3, ...} * ]; * * mixer.dataset(myDataset) * .then(function(state) { * console.log(state.totalShow === 3); // true * }); * * @example <caption>Example 2: Sorting a dataset</caption> * * // Create a new dataset in reverse order * * var newDataset = myDataset.slice().reverse(); * * mixer.dataset(newDataset) * .then(function(state) { * console.log(state.activeDataset[0] === myDataset[2]); // true * }); * * @example <caption>Example 3: Removing an item from the dataset</caption> * * console.log(myDataset.length); // 3 * * // Create a new dataset with the last item removed. * * var newDataset = myDataset.slice().pop(); * * mixer.dataset(newDataset) * .then(function(state) { * console.log(state.totalShow === 2); // true * }); * * @public * @instance * @since 3.0.0 * @param {Array.<object>} dataset * An array of objects, each one representing the underlying data model of a target to be rendered. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ dataset: function() { var self = this, instruction = self.parseDatasetArgs(arguments), operation = self.getDataOperation(instruction.command.dataset), queueItem = null, animate = false; self.callActions('beforeDataset', arguments); if (!self.isBusy) { if (instruction.callback) self.userCallback = instruction.callback; animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; return self.queueMix(queueItem); } }, /** * Performs simultaneous `filter`, `sort`, `insert`, `remove` and `changeLayout` * operations as requested. * * @example * * .multimix(multimixCommand [, animate] [, callback]) * * @example <caption>Example 1: Performing simultaneous filtering and sorting</caption> * * mixer.multimix({ * filter: '.category-b', * sort: 'published-date:desc' * }) * .then(function(state) { * console.log(state.activeFilter.selector === '.category-b'); // true * console.log(state.activeSort.attribute === 'published-date'); // true * }); * * @example <caption>Example 2: Performing simultaneous sorting, insertion, and removal</caption> * * console.log(mixer.getState().totalShow); // 6 * * // NB: When inserting via `multimix()`, an object should be provided as the value * // for the `insert` portion of the command, allowing for a collection of elements * // and an insertion index to be specified. * * mixer.multimix({ * sort: 'published-date:desc', // Sort the container, including any new elements * insert: { * collection: [newElementReferenceA, newElementReferenceB], // Add 2 new elements at index 5 * index: 5 * }, * remove: existingElementReference // Remove 1 existing element * }) * .then(function(state) { * console.log(state.activeSort.attribute === 'published-date'); // true * console.log(state.totalShow === 7); // true * }); * * @public * @instance * @since 2.0.0 * @param {object} multimixCommand * An object containing one or more things to do * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ multimix: function() { var self = this, operation = null, animate = false, queueItem = null, instruction = self.parseMultimixArgs(arguments); self.callActions('beforeMultimix', arguments); if (!self.isBusy) { operation = self.getOperation(instruction.command); if (self.config.controls.enable) { // Update controls for API calls if (instruction.command.filter && !self.isToggling) { // As we are not toggling, reset the toggle array // so new filter overrides existing toggles self.toggleArray.length = 0; self.buildToggleArray(operation.command); } if (self.queue.length < 1) { self.updateControls(operation.command); } } if (instruction.callback) self.userCallback = instruction.callback; // Always allow the instruction to override the instance setting animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; self.callFilters('operationMultimix', operation, arguments); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; queueItem.triggerElement = self.lastClicked; queueItem.isToggling = self.isToggling; return self.queueMix(queueItem); } }, /** * @private * @instance * @since 3.0.0 * @param {object} multimixCommand * @param {boolean} [isPreFetch] * An optional boolean indicating that the operation is being pre-fetched for execution at a later time. * @return {Operation|null} */ getOperation: function(multimixCommand) { var self = this, sortCommand = multimixCommand.sort, filterCommand = multimixCommand.filter, changeLayoutCommand = multimixCommand.changeLayout, removeCommand = multimixCommand.remove, insertCommand = multimixCommand.insert, operation = new mixitup.Operation(); operation = self.callFilters('operationUnmappedGetOperation', operation, arguments); operation.id = h.randomHex(); operation.command = multimixCommand; operation.startState = self.state; operation.triggerElement = self.lastClicked; if (self.isBusy) { if (self.config.debug.showWarnings) { console.warn(mixitup.messages.warningGetOperationInstanceBusy()); } return null; } if (insertCommand) { self.insertTargets(insertCommand, operation); } if (removeCommand) { operation.toRemove = removeCommand.targets; } operation.startSort = operation.newSort = operation.startState.activeSort; operation.startOrder = operation.newOrder = self.targets; if (sortCommand) { operation.startSort = operation.startState.activeSort; operation.newSort = sortCommand; operation.willSort = self.willSort(sortCommand, operation.startState.activeSort); if (operation.willSort) { self.sortOperation(operation); } } operation.startFilter = operation.startState.activeFilter; if (filterCommand) { operation.newFilter = filterCommand; } else { operation.newFilter = h.extend(new mixitup.CommandFilter(), operation.startFilter); } if (operation.newFilter.selector === 'all') { operation.newFilter.selector = self.config.selectors.target; } else if (operation.newFilter.selector === 'none') { operation.newFilter.selector = ''; } self.filterOperation(operation); if (changeLayoutCommand) { operation.startContainerClassName = operation.startState.activeContainerClassName; operation.newContainerClassName = changeLayoutCommand.containerClassName; if (operation.newContainerClassName !== operation.startContainerClassName) { operation.willChangeLayout = true; } } if (self.config.animation.enable) { // Populate the operation's position data self.getStartMixData(operation); self.setInter(operation); operation.docState = h.getDocumentState(self.dom.document); self.getInterMixData(operation); self.setFinal(operation); self.getFinalMixData(operation); self.parseEffects(); operation.hasEffect = self.hasEffect(); self.getTweenData(operation); } operation.newState = self.buildState(operation); return self.callFilters('operationMappedGetOperation', operation, arguments); }, /** * Renders a previously created operation at a specific point in its path, as * determined by a multiplier between 0 and 1. * * @example * .tween(operation, multiplier) * * @private * @instance * @since 3.0.0 * @param {mixitup.Operation} operation * An operation object created via the `getOperation` method * * @param {Float} multiplier * Any number between 0 and 1 representing the percentage complete of the operation * @return {void} */ tween: function(operation, multiplier) { var target = null, posData = null, toHideIndex = -1, i = -1; multiplier = Math.min(multiplier, 1); multiplier = Math.max(multiplier, 0); for (i = 0; target = operation.show[i]; i++) { posData = operation.showPosData[i]; target.applyTween(posData, multiplier); } for (i = 0; target = operation.hide[i]; i++) { if (target.isShown) { target.hide(); } if ((toHideIndex = operation.toHide.indexOf(target)) > -1) { posData = operation.toHidePosData[toHideIndex]; if (!target.isShown) { target.show(); } target.applyTween(posData, multiplier); } } }, /** * Inserts one or more new target elements into the container at a specified * index. * * To be indexed as targets, new elements must match the `selectors.target` * selector (`'.mix'` by default). * * @example * * .insert(newElements [, index] [, animate], [, callback]) * * @example <caption>Example 1: Inserting a single element via reference</caption> * * console.log(mixer.getState().totalShow); // 0 * * // Create a new element * * var newElement = document.createElement('div'); * newElement.classList.add('mix'); * * mixer.insert(newElement) * .then(function(state) { * console.log(state.totalShow === 1); // true * }); * * @example <caption>Example 2: Inserting a single element via HTML string</caption> * * console.log(mixer.getState().totalShow); // 1 * * // Create a new element via reference * * var newElementHtml = '&lt;div class="mix"&gt;&lt;/div&gt;'; * * // Create and insert the new element at index 1 * * mixer.insert(newElementHtml, 1) * .then(function(state) { * console.log(state.totalShow === 2); // true * console.log(state.show[1].outerHTML === newElementHtml); // true * }); * * @example <caption>Example 3: Inserting multiple elements via reference</caption> * * console.log(mixer.getState().totalShow); // 2 * * // Create an array of new elements to insert. * * var newElement1 = document.createElement('div'); * var newElement2 = document.createElement('div'); * * newElement1.classList.add('mix'); * newElement2.classList.add('mix'); * * var newElementsCollection = [newElement1, newElement2]; * * // Insert the new elements starting at index 1 * * mixer.insert(newElementsCollection, 1) * .then(function(state) { * console.log(state.totalShow === 4); // true * console.log(state.show[1] === newElement1); // true * console.log(state.show[2] === newElement2); // true * }); * * @example <caption>Example 4: Inserting a jQuery collection object containing one or more elements</caption> * * console.log(mixer.getState().totalShow); // 4 * * var $newElement = $('&lt;div class="mix"&gt;&lt;/div&gt;'); * * // Insert the new elements starting at index 3 * * mixer.insert(newElementsCollection, 3) * .then(function(state) { * console.log(state.totalShow === 5); // true * console.log(state.show[3] === $newElement[0]); // true * }); * * @public * @instance * @since 2.0.0 * @param {(HTMLElement|Array.<HTMLElement>|string)} newElements * A reference to a single element to insert, an array-like collection of elements, or an HTML string representing a single element. * @param {number} index=0 * The index at which to insert the new element(s). `0` by default. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ insert: function() { var self = this, args = self.parseInsertArgs(arguments); return self.multimix({ insert: args.command }, args.animate, args.callback); }, /** * Inserts one or more new elements before a provided reference element. * * @example * * .insertBefore(newElements, referenceElement [, animate] [, callback]) * * @example <caption>Example: Inserting a new element before a reference element</caption> * * // An existing reference element is chosen at index 2 * * var referenceElement = mixer.getState().show[2]; * * // Create a new element * * var newElement = document.createElement('div'); * newElement.classList.add('mix'); * * mixer.insertBefore(newElement, referenceElement) * .then(function(state) { * // The new element is inserted into the container at index 2, before the reference element * * console.log(state.show[2] === newElement); // true * * // The reference element is now at index 3 * * console.log(state.show[3] === referenceElement); // true * }); * * @public * @instance * @since 3.0.0 * @param {(HTMLElement|Array.<HTMLElement>|string)} newElements * A reference to a single element to insert, an array-like collection of elements, or an HTML string representing a single element. * @param {HTMLElement} referenceElement * A reference to an existing element in the container to insert new elements before. *@param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ insertBefore: function() { var self = this, args = self.parseInsertArgs(arguments); return self.insert(args.command.collection, 'before', args.command.sibling, args.animate, args.callback); }, /** * Inserts one or more new elements after a provided reference element. * * @example * * .insertAfter(newElements, referenceElement [, animate] [, callback]) * * @example <caption>Example: Inserting a new element after a reference element</caption> * * // An existing reference element is chosen at index 2 * * var referenceElement = mixer.getState().show[2]; * * // Create a new element * * var newElement = document.createElement('div'); * newElement.classList.add('mix'); * * mixer.insertAfter(newElement, referenceElement) * .then(function(state) { * // The new element is inserted into the container at index 3, after the reference element * * console.log(state.show[3] === newElement); // true * }); * * @public * @instance * @since 3.0.0 * @param {(HTMLElement|Array.<HTMLElement>|string)} newElements * A reference to a single element to insert, an array-like collection of elements, or an HTML string representing a single element. * @param {HTMLElement} referenceElement * A reference to an existing element in the container to insert new elements after. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ insertAfter: function() { var self = this, args = self.parseInsertArgs(arguments); return self.insert(args.command.collection, 'after', args.command.sibling, args.animate, args.callback); }, /** * Inserts one or more new elements into the container before all existing targets. * * @example * * .prepend(newElements [,animate] [,callback]) * * @example <caption>Example: Prepending a new element</caption> * * // Create a new element * * var newElement = document.createElement('div'); * newElement.classList.add('mix'); * * // Insert the element into the container * * mixer.prepend(newElement) * .then(function(state) { * console.log(state.show[0] === newElement); // true * }); * * @public * @instance * @since 3.0.0 * @param {(HTMLElement|Array.<HTMLElement>|string)} newElements * A reference to a single element to insert, an array-like collection of elements, or an HTML string representing a single element. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ prepend: function() { var self = this, args = self.parseInsertArgs(arguments); return self.insert(0, args.command.collection, args.animate, args.callback); }, /** * Inserts one or more new elements into the container after all existing targets. * * @example * * .append(newElements [,animate] [,callback]) * * @example <caption>Example: Appending a new element</caption> * * // Create a new element * * var newElement = document.createElement('div'); * newElement.classList.add('mix'); * * // Insert the element into the container * * mixer.append(newElement) * .then(function(state) { * console.log(state.show[state.show.length - 1] === newElement); // true * }); * * @public * @instance * @since 3.0.0 * @param {(HTMLElement|Array.<HTMLElement>|string)} newElements * A reference to a single element to insert, an array-like collection of elements, or an HTML string representing a single element. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ append: function() { var self = this, args = self.parseInsertArgs(arguments); return self.insert(self.state.totalTargets, args.command.collection, args.animate, args.callback); }, /** * Removes one or more existing target elements from the container. * * @example * * .remove(elements [, animate] [, callback]) * * @example <caption>Example 1: Removing an element by reference</caption> * * var elementToRemove = containerEl.firstElementChild; * * mixer.remove(elementToRemove) * .then(function(state) { * console.log(state.targets.indexOf(elementToRemove) === -1); // true * }); * * @example <caption>Example 2: Removing a collection of elements by reference</caption> * * var elementsToRemove = containerEl.querySelectorAll('.category-a'); * * console.log(elementsToRemove.length) // 3 * * mixer.remove(elementsToRemove) * .then(function() { * console.log(containerEl.querySelectorAll('.category-a').length); // 0 * }); * * @example <caption>Example 3: Removing one or more elements by selector</caption> * * mixer.remove('.category-a') * .then(function() { * console.log(containerEl.querySelectorAll('.category-a').length); // 0 * }); * * @example <caption>Example 4: Removing an element by index</caption> * * console.log(mixer.getState.totalShow); // 4 * * // Remove the element at index 3 * * mixer.remove(3) * .then(function(state) { * console.log(state.totalShow); // 3 * console.log(state.show[3]); // undefined * }); * * * @public * @instance * @since 3.0.0 * @param {(HTMLElement|Array.<HTMLElement>|string|number)} elements * A reference to a single element to remove, an array-like collection of elements, a selector string, or the index of an element to remove. * @param {boolean} [animate=true] * An optional boolean dictating whether the operation should animate, or occur syncronously with no animation. `true` by default. * @param {function} [callback=null] * An optional callback function to be invoked after the operation has completed. * @return {Promise.<mixitup.State>} * A promise resolving with the current state object. */ remove: function() { var self = this, args = self.parseRemoveArgs(arguments); return self.multimix({ remove: args.command }, args.animate, args.callback); }, /** * Retrieves the the value of any property or sub-object within the current * mixitup configuration, or the whole configuration object. * * @example * * .getConfig([stringKey]) * * @example <caption>Example 1: retrieve the entire configuration object</caption> * * var config = mixer.getConfig(); // Config { ... } * * @example <caption>Example 2: retrieve a named sub-object of configuration object</caption> * * var animation = mixer.getConfig('animation'); // ConfigAnimation { ... } * * @example <caption>Example 3: retrieve a value of configuration object via a dot-notation string key</caption> * * var effects = mixer.getConfig('animation.effects'); // 'fade scale' * * @public * @instance * @since 2.0.0 * @param {string} [stringKey] A "dot-notation" string key * @return {*} */ getConfig: function(stringKey) { var self = this, value = null; if (!stringKey) { value = self.config; } else { value = h.getProperty(self.config, stringKey); } return self.callFilters('valueGetConfig', value, arguments); }, /** * Updates the configuration of the mixer, after it has been instantiated. * * See the Configuration Object documentation for a full list of avilable * configuration options. * * @example * * .configure(config) * * @example <caption>Example 1: Updating animation options</caption> * * mixer.configure({ * animation: { * effects: 'fade translateX(-100%)', * duration: 300 * } * }); * * @example <caption>Example 2: Removing a callback after it has been set</caption> * * var mixer; * * function handleMixEndOnce() { * // Do something .. * * // Then nullify the callback * * mixer.configure({ * callbacks: { * onMixEnd: null * } * }); * }; * * // Instantiate a mixer with a callback defined * * mixer = mixitup(containerEl, { * callbacks: { * onMixEnd: handleMixEndOnce * } * }); * * @public * @instance * @since 3.0.0 * @param {object} config * An object containing one of more configuration options. * @return {void} */ configure: function(config) { var self = this; self.callActions('beforeConfigure', arguments); h.extend(self.config, config, true, true); self.callActions('afterConfigure', arguments); }, /** * Returns an object containing information about the current state of the * mixer. See the State Object documentation for more information. * * NB: State objects are immutable and should therefore be regenerated * after any operation. * * @example * * .getState(); * * @example <caption>Example: Retrieving a state object</caption> * * var state = mixer.getState(); * * console.log(state.totalShow + 'targets are currently shown'); * * @public * @instance * @since 2.0.0 * @return {mixitup.State} An object reflecting the current state of the mixer. */ getState: function() { var self = this, state = null; state = new mixitup.State(); h.extend(state, self.state); h.freeze(state); return self.callFilters('stateGetState', state, arguments); }, /** * Forces the re-indexing all targets within the container. * * This should only be used if some other piece of code in your application * has manipulated the contents of your container, which should be avoided. * * If you need to add or remove target elements from the container, use * the built-in `.insert()` or `.remove()` methods, and MixItUp will keep * itself up to date. * * @example * * .forceRefresh() * * @example <caption>Example: Force refreshing the mixer after external DOM manipulation</caption> * * console.log(mixer.getState().totalShow); // 3 * * // An element is removed from the container via some external DOM manipulation code: * * containerEl.removeChild(containerEl.firstElementChild); * * // The mixer does not know that the number of targets has changed: * * console.log(mixer.getState().totalShow); // 3 * * mixer.forceRefresh(); * * // After forceRefresh, the mixer is in sync again: * * console.log(mixer.getState().totalShow); // 2 * * @public * @instance * @since 2.1.2 * @return {void} */ forceRefresh: function() { var self = this; self.indexTargets(); }, /** * Removes mixitup functionality from the container, unbinds all control * event handlers, and deletes the mixer instance from MixItUp's internal * cache. * * This should be performed whenever a mixer's container is removed from * the DOM, such as during a page change in a single page application, * or React's `componentWillUnmount()`. * * @example * * .destroy([cleanUp]) * * @example <caption>Example: Destroying the mixer before removing its container element</caption> * * mixer.destroy(); * * containerEl.parentElement.removeChild(containerEl); * * @public * @instance * @since 2.0.0 * @param {boolean} [cleanUp=false] * An optional boolean dictating whether or not to clean up any inline `display: none;` styling applied to hidden targets. * @return {void} */ destroy: function(cleanUp) { var self = this, control = null, target = null, i = 0; self.callActions('beforeDestroy', arguments); for (i = 0; control = self.controls[i]; i++) { control.removeBinding(self); } for (i = 0; target = self.targets[i]; i++) { if (cleanUp) { target.show(); } target.unbindEvents(); } if (self.dom.container.id.match(/^MixItUp/)) { self.dom.container.removeAttribute('id'); } delete mixitup.instances[self.id]; self.callActions('afterDestroy', arguments); } }); /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.IMoveData = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.posIn = null; this.posOut = null; this.operation = null; this.callback = null; this.statusChange = ''; this.duration = -1; this.staggerIndex = -1; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.IMoveData); mixitup.IMoveData.prototype = Object.create(mixitup.Base.prototype); mixitup.IMoveData.prototype.constructor = mixitup.IMoveData; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.TargetDom = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.el = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.TargetDom); mixitup.TargetDom.prototype = Object.create(mixitup.Base.prototype); mixitup.TargetDom.prototype.constructor = mixitup.TargetDom; /** * @constructor * @namespace * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Target = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.id = ''; this.sortString = ''; this.mixer = null; this.callback = null; this.isShown = false; this.isBound = false; this.isExcluded = false; this.isInDom = false; this.handler = null; this.operation = null; this.data = null; this.dom = new mixitup.TargetDom(); this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Target); mixitup.Target.prototype = Object.create(mixitup.Base.prototype); h.extend(mixitup.Target.prototype, { constructor: mixitup.Target, /** * Initialises a newly instantiated Target. * * @private * @instance * @since 3.0.0 * @param {Element} el * @param {object} mixer * @param {object} [data] * @return {void} */ init: function(el, mixer, data) { var self = this, id = ''; self.callActions('beforeInit', arguments); self.mixer = mixer; self.cacheDom(el); self.bindEvents(); if (self.dom.el.style.display !== 'none') { self.isShown = true; } if (data && mixer.config.data.uidKey) { if (typeof (id = data[mixer.config.data.uidKey]) === 'undefined' || id.toString().length < 1) { throw new TypeError(mixitup.messages.errorDatasetInvalidUidKey({ uidKey: mixer.config.data.uidKey })); } self.id = id; self.data = data; mixer.cache[id] = self; } self.callActions('afterInit', arguments); }, /** * Caches references of DOM elements neccessary for the target's functionality. * * @private * @instance * @since 3.0.0 * @param {Element} el * @return {void} */ cacheDom: function(el) { var self = this; self.callActions('beforeCacheDom', arguments); self.dom.el = el; self.callActions('beforeCacheDom', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {string} attributeName * @return {void} */ getSortString: function(attributeName) { var self = this, value = self.dom.el.getAttribute('data-' + attributeName) || ''; self.callActions('beforeGetSortString', arguments); value = isNaN(value * 1) ? value.toLowerCase() : value * 1; self.sortString = value; self.callActions('afterGetSortString', arguments); }, /** * @private * @instance * @since 3.0.0 * @return {void} */ show: function() { var self = this; self.callActions('beforeShow', arguments); if (!self.isShown) { self.dom.el.style.display = ''; self.isShown = true; } self.callActions('afterShow', arguments); }, /** * @private * @instance * @since 3.0.0 * @return {void} */ hide: function() { var self = this; self.callActions('beforeHide', arguments); if (self.isShown) { self.dom.el.style.display = 'none'; self.isShown = false; } self.callActions('afterHide', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {mixitup.IMoveData} moveData * @return {void} */ move: function(moveData) { var self = this; self.callActions('beforeMove', arguments); if (!self.isExcluded) { self.mixer.targetsMoved++; } self.applyStylesIn(moveData); requestAnimationFrame(function() { self.applyStylesOut(moveData); }); self.callActions('afterMove', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {object} posData * @param {number} multiplier * @return {void} */ applyTween: function(posData, multiplier) { var self = this, propertyName = '', tweenData = null, posIn = posData.posIn, currentTransformValues = [], currentValues = new mixitup.StyleData(), i = -1; self.callActions('beforeApplyTween', arguments); currentValues.x = posIn.x; currentValues.y = posIn.y; if (multiplier === 0) { self.hide(); } else if (!self.isShown) { self.show(); } for (i = 0; propertyName = mixitup.features.TWEENABLE[i]; i++) { tweenData = posData.tweenData[propertyName]; if (propertyName === 'x') { if (!tweenData) continue; currentValues.x = posIn.x + (tweenData * multiplier); } else if (propertyName === 'y') { if (!tweenData) continue; currentValues.y = posIn.y + (tweenData * multiplier); } else if (tweenData instanceof mixitup.TransformData) { if (!tweenData.value) continue; currentValues[propertyName].value = posIn[propertyName].value + (tweenData.value * multiplier); currentValues[propertyName].unit = tweenData.unit; currentTransformValues.push( propertyName + '(' + currentValues[propertyName].value + tweenData.unit + ')' ); } else { if (!tweenData) continue; currentValues[propertyName] = posIn[propertyName] + (tweenData * multiplier); self.dom.el.style[propertyName] = currentValues[propertyName]; } } if (currentValues.x || currentValues.y) { currentTransformValues.unshift('translate(' + currentValues.x + 'px, ' + currentValues.y + 'px)'); } if (currentTransformValues.length) { self.dom.el.style[mixitup.features.transformProp] = currentTransformValues.join(' '); } self.callActions('afterApplyTween', arguments); }, /** * Applies the initial styling to a target element before any transition * is applied. * * @private * @instance * @param {mixitup.IMoveData} moveData * @return {void} */ applyStylesIn: function(moveData) { var self = this, posIn = moveData.posIn, isFading = self.mixer.effectsIn.opacity !== 1, transformValues = []; self.callActions('beforeApplyStylesIn', arguments); transformValues.push('translate(' + posIn.x + 'px, ' + posIn.y + 'px)'); if (self.mixer.config.animation.animateResizeTargets) { if (moveData.statusChange !== 'show') { // Don't apply posIn width or height or showing, as will be 0 self.dom.el.style.width = posIn.width + 'px'; self.dom.el.style.height = posIn.height + 'px'; } self.dom.el.style.marginRight = posIn.marginRight + 'px'; self.dom.el.style.marginBottom = posIn.marginBottom + 'px'; } isFading && (self.dom.el.style.opacity = posIn.opacity); if (moveData.statusChange === 'show') { transformValues = transformValues.concat(self.mixer.transformIn); } self.dom.el.style[mixitup.features.transformProp] = transformValues.join(' '); self.callActions('afterApplyStylesIn', arguments); }, /** * Applies a transition followed by the final styles for the element to * transition towards. * * @private * @instance * @param {mixitup.IMoveData} moveData * @return {void} */ applyStylesOut: function(moveData) { var self = this, transitionRules = [], transformValues = [], isResizing = self.mixer.config.animation.animateResizeTargets, isFading = typeof self.mixer.effectsIn.opacity !== 'undefined'; self.callActions('beforeApplyStylesOut', arguments); // Build the transition rules transitionRules.push(self.writeTransitionRule( mixitup.features.transformRule, moveData.staggerIndex )); if (moveData.statusChange !== 'none') { transitionRules.push(self.writeTransitionRule( 'opacity', moveData.staggerIndex, moveData.duration )); } if (isResizing) { transitionRules.push(self.writeTransitionRule( 'width', moveData.staggerIndex, moveData.duration )); transitionRules.push(self.writeTransitionRule( 'height', moveData.staggerIndex, moveData.duration )); transitionRules.push(self.writeTransitionRule( 'margin', moveData.staggerIndex, moveData.duration )); } // If no callback was provided, the element will // not transition in any way so tag it as "immovable" if (!moveData.callback) { self.mixer.targetsImmovable++; if (self.mixer.targetsMoved === self.mixer.targetsImmovable) { // If the total targets moved is equal to the // number of immovable targets, the operation // should be considered finished self.mixer.cleanUp(moveData.operation); } return; } // If the target will transition in some fasion, // assign a callback function self.operation = moveData.operation; self.callback = moveData.callback; // As long as the target is not excluded, increment // the total number of targets bound !self.isExcluded && self.mixer.targetsBound++; // Tag the target as bound to differentiate from transitionEnd // events that may come from stylesheet driven effects self.isBound = true; // Apply the transition self.applyTransition(transitionRules); // Apply width, height and margin negation if (isResizing && moveData.posOut.width > 0 && moveData.posOut.height > 0) { self.dom.el.style.width = moveData.posOut.width + 'px'; self.dom.el.style.height = moveData.posOut.height + 'px'; self.dom.el.style.marginRight = moveData.posOut.marginRight + 'px'; self.dom.el.style.marginBottom = moveData.posOut.marginBottom + 'px'; } if (!self.mixer.config.animation.nudge && moveData.statusChange === 'hide') { // If we're not nudging, the translation should be // applied before any other transforms to prevent // lateral movement transformValues.push('translate(' + moveData.posOut.x + 'px, ' + moveData.posOut.y + 'px)'); } // Apply fade switch (moveData.statusChange) { case 'hide': isFading && (self.dom.el.style.opacity = self.mixer.effectsOut.opacity); transformValues = transformValues.concat(self.mixer.transformOut); break; case 'show': isFading && (self.dom.el.style.opacity = 1); } if ( self.mixer.config.animation.nudge || (!self.mixer.config.animation.nudge && moveData.statusChange !== 'hide') ) { // Opposite of above - apply translate after // other transform transformValues.push('translate(' + moveData.posOut.x + 'px, ' + moveData.posOut.y + 'px)'); } // Apply transforms self.dom.el.style[mixitup.features.transformProp] = transformValues.join(' '); self.callActions('afterApplyStylesOut', arguments); }, /** * Combines the name of a CSS property with the appropriate duration and delay * values to created a valid transition rule. * * @private * @instance * @since 3.0.0 * @param {string} property * @param {number} staggerIndex * @param {number} duration * @return {string} */ writeTransitionRule: function(property, staggerIndex, duration) { var self = this, delay = self.getDelay(staggerIndex), rule = ''; rule = property + ' ' + (duration > 0 ? duration : self.mixer.config.animation.duration) + 'ms ' + delay + 'ms ' + (property === 'opacity' ? 'linear' : self.mixer.config.animation.easing); return self.callFilters('ruleWriteTransitionRule', rule, arguments); }, /** * Calculates the transition delay for each target element based on its index, if * staggering is applied. If defined, A custom `animation.staggerSeqeuence` * function can be used to manipulate the order of indices to produce custom * stagger effects (e.g. for use in a grid with irregular row lengths). * * @private * @instance * @since 2.0.0 * @param {number} index * @return {number} */ getDelay: function(index) { var self = this, delay = -1; if (typeof self.mixer.config.animation.staggerSequence === 'function') { index = self.mixer.config.animation.staggerSequence.call(self, index, self.state); } delay = !!self.mixer.staggerDuration ? index * self.mixer.staggerDuration : 0; return self.callFilters('delayGetDelay', delay, arguments); }, /** * @private * @instance * @since 3.0.0 * @param {string[]} rules * @return {void} */ applyTransition: function(rules) { var self = this, transitionString = rules.join(', '); self.callActions('beforeApplyTransition', arguments); self.dom.el.style[mixitup.features.transitionProp] = transitionString; self.callActions('afterApplyTransition', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {Event} e * @return {void} */ handleTransitionEnd: function(e) { var self = this, propName = e.propertyName, canResize = self.mixer.config.animation.animateResizeTargets; self.callActions('beforeHandleTransitionEnd', arguments); if ( self.isBound && e.target.matches(self.mixer.config.selectors.target) && ( propName.indexOf('transform') > -1 || propName.indexOf('opacity') > -1 || canResize && propName.indexOf('height') > -1 || canResize && propName.indexOf('width') > -1 || canResize && propName.indexOf('margin') > -1 ) ) { self.callback.call(self, self.operation); self.isBound = false; self.callback = null; self.operation = null; } self.callActions('afterHandleTransitionEnd', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {Event} e * @return {void} */ eventBus: function(e) { var self = this; self.callActions('beforeEventBus', arguments); switch (e.type) { case 'webkitTransitionEnd': case 'transitionend': self.handleTransitionEnd(e); } self.callActions('afterEventBus', arguments); }, /** * @private * @instance * @since 3.0.0 * @return {void} */ unbindEvents: function() { var self = this; self.callActions('beforeUnbindEvents', arguments); h.off(self.dom.el, 'webkitTransitionEnd', self.handler); h.off(self.dom.el, 'transitionend', self.handler); self.callActions('afterUnbindEvents', arguments); }, /** * @private * @instance * @since 3.0.0 * @return {void} */ bindEvents: function() { var self = this, transitionEndEvent = ''; self.callActions('beforeBindEvents', arguments); transitionEndEvent = mixitup.features.transitionPrefix === 'webkit' ? 'webkitTransitionEnd' : 'transitionend'; self.handler = function(e) { return self.eventBus(e); }; h.on(self.dom.el, transitionEndEvent, self.handler); self.callActions('afterBindEvents', arguments); }, /** * @private * @instance * @since 3.0.0 * @param {boolean} [getBox] * @return {PosData} */ getPosData: function(getBox) { var self = this, styles = {}, rect = null, posData = new mixitup.StyleData(); self.callActions('beforeGetPosData', arguments); posData.x = self.dom.el.offsetLeft; posData.y = self.dom.el.offsetTop; if (self.mixer.config.animation.animateResizeTargets || getBox) { rect = self.dom.el.getBoundingClientRect(); posData.top = rect.top; posData.right = rect.right; posData.bottom = rect.bottom; posData.left = rect.left; posData.width = rect.width; posData.height = rect.height; } if (self.mixer.config.animation.animateResizeTargets) { styles = window.getComputedStyle(self.dom.el); posData.marginBottom = parseFloat(styles.marginBottom); posData.marginRight = parseFloat(styles.marginRight); } return self.callFilters('posDataGetPosData', posData, arguments); }, /** * @private * @instance * @since 3.0.0 * @return {void} */ cleanUp: function() { var self = this; self.callActions('beforeCleanUp', arguments); self.dom.el.style[mixitup.features.transformProp] = ''; self.dom.el.style[mixitup.features.transitionProp] = ''; self.dom.el.style.opacity = ''; if (self.mixer.config.animation.animateResizeTargets) { self.dom.el.style.width = ''; self.dom.el.style.height = ''; self.dom.el.style.marginRight = ''; self.dom.el.style.marginBottom = ''; } self.callActions('afterCleanUp', arguments); } }); /** * A jQuery-collection-like wrapper around one or more `mixitup.Mixer` instances * allowing simultaneous control of said instances similar to the MixItUp 2 API. * * @example * new mixitup.Collection(instances) * * @constructor * @namespace * @memberof mixitup * @private * @since 3.0.0 * @param {mixitup.Mixer[]} instances */ mixitup.Collection = function(instances) { var instance = null, i = -1; this.callActions('beforeConstruct'); for (i = 0; instance = instances[i]; i++) { this[i] = instance; } this.length = instances.length; this.callActions('afterConstruct'); h.freeze(this); }; mixitup.BaseStatic.call(mixitup.Collection); mixitup.Collection.prototype = Object.create(mixitup.Base.prototype); h.extend(mixitup.Collection.prototype, /** @lends mixitup.Collection */ { constructor: mixitup.Collection, /** * Calls a method on all instances in the collection by passing the method * name as a string followed by any applicable parameters to be curried into * to the method. * * @example * .mixitup(methodName[,arg1][,arg2..]); * * @example * var collection = new Collection([mixer1, mixer2]); * * return collection.mixitup('filter', '.category-a') * .then(function(states) { * state.forEach(function(state) { * console.log(state.activeFilter.selector); // .category-a * }); * }); * * @public * @instance * @since 3.0.0 * @param {string} methodName * @return {Promise<Array<mixitup.State>>} */ mixitup: function(methodName) { var self = this, instance = null, args = Array.prototype.slice.call(arguments), tasks = [], i = -1; this.callActions('beforeMixitup'); args.shift(); for (i = 0; instance = self[i]; i++) { tasks.push(instance[methodName].apply(instance, args)); } return self.callFilters('promiseMixitup', h.all(tasks, mixitup.libraries), arguments); } }); /** * `mixitup.Operation` objects contain all data neccessary to describe the full * lifecycle of any MixItUp operation. They can be used to compute and store an * operation for use at a later time (e.g. programmatic tweening). * * @constructor * @namespace * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Operation = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.id = ''; this.args = []; this.command = null; this.showPosData = []; this.toHidePosData = []; this.startState = null; this.newState = null; this.docState = null; this.willSort = false; this.willChangeLayout = false; this.hasEffect = false; this.hasFailed = false; this.triggerElement = null; this.show = []; this.hide = []; this.matching = []; this.toShow = []; this.toHide = []; this.toMove = []; this.toRemove = []; this.startOrder = []; this.newOrder = []; this.startSort = null; this.newSort = null; this.startFilter = null; this.newFilter = null; this.startDataset = null; this.newDataset = null; this.startX = 0; this.startY = 0; this.startHeight = 0; this.startWidth = 0; this.newX = 0; this.newY = 0; this.newHeight = 0; this.newWidth = 0; this.startContainerClassName = ''; this.startDisplay = ''; this.newContainerClassName = ''; this.newDisplay = ''; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Operation); mixitup.Operation.prototype = Object.create(mixitup.Base.prototype); mixitup.Operation.prototype.constructor = mixitup.Operation; /** * `mixitup.State` objects expose various pieces of data detailing the state of * a MixItUp instance. They are provided at the start and end of any operation via * callbacks and events, with the most recent state stored between operations * for retrieval at any time via the API. * * @constructor * @namespace * @memberof mixitup * @public * @since 3.0.0 */ mixitup.State = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /** * The ID of the mixer instance. * * @name id * @memberof mixitup.State * @instance * @type {string} * @default '' */ this.id = ''; /** * The currently active filter command as set by a control click or API call. * * @name activeFilter * @memberof mixitup.State * @instance * @type {mixitup.CommandFilter} * @default null */ this.activeFilter = null; /** * The currently active sort command as set by a control click or API call. * * @name activeSort * @memberof mixitup.State * @instance * @type {mixitup.CommandSort} * @default null */ this.activeSort = null; /** * The current layout-specific container class name, if applied. * * @name activeContainerClassName * @memberof mixitup.State * @instance * @type {string} * @default '' */ this.activeContainerClassName = ''; /** * A reference to the container element that the mixer is instantiated on. * * @name container * @memberof mixitup.State * @instance * @type {Element} * @default null */ this.container = null; /** * An array of all target elements indexed by the mixer. * * @name targets * @memberof mixitup.State * @instance * @type {Array.<Element>} * @default [] */ this.targets = []; /** * An array of all target elements not matching the current filter. * * @name hide * @memberof mixitup.State * @instance * @type {Array.<Element>} * @default [] */ this.hide = []; /** * An array of all target elements matching the current filter and any additional * limits applied such as pagination. * * @name show * @memberof mixitup.State * @instance * @type {Array.<Element>} * @default [] */ this.show = []; /** * An array of all target elements matching the current filter irrespective of * any additional limits applied such as pagination. * * @name matching * @memberof mixitup.State * @instance * @type {Array.<Element>} * @default [] */ this.matching = []; /** * An integer representing the total number of target elements indexed by the * mixer. Equivalent to `state.targets.length`. * * @name totalTargets * @memberof mixitup.State * @instance * @type {number} * @default -1 */ this.totalTargets = -1; /** * An integer representing the total number of target elements matching the * current filter and any additional limits applied such as pagination. * Equivalent to `state.show.length`. * * @name totalShow * @memberof mixitup.State * @instance * @type {number} * @default -1 */ this.totalShow = -1; /** * An integer representing the total number of target elements not matching * the current filter. Equivalent to `state.hide.length`. * * @name totalHide * @memberof mixitup.State * @instance * @type {number} * @default -1 */ this.totalHide = -1; /** * An integer representing the total number of target elements matching the * current filter irrespective of any other limits applied such as pagination. * Equivalent to `state.matching.length`. * * @name totalMatching * @memberof mixitup.State * @instance * @type {number} * @default -1 */ this.totalMatching = -1; /** * A boolean indicating whether the last operation "failed", i.e. no targets * could be found matching the filter. * * @name hasFailed * @memberof mixitup.State * @instance * @type {boolean} * @default false */ this.hasFailed = false; /** * The DOM element that was clicked if the last operation was triggered by the * clicking of a control and not an API call. * * @name triggerElement * @memberof mixitup.State * @instance * @type {Element|null} * @default null */ this.triggerElement = null; /** * The currently active dataset underlying the rendered targets, if the * dataset API is in use. * * @name activeDataset * @memberof mixitup.State * @instance * @type {Array.<object>} * @default null */ this.activeDataset = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.State); mixitup.State.prototype = Object.create(mixitup.Base.prototype); mixitup.State.prototype.constructor = mixitup.State; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.UserInstruction = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); this.command = {}; this.animate = false; this.callback = null; this.callActions('afterConstruct'); h.seal(this); }; mixitup.BaseStatic.call(mixitup.UserInstruction); mixitup.UserInstruction.prototype = Object.create(mixitup.Base.prototype); mixitup.UserInstruction.prototype.constructor = mixitup.UserInstruction; /** * @constructor * @memberof mixitup * @private * @since 3.0.0 */ mixitup.Messages = function() { mixitup.Base.call(this); this.callActions('beforeConstruct'); /* Errors ----------------------------------------------------------------------------- */ this.ERROR_FACTORY_INVALID_CONTAINER = '[MixItUp] An invalid selector or element reference was passed to the mixitup factory function'; this.ERROR_FACTORY_CONTAINER_NOT_FOUND = '[MixItUp] The provided selector yielded no container element'; this.ERROR_CONFIG_INVALID_ANIMATION_EFFECTS = '[MixItUp] Invalid value for `animation.effects`'; this.ERROR_CONFIG_INVALID_CONTROLS_SCOPE = '[MixItUp] Invalid value for `controls.scope`'; this.ERROR_CONFIG_INVALID_PROPERTY = '[MixitUp] Invalid configuration object property "${erroneous}"${suggestion}'; this.ERROR_CONFIG_INVALID_PROPERTY_SUGGESTION = '. Did you mean "${probableMatch}"?'; this.ERROR_CONFIG_DATA_UID_KEY_NOT_SET = '[MixItUp] To use the dataset API, a UID key must be specified using `data.uidKey`'; this.ERROR_DATASET_INVALID_UID_KEY = '[MixItUp] The specified UID key "${uidKey}" is not present on one or more dataset items'; this.ERROR_DATASET_DUPLICATE_UID = '[MixItUp] The UID "${uid}" was found on two or more dataset items. UIDs must be unique.'; this.ERROR_INSERT_INVALID_ARGUMENTS = '[MixItUp] Please provider either an index or a sibling and position to insert, not both'; this.ERROR_INSERT_PREEXISTING_ELEMENT = '[MixItUp] An element to be inserted already exists in the container'; this.ERROR_FILTER_INVALID_ARGUMENTS = '[MixItUp] Please provide either a selector or collection `.filter()`, not both'; this.ERROR_DATASET_NOT_SET = '[MixItUp] To use the dataset API with pre-rendered targets, a starting dataset must be set using `load.dataset`'; this.ERROR_DATASET_PRERENDERED_MISMATCH = '[MixItUp] `load.dataset` does not match pre-rendered targets'; this.ERROR_DATASET_RENDERER_NOT_SET = '[MixItUp] To insert an element via the dataset API, a target renderer function must be provided to `render.target`'; /* Warnings ----------------------------------------------------------------------------- */ this.WARNING_FACTORY_PREEXISTING_INSTANCE = '[MixItUp] WARNING: This element already has an active MixItUp instance. The provided configuration object will be ignored.' + ' If you wish to perform additional methods on this instance, please create a reference.'; this.WARNING_INSERT_NO_ELEMENTS = '[MixItUp] WARNING: No valid elements were passed to `.insert()`'; this.WARNING_REMOVE_NO_ELEMENTS = '[MixItUp] WARNING: No valid elements were passed to `.remove()`'; this.WARNING_MULTIMIX_INSTANCE_QUEUE_FULL = '[MixItUp] WARNING: An operation was requested but the MixItUp instance was busy. The operation was rejected because the ' + 'queue is full or queuing is disabled.'; this.WARNING_GET_OPERATION_INSTANCE_BUSY = '[MixItUp] WARNING: Operations can be be created while the MixItUp instance is busy.'; this.WARNING_NO_PROMISE_IMPLEMENTATION = '[MixItUp] WARNING: No Promise implementations could be found. If you wish to use promises with MixItUp please install' + ' an ES6 Promise polyfill.'; this.WARNING_INCONSISTENT_SORTING_ATTRIBUTES = '[MixItUp] WARNING: The requested sorting data attribute "${attribute}" was not present on one or more target elements' + ' which may product unexpected sort output'; this.callActions('afterConstruct'); this.compileTemplates(); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Messages); mixitup.Messages.prototype = Object.create(mixitup.Base.prototype); mixitup.Messages.prototype.constructor = mixitup.Messages; /** * @return {void} */ mixitup.Messages.prototype.compileTemplates = function() { var errorKey = ''; var errorMessage = ''; for (errorKey in this) { if (typeof (errorMessage = this[errorKey]) !== 'string') continue; this[h.camelCase(errorKey)] = h.template(errorMessage); } }; mixitup.messages = new mixitup.Messages(); /** * @constructor * @memberof mixitup * @private * @since 3.0.0 * @param {mixitup.Mixer} mixer */ mixitup.Facade = function Mixer(mixer) { mixitup.Base.call(this); this.callActions('beforeConstruct', arguments); this.configure = mixer.configure.bind(mixer); this.show = mixer.show.bind(mixer); this.hide = mixer.hide.bind(mixer); this.filter = mixer.filter.bind(mixer); this.sort = mixer.sort.bind(mixer); this.changeLayout = mixer.changeLayout.bind(mixer); this.multimix = mixer.multimix.bind(mixer); this.multiMix = mixer.multimix.bind(mixer); this.dataset = mixer.dataset.bind(mixer); this.tween = mixer.tween.bind(mixer); this.insert = mixer.insert.bind(mixer); this.insertBefore = mixer.insertBefore.bind(mixer); this.insertAfter = mixer.insertAfter.bind(mixer); this.prepend = mixer.prepend.bind(mixer); this.append = mixer.append.bind(mixer); this.remove = mixer.remove.bind(mixer); this.destroy = mixer.destroy.bind(mixer); this.forceRefresh = mixer.forceRefresh.bind(mixer); this.isMixing = mixer.isMixing.bind(mixer); this.getOperation = mixer.getOperation.bind(mixer); this.getConfig = mixer.getConfig.bind(mixer); this.getState = mixer.getState.bind(mixer); this.callActions('afterConstruct', arguments); h.freeze(this); h.seal(this); }; mixitup.BaseStatic.call(mixitup.Facade); mixitup.Facade.prototype = Object.create(mixitup.Base.prototype); mixitup.Facade.prototype.constructor = mixitup.Facade; if (typeof exports === 'object' && typeof module === 'object') { module.exports = mixitup; } else if (typeof define === 'function' && define.amd) { define(function() { return mixitup; }); } else if (typeof window.mixitup === 'undefined' || typeof window.mixitup !== 'function') { window.mixitup = window.mixItUp = mixitup; } if ((jq = window.$ || window.jQuery) && jq.fn.jquery) { mixitup.registerJqPlugin(jq); } mixitup.NAME = 'mixitup'; mixitup.CORE_VERSION = '3.0.0'; })(window);
// Karma configuration // Generated on Sat Dec 14 2013 01:54:41 GMT+0100 (CET) module.exports = function(config) { 'use strict'; config.set({ // base path, that will be used to resolve files and exclude basePath: '..', // frameworks to use frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/ace-builds/src-min-noconflict/ace.js', 'src/*.js', 'test/*.spec.js' ], // list of files to exclude exclude: [ ], // test results reporter to use // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' reporters: ['dots'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera (has to be installed with `npm install karma-opera-launcher`) // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`) // - PhantomJS // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`) browsers: ['Chrome', 'Firefox', 'PhantomJS'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); if(process.env.TRAVIS){ config.set({ browsers: ['TravisCI_Chrome', 'Firefox', 'PhantomJS'], customLaunchers: { TravisCI_Chrome: { base: 'Chrome', flags: ['--no-sandbox'] } } }); } };
import ValidationEngine from 'ghost/mixins/validation-engine'; import NProgressSaveMixin from 'ghost/mixins/nprogress-save'; import SelectiveSaveMixin from 'ghost/mixins/selective-save'; var User = DS.Model.extend(NProgressSaveMixin, SelectiveSaveMixin, ValidationEngine, { validationType: 'user', uuid: DS.attr('string'), name: DS.attr('string'), slug: DS.attr('string'), email: DS.attr('string'), image: DS.attr('string'), cover: DS.attr('string'), bio: DS.attr('string'), website: DS.attr('string'), location: DS.attr('string'), accessibility: DS.attr('string'), status: DS.attr('string'), language: DS.attr('string', {defaultValue: 'en_US'}), meta_title: DS.attr('string'), meta_description: DS.attr('string'), last_login: DS.attr('moment-date'), created_at: DS.attr('moment-date'), created_by: DS.attr('number'), updated_at: DS.attr('moment-date'), updated_by: DS.attr('number'), roles: DS.hasMany('role', { embedded: 'always' }), role: Ember.computed('roles', function (name, value) { if (arguments.length > 1) { //Only one role per user, so remove any old data. this.get('roles').clear(); this.get('roles').pushObject(value); return value; } return this.get('roles.firstObject'); }), // TODO: Once client-side permissions are in place, // remove the hard role check. isAuthor: Ember.computed.equal('role.name', 'Author'), isEditor: Ember.computed.equal('role.name', 'Editor'), isAdmin: Ember.computed.equal('role.name', 'Administrator'), isOwner: Ember.computed.equal('role.name', 'Owner'), saveNewPassword: function () { var url = this.get('ghostPaths.url').api('users', 'password'); return ic.ajax.request(url, { type: 'PUT', data: { password: [{ 'oldPassword': this.get('password'), 'newPassword': this.get('newPassword'), 'ne2Password': this.get('ne2Password') }] } }); }, resendInvite: function () { var fullUserData = this.toJSON(), userData = { email: fullUserData.email, roles: fullUserData.roles }; return ic.ajax.request(this.get('ghostPaths.url').api('users'), { type: 'POST', data: JSON.stringify({users: [userData]}), contentType: 'application/json' }); }, passwordValidationErrors: Ember.computed('password', 'newPassword', 'ne2Password', function () { var validationErrors = []; if (!validator.equals(this.get('newPassword'), this.get('ne2Password'))) { validationErrors.push({message: 'Your new passwords do not match'}); } if (!validator.isLength(this.get('newPassword'), 8)) { validationErrors.push({message: 'Your password is not long enough. It must be at least 8 characters long.'}); } return validationErrors; }), isPasswordValid: Ember.computed.empty('passwordValidationErrors.[]'), active: Ember.computed('status', function () { return _.contains(['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked'], this.get('status')); }), invited: Ember.computed('status', function () { return _.contains(['invited', 'invited-pending'], this.get('status')); }), pending: Ember.computed.equal('status', 'invited-pending') }); export default User;
/* * Spanish translation * @author Alex Vavilin <xand@xand.es> * @version 2010-09-22 */ (function($) { if (elFinder && elFinder.prototype.options && elFinder.prototype.options.i18n) elFinder.prototype.options.i18n.es = { /* errors */ 'Root directory does not exists' : 'El directorio raíz no existe', 'Unable to connect to backend' : 'No se ha podido establecer la conexión con el servidor', 'Access denied' : 'Acceso denegado', 'Invalid backend configuration' : 'La respuesta del servidor es incorrecta', 'Unknown command' : 'Comando desconocido', 'Command not allowed' : 'No puede ejecutar este comando', 'Invalid parameters' : 'Parámetros incorrectos', 'File not found' : 'Fichero no encontrado', 'Invalid name' : 'Nombre incorrecto', 'File or folder with the same name already exists' : 'Ya existe un fichero o un directorio con este nombre', 'Unable to rename file' : 'No se ha podido cambiar el nombre al directorio', 'Unable to create folder' : 'No se ha podido crear el directorio', 'Unable to create file' : 'No se ha podido crear el fichero', 'No file to upload' : 'No hay ficheros para subir', 'Select at least one file to upload' : 'Seleccione, como mínimo un fichero, para subir', 'File exceeds the maximum allowed filesize' : 'El tamaño del fichero es más grande que el tamaño máximo autorizado', 'Data exceeds the maximum allowed size' : 'Los datos exceden el tamaño máximo permitido', 'Not allowed file type' : 'Tipo de fichero no permitido', 'Unable to upload file' : 'No se ha podido subir el fichero', 'Unable to upload files' : 'No se han podido subir los ficheros', 'Unable to remove file' : 'No se ha podido eliminar el fichero', 'Unable to save uploaded file' : 'No se ha podido guardar el fichero subido', 'Some files was not uploaded' : 'Algunos ficheros no han podido ser subidos', 'Unable to copy into itself' : 'No se puede copiar dentro de sí mismo', 'Unable to move files' : 'No se ha podido mover los ficheros', 'Unable to copy files' : 'No se ha podido copiar los ficheros', 'Unable to create file copy' : 'No se ha podido crear copia del fichero', 'File is not an image' : 'Este fichero no es una imagen', 'Unable to resize image' : 'No se han podido cambiar las dimensiones de la imagen', 'Unable to write to file' : 'No se ha podido escribir el fichero', 'Unable to create archive' : 'No se ha podido crear el archivo', 'Unable to extract files from archive' : 'No se ha podido extraer fichero desde archivo', 'Unable to open broken link' : 'No se puede abrir un enlace roto', 'File URL disabled by connector config' : 'El acceso a las rutas de los ficheros está prohibido en la configuración del conector', /* statusbar */ 'items' : 'objetos', 'selected items' : 'objetos seleccionados', /* commands/buttons */ 'Back' : 'Atrás', 'Reload' : 'Refrescar', 'Open' : 'Abrir', 'Preview with Quick Look' : 'Vista previa', 'Select file' : 'Seleccionar fichero', 'New folder' : 'Nueva carpeta', 'New text file' : 'Nuevo fichero', 'Upload files' : 'Subir ficheros', 'Copy' : 'Copiar', 'Cut' : 'Cortar', 'Paste' : 'Pegar', 'Duplicate' : 'Duplicar', 'Remove' : 'Eliminar', 'Rename' : 'Cambiar nombre', 'Edit text file' : 'Editar fichero', 'View as icons' : 'Iconos', 'View as list' : 'Lista', 'Resize image' : 'Tamaño de imagen', 'Create archive' : 'Nuevo archivo', 'Uncompress archive' : 'Extraer archivo', 'Get info' : 'Propiedades', 'Help' : 'Ayuda', 'Dock/undock filemanager window' : 'Despegar/pegar el gestor de ficheros a la página', /* upload/get info dialogs */ 'Maximum allowed files size' : 'Tamaño máximo del fichero', 'Add field' : 'Añadir campo', 'File info' : 'Propiedades de fichero', 'Folder info' : 'Propiedades de carpeta', 'Name' : 'Nombre', 'Kind' : 'Tipo', 'Size' : 'Tamaño', 'Modified' : 'Modificado', 'Permissions' : 'Acceso', 'Link to' : 'Enlaza con', 'Dimensions' : 'Dimensiones', 'Confirmation required' : 'Se requiere confirmación', 'Are you sure you want to remove files?<br /> This cannot be undone!' : '¿Está seguir que desea eliminar el fichero? <br />Esta acción es irreversible.', /* permissions */ 'read' : 'lectura', 'write' : 'escritura', 'remove' : 'eliminación', /* dates */ 'Jan' : 'Ene', 'Feb' : 'Feb', 'Mar' : 'Mar', 'Apr' : 'Abr', 'May' : 'May', 'Jun' : 'Jun', 'Jul' : 'Jul', 'Aug' : 'Ago', 'Sep' : 'Sep', 'Oct' : 'Oct', 'Nov' : 'Nov', 'Dec' : 'Dec', 'Today' : 'Hoy', 'Yesterday' : 'Ayer', /* mimetypes */ 'Unknown' : 'Desconocido', 'Folder' : 'Carpeta', 'Alias' : 'Enlace', 'Broken alias' : 'Enlace roto', 'Plain text' : 'Texto', 'Postscript document' : 'Documento postscript', 'Application' : 'Aplicación', 'Microsoft Office document' : 'Documento Microsoft Office', 'Microsoft Word document' : 'Documento Microsoft Word', 'Microsoft Excel document' : 'Documento Microsoft Excel', 'Microsoft Powerpoint presentation' : 'Documento Microsoft Powerpoint', 'Open Office document' : 'Documento Open Office', 'Flash application' : 'Aplicación Flash', 'XML document' : 'Documento XML', 'Bittorrent file' : 'Fichero bittorrent', '7z archive' : 'Archivo 7z', 'TAR archive' : 'Archivo TAR', 'GZIP archive' : 'Archivo GZIP', 'BZIP archive' : 'Archivo BZIP', 'ZIP archive' : 'Archivo ZIP', 'RAR archive' : 'Archivo RAR', 'Javascript application' : 'Aplicación Javascript', 'PHP source' : 'Documento PHP', 'HTML document' : 'Documento HTML', 'Javascript source' : 'Documento Javascript', 'CSS style sheet' : 'Documento CSS', 'C source' : 'Documento C', 'C++ source' : 'Documento C++', 'Unix shell script' : 'Script Unix shell', 'Python source' : 'Documento Python', 'Java source' : 'Documento Java', 'Ruby source' : 'Documento Ruby', 'Perl script' : 'Script Perl', 'BMP image' : 'Imagen BMP', 'JPEG image' : 'Imagen JPEG', 'GIF Image' : 'Imagen GIF', 'PNG Image' : 'Imagen PNG', 'TIFF image' : 'Imagen TIFF', 'TGA image' : 'Imagen TGA', 'Adobe Photoshop image' : 'Imagen Adobe Photoshop', 'MPEG audio' : 'Audio MPEG', 'MIDI audio' : 'Audio MIDI', 'Ogg Vorbis audio' : 'Audio Ogg Vorbis', 'MP4 audio' : 'Audio MP4', 'WAV audio' : 'Audio WAV', 'DV video' : 'Video DV', 'MP4 video' : 'Video MP4', 'MPEG video' : 'Video MPEG', 'AVI video' : 'Video AVI', 'Quicktime video' : 'Video Quicktime', 'WM video' : 'Video WM', 'Flash video' : 'Video Flash', 'Matroska video' : 'Video Matroska', // 'Shortcuts' : 'Клавиши', 'Select all files' : 'Seleccionar todos ficheros', 'Copy/Cut/Paste files' : 'Copiar/Cortar/Pegar ficheros', 'Open selected file/folder' : 'Abrir carpeta/fichero', 'Open/close QuickLook window' : 'Abrir/Cerrar la ventana de vista previa', 'Remove selected files' : 'Eliminar ficheros seleccionados', 'Selected files or current directory info' : 'Información sobre los ficheros seleccionados en la carpeta actual', 'Create new directory' : 'Nueva carpeta', 'Open upload files form' : 'Abrir ventana para subir ficheros', 'Select previous file' : 'Seleccionar el fichero anterior', 'Select next file' : 'Seleccionar el fichero siguiente', 'Return into previous folder' : 'Volver a la carpeta anterior', 'Increase/decrease files selection' : 'Aumentar/disminuir la selección de ficheros', 'Authors' : 'Autores', 'Sponsors' : 'Colaboradores', 'elFinder: Web file manager' : 'elFinder: Gestor de ficheros para la web', 'Version' : 'Versión', 'Copyright: Studio 42 LTD' : 'Copyright: Studio 42', 'Donate to support project development' : 'Ayuda al desarrollo', 'Javascripts/PHP programming: Dmitry (dio) Levashov, dio@std42.ru' : 'Programación Javascripts/php: Dmitry (dio) Levashov, dio@std42.ru', 'Python programming, techsupport: Troex Nevelin, troex@fury.scancode.ru' : 'Programación Python, soporte técnico: Troex Nevelin, troex@fury.scancode.ru', 'Design: Valentin Razumnih' : 'Diseño: Valentin Razumnyh', 'Spanish localization' : 'Traducción al español', 'Icons' : 'Iconos', 'License: BSD License' : 'Licencia: BSD License', 'elFinder documentation' : 'Documentación elFinder', 'Simple and usefull Content Management System' : 'Un CMS sencillo y cómodo', 'Support project development and we will place here info about you' : 'Ayude al desarrollo del producto y la información sobre usted aparecerá aqui.', 'Contacts us if you need help integrating elFinder in you products' : 'Pregúntenos si quiere integrar elFinder en su producto.', 'elFinder support following shortcuts' : 'elFinder soporta los siguientes atajos de teclado', 'helpText' : 'elFinder funciona igual que el gestor de ficheros de su PC. <br />Puede manipular los ficheros con la ayuda del panel superior, el menu o bien con atajos de teclado. Para mover fichero/carpetas simplemente arrastrelos a la carpeta deseada. Si simultáneamente presiona la tecla Shift los ficheros se copiarán.' }; })(jQuery);
import isBlank from 'ember-metal/is_blank'; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(''); // false Ember.isPresent([]); // false Ember.isPresent('\n\t'); // false Ember.isPresent(' '); // false Ember.isPresent({}); // true Ember.isPresent(false); // true Ember.isPresent('\n\t Hello'); // true Ember.isPresent('Hello world'); // true Ember.isPresent([1,2,3]); // true ``` @method isPresent @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.8.0 @public */ export default function isPresent(obj) { return !isBlank(obj); }
URLs = new Mongo.Collection("urls"); if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str){ return this.slice(0, str.length) == str; }; }
(function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['empower', 'assert'], factory); } else if (typeof exports === 'object') { factory(require('../lib/empower'), require('assert')); } else { factory(root.empower, root.assert); } }(this, function ( empower, baseAssert ) { function fakeFormatter (context) { throw new Error('formatter should not be called'); } function testWithOption (option) { var assert = empower(baseAssert, fakeFormatter, option); test(JSON.stringify(option) + ' argument is null Literal.', function () { var foo = 'foo'; try { eval('assert.equal(foo, null);'); assert.ok(false, 'AssertionError should be thrown'); } catch (e) { baseAssert.equal(e.name, 'AssertionError'); baseAssert.equal(e.message, '"foo" == null'); baseAssert(e.powerAssertContext === undefined); } }); test(JSON.stringify(option) + ' empowered function also acts like an assert function', function () { var falsy = 0; try { eval('assert(falsy);'); assert.ok(false, 'AssertionError should be thrown'); } catch (e) { baseAssert.equal(e.name, 'AssertionError'); baseAssert.equal(e.message, '0 == true'); baseAssert(e.powerAssertContext === undefined); } }); suite(JSON.stringify(option) + ' assertion method with one argument', function () { test('Identifier', function () { var falsy = 0; try { eval('assert.ok(falsy);'); assert.ok(false, 'AssertionError should be thrown'); } catch (e) { baseAssert.equal(e.name, 'AssertionError'); baseAssert.equal(e.message, '0 == true'); baseAssert(e.powerAssertContext === undefined); } }); }); suite(JSON.stringify(option) + ' assertion method with two arguments', function () { test('both Identifier', function () { var foo = 'foo', bar = 'bar'; try { eval('assert.equal(foo, bar);'); assert.ok(false, 'AssertionError should be thrown'); } catch (e) { baseAssert.equal(e.name, 'AssertionError'); baseAssert.equal(e.message, '"foo" == "bar"'); baseAssert(e.powerAssertContext === undefined); } }); test('first argument is Literal', function () { var bar = 'bar'; try { eval('assert.equal("foo", bar);'); assert.ok(false, 'AssertionError should be thrown'); } catch (e) { baseAssert.equal(e.name, 'AssertionError'); baseAssert.equal(e.message, '"foo" == "bar"'); baseAssert(e.powerAssertContext === undefined); } }); test('second argument is Literal', function () { var foo = 'foo'; try { eval('assert.equal(foo, "bar");'); assert.ok(false, 'AssertionError should be thrown'); } catch (e) { baseAssert.equal(e.name, 'AssertionError'); baseAssert.equal(e.message, '"foo" == "bar"'); baseAssert(e.powerAssertContext === undefined); } }); }); } testWithOption({ modifyMessageOnFail: false, saveContextOnFail: false }); testWithOption({ modifyMessageOnFail: true, saveContextOnFail: false }); testWithOption({ modifyMessageOnFail: false, saveContextOnFail: true }); testWithOption({ modifyMessageOnFail: true, saveContextOnFail: true }); }));
/** * @jsx React.DOM */ var _ = require('lodash'); var React = require('react'); var classNames = require('classnames'); var CodeSample = React.createClass({ render: function() { var panelClasses = classNames({ 'code-sample-panel': true, 'hide': this.props.hidden }); return ( <div className={panelClasses}> <a href="#" className="close-btn" onClick={this.props.onCloseClick}> <span className="icon glyphicon glyphicon glyphicon-remove-circle no-margin"></span> </a> <div className="sample"><pre>{this.props.codeSample}</pre></div> </div> ); } }); module.exports = CodeSample;
var tns = (function (){ // keys if (!Object.keys) { Object.keys = function (object) { var keys = []; for (var name in object) { if (Object.prototype.hasOwnProperty.call(object, name)) { keys.push(name); } } return keys; }; } // ChildNode.remove (function () { "use strict"; if(!("remove" in Element.prototype)){ Element.prototype.remove = function(){ if(this.parentNode) { this.parentNode.removeChild(this); } }; } })(); /** DOMTokenList polyfill */ (function(){ "use strict"; /*<*/ var UNDEF, WIN = window, DOC = document, OBJ = Object, NULL = null, TRUE = true, FALSE = false, /*>*/ /** Munge the hell out of our string literals. Saves a tonne of space after compression. */ SPACE = " ", ELEMENT = "Element", CREATE_ELEMENT = "create"+ELEMENT, DOM_TOKEN_LIST = "DOMTokenList", DEFINE_GETTER = "__defineGetter__", DEFINE_PROPERTY = "defineProperty", CLASS_ = "class", LIST = "List", CLASS_LIST = CLASS_+LIST, REL = "rel", REL_LIST = REL+LIST, DIV = "div", LENGTH = "length", CONTAINS = "contains", APPLY = "apply", HTML_ = "HTML", METHODS = ("item "+CONTAINS+" add remove toggle toString toLocaleString").split(SPACE), ADD = METHODS[2], REMOVE = METHODS[3], TOGGLE = METHODS[4], PROTOTYPE = "prototype", /** Ascertain browser support for Object.defineProperty */ dpSupport = DEFINE_PROPERTY in OBJ || DEFINE_GETTER in OBJ[ PROTOTYPE ] || NULL, /** Wrapper for Object.defineProperty that falls back to using the legacy __defineGetter__ method if available. */ defineGetter = function(object, name, fn, configurable){ if(OBJ[ DEFINE_PROPERTY ]) OBJ[ DEFINE_PROPERTY ](object, name, { configurable: FALSE === dpSupport ? TRUE : !!configurable, get: fn }); else object[ DEFINE_GETTER ](name, fn); }, /** DOMTokenList interface replacement */ DOMTokenList = function(el, prop){ var THIS = this, /** Private variables */ tokens = [], tokenMap = {}, length = 0, maxLength = 0, reindex = function(){ /** Define getter functions for array-like access to the tokenList's contents. */ if(length >= maxLength) for(; maxLength < length; ++maxLength) (function(i){ defineGetter(THIS, i, function(){ preop(); return tokens[i]; }, FALSE); })(maxLength); }, /** Helper function called at the start of each class method. Internal use only. */ preop = function(){ var error, i, args = arguments, rSpace = /\s+/; /** Validate the token/s passed to an instance method, if any. */ if(args[ LENGTH ]) for(i = 0; i < args[ LENGTH ]; ++i) if(rSpace.test(args[i])){ error = new SyntaxError('String "' + args[i] + '" ' + CONTAINS + ' an invalid character'); error.code = 5; error.name = "InvalidCharacterError"; throw error; } /** Split the new value apart by whitespace*/ tokens = ("" + el[prop]).replace(/^\s+|\s+$/g, "").split(rSpace); /** Avoid treating blank strings as single-item token lists */ if("" === tokens[0]) tokens = []; /** Repopulate the internal token lists */ tokenMap = {}; for(i = 0; i < tokens[ LENGTH ]; ++i) tokenMap[tokens[i]] = TRUE; length = tokens[ LENGTH ]; reindex(); }; /** Populate our internal token list if the targeted attribute of the subject element isn't empty. */ preop(); /** Return the number of tokens in the underlying string. Read-only. */ defineGetter(THIS, LENGTH, function(){ preop(); return length; }); /** Override the default toString/toLocaleString methods to return a space-delimited list of tokens when typecast. */ THIS[ METHODS[6] /** toLocaleString */ ] = THIS[ METHODS[5] /** toString */ ] = function(){ preop(); return tokens.join(SPACE); }; /** Return an item in the list by its index (or undefined if the number is greater than or equal to the length of the list) */ THIS.item = function(idx){ preop(); return tokens[idx]; }; /** Return TRUE if the underlying string contains `token`; otherwise, FALSE. */ THIS[ CONTAINS ] = function(token){ preop(); return !!tokenMap[token]; }; /** Add one or more tokens to the underlying string. */ THIS[ADD] = function(){ preop[APPLY](THIS, args = arguments); for(var args, token, i = 0, l = args[ LENGTH ]; i < l; ++i){ token = args[i]; if(!tokenMap[token]){ tokens.push(token); tokenMap[token] = TRUE; } } /** Update the targeted attribute of the attached element if the token list's changed. */ if(length !== tokens[ LENGTH ]){ length = tokens[ LENGTH ] >>> 0; el[prop] = tokens.join(SPACE); reindex(); } }; /** Remove one or more tokens from the underlying string. */ THIS[ REMOVE ] = function(){ preop[APPLY](THIS, args = arguments); /** Build a hash of token names to compare against when recollecting our token list. */ for(var args, ignore = {}, i = 0, t = []; i < args[ LENGTH ]; ++i){ ignore[args[i]] = TRUE; delete tokenMap[args[i]]; } /** Run through our tokens list and reassign only those that aren't defined in the hash declared above. */ for(i = 0; i < tokens[ LENGTH ]; ++i) if(!ignore[tokens[i]]) t.push(tokens[i]); tokens = t; length = t[ LENGTH ] >>> 0; /** Update the targeted attribute of the attached element. */ el[prop] = tokens.join(SPACE); reindex(); }; /** Add or remove a token depending on whether it's already contained within the token list. */ THIS[TOGGLE] = function(token, force){ preop[APPLY](THIS, [token]); /** Token state's being forced. */ if(UNDEF !== force){ if(force) { THIS[ADD](token); return TRUE; } else { THIS[REMOVE](token); return FALSE; } } /** Token already exists in tokenList. Remove it, and return FALSE. */ if(tokenMap[token]){ THIS[ REMOVE ](token); return FALSE; } /** Otherwise, add the token and return TRUE. */ THIS[ADD](token); return TRUE; }; /** Mark our newly-assigned methods as non-enumerable. */ (function(o, defineProperty){ if(defineProperty) for(var i = 0; i < 7; ++i) defineProperty(o, METHODS[i], {enumerable: FALSE}); }(THIS, OBJ[ DEFINE_PROPERTY ])); return THIS; }, /** Polyfills a property with a DOMTokenList */ addProp = function(o, name, attr){ defineGetter(o[PROTOTYPE], name, function(){ var tokenList, THIS = this, /** Prevent this from firing twice for some reason. What the hell, IE. */ gibberishProperty = DEFINE_GETTER + DEFINE_PROPERTY + name; if(THIS[gibberishProperty]) return tokenList; THIS[gibberishProperty] = TRUE; /** * IE8 can't define properties on native JavaScript objects, so we'll use a dumb hack instead. * * What this is doing is creating a dummy element ("reflection") inside a detached phantom node ("mirror") * that serves as the target of Object.defineProperty instead. While we could simply use the subject HTML * element instead, this would conflict with element types which use indexed properties (such as forms and * select lists). */ if(FALSE === dpSupport){ var visage, mirror = addProp.mirror = addProp.mirror || DOC[ CREATE_ELEMENT ](DIV), reflections = mirror.childNodes, /** Iterator variables */ l = reflections[ LENGTH ], i = 0; for(; i < l; ++i) if(reflections[i]._R === THIS){ visage = reflections[i]; break; } /** Couldn't find an element's reflection inside the mirror. Materialise one. */ visage || (visage = mirror.appendChild(DOC[ CREATE_ELEMENT ](DIV))); tokenList = DOMTokenList.call(visage, THIS, attr); } else tokenList = new DOMTokenList(THIS, attr); defineGetter(THIS, name, function(){ return tokenList; }); delete THIS[gibberishProperty]; return tokenList; }, TRUE); }, /** Variables used for patching native methods that're partially implemented (IE doesn't support adding/removing multiple tokens, for instance). */ testList, nativeAdd, nativeRemove; /** No discernible DOMTokenList support whatsoever. Time to remedy that. */ if(!WIN[ DOM_TOKEN_LIST ]){ /** Ensure the browser allows Object.defineProperty to be used on native JavaScript objects. */ if(dpSupport) try{ defineGetter({}, "support"); } catch(e){ dpSupport = FALSE; } DOMTokenList.polyfill = TRUE; WIN[ DOM_TOKEN_LIST ] = DOMTokenList; addProp( WIN[ ELEMENT ], CLASS_LIST, CLASS_ + "Name"); /* Element.classList */ addProp( WIN[ HTML_+ "Link" + ELEMENT ], REL_LIST, REL); /* HTMLLinkElement.relList */ addProp( WIN[ HTML_+ "Anchor" + ELEMENT ], REL_LIST, REL); /* HTMLAnchorElement.relList */ addProp( WIN[ HTML_+ "Area" + ELEMENT ], REL_LIST, REL); /* HTMLAreaElement.relList */ } /** * Possible support, but let's check for bugs. * * Where arbitrary values are needed for performing a test, previous variables * are recycled to save space in the minified file. */ else{ testList = DOC[ CREATE_ELEMENT ](DIV)[CLASS_LIST]; /** We'll replace a "string constant" to hold a reference to DOMTokenList.prototype (filesize optimisation, yaddah-yaddah...) */ PROTOTYPE = WIN[DOM_TOKEN_LIST][PROTOTYPE]; /** Check if we can pass multiple arguments to add/remove. To save space, we'll just recycle a previous array of strings. */ testList[ADD][APPLY](testList, METHODS); if(2 > testList[LENGTH]){ nativeAdd = PROTOTYPE[ADD]; nativeRemove = PROTOTYPE[REMOVE]; PROTOTYPE[ADD] = function(){ for(var i = 0, args = arguments; i < args[LENGTH]; ++i) nativeAdd.call(this, args[i]); }; PROTOTYPE[REMOVE] = function(){ for(var i = 0, args = arguments; i < args[LENGTH]; ++i) nativeRemove.call(this, args[i]); }; } /** Check if the "force" option of .toggle is supported. */ if(testList[TOGGLE](LIST, FALSE)) PROTOTYPE[TOGGLE] = function(token, force){ var THIS = this; THIS[(force = UNDEF === force ? !THIS[CONTAINS](token) : force) ? ADD : REMOVE](token); return !!force; }; } }()); function extend() { var obj, name, copy, target = arguments[0] || {}, i = 1, length = arguments.length; for (; i < length; i++) { if ((obj = arguments[i]) !== null) { for (name in obj) { copy = obj[name]; if (target === copy) { continue; } else if (copy !== undefined) { target[name] = copy; } } } } return target; } function checkStorageValue (value) { return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value; } function setLocalStorage(key, value, access) { if (access) { localStorage.setItem(key, value); } return value; } function getSlideId() { var id = window.tnsId; window.tnsId = !id ? 1 : id + 1; return 'tns' + window.tnsId; } // get css-calc // @return - false | calc | -webkit-calc | -moz-calc // @usage - var calc = getCalc(); function calc() { var doc = document, body = doc.body, el = doc.createElement('div'), result = false; body.appendChild(el); try { var vals = ['calc(10px)', '-moz-calc(10px)', '-webkit-calc(10px)'], val; for (var i = 0; i < 3; i++) { val = vals[i]; el.style.width = val; if (el.offsetWidth === 10) { result = val.replace('(10px)', ''); break; } } } catch (e) {} body.removeChild(el); return result; } // get subpixel support value // @return - boolean function subpixelLayout() { var doc = document, body = doc.body, parent = doc.createElement('div'), child1 = doc.createElement('div'), child2; parent.style.cssText = 'width: 10px'; child1.style.cssText = 'float: left; width: 5.5px; height: 10px;'; child2 = child1.cloneNode(true); parent.appendChild(child1); parent.appendChild(child2); body.appendChild(parent); var supported = child1.offsetTop !== child2.offsetTop; body.removeChild(parent); return supported; } function mediaquerySupport () { var doc = document, body = doc.body, div = doc.createElement('div'); div.className = 'tns-mq-test'; body.appendChild(div); var position = (window.getComputedStyle) ? window.getComputedStyle(div).position : div.currentStyle['position']; body.removeChild(div); return position === "absolute"; } // create and append style sheet function createStyleSheet (media) { // Create the <style> tag var style = document.createElement("style"); // style.setAttribute("type", "text/css"); // Add a media (and/or media query) here if you'd like! // style.setAttribute("media", "screen") // style.setAttribute("media", "only screen and (max-width : 1024px)") if (media) { style.setAttribute("media", media); } // WebKit hack :( // style.appendChild(document.createTextNode("")); // Add the <style> element to the page document.querySelector('head').appendChild(style); return (style.sheet) ? style.sheet : style.styleSheet; } // cross browsers addRule method var addCSSRule = (function () { var styleSheet = document.styleSheets[0]; if('insertRule' in styleSheet) { return function (sheet, selector, rules, index) { sheet.insertRule(selector + '{' + rules + '}', index); }; } else if('addRule' in styleSheet) { return function (sheet, selector, rules, index) { sheet.addRule(selector, rules, index); }; } })(); function getCssRulesLength(sheet) { var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules; return rule.length; } function toDegree (y, x) { return Math.atan2(y, x) * (180 / Math.PI); } function getTouchDirection(angle, range) { var direction = false, gap = Math.abs(90 - Math.abs(angle)); if (gap >= 90 - range) { direction = 'horizontal'; } else if (gap <= range) { direction = 'vertical'; } return direction; } function hasAttr(el, attr) { return el.hasAttribute(attr); } function getAttr(el, attr) { return el.getAttribute(attr); } function isNodeList(el) { // Only NodeList has the "item()" function return typeof el.item !== "undefined"; } function setAttrs(els, attrs) { els = (isNodeList(els) || els instanceof Array) ? els : [els]; if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; } for (var i = els.length; i--;) { for(var key in attrs) { els[i].setAttribute(key, attrs[key]); } } } function removeAttrs(els, attrs) { els = (isNodeList(els) || els instanceof Array) ? els : [els]; attrs = (attrs instanceof Array) ? attrs : [attrs]; var attrLength = attrs.length; for (var i = els.length; i--;) { for (var j = attrLength; j--;) { els[i].removeAttribute(attrs[j]); } } } function hideElement(el) { if (!hasAttr(el, 'hidden')) { setAttrs(el, {'hidden': ''}); } } function showElement(el) { if (hasAttr(el, 'hidden')) { removeAttrs(el, 'hidden'); } } // check if an image is loaded // 1. See if "naturalWidth" and "naturalHeight" properties are available. // 2. See if "complete" property is available. function imageLoaded(img) { if (typeof img.complete === 'boolean') { return img.complete; } else if (typeof img.naturalWidth === 'number') { return img.naturalWidth !== 0; } } function whichProperty(props){ var el = document.createElement('fakeelement'), len = props.length; for(var i = 0; i < props.length; i++){ var prop = props[i]; if( el.style[prop] !== undefined ){ return prop; } } return false; // explicit for ie9- } // get transitionend, animationend based on transitionDuration // @propin: string // @propOut: string, first-letter uppercase // Usage: getEndProperty('WebkitTransitionDuration', 'Transition') => webkitTransitionEnd function getEndProperty(propIn, propOut) { var endProp = false; if (/^Webkit/.test(propIn)) { endProp = 'webkit' + propOut + 'End'; } else if (/^O/.test(propIn)) { endProp = 'o' + propOut + 'End'; } else if (propIn) { endProp = propOut.toLowerCase() + 'end'; } return endProp; } // Test via a getter in the options object to see if the passive property is accessed var supportsPassive = false; try { var opts = Object.defineProperty({}, 'passive', { get: function() { supportsPassive = true; } }); window.addEventListener("test", null, opts); } catch (e) {} var passiveOption = supportsPassive ? { passive: true } : false; function addEvents(el, obj) { for (var prop in obj) { var option = (prop === 'touchstart' || prop === 'touchmove') ? passiveOption : false; el.addEventListener(prop, obj[prop], option); } } function removeEvents(el, obj) { for (var prop in obj) { var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false; el.removeEventListener(prop, obj[prop], option); } } function Events() { return { topics: {}, on: function (eventName, fn) { this.topics[eventName] = this.topics[eventName] || []; this.topics[eventName].push(fn); }, off: function(eventName, fn) { if (this.topics[eventName]) { for (var i = 0; i < this.topics[eventName].length; i++) { if (this.topics[eventName][i] === fn) { this.topics[eventName].splice(i, 1); break; } } } }, emit: function (eventName, data) { if (this.topics[eventName]) { this.topics[eventName].forEach(function(fn) { fn(data); }); } } }; } function jsTransform(element, attr, prefix, postfix, to, duration, callback) { var tick = Math.min(duration, 10), unit = (to.indexOf('%') >= 0) ? '%' : 'px', to = to.replace(unit, ''), from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')), positionTick = (to - from) / duration * tick, running; setTimeout(moveElement, tick); function moveElement() { duration -= tick; from += positionTick; element.style[attr] = prefix + from + unit + postfix; if (duration > 0) { setTimeout(moveElement, tick); } else { callback(); } } } // Format: IIFE // Version: 2.1.8 // from go-native // helper functions // check browser version and local storage // if browser upgraded, // 1. delete browser ralated data from local storage and // 2. recheck these options and save them to local storage var browserInfo = navigator.userAgent; var localStorageAccess = true; var tnsStorage = localStorage; try { if (!tnsStorage['tnsApp']) { tnsStorage['tnsApp'] = browserInfo; } else if (tnsStorage['tnsApp'] !== browserInfo) { tnsStorage['tnsApp'] = browserInfo; // tC => calc // tSP => subpixel // tMQ => mediaquery // tTf => transform // tTDu => transitionDuration // tTDe => transitionDelay // tADu => animationDuration // tADe => animationDelay // tTE => transitionEnd // tAE => animationEnd ['tC', 'tSP', 'tMQ', 'tTf', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function (item) { tnsStorage.removeItem(item); }) } } catch(e) { localStorageAccess = false; } // get browser related data from local storage if they exist // otherwise, run the functions again and save these data to local storage // checkStorageValue() convert non-string value to its original value: 'true' > true var doc = document; var win = window; var KEYS = { ENTER: 13, SPACE: 32, PAGEUP: 33, PAGEDOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }; var CALC = checkStorageValue(tnsStorage['tC']) || setLocalStorage('tC', calc(), localStorageAccess); var SUBPIXEL = checkStorageValue(tnsStorage['tSP']) || setLocalStorage('tSP', subpixelLayout(), localStorageAccess); var CSSMQ = checkStorageValue(tnsStorage['tMQ']) || setLocalStorage('tMQ', mediaquerySupport(), localStorageAccess); var TRANSFORM = checkStorageValue(tnsStorage['tTf']) || setLocalStorage('tTf', whichProperty([ 'transform', 'WebkitTransform', 'MozTransform', 'msTransform', 'OTransform' ]), localStorageAccess); var TRANSITIONDURATION = checkStorageValue(tnsStorage['tTDu']) || setLocalStorage('tTDu', whichProperty([ 'transitionDuration', 'WebkitTransitionDuration', 'MozTransitionDuration', 'OTransitionDuration' ]), localStorageAccess); var TRANSITIONDELAY = checkStorageValue(tnsStorage['tTDe']) || setLocalStorage('tTDe', whichProperty([ 'transitionDelay', 'WebkitTransitionDelay', 'MozTransitionDelay', 'OTransitionDelay' ]), localStorageAccess); var ANIMATIONDURATION = checkStorageValue(tnsStorage['tADu']) || setLocalStorage('tADu', whichProperty([ 'animationDuration', 'WebkitAnimationDuration', 'MozAnimationDuration', 'OAnimationDuration' ]), localStorageAccess); var ANIMATIONDELAY = checkStorageValue(tnsStorage['tADe']) || setLocalStorage('tADe', whichProperty([ 'animationDelay', 'WebkitAnimationDelay', 'MozAnimationDelay', 'OAnimationDelay' ]), localStorageAccess); var TRANSITIONEND = checkStorageValue(tnsStorage['tTE']) || setLocalStorage('tTE', getEndProperty(TRANSITIONDURATION, 'Transition'), localStorageAccess); var ANIMATIONEND = checkStorageValue(tnsStorage['tAE']) || setLocalStorage('tAE', getEndProperty(ANIMATIONDURATION, 'Animation'), localStorageAccess); // reset SUBPIXEL for IE8 if (!CSSMQ) { SUBPIXEL = false; } var tns = function(options) { options = extend({ container: doc.querySelector('.slider'), mode: 'carousel', axis: 'horizontal', items: 1, gutter: 0, edgePadding: 0, fixedWidth: false, slideBy: 1, controls: true, controlsText: ['prev', 'next'], controlsContainer: false, nav: true, navContainer: false, // navAnimationIn: false, // navAnimationOut: false, arrowKeys: false, speed: 300, autoplay: false, autoplayTimeout: 5000, autoplayDirection: 'forward', autoplayText: ['start', 'stop'], autoplayHoverPause: false, autoplayButton: false, autoplayButtonOutput: true, autoplayResetOnVisibility: true, // animateIn: 'tns-fadeIn', // animateOut: 'tns-fadeOut', // animateNormal: 'tns-normal', // animateDelay: false, loop: true, rewind: false, autoHeight: false, responsive: false, lazyload: false, touch: true, mouseDrag: false, nested: false, onInit: false }, options || {}); // get element nodes from selectors ['container', 'controlsContainer', 'navContainer', 'autoplayButton'].forEach(function(item) { if (typeof options[item] === 'string') { options[item] = doc.querySelector(options[item]); } }); // make sure slide container exists if (!options.container || !options.container.nodeName || options.container.children.length < 2) { return; } // update responsive // from: { // 300: 2, // 800: { // loop: false // } // } // to: { // 300: { // items: 2 // }, // 800: { // loop: false // } // } if (options.responsive) { var resTem = {}, res = options.responsive; for(var key in res) { var val = res[key]; resTem[key] = typeof val === 'number' ? {items: val} : val; } options.responsive = resTem; resTem = null; } // === define and set variables === var carousel = options.mode === 'carousel' ? true : false; if (!carousel) { options.axis = 'horizontal'; options.rewind = false; options.loop = true; options.edgePadding = false; var animateIn = 'tns-fadeIn', animateOut = 'tns-fadeOut', animateDelay = false, animateNormal = options.animateNormal || 'tns-normal'; if (TRANSITIONEND && ANIMATIONEND) { animateIn = options.animateIn || animateIn; animateOut = options.animateOut || animateOut; animateDelay = options.animateDelay || animateDelay; } } var horizontal = options.axis === 'horizontal' ? true : false, outerWrapper = doc.createElement('div'), innerWrapper = doc.createElement('div'), container = options.container, containerParent = container.parentNode, slideItems = container.children, slideCount = slideItems.length, vpOuter = containerParent.clientWidth, vpInner, responsive = options.responsive, responsiveItems = [], breakpoints = false, breakpointZone = 0, breakpointZoneAdjust = 0; if (responsive) { breakpoints = Object.keys(responsive) .map(function (x) { return parseInt(x); }) .sort(function (a, b) { return a - b; }); if (breakpoints.indexOf(0) < 0) { breakpointZoneAdjust = 1; } breakpoints.forEach(function(bp) { responsiveItems = responsiveItems.concat(Object.keys(responsive[bp])); }); var arr = []; responsiveItems.forEach(function (item) { if (arr.indexOf(item) < 0) { arr.push(item); } }); responsiveItems = arr; // alert(responsiveItems); breakpointZone = getBreakpointZone(); } var items = getOption('items'), slideBy = getOption('slideBy') === 'page' ? items : getOption('slideBy'), nested = options.nested, gutter = getOption('gutter'), edgePadding = getOption('edgePadding'), fixedWidth = getOption('fixedWidth'), arrowKeys = getOption('arrowKeys'), speed = getOption('speed'), rewind = options.rewind, loop = rewind ? false : options.loop, autoHeight = getOption('autoHeight'), sheet = createStyleSheet(), lazyload = options.lazyload, slideOffsetTops, // collection of slide offset tops slideItemsOut = [], cloneCount = loop ? slideCount * 2 : checkOption('edgePadding') ? 1 : 0, slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2, hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false, checkIndexBeforeTransform = !carousel || !loop ? true : false, // transform transformAttr = horizontal ? 'left' : 'top', transformPrefix = '', transformPostfix = '', // index index = !carousel ? 0 : cloneCount, indexCached = index, indexAdjust = !loop && checkOption('edgePadding') ? 1 : 0, indexMin = indexAdjust, indexMax = slideCountNew - items - indexAdjust, // resize resizeTimer, touchedOrDraged, running = false, onInit = options.onInit, events = new Events(), // id, class containerIdCached = container.id, containerClassCached = container.className, slideItemIdCached = slideItems[0].id, slideItemClassCached = slideItems[0].className, slideId = container.id || getSlideId(), freeze = slideCount <= items, importantStr = nested === 'inner' ? ' !important' : '', controlsEvents = { 'click': onControlsClick, 'keydown': onControlsKeydown }, navEvents = { 'click': onNavClick, 'keydown': onNavKeydown }, hoverEvents = { 'mouseover': mouseoverPause, 'mouseout': mouseoutRestart }, visibilityEvent = {'visibilitychange': onVisibilityChange}, docmentKeydownEvent = {'keydown': onDocumentKeydown}, touchEvents = { 'touchstart': onTouchOrMouseStart, 'touchmove': onTouchOrMouseMove, 'touchend': onTouchOrMouseEnd, 'touchcancel': onTouchOrMouseEnd }, dragEvents = { 'mousedown': onTouchOrMouseStart, 'mousemove': onTouchOrMouseMove, 'mouseup': onTouchOrMouseEnd, 'mouseleave': onTouchOrMouseEnd }, hasControls = checkOption('controls'), hasNav = checkOption('nav'), hasAutoplay = checkOption('autoplay'), hasTouch = checkOption('touch'), hasMouseDrag = checkOption('mouseDrag'); // controls if (hasControls) { var controls = getOption('controls'), controlsText = getOption('controlsText'), controlsContainer = options.controlsContainer, prevButton, nextButton, prevIsButton, nextIsButton; } // nav if (hasNav) { var nav = getOption('nav'), navContainer = options.navContainer, // navAnimationIn = options.navAnimationIn, // navAnimationOut = options.navAnimationOut, navItems, visibleNavIndexes = [], visibleNavIndexesCached = visibleNavIndexes, navClicked = -1, navCurrentIndex = 0, navCurrentIndexCached = 0; } // autoplay if (hasAutoplay) { var autoplay = getOption('autoplay'), autoplayTimeout = getOption('autoplayTimeout'), autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1, autoplayText = getOption('autoplayText'), autoplayHoverPause = getOption('autoplayHoverPause'), autoplayTimer, autoplayButton = options.autoplayButton, animating = false, autoplayHoverStopped = false, autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'], autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'), autoplayResetVisibilityState = false; } // touch if (hasTouch) { var touch = getOption('touch'), startX = null, startY = null, translateInit, disX, disY; } // mouse drag if (hasMouseDrag) { var mouseDrag = getOption('mouseDrag'), isDragEvent = false; } // disable slider when slidecount <= items if (freeze) { controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = autoplayResetOnVisibility = false; } if (TRANSFORM) { transformAttr = TRANSFORM; transformPrefix = 'translate'; transformPrefix += horizontal ? 'X(' : 'Y('; transformPostfix = ')'; } // === COMMON FUNCTIONS === // function checkOption(item) { var result = options[item]; if (!result && breakpoints && responsiveItems.indexOf(item) >= 0) { breakpoints.forEach(function (bp) { if (responsive[bp][item]) { result = true; } }); } return result; } function getOption(item, view) { view = view ? view : vpOuter; var result; if (item === 'items' && getOption('fixedWidth')) { result = Math.floor(view / (getOption('fixedWidth') + getOption('gutter'))); } else if (item === 'slideBy' && !carousel) { result = 'page'; } else if (item === 'edgePadding' && !carousel) { result = false; } else if (item === 'autoHeight' && (!carousel || nested === 'outer')) { result = true; } else { result = options[item]; if (breakpoints && responsiveItems.indexOf(item) >= 0) { for (var i = 0, len = breakpoints.length; i < len; i++) { var bp = breakpoints[i]; if (view >= bp) { if (item in responsive[bp]) { result = responsive[bp][item]; } } else { break; } } } } if (item === 'items') { result = Math.max(1, Math.min(slideCount, result)); } if (item === 'slideBy' && result === 'page') { result = getOption('items'); } return result; } function getSlideMarginLeft(i) { var str = CALC ? CALC + '(' + i * 100 + '% / ' + slideCountNew + ')' : i * 100 / slideCountNew + '%'; return str; } function getInnerWrapperStyles(edgePaddingTem, gutterTem, fixedWidthTem) { var str = ''; if (edgePaddingTem) { var gap = edgePaddingTem; if (gutterTem) { gap += gutterTem; } if (fixedWidthTem) { str = 'margin: 0px ' + (vpOuter%(fixedWidthTem + gutterTem) + gutterTem) / 2 + 'px'; } else { str = horizontal ? 'margin: 0 ' + edgePaddingTem + 'px 0 ' + gap + 'px;' : 'padding: ' + gap + 'px 0 ' + edgePaddingTem + 'px 0;'; } } else if (gutterTem && !fixedWidthTem) { var dir = horizontal ? 'right' : 'bottom'; str = 'margin-' + dir + ': -' + gutterTem + 'px;'; } return str; } function getContainerWidth(fixedWidthTem, gutterTem, itemsTem) { itemsTem = Math.min(slideCount, itemsTem); var str; if (fixedWidthTem) { str = (fixedWidthTem + gutterTem) * slideCountNew + 'px'; } else { str = CALC ? CALC + '(' + slideCountNew * 100 + '% / ' + itemsTem + ')' : slideCountNew * 100 / itemsTem + '%'; } return str; } function getSlideWidthStyle(fixedWidthTem, gutterTem, itemsTem) { itemsTem = Math.min(slideCount, itemsTem); var str = ''; if (horizontal) { str = 'width:'; if (fixedWidthTem) { str += (fixedWidthTem + gutterTem) + 'px'; } else { var dividend = carousel ? slideCountNew : Math.min(slideCount, itemsTem); str += CALC ? CALC + '(100% / ' + dividend + ')' : 100 / dividend + '%'; } str += importantStr + ';'; } return str; } function getSlideGutterStyle(gutterTem) { var str = ''; // gutter maybe interger || 0 // so can't use 'if (gutter)' if (gutterTem !== false) { var prop = horizontal ? 'padding-' : 'margin-', dir = horizontal ? 'right' : 'bottom'; str = prop + dir + ': ' + gutterTem + 'px;'; } return str; } (function sliderInit() { // First thing first, wrap container with 'outerWrapper > innerWrapper', // to get the correct view width outerWrapper.appendChild(innerWrapper); containerParent.insertBefore(outerWrapper, container); innerWrapper.appendChild(container); vpInner = innerWrapper.clientWidth; var dataOuter = 'tns-outer', dataInner = 'tns-inner', dataContainer = ' tns-slider tns-' + options.mode; if (carousel) { if (horizontal) { if (checkOption('edgePadding') || checkOption('gutter') && !options.fixedWidth) { dataOuter += ' tns-ovh'; } else { dataInner += ' tns-ovh'; } } else { dataInner += ' tns-ovh'; } // } else { // dataOuter += ' tns-hdx'; } outerWrapper.className = dataOuter; innerWrapper.className = dataInner; innerWrapper.id = slideId + '-iw'; if (autoHeight) { innerWrapper.className += ' tns-ah'; innerWrapper.style[TRANSITIONDURATION] = speed / 1000 + 's'; } // set container properties if (container.id === '') { container.id = slideId; } dataContainer += SUBPIXEL ? ' tns-subpixel' : ' tns-no-subpixel'; dataContainer += CALC ? ' tns-calc' : ' tns-no-calc'; if (carousel) { dataContainer += ' tns-' + options.axis; } container.className += dataContainer; // add event if (carousel && TRANSITIONEND) { var eve = {}; eve[TRANSITIONEND] = onTransitionEnd; addEvents(container, eve); } // delete datas after init dataOuter = dataInner = dataContainer = null; // add id, class, aria attributes // before clone slides for (var x = 0; x < slideCount; x++) { var item = slideItems[x]; item.id = slideId + '-item' + x; item.classList.add('tns-item'); if (!carousel && animateNormal) { item.classList.add(animateNormal); } setAttrs(item, { 'aria-hidden': 'true', 'tabindex': '-1' }); } // clone slides if (loop || edgePadding) { var fragmentBefore = doc.createDocumentFragment(), fragmentAfter = doc.createDocumentFragment(); for (var j = cloneCount; j--;) { var num = j%slideCount, cloneFirst = slideItems[num].cloneNode(true); removeAttrs(cloneFirst, 'id'); fragmentAfter.insertBefore(cloneFirst, fragmentAfter.firstChild); if (carousel) { var cloneLast = slideItems[slideCount - 1 - num].cloneNode(true); removeAttrs(cloneLast, 'id'); fragmentBefore.appendChild(cloneLast); } } container.insertBefore(fragmentBefore, container.firstChild); container.appendChild(fragmentAfter); slideItems = container.children; } // activate visible slides // add aria attrs // set animation classes and left value for gallery slider for (var i = index; i < index + items; i++) { var item = slideItems[i]; setAttrs(item, {'aria-hidden': 'false'}); removeAttrs(item, ['tabindex']); if (!carousel) { item.style.left = (i - index) * 100 / items + '%'; item.classList.remove(animateNormal); item.classList.add(animateIn); } } if (carousel && horizontal) { // set font-size rules // for modern browsers // run once if (SUBPIXEL) { var cssFontSize = win.getComputedStyle(slideItems[0]).fontSize; // em, rem to px (for IE8-) if (cssFontSize.indexOf('em') > 0) { cssFontSize = parseFloat(cssFontSize) * 16 + 'px'; } addCSSRule(sheet, '#' + slideId, 'font-size:0;', getCssRulesLength(sheet)); addCSSRule(sheet, '#' + slideId + ' > .tns-item', 'font-size:' + cssFontSize + ';', getCssRulesLength(sheet)); // slide left margin // for IE8 & webkit browsers (no subpixel) } else { [].forEach.call(slideItems, function (slide, i) { slide.style.marginLeft = getSlideMarginLeft(i); }); } } if (CSSMQ) { // inner wrapper styles var str = getInnerWrapperStyles(options.edgePadding, options.gutter, options.fixedWidth); addCSSRule(sheet, '#' + slideId + '-iw', str, getCssRulesLength(sheet)); // container styles if (carousel && horizontal) { str = 'width:' + getContainerWidth(options.fixedWidth, options.gutter, options.items); addCSSRule(sheet, '#' + slideId, str, getCssRulesLength(sheet)); } // slide styles if (horizontal || options.gutter) { str = getSlideWidthStyle(options.fixedWidth, options.gutter, options.items) + getSlideGutterStyle(options.gutter); addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet)); } // non CSS mediaqueries: IE8 // ## update inner wrapper, container, slides if needed // set inline styles for inner wrapper & container // insert stylesheet (one line) for slides only (since slides are many) } else { // inner wrapper styles innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth); // container styles if (carousel && horizontal) { container.style.width = getContainerWidth(fixedWidth, gutter, items); } // slide styles if (horizontal || gutter) { var str = getSlideWidthStyle(fixedWidth, gutter, items) + getSlideGutterStyle(gutter); // append to the last line addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet)); } } if (!horizontal) { getSlideOffsetTops(); updateContentWrapperHeight(); } // media queries if (responsive && CSSMQ) { breakpoints.forEach(function(bp) { var opts = responsive[bp], str = '', innerWrapperStr = '', containerStr = '', slideStr = '', itemsBP = getOption('items', bp), fixedWidthBP = getOption('fixedWidth', bp), edgePaddingBP = getOption('edgePadding', bp), gutterBP = getOption('gutter', bp); // inner wrapper string if ('edgePadding' in opts || 'gutter' in opts) { innerWrapperStr = '#' + slideId + '-iw{' + getInnerWrapperStyles(edgePaddingBP, gutterBP, fixedWidthBP) + '}'; } // container string if (carousel && horizontal && ('fixedWidth' in opts || 'gutter' in opts || 'items' in opts)) { containerStr = '#' + slideId + '{' + 'width:' + getContainerWidth(fixedWidthBP, gutterBP, itemsBP) + '}'; } // slide string if ('fixedWidth' in opts || checkOption('fixedWidth') && 'gutter' in opts) { slideStr += getSlideWidthStyle(fixedWidthBP, gutterBP, itemsBP); } if ('gutter' in opts) { slideStr += getSlideGutterStyle(gutterBP); } if (slideStr.length > 0) { slideStr = '#' + slideId + ' > .tns-item{' + slideStr + '}'; } str = innerWrapperStr + containerStr + slideStr; if (str.length > 0) { sheet.insertRule('@media (min-width: ' + bp / 16 + 'em) {' + str + '}', sheet.cssRules.length); } }); } // set container transform property if (carousel) { doContainerTransform(); } // == msInit == // for IE10 if (navigator.msMaxTouchPoints) { outerWrapper.classList.add('ms-touch'); addEvents(outerWrapper, {'scroll': ie10Scroll}); setSnapInterval(); } // == navInit == if (hasNav) { // customized nav // will not hide the navs in case they're thumbnails if (navContainer) { setAttrs(navContainer, {'aria-label': 'Carousel Pagination'}); navItems = navContainer.children; [].forEach.call(navItems, function (item, index) { setAttrs(item, { 'data-nav': index, 'tabindex': '-1', 'aria-selected': 'false', 'aria-controls': slideId + '-item' + index, }); // if (navAnimationOut) { // item.classList.add(navAnimationOut); // } }); // generated nav } else { var navHtml = ''; // classStr = navAnimationOut ? 'class="' + navAnimationOut + '"' : ''; for (var i = 0; i < slideCount; i++) { // hide nav items by default // navHtml += '<button ' + classStr + ' data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideId + '-item' + i +'" hidden type="button"></button>'; navHtml += '<button data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideId + '-item' + i +'" hidden type="button"></button>'; } navHtml = '<div class="tns-nav" aria-label="Carousel Pagination">' + navHtml + '</div>'; outerWrapper.insertAdjacentHTML('afterbegin', navHtml); navContainer = outerWrapper.querySelector('.tns-nav'); navItems = navContainer.children; updateNavVisibility(); } // add transition if (TRANSITIONDURATION) { var prefix = TRANSITIONDURATION.substring(0, TRANSITIONDURATION.length - 18).toLowerCase(), str = 'transition: all ' + speed / 1000 + 's'; if (prefix) { str = '-' + prefix + '-' + str; } addCSSRule(sheet, '[aria-controls^=' + slideId + '-item]', str, getCssRulesLength(sheet)); } setAttrs(navItems[0], {'tabindex': '0', 'aria-selected': 'true'}); // if (navAnimationOut) { // navItems[0].classList.remove(navAnimationOut); // } // if (navAnimationIn) { // navItems[0].classList.add(navAnimationIn); // } // add events addEvents(navContainer, navEvents); if (!nav) { hideElement(navContainer); } } // == autoplayInit == if (hasAutoplay) { var txt = autoplay ? 'stop' : 'start'; if (autoplayButton) { setAttrs(autoplayButton, {'data-action': txt}); } else if (options.autoplayButtonOutput) { innerWrapper.insertAdjacentHTML('beforebegin', '<button data-action="' + txt + '" type="button">' + autoplayHtmlStrings[0] + txt + autoplayHtmlStrings[1] + autoplayText[0] + '</button>'); autoplayButton = outerWrapper.querySelector('[data-action]'); } // add event if (autoplayButton) { addEvents(autoplayButton, {'click': toggleAnimation}); } if (!autoplay) { if (autoplayButton) { hideElement(autoplayButton); } } else { startAction(); if (autoplayHoverPause) { addEvents(container, hoverEvents); } if (autoplayResetOnVisibility) { addEvents(container, visibilityEvent); } } } // == controlsInit == if (hasControls) { if (controlsContainer) { prevButton = controlsContainer.children[0]; nextButton = controlsContainer.children[1]; setAttrs(controlsContainer, { 'aria-label': 'Carousel Navigation', 'tabindex': '0' }); setAttrs(prevButton, {'data-controls' : 'prev'}); setAttrs(nextButton, {'data-controls' : 'next'}); setAttrs(controlsContainer.children, { 'aria-controls': slideId, 'tabindex': '-1', }); } else { outerWrapper.insertAdjacentHTML('afterbegin', '<div class="tns-controls" aria-label="Carousel Navigation" tabindex="0"><button data-controls="prev" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[0] + '</button><button data-controls="next" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[1] + '</button></div>'); controlsContainer = outerWrapper.querySelector('.tns-controls'); prevButton = controlsContainer.children[0]; nextButton = controlsContainer.children[1]; } prevIsButton = isButton(prevButton); nextIsButton = isButton(nextButton); if (!loop) { disEnableElement(prevIsButton, prevButton, true); } // add events addEvents(controlsContainer, controlsEvents); if (!controls) { hideElement(controlsContainer); } } if (touch) { addEvents(container, touchEvents); } if (mouseDrag) { addEvents(container, dragEvents); } if (arrowKeys) { addEvents(doc, docmentKeydownEvent); } if (nested === 'inner') { events.on('outerResized', function () { resizeTasks(); events.emit('innerLoaded', info()); }); } else { addEvents(win, {'resize': onResize}); if (nested === 'outer') { events.on('innerLoaded', runAutoHeight); } } lazyLoad(); runAutoHeight(); checkFixedWidthSlideCount(); if (typeof onInit === 'function') { onInit(info()); } if (nested === 'inner') { events.emit('innerLoaded', info()); } })(); // === ON RESIZE === function onResize(e) { e = e || win.event; clearTimeout(resizeTimer); resizeTimer = setTimeout(function () { if (vpOuter !== outerWrapper.clientWidth) { resizeTasks(); if (nested === 'outer') { events.emit('outerResized', info(e)); } } }, 100); // update after stop resizing for 100 ms } function resizeTasks() { var breakpointZoneTem = breakpointZone, indexTem = index, itemsTem = items, freezeTem = freeze; vpOuter = outerWrapper.clientWidth; vpInner = innerWrapper.clientWidth; if (breakpoints) { breakpointZone = getBreakpointZone(); } // things do when breakpoint zone change if (breakpointZoneTem !== breakpointZone || fixedWidth) { var slideByTem = slideBy, arrowKeysTem = arrowKeys, autoHeightTem = autoHeight, fixedWidthTem = fixedWidth, edgePaddingTem = edgePadding, gutterTem = gutter; // get options for current breakpoint zone var opts = breakpointZone > 0 ? responsive[breakpoints[breakpointZone - 1]] : options; // update variables items = getOption('items'); slideBy = getOption('slideBy'); freeze = slideCount <= items; if (items !== itemsTem) { indexMax = slideCountNew - items - indexAdjust; // check index before transform in case // slider reach the right edge then items become bigger checkIndex(); } if (freeze !== freezeTem && freeze) { // reset index to initial status index = !carousel ? 0 : cloneCount; } if (breakpointZoneTem !== breakpointZone) { speed = opts.speed || getOption('speed'); edgePadding = opts.edgePadding || getOption('edgePadding'); gutter = opts.gutter || getOption('gutter'); fixedWidth = opts.fixedWidth || getOption('fixedWidth'); if (fixedWidth !== fixedWidthTem) { doContainerTransform(); } autoHeight = getOption('autoHeight'); if (autoHeight !== autoHeightTem) { if (!autoHeight) { innerWrapper.style.height = ''; } } } arrowKeys = freeze ? false : opts.arrowKeys || getOption('arrowKeys'); if (arrowKeys !== arrowKeysTem) { arrowKeys ? addEvents(doc, docmentKeydownEvent) : removeEvents(doc, docmentKeydownEvent); } if (hasControls) { var controlsTem = controls, controlsTextTem = controlsText; controls = freeze ? false : opts.controls || getOption('controls'); controlsText = opts.controlsText || getOption('controlsText'); if (controls !== controlsTem) { controls ? showElement(controlsContainer) : hideElement(controlsContainer); } if (controlsText !== controlsTextTem) { prevButton.innerHTML = controlsText[0]; nextButton.innerHTML = controlsText[1]; } } if (hasNav) { var navTem = nav; nav = freeze ? false : opts.nav || getOption('nav'); if (nav !== navTem) { if (nav) { showElement(navContainer); updateNavVisibility(); } else { hideElement(navContainer); } } } if (hasTouch) { var touchTem = touch; touch = freeze ? false : opts.touch || getOption('touch'); if (touch !== touchTem && carousel) { touch ? addEvents(container, touchEvents) : removeEvents(container, touchEvents); } } if (hasMouseDrag) { var mouseDragTem = mouseDrag; mouseDrag = freeze ? false : opts.mouseDrag || getOption('mouseDrag'); if (mouseDrag !== mouseDragTem && carousel) { mouseDrag ? addEvents(container, dragEvents) : removeEvents(container, dragEvents); } } if (hasAutoplay) { var autoplayTem = autoplay, autoplayHoverPauseTem = autoplayHoverPause, autoplayResetOnVisibilityTem = autoplayResetOnVisibility, autoplayTextTem = autoplayText; if (freeze) { autoplay = autoplayHoverPause = autoplayResetOnVisibility = false; } else { autoplay = opts.autoplay || getOption('autoplay'); if (autoplay) { autoplayHoverPause = opts.autoplayHoverPause || getOption('autoplayHoverPause'); autoplayResetOnVisibility = opts.autoplayResetOnVisibility || getOption('autoplayResetOnVisibility'); } else { autoplayHoverPause = autoplayResetOnVisibility = false; } } autoplayText = opts.autoplayText || getOption('autoplayText'); autoplayTimeout = opts.autoplayTimeout || getOption('autoplayTimeout'); if (autoplay !== autoplayTem) { if (autoplay) { if (autoplayButton) { showElement(autoplayButton); } if (!animating) { startAction(); } } else { if (autoplayButton) { hideElement(autoplayButton); } if (animating) { stopAction(); } } } if (autoplayHoverPause !== autoplayHoverPauseTem) { autoplayHoverPause ? addEvents(container, hoverEvents) : removeEvents(container, hoverEvents); } if (autoplayResetOnVisibility !== autoplayResetOnVisibilityTem) { autoplayResetOnVisibility ? addEvents(doc, visibilityEvent) : removeEvents(doc, visibilityEvent); } if (autoplayButton && autoplayText !== autoplayTextTem) { var i = autoplay ? 1 : 0, html = autoplayButton.innerHTML, len = html.length - autoplayTextTem[i].length; if (html.substring(len) === autoplayTextTem[i]) { autoplayButton.innerHTML = html.substring(0, len) + autoplayText[i]; } } } // IE8 // ## update inner wrapper, container, slides if needed // set inline styles for inner wrapper & container // insert stylesheet (one line) for slides only (since slides are many) if (!CSSMQ) { // inner wrapper styles if (edgePadding !== edgePaddingTem || gutter !== gutterTem) { innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth); } // container styles if (carousel && horizontal && (fixedWidth !== fixedWidthTem || gutter !== gutterTem || items !== itemsTem)) { container.style.width = getContainerWidth(fixedWidth, gutter, items); } // slide styles // always need to get width property var str = getSlideWidthStyle(fixedWidth, gutter, items); if (gutter !== gutterTem) { str += getSlideGutterStyle(gutter); } // remove the last line and // add it again if (str.length > 0) { sheet.removeRule(getCssRulesLength(sheet) - 1); addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet)); } // will do transform later if index !== indexTem // make sure doTransform will only run once if (!fixedWidth && index === indexTem) { doTransform(0); } } if (index !== indexTem) { events.emit('indexChanged', info()); doTransform(0); indexCached = index; } if (items !== itemsTem) { lazyLoad(); updateSlideStatus(); updateControlsStatus(); updateNavVisibility(); updateNavStatus(); if (navigator.msMaxTouchPoints) { setSnapInterval(); } } } // things always do regardless of breakpoint zone changing if (!horizontal) { getSlideOffsetTops(); updateContentWrapperHeight(); doContainerTransform(); } checkFixedWidthSlideCount(); // auto height runAutoHeight(); } // === INITIALIZATION FUNCTIONS === // function getBreakpointZone() { breakpointZone = 0; breakpoints.forEach(function(bp, i) { if (vpOuter >= bp) { breakpointZone = i + breakpointZoneAdjust; } }); return breakpointZone; } // (slideBy, indexMin, indexMax) => index var checkIndex = (function () { if (loop) { return function () { var leftEdge = indexMin, rightEdge = indexMax; if (carousel) { leftEdge += slideBy; rightEdge -= slideBy; } var gt = gutter ? gutter : 0; if (fixedWidth && vpOuter%(fixedWidth + gt) > gt) { rightEdge -= 1; } if (index > rightEdge) { while(index >= leftEdge + slideCount) { index -= slideCount; } } else if(index < leftEdge) { while(index <= rightEdge - slideCount) { index += slideCount; } } }; } else { return function () { index = Math.max(indexMin, Math.min(indexMax, index)); }; } })(); function checkFixedWidthSlideCount() { if (fixedWidth && cloneCount) { if (freeze) { if (!slideItems[0].classList.contains('tns-transparent')) { // remove edge padding from inner wrapper if (edgePadding) { innerWrapper.style.margin = '0'; } // add class tns-transparent to cloned slides for (var i = cloneCount; i--;) { slideItems[i].classList.add('tns-transparent'); slideItems[slideCountNew - i - 1].classList.add('tns-transparent'); } } } else { // restore edge padding for inner wrapper if (edgePadding) { if (vpOuter <= (fixedWidth + gutter)) { if (innerWrapper.style.margin !== '0px') { innerWrapper.style.margin = '0'; } } else { innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth); } } if (slideItems[0].classList.contains('tns-transparent')) { // remove class tns-transparent to cloned slides for (var i = cloneCount; i--;) { slideItems[i].classList.remove('tns-transparent'); slideItems[slideCountNew - i - 1].classList.remove('tns-transparent'); } } } } } function mouseoverPause() { if (animating) { stopAction(); autoplayHoverStopped = true; } } function mouseoutRestart() { if (!animating && autoplayHoverStopped) { startAction(); autoplayHoverStopped = false; } } // lazyload function lazyLoad() { if (lazyload) { var i = index, len = index + items; if (edgePadding) { i -=1; len +=1; } for(; i < len; i++) { [].forEach.call(slideItems[i].querySelectorAll('.tns-lazy-img'), function (img) { // stop propagationl transitionend event to container var eve = {}; eve[TRANSITIONEND] = function (e) { e.stopPropagation(); }; addEvents(img, eve); if (!img.classList.contains('loaded')) { img.src = getAttr(img, 'data-src'); img.classList.add('loaded'); } }); } } } // check if all visible images are loaded // and update container height if it's done function runAutoHeight() { if (!autoHeight) { return; } // get all images inside visible slide items var images = []; for (var i = index; i < index + items; i++) { [].forEach.call(slideItems[i].querySelectorAll('img'), function (img) { images.push(img); }); } if (images.length === 0) { updateInnerWrapperHeight(); } else { checkImagesLoaded(images); } } function checkImagesLoaded(images) { images.forEach(function (img, index) { if (imageLoaded(img)) { images.splice(index, 1); } }); if (images.length === 0) { updateInnerWrapperHeight(); } else { setTimeout(function () { checkImagesLoaded(images); }, 16); } } // update inner wrapper height // 1. get the max-height of the visible slides // 2. set transitionDuration to speed // 3. update inner wrapper height to max-height // 4. set transitionDuration to 0s after transition done function updateInnerWrapperHeight() { var heights = [], maxHeight; for (var i = index; i < index + items; i++) { heights.push(slideItems[i].offsetHeight); } maxHeight = Math.max.apply(null, heights); if (innerWrapper.style.height !== maxHeight) { if (TRANSITIONDURATION) { setDurations(speed); } innerWrapper.style.height = maxHeight + 'px'; } } // get the distance from the top edge of the first slide to each slide // (init) => slideOffsetTops function getSlideOffsetTops() { slideOffsetTops = [0]; var topFirst = slideItems[0].getBoundingClientRect().top, attr; for (var i = 1; i < slideCountNew; i++) { attr = slideItems[i].getBoundingClientRect().top; slideOffsetTops.push(attr - topFirst); } } // set snapInterval (for IE10) function setSnapInterval() { outerWrapper.style.msScrollSnapPointsX = 'snapInterval(0%, ' + (100 / items) + '%)'; } // update slide function updateSlideStatus() { for (var i = slideCountNew; i--;) { var item = slideItems[i]; // visible slides if (i >= index && i < index + items) { if (hasAttr(item, 'tabindex')) { setAttrs(item, {'aria-hidden': 'false'}); removeAttrs(item, ['tabindex']); } // hidden slides } else { if (!hasAttr(item, 'tabindex')) { setAttrs(item, { 'aria-hidden': 'true', 'tabindex': '-1' }); } } } } // set tabindex & aria-selected on Nav function updateNavStatus() { // get current nav if (nav) { navCurrentIndex = navClicked !== -1 ? navClicked : (index - indexAdjust)%slideCount; navClicked = -1; if (navCurrentIndex !== navCurrentIndexCached) { var navPrev = navItems[navCurrentIndexCached], navCurrent = navItems[navCurrentIndex]; setAttrs(navPrev, { 'tabindex': '-1', 'aria-selected': 'false' }); setAttrs(navCurrent, { 'tabindex': '0', 'aria-selected': 'true' }); // if (navAnimationOut) { // navPrev.classList.remove(navAnimationIn); // navPrev.classList.add(navAnimationOut); // } // if (navAnimationIn) { // navCurrent.classList.remove(navAnimationOut); // navCurrent.classList.add(navAnimationIn); // } } } } function isButton(el) { return el.nodeName.toLowerCase() === 'button'; } function isAriaDisabled(el) { return el.getAttribute('aria-disabled') === 'true'; } function disEnableElement(isButton, el, val) { if (isButton) { el.disabled = val; } else { el.setAttribute('aria-disabled', val.toString()); } } // set 'disabled' to true on controls when reach the edges function updateControlsStatus() { if (!controls || loop) { return; } var prevDisabled = (prevIsButton) ? prevButton.disabled : isAriaDisabled(prevButton), nextDisabled = (nextIsButton) ? nextButton.disabled : isAriaDisabled(nextButton), disablePrev = (index === indexMin) ? true : false, disableNext = (!rewind && index === indexMax) ? true : false; if (disablePrev && !prevDisabled) { disEnableElement(prevIsButton, prevButton, true); } if (!disablePrev && prevDisabled) { disEnableElement(prevIsButton, prevButton, false); } if (disableNext && !nextDisabled) { disEnableElement(nextIsButton, nextButton, true); } if (!disableNext && nextDisabled) { disEnableElement(nextIsButton, nextButton, false); } } // set duration function setDurations (duration, target) { duration = !duration ? '' : duration / 1000 + 's'; target = target || container; target.style[TRANSITIONDURATION] = duration; if (!carousel) { target.style[ANIMATIONDURATION] = duration; } if (!horizontal) { innerWrapper.style[TRANSITIONDURATION] = duration; } } function getContainerTransformValue() { var val; if (horizontal) { if (fixedWidth) { val = - (fixedWidth + gutter) * index + 'px'; } else { var denominator = TRANSFORM ? slideCountNew : items; val = - index * 100 / denominator + '%'; } } else { val = - slideOffsetTops[index] + 'px'; } return val; } function doContainerTransform(val) { if (!val) { val = getContainerTransformValue(); } container.style[transformAttr] = transformPrefix + val + transformPostfix; } function animateSlide(number, classOut, classIn, isOut) { for (var i = number, l = number + items; i < l; i++) { var item = slideItems[i]; // set item positions if (!isOut) { item.style.left = (i - index) * 100 / items + '%'; } if (TRANSITIONDURATION) { setDurations(speed, item); } if (animateDelay && TRANSITIONDELAY) { item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = animateDelay * (i - number) / 1000 + 's'; } item.classList.remove(classOut); item.classList.add(classIn); if (isOut) { slideItemsOut.push(item); } } } // make transfer after click/drag: // 1. change 'transform' property for mordern browsers // 2. change 'left' property for legacy browsers var transformCore = (function () { // carousel if (carousel) { return function (duration, distance) { if (!distance) { distance = getContainerTransformValue(); } // constrain the distance when non-loop no-edgePadding fixedWidth reaches the right edge if (hasRightDeadZone && index === indexMax) { var containerRightEdge = TRANSFORM ? - ((slideCountNew - items) / slideCountNew) * 100 : - (slideCountNew / items - 1) * 100; distance = Math.max(parseFloat(distance), containerRightEdge) + '%'; } if (TRANSITIONDURATION || !duration) { doContainerTransform(distance); if (speed === 0) { onTransitionEnd(); } } else { jsTransform(container, transformAttr, transformPrefix, transformPostfix, distance, speed, onTransitionEnd); } if (!horizontal) { updateContentWrapperHeight(); } }; // gallery } else { return function () { slideItemsOut = []; var eve = {}; eve[TRANSITIONEND] = eve[ANIMATIONEND] = onTransitionEnd; removeEvents(slideItems[indexCached], eve); addEvents(slideItems[index], eve); animateSlide(indexCached, animateIn, animateOut, true); animateSlide(index, animateNormal, animateIn); if (!TRANSITIONEND || !ANIMATIONEND || speed === 0) { setTimeout(onTransitionEnd, 0); } }; } })(); function doTransform (duration, distance) { if (duration === undefined) { duration = speed; } if (TRANSITIONDURATION) { setDurations(duration); } transformCore(duration, distance); updateSlideStatus(); // loop: update nav visibility when visibleNavIndexes doesn't contain current index if (nav && visibleNavIndexes.indexOf(index%slideCount) < 0) { updateNavVisibility(); } updateNavStatus(); updateControlsStatus(); lazyLoad(); } function render() { if (checkIndexBeforeTransform) { checkIndex(); } if (index !== indexCached) { // events events.emit('indexChanged', info()); events.emit('transitionStart', info()); running = true; doTransform(); } } // AFTER TRANSFORM // Things need to be done after a transfer: // 1. check index // 2. add classes to visible slide // 3. disable controls buttons when reach the first/last slide in non-loop slider // 4. update nav status // 5. lazyload images // 6. update container height function onTransitionEnd(event) { events.emit('transitionEnd', info(event)); if (!carousel && slideItemsOut.length > 0) { for (var i = 0; i < items; i++) { var item = slideItemsOut[i]; // set item positions item.style.left = ''; if (TRANSITIONDURATION) { setDurations(0, item); } if (animateDelay && TRANSITIONDELAY) { item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = ''; } item.classList.remove(animateOut); item.classList.add(animateNormal); } } /* * Transfer prefixed properties to the same format * CSS: -Webkit-Transform => webkittransform * JS: WebkitTransform => webkittransform * @param {string} str - property * */ function strTrans(str) { return str.toLowerCase().replace(/-/g, ''); } /* update slides, nav, controls after checking ... * => legacy browsers who don't support 'event' * have to check event first, otherwise event.target will cause an error * => or 'gallery' mode: * + event target is slide item * => or 'carousel' mode: * + event target is container, * + event.property is the same with transform attribute */ if (!event || !carousel && event.target.parentNode === container || event.target === container && strTrans(event.propertyName) === strTrans(transformAttr)) { if (!checkIndexBeforeTransform) { var indexTem = index; checkIndex(); if (index !== indexTem) { if (TRANSITIONDURATION) { setDurations(0); } doContainerTransform(); events.emit('indexChanged', info()); } } runAutoHeight(); if (nested === 'inner') { events.emit('innerLoaded', info()); } running = false; navCurrentIndexCached = navCurrentIndex; indexCached = index; } } // # ACTIONS function goTo (targetIndex) { if (freeze) { return; } // prev slideBy if (targetIndex === 'prev') { onControlsClick(null, -1); // next slideBy } else if (targetIndex === 'next') { onControlsClick(null, 1); // go to exact slide } else if (!running) { var absIndex = index%slideCount, indexGap = 0; if (!loop && checkOption('edgePadding')) { absIndex--; } if (absIndex < 0) { absIndex += slideCount; } if (targetIndex === 'first') { indexGap = - absIndex; } else if (targetIndex === 'last') { indexGap = slideCount - items - absIndex; } else { if (typeof targetIndex !== 'number') { targetIndex = parseInt(targetIndex); } if (!isNaN(targetIndex)) { var absTargetIndex = targetIndex%slideCount; if (absTargetIndex < 0) { absTargetIndex += slideCount; } if (!loop && edgePadding) { absTargetIndex += 1; } indexGap = absTargetIndex - absIndex; } } index += indexGap; // if index is changed, start rendering if (index%slideCount !== indexCached%slideCount) { render(); } } } // on controls click function onControlsClick(e, dir) { if (!running) { var shouldRender; if (!dir) { e = e || win.event; var target = e.target || e.srcElement; while (target !== controlsContainer && [prevButton, nextButton].indexOf(target) < 0) { target = target.parentNode; } } if (target && target === prevButton || dir === -1) { if (index > indexMin) { index -= slideBy; shouldRender = true; } } else if (target && target === nextButton || dir === 1) { // Go to the first if reach the end in rewind mode // Otherwise go to the next if (rewind && index === indexMax){ goTo(0); } else if (index < indexMax) { index += slideBy; shouldRender = true; } } if (shouldRender) { render(); } } } // on nav click function onNavClick(e) { if (!running) { e = e || win.event; var target = e.target || e.srcElement, navIndex; // find the clicked nav item while (target !== navContainer && !hasAttr(target, 'data-nav')) { target = target.parentNode; } if (hasAttr(target, 'data-nav')) { navIndex = navClicked = [].indexOf.call(navItems, target); goTo(navIndex); } } } function updateAutoplayButton(action, txt) { setAttrs(autoplayButton, {'data-action': action}); autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt; } function startAction() { resetActionTimer(); if (autoplayButton) { updateAutoplayButton('stop', autoplayText[1]); } animating = true; } function stopAction() { pauseActionTimer(); if (autoplayButton) { updateAutoplayButton('start', autoplayText[0]); } animating = false; } function pauseActionTimer() { animating = 'paused'; clearInterval(autoplayTimer); } function resetActionTimer() { if (animating === true) { return; } clearInterval(autoplayTimer); autoplayTimer = setInterval(function () { onControlsClick(null, autoplayDirection); }, autoplayTimeout); } function toggleAnimation() { if (animating) { stopAction(); } else { startAction(); } } function onVisibilityChange() { if (autoplayResetVisibilityState != doc.hidden && animating !== false) { doc.hidden ? pauseActionTimer() : resetActionTimer(); } autoplayResetVisibilityState = doc.hidden; } // keydown events on document function onDocumentKeydown(e) { e = e || win.event; switch(e.keyCode) { case KEYS.LEFT: onControlsClick(null, -1); break; case KEYS.RIGHT: onControlsClick(null, 1); } } // on key control function onControlsKeydown(e) { e = e || win.event; var code = e.keyCode; switch (code) { case KEYS.LEFT: case KEYS.UP: case KEYS.PAGEUP: if (!prevButton.disabled) { onControlsClick(null, -1); } break; case KEYS.RIGHT: case KEYS.DOWN: case KEYS.PAGEDOWN: if (!nextButton.disabled) { onControlsClick(null, 1); } break; case KEYS.HOME: goTo(0); break; case KEYS.END: goTo(slideCount - 1); break; } } // set focus function setFocus(focus) { focus.focus(); } // on key nav function onNavKeydown(e) { var curElement = doc.activeElement; if (!hasAttr(curElement, 'data-nav')) { return; } e = e || win.event; var code = e.keyCode, navIndex = [].indexOf.call(navItems, curElement), len = visibleNavIndexes.length, current = visibleNavIndexes.indexOf(navIndex); if (options.navContainer) { len = slideCount; current = navIndex; } function getNavIndex(num) { return options.navContainer ? num : visibleNavIndexes[num]; } switch(code) { case KEYS.LEFT: case KEYS.PAGEUP: if (current > 0) { setFocus(navItems[getNavIndex(current - 1)]); } break; case KEYS.UP: case KEYS.HOME: if (current > 0) { setFocus(navItems[getNavIndex(0)]); } break; case KEYS.RIGHT: case KEYS.PAGEDOWN: if (current < len - 1) { setFocus(navItems[getNavIndex(current + 1)]); } break; case KEYS.DOWN: case KEYS.END: if (current < len - 1) { setFocus(navItems[getNavIndex(len - 1)]); } break; // Can't use onNavClick here, // Because onNavClick require event.target as nav items case KEYS.ENTER: case KEYS.SPACE: navClicked = navIndex; goTo(navIndex); break; } } // IE10 scroll function function ie10Scroll() { doTransform(0, container.scrollLeft()); indexCached = index; } function getTarget(e) { return e.target || e.srcElement; } function isTouchEvent(e) { return e.type.indexOf('touch') >= 0; } function preventDefaultBehavior(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } function onTouchOrMouseStart(e) { e = e || win.event; var ev; if (isTouchEvent(e)) { ev = e.changedTouches[0]; events.emit('touchStart', info(e)); } else { ev = e; preventDefaultBehavior(e); events.emit('dragStart', info(e)); } startX = parseInt(ev.clientX); startY = parseInt(ev.clientY); translateInit = parseFloat(container.style[transformAttr].replace(transformPrefix, '').replace(transformPostfix, '')); } function onTouchOrMouseMove(e) { e = e || win.event; // make sure touch started or mouse draged if (startX !== null) { var ev; if (isTouchEvent(e)) { ev = e.changedTouches[0]; } else { ev = e; preventDefaultBehavior(e); } disX = parseInt(ev.clientX) - startX; disY = parseInt(ev.clientY) - startY; if (getTouchDirection(toDegree(disY, disX), 15) === options.axis && disX) { if (isTouchEvent(e)) { events.emit('touchMove', info(e)); } else { // "mousemove" event after "mousedown" indecate // it is "drag", not "click" if (!isDragEvent) { isDragEvent = true; } events.emit('dragMove', info(e)); } if (!touchedOrDraged) { touchedOrDraged = true; } var x = translateInit; if (horizontal) { if (fixedWidth) { x += disX; x += 'px'; } else { var percentageX = TRANSFORM ? disX * items * 100 / (vpInner * slideCountNew): disX * 100 / vpInner; x += percentageX; x += '%'; } } else { x += disY; x += 'px'; } if (TRANSFORM) { setDurations(0); } container.style[transformAttr] = transformPrefix + x + transformPostfix; } } } function onTouchOrMouseEnd(e) { e = e || win.event; if (touchedOrDraged) { touchedOrDraged = false; var ev; if (isTouchEvent(e)) { ev = e.changedTouches[0]; events.emit('touchEnd', info(e)); } else { ev = e; events.emit('dragEnd', info(e)); } disX = parseInt(ev.clientX) - startX; disY = parseInt(ev.clientY) - startY; // reset startX, startY startX = startY = null; if (horizontal) { var indexMoved = - disX * items / vpInner; indexMoved = disX > 0 ? Math.floor(indexMoved) : Math.ceil(indexMoved); index += indexMoved; } else { var moved = - (translateInit + disY); if (moved <= 0) { index = indexMin; } else if (moved >= slideOffsetTops[slideOffsetTops.length - 1]) { index = indexMax; } else { var i = 0; do { i++; index = disY < 0 ? i + 1 : i; } while (i < slideCountNew && moved >= slideOffsetTops[i + 1]); } } render(); // drag vs click if (isDragEvent) { // reset isDragEvent isDragEvent = false; // prevent "click" var target = getTarget(e); addEvents(target, {'click': function preventClick(e) { preventDefaultBehavior(e); removeEvents(target, {'click': preventClick}); }}); } } } // === RESIZE FUNCTIONS === // // (slideOffsetTops, index, items) => vertical_conentWrapper.height function updateContentWrapperHeight() { innerWrapper.style.height = slideOffsetTops[index + items] - slideOffsetTops[index] + 'px'; } /* * get nav item indexes per items * add 1 more if the nav items cann't cover all slides * [0, 1, 2, 3, 4] / 3 => [0, 3] */ function getVisibleNavIndex() { // reset visibleNavIndexes visibleNavIndexes = []; var temIndex = !loop && edgePadding ? (index - 1) : index; var absIndexMin = temIndex%slideCount%items; while (absIndexMin < slideCount) { if (!loop && absIndexMin + items > slideCount) { absIndexMin = slideCount - items; } visibleNavIndexes.push(absIndexMin); absIndexMin += items; } // nav count * items < slide count means // some slides can not be displayed only by nav clicking if (loop && visibleNavIndexes.length * items < slideCount || !loop && visibleNavIndexes[0] > 0) { visibleNavIndexes.unshift(0); } } /* * 1. update visible nav items list * 2. add "hidden" attributes to previous visible nav items * 3. remove "hidden" attrubutes to new visible nav items */ function updateNavVisibility() { if (!nav || options.navContainer) { return; } // update visible nav indexes getVisibleNavIndex(); if (visibleNavIndexes !== visibleNavIndexesCached) { // add 'hidden' attribute to previous visible navs if (visibleNavIndexesCached.length > 0) { visibleNavIndexesCached.forEach(function (ind) { setAttrs(navItems[ind], {'hidden': ''}); }); } // remove 'hidden' attribute from visible navs if (visibleNavIndexes.length > 0) { visibleNavIndexes.forEach(function (ind) { removeAttrs(navItems[ind], 'hidden'); }); } // cache visible nav indexes visibleNavIndexesCached = visibleNavIndexes; } } function info(e) { return { container: container, slideItems: slideItems, navContainer: navContainer, navItems: navItems, controlsContainer: controlsContainer, prevButton: prevButton, nextButton: nextButton, items: items, slideBy: slideBy, cloneCount: cloneCount, slideCount: slideCount, slideCountNew: slideCountNew, index: index, indexCached: indexCached, navCurrentIndex: navCurrentIndex, navCurrentIndexCached: navCurrentIndexCached, visibleNavIndexes: visibleNavIndexes, visibleNavIndexesCached: visibleNavIndexesCached, event: e || {}, }; } return { getInfo: info, events: events, goTo: goTo, destroy: function () { // sheet sheet.disabled = true; // cloned items if (loop) { for (var j = cloneCount; j--;) { slideItems[0].remove(); slideItems[slideItems.length - 1].remove(); } } // Slide Items for (var i = slideCount; i--;) { slideItems[i].id = slideItemIdCached || ''; slideItems[i].className = slideItemClassCached || ''; } removeAttrs(slideItems, ['style', 'aria-hidden', 'tabindex']); slideItems = slideId = slideCount = slideCountNew = cloneCount = null; // controls if (controls) { removeEvents(controlsContainer, controlsEvents); if (options.controlsContainer) { removeAttrs(controlsContainer, ['aria-label', 'tabindex']); removeAttrs(controlsContainer.children, ['aria-controls', 'aria-disabled', 'tabindex']); } controlsContainer = prevButton = nextButton = null; } // nav if (nav) { removeEvents(navContainer, navEvents); if (options.navContainer) { removeAttrs(navContainer, ['aria-label']); removeAttrs(navItems, ['aria-selected', 'aria-controls', 'tabindex']); } navContainer = navItems = null; } // auto if (autoplay) { if (autoplayButton) { removeEvents(autoplayButton, {'click': toggleAnimation}); } removeEvents(container, hoverEvents); removeEvents(container, visibilityEvent); if (options.autoplayButton) { removeAttrs(autoplayButton, ['data-action']); } } // container container.id = containerIdCached || ''; container.className = containerClassCached || ''; container.style = ''; if (carousel && TRANSITIONEND) { var eve = {}; eve[TRANSITIONEND] = onTransitionEnd; removeEvents(container, eve); } removeEvents(container, touchEvents); removeEvents(container, dragEvents); // outerWrapper containerParent.insertBefore(container, outerWrapper); outerWrapper.remove(); outerWrapper = innerWrapper = container = null; // remove arrowKeys eventlistener removeEvents(doc, docmentKeydownEvent); // remove win event listeners removeEvents(win, {'resize': onResize}); } }; }; return tns; })();
/*globals describe, beforeEach, it, expect, module, inject, jQuery, moment, spyOn */ /** * @license angular-bootstrap-datetimepicker * Copyright 2013 Knight Rider Consulting, Inc. http://www.knightrider.com * License: MIT */ /** * * @author Dale "Ducky" Lotts * @since 11/8/2014 */ describe('beforeRender', function () { 'use strict'; var $rootScope; var $compile; beforeEach(module('ui.bootstrap.datetimepicker')); beforeEach(inject(function (_$compile_, _$rootScope_) { moment.locale('en'); $compile = _$compile_; $rootScope = _$rootScope_; })); describe('does not throw exception', function () { it('when beforeRender is missing', function () { $compile('<datetimepicker data-ng-model="date"></datetimepicker>')($rootScope); }); it('when beforeRender is not a function', function () { $compile('<datetimepicker data-ng-model="date" data-beforeRender="foo"></datetimepicker>')($rootScope); }); }); describe('called before a new view is rendered', function () { it('in year view $dates parameter contains 12 members', function () { $rootScope.date = moment('2008-01-01T00:00:00.000').toDate(); $rootScope.beforeRender = function (dates) { expect(dates.length).toBe(12); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($dates)\' data-datetimepicker-config="{ startView: \'year\', minView: \'year\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.year', element)[2]); expect(selectedElement.hasClass('disabled')).toBeFalsy(); selectedElement.trigger('click'); expect($rootScope.date).toEqual(moment('2001-01-01T00:00:00.000').toDate()); expect($rootScope.beforeRender).toHaveBeenCalled(); }); it('in month view $dates parameter contains 12 members', function () { $rootScope.date = moment('2008-01-01T00:00:00.000').toDate(); $rootScope.beforeRender = function (dates) { expect(dates.length).toBe(12); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($dates)\' data-datetimepicker-config="{ startView: \'month\', minView: \'month\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.month', element)[4]); expect(selectedElement.hasClass('disabled')).toBeFalsy(); selectedElement.trigger('click'); expect($rootScope.date).toEqual(moment('2008-05-01T00:00:00.000').toDate()); expect($rootScope.beforeRender).toHaveBeenCalled(); }); it('in day view $dates parameter contains 42 members', function () { $rootScope.date = moment('2014-01-01T00:00:00.000').toDate(); var offset = new Date().getTimezoneOffset() * 60000; $rootScope.beforeRender = function (dates) { expect(dates.length).toBe(42); expect(dates[0].utcDateValue).toBe(1388275200000); expect(dates[0].localDateValue()).toBe(1388275200000 + offset); expect(dates[11].utcDateValue).toBe(1389225600000); expect(dates[11].localDateValue()).toBe(1389225600000 + offset); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($dates)\' data-datetimepicker-config="{ startView: \'day\', minView: \'day\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); expect($rootScope.date).toEqual(moment('2014-01-01T00:00:00.000').toDate()); var selectedElement = jQuery(jQuery('.day', element)[11]); expect(jQuery(jQuery('.day', element)[0]).text()).toBe('29'); expect(selectedElement.text()).toBe('9'); expect(selectedElement.hasClass('disabled')).toBeFalsy(); selectedElement.trigger('click'); expect($rootScope.date).toEqual(moment('2014-01-09T00:00:00.000').toDate()); expect($rootScope.beforeRender).toHaveBeenCalled(); }); it('dates parameter has 12 members', function () { $rootScope.date = moment('2008-01-01T00:00:00.000').toDate(); $rootScope.beforeRender = function (dates) { expect(dates).not.toBeUndefined(); expect(dates.length).toEqual(12); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($dates)\' data-datetimepicker-config="{ startView: \'year\', minView: \'year\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.year', element)[2]); expect(selectedElement.hasClass('disabled')).toBeFalsy(); selectedElement.trigger('click'); expect($rootScope.beforeRender).toHaveBeenCalled(); }); it('view parameter is "year"', function () { $rootScope.date = moment('2008-01-01T00:00:00.000').toDate(); $rootScope.beforeRender = function (view) { expect(view).toEqual('year'); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($view)\' data-datetimepicker-config="{ startView: \'year\', minView: \'year\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.year', element)[2]); selectedElement.trigger('click'); expect($rootScope.beforeRender).toHaveBeenCalled(); }); it('$leftDate parameter is the beginning of the previous view', function () { $rootScope.date = moment('2008-01-01T00:00:00.000').toDate(); $rootScope.beforeRender = function ($leftDate) { expect($leftDate).not.toBeUndefined(); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($leftDate)\' data-datetimepicker-config="{ startView: \'year\', minView: \'year\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.year', element)[2]); selectedElement.trigger('click'); expect($rootScope.beforeRender).toHaveBeenCalled(); expect($rootScope.beforeRender.calls.argsFor(0)[0].utcDateValue).toEqual(631152000000); // 1990-01-01 }); it('$rightDate parameter is the beginning of the next view', function () { $rootScope.date = moment('2014-04-01T00:00:00.000').toDate(); $rootScope.beforeRender = function ($rightDate) { expect($rightDate).not.toBeUndefined(); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($rightDate)\' data-datetimepicker-config="{ startView: \'month\', minView: \'month\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.month', element)[2]); selectedElement.trigger('click'); expect($rootScope.beforeRender).toHaveBeenCalled(); expect($rootScope.beforeRender.calls.argsFor(0)[0].utcDateValue).toEqual(1420070400000); // 2015-01-01 }); it('startview = "day" and $upDate parameter is the beginning of the next view up ', function () { // i.e. minute -> hour -> day -> month -> year $rootScope.date = moment('2014-10-18T13:00:00.000').toDate(); $rootScope.beforeRender = function ($upDate) { expect($upDate).not.toBeUndefined(); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($upDate)\' data-datetimepicker-config="{ startView: \'day\', minView: \'day\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); expect($rootScope.beforeRender).toHaveBeenCalled(); expect($rootScope.beforeRender.calls.argsFor(0)[0].utcDateValue).toEqual(1388534400000); // 2014-01-01 - the start of the 'month' view. var selectedElement = jQuery(jQuery('.day', element)[2]); selectedElement.trigger('click'); }); it('startview = "hour" and $upDate parameter is the beginning of the next view up ', function () { // i.e. minute -> hour -> day -> month -> year var $scope = $rootScope.$new(); $scope.date = moment('2014-10-18T13:00:00.000').toDate(); $scope.beforeRender = function ($upDate) { expect($upDate).not.toBeUndefined(); }; spyOn($scope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($upDate)\' data-datetimepicker-config="{ startView: \'hour\', minView: \'hour\' }" ></datetimepicker>')($scope); $rootScope.$digest(); expect($scope.beforeRender).toHaveBeenCalled(); expect($scope.beforeRender.calls.argsFor(0)[0].utcDateValue).toEqual(1412121600000); // 2014-10-01 12:00 the start of the 'day' view var selectedElement = jQuery(jQuery('.hour', element)[2]); selectedElement.trigger('click'); }); it('startview = "minute" and $upDate parameter is the beginning of the next view up ', function () { // i.e. minute -> hour -> day -> month -> year $rootScope.date = moment('2014-10-18T13:00:00.000').toDate(); $rootScope.beforeRender = function ($upDate) { expect($upDate).not.toBeUndefined(); }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($upDate)\' data-datetimepicker-config="{ startView: \'minute\', minView: \'minute\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); expect($rootScope.beforeRender).toHaveBeenCalled(); expect($rootScope.beforeRender.calls.argsFor(0)[0].utcDateValue).toEqual(1413590400000); // 2014-10-18 00:00 Z var selectedElement = jQuery(jQuery('.minute', element)[2]); selectedElement.trigger('click'); }); it('year view and 2001 date is disabled', function () { $rootScope.date = moment('2008-01-01T00:00:00.000').toDate(); $rootScope.beforeRender = function (dates) { dates[2].selectable = false; }; spyOn($rootScope, 'beforeRender').and.callThrough(); var element = $compile('<datetimepicker data-ng-model=\'date\' data-before-render=\'beforeRender($dates)\' data-datetimepicker-config="{ startView: \'year\', minView: \'year\' }" ></datetimepicker>')($rootScope); $rootScope.$digest(); var selectedElement = jQuery(jQuery('.year', element)[2]); expect(selectedElement.hasClass('disabled')).toBeTruthy(); selectedElement.trigger('click'); // No change if clicked! expect($rootScope.beforeRender).toHaveBeenCalled(); expect($rootScope.date).toEqual(moment('2008-01-01T00:00:00.000').toDate()); }); }); });
const logger = new Logger('steffo:meteor-accounts-saml', { methods: { updated: { type: 'info' } } }); RocketChat.settings.addGroup('SAML'); Meteor.methods({ addSamlService(name) { RocketChat.settings.add(`SAML_Custom_${ name }`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Enable' }); RocketChat.settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Provider' }); RocketChat.settings.add(`SAML_Custom_${ name }_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Entry_point' }); RocketChat.settings.add(`SAML_Custom_${ name }_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_IDP_SLO_Redirect_URL' }); RocketChat.settings.add(`SAML_Custom_${ name }_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Issuer' }); RocketChat.settings.add(`SAML_Custom_${ name }_cert`, '', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Cert', multiline: true }); RocketChat.settings.add(`SAML_Custom_${ name }_public_cert`, '', { type: 'string', group: 'SAML', section: name, multiline: true, i18nLabel: 'SAML_Custom_Public_Cert' }); RocketChat.settings.add(`SAML_Custom_${ name }_private_key`, '', { type: 'string', group: 'SAML', section: name, multiline: true, i18nLabel: 'SAML_Custom_Private_Key' }); RocketChat.settings.add(`SAML_Custom_${ name }_button_label_text`, '', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text' }); RocketChat.settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color' }); RocketChat.settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Color' }); RocketChat.settings.add(`SAML_Custom_${ name }_generate_username`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Generate_Username' }); } }); const getSamlConfigs = function(service) { return { buttonLabelText: RocketChat.settings.get(`${ service.key }_button_label_text`), buttonLabelColor: RocketChat.settings.get(`${ service.key }_button_label_color`), buttonColor: RocketChat.settings.get(`${ service.key }_button_color`), clientConfig: { provider: RocketChat.settings.get(`${ service.key }_provider`) }, entryPoint: RocketChat.settings.get(`${ service.key }_entry_point`), idpSLORedirectURL: RocketChat.settings.get(`${ service.key }_idp_slo_redirect_url`), generateUsername: RocketChat.settings.get(`${ service.key }_generate_username`), issuer: RocketChat.settings.get(`${ service.key }_issuer`), secret: { privateKey: RocketChat.settings.get(`${ service.key }_private_key`), publicCert: RocketChat.settings.get(`${ service.key }_public_cert`), cert: RocketChat.settings.get(`${ service.key }_cert`) } }; }; const debounce = (fn, delay) => { let timer = null; return () => { if (timer != null) { Meteor.clearTimeout(timer); } return timer = Meteor.setTimeout(fn, delay); }; }; const serviceName = 'saml'; const configureSamlService = function(samlConfigs) { let privateCert = false; let privateKey = false; if (samlConfigs.secret.privateKey && samlConfigs.secret.publicCert) { privateKey = samlConfigs.secret.privateKey; privateCert = samlConfigs.secret.publicCert; } else if (samlConfigs.secret.privateKey || samlConfigs.secret.publicCert) { logger.error('You must specify both cert and key files.'); } // TODO: the function configureSamlService is called many times and Accounts.saml.settings.generateUsername keeps just the last value Accounts.saml.settings.generateUsername = samlConfigs.generateUsername; return { provider: samlConfigs.clientConfig.provider, entryPoint: samlConfigs.entryPoint, idpSLORedirectURL: samlConfigs.idpSLORedirectURL, issuer: samlConfigs.issuer, cert: samlConfigs.secret.cert, privateCert, privateKey }; }; const updateServices = debounce(() => { const services = RocketChat.settings.get(/^(SAML_Custom_)[a-z]+$/i); Accounts.saml.settings.providers = services.map((service) => { if (service.value === true) { const samlConfigs = getSamlConfigs(service); logger.updated(service.key); ServiceConfiguration.configurations.upsert({ service: serviceName.toLowerCase() }, { $set: samlConfigs }); return configureSamlService(samlConfigs); } else { ServiceConfiguration.configurations.remove({ service: serviceName.toLowerCase() }); } }).filter(e => e); }, 2000); RocketChat.settings.get(/^SAML_.+/, updateServices); Meteor.startup(() => { return Meteor.call('addSamlService', 'Default'); }); export { updateServices, configureSamlService, getSamlConfigs, debounce, logger };
/** * Module dependencies. */ var mongoose = require('./common').mongoose , MongooseArray = mongoose.Types.Array , MongooseDocumentArray = mongoose.Types.DocumentArray , EmbeddedDocument = require('../lib/types/embedded') , DocumentArray = require('../lib/types/documentarray') , Schema = mongoose.Schema /** * Setup. */ function TestDoc (schema) { var Subdocument = function () { EmbeddedDocument.call(this, {}, new DocumentArray); }; /** * Inherits from EmbeddedDocument. */ Subdocument.prototype.__proto__ = EmbeddedDocument.prototype; /** * Set schema. */ var SubSchema = new Schema({ title: { type: String } }); Subdocument.prototype.schema = schema || SubSchema; return Subdocument; } /** * Test. */ module.exports = { 'test that a mongoose array behaves and quacks like an array': function(){ var a = new MongooseDocumentArray(); a.should.be.an.instanceof(Array); a.should.be.an.instanceof(MongooseArray); a.should.be.an.instanceof(MongooseDocumentArray); Array.isArray(a).should.be.true; a._atomics.constructor.name.should.equal('Object'); 'object'.should.eql(typeof a); var b = new MongooseArray([1,2,3,4]); 'object'.should.eql(typeof b); Object.keys(b.toObject()).length.should.equal(4); }, '#id': function () { var Subdocument = TestDoc(); var sub1 = new Subdocument(); sub1.title = 'Hello again to all my friends'; var id = sub1.id; var a = new MongooseDocumentArray([sub1]); a.id(id).title.should.equal('Hello again to all my friends'); a.id(sub1._id).title.should.equal('Hello again to all my friends'); // test with custom string _id var Custom = new Schema({ title: { type: String } , _id: { type: String, required: true } }); var Subdocument = TestDoc(Custom); var sub2 = new Subdocument(); sub2.title = 'together we can play some rock-n-roll'; sub2._id = 'a25'; var id2 = sub2.id; var a = new MongooseDocumentArray([sub2]); a.id(id2).title.should.equal('together we can play some rock-n-roll'); a.id(sub2._id).title.should.equal('together we can play some rock-n-roll'); // test with custom number _id var CustNumber = new Schema({ title: { type: String } , _id: { type: Number, required: true } }); var Subdocument = TestDoc(CustNumber); var sub3 = new Subdocument(); sub3.title = 'rock-n-roll'; sub3._id = 1995; var id3 = sub3.id; var a = new MongooseDocumentArray([sub3]); a.id(id3).title.should.equal('rock-n-roll'); a.id(sub3._id).title.should.equal('rock-n-roll'); }, 'inspect works with bad data': function () { var threw = false; var a = new MongooseDocumentArray([null]); try { a.inspect(); } catch (err) { threw = true; console.error(err.stack); } threw.should.be.false; }, 'toObject works with bad data': function () { var threw = false; var a = new MongooseDocumentArray([null]); try { a.toObject(); } catch (err) { threw = true; console.error(err.stack); } threw.should.be.false; } };
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/SuppMathOperators.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral'], { 0x2A07: [763,259,1180,83,1097], // TWO LOGICAL AND OPERATOR 0x2A08: [763,259,1180,83,1097], // TWO LOGICAL OR OPERATOR 0x2A09: [763,259,1021,50,971], // N-ARY TIMES OPERATOR 0x2A0A: [763,259,914,58,856], // MODULO TWO SUM 0x2A0B: [824,320,690,33,659], // SUMMATION WITH INTEGRAL 0x2A0C: [824,320,1184,32,1364], // QUADRUPLE INTEGRAL OPERATOR 0x2A0D: [824,320,499,32,639], // FINITE PART INTEGRAL 0x2A0E: [824,320,499,32,639], // INTEGRAL WITH DOUBLE STROKE 0x2A0F: [824,320,499,32,639], // INTEGRAL AVERAGE WITH SLASH 0x2A10: [824,320,499,32,639], // CIRCULATION FUNCTION 0x2A11: [824,320,499,32,639], // ANTICLOCKWISE INTEGRATION 0x2A12: [824,320,519,32,639], // LINE INTEGRATION WITH RECTANGULAR PATH AROUND POLE 0x2A13: [824,320,499,32,639], // LINE INTEGRATION WITH SEMICIRCULAR PATH AROUND POLE 0x2A14: [824,320,628,32,688], // LINE INTEGRATION NOT INCLUDING THE POLE 0x2A15: [824,320,499,32,639], // INTEGRAL AROUND A POINT OPERATOR 0x2A16: [824,320,529,32,639], // QUATERNION INTEGRAL OPERATOR 0x2A17: [824,320,738,32,818], // INTEGRAL WITH LEFTWARDS ARROW WITH HOOK 0x2A18: [824,320,539,32,639], // INTEGRAL WITH TIMES SIGN 0x2A19: [824,320,559,32,639], // INTEGRAL WITH INTERSECTION 0x2A1A: [824,320,559,32,639], // INTEGRAL WITH UNION 0x2A1B: [947,320,459,32,639], // INTEGRAL WITH OVERBAR 0x2A1C: [824,443,459,32,639], // INTEGRAL WITH UNDERBAR 0x2A1D: [770,252,1270,93,1177], // JOIN 0x2A1E: [764,258,1018,45,924], // LARGE LEFT TRIANGLE OPERATOR 0x2A1F: [566,291,503,110,410], // Z NOTATION SCHEMA COMPOSITION 0x2A20: [633,127,1177,98,1079], // Z NOTATION SCHEMA PIPING 0x2A21: [805,300,547,215,472], // Z NOTATION SCHEMA PROJECTION 0x2A22: [819,41,685,48,636], // PLUS SIGN WITH SMALL CIRCLE ABOVE 0x2A23: [707,41,685,48,636], // PLUS SIGN WITH CIRCUMFLEX ACCENT ABOVE 0x2A24: [704,41,685,48,636], // PLUS SIGN WITH TILDE ABOVE 0x2A25: [547,235,685,48,636], // PLUS SIGN WITH DOT BELOW 0x2A26: [547,198,685,48,636], // PLUS SIGN WITH TILDE BELOW 0x2A27: [547,210,685,41,673], // PLUS SIGN WITH SUBSCRIPT TWO 0x2A28: [547,41,685,48,636], // PLUS SIGN WITH BLACK TRIANGLE 0x2A29: [556,-220,685,48,637], // MINUS SIGN WITH COMMA ABOVE 0x2A2A: [286,5,685,48,637], // MINUS SIGN WITH DOT BELOW 0x2A2B: [511,5,685,48,637], // MINUS SIGN WITH FALLING DOTS 0x2A2C: [511,5,685,48,637], // MINUS SIGN WITH RISING DOTS 0x2A2D: [623,119,724,50,674], // PLUS SIGN IN LEFT HALF CIRCLE 0x2A2E: [623,119,724,50,674], // PLUS SIGN IN RIGHT HALF CIRCLE 0x2A2F: [447,-59,490,50,439], // VECTOR OR CROSS PRODUCT 0x2A30: [686,25,640,43,597], // MULTIPLICATION SIGN WITH DOT ABOVE 0x2A31: [529,130,640,43,597], // MULTIPLICATION SIGN WITH UNDERBAR 0x2A32: [529,45,640,43,597], // SEMIDIRECT PRODUCT WITH BOTTOM CLOSED 0x2A33: [538,32,685,57,627], // SMASH PRODUCT 0x2A34: [623,119,674,50,624], // MULTIPLICATION SIGN IN LEFT HALF CIRCLE 0x2A35: [623,119,674,50,624], // MULTIPLICATION SIGN IN RIGHT HALF CIRCLE 0x2A36: [810,119,842,50,792], // CIRCLED MULTIPLICATION SIGN WITH CIRCUMFLEX ACCENT 0x2A37: [752,248,1100,50,1050], // MULTIPLICATION SIGN IN DOUBLE CIRCLE 0x2A38: [623,119,842,50,792], // CIRCLED DIVISION SIGN 0x2A39: [811,127,1145,35,1110], // PLUS SIGN IN TRIANGLE 0x2A3A: [811,127,1145,35,1110], // MINUS SIGN IN TRIANGLE 0x2A3B: [811,127,1145,35,1110], // MULTIPLICATION SIGN IN TRIANGLE 0x2A3C: [393,-115,600,48,552], // stix-vert, low bar to left from base 0x2A3D: [393,-115,600,48,552], // stix-vert, low bar to right from base 0x2A3E: [488,170,300,60,230], // Z NOTATION RELATIONAL COMPOSITION 0x2A40: [536,31,620,48,572], // INTERSECTION WITH DOT 0x2A41: [536,31,620,48,572], // UNION WITH MINUS SIGN 0x2A42: [668,31,620,48,572], // UNION WITH OVERBAR 0x2A43: [668,31,620,48,572], // INTERSECTION WITH OVERBAR 0x2A44: [536,31,620,48,572], // INTERSECTION WITH LOGICAL AND 0x2A45: [536,31,620,48,572], // UNION WITH LOGICAL OR 0x2A46: [914,406,620,48,572], // UNION ABOVE INTERSECTION 0x2A47: [914,406,620,48,572], // INTERSECTION ABOVE UNION 0x2A48: [914,406,620,48,572], // UNION ABOVE BAR ABOVE INTERSECTION 0x2A49: [914,406,620,48,572], // INTERSECTION ABOVE BAR ABOVE UNION 0x2A4A: [528,39,1078,48,1030], // UNION BESIDE AND JOINED WITH UNION 0x2A4B: [527,40,1078,48,1030], // INTERSECTION BESIDE AND JOINED WITH INTERSECTION 0x2A4C: [602,31,620,10,610], // CLOSED UNION WITH SERIFS 0x2A4D: [536,97,620,10,610], // CLOSED INTERSECTION WITH SERIFS 0x2A4E: [536,31,620,48,572], // DOUBLE SQUARE INTERSECTION 0x2A4F: [536,31,620,48,572], // DOUBLE SQUARE UNION 0x2A50: [602,31,620,10,610], // CLOSED UNION WITH SERIFS AND SMASH PRODUCT 0x2A51: [710,29,620,31,589], // LOGICAL AND WITH DOT ABOVE 0x2A52: [710,29,620,31,589], // LOGICAL OR WITH DOT ABOVE 0x2A53: [536,29,620,31,589], // DOUBLE LOGICAL AND 0x2A54: [536,29,620,31,589], // DOUBLE LOGICAL OR 0x2A55: [536,29,780,32,748], // TWO INTERSECTING LOGICAL AND 0x2A56: [536,29,780,32,748], // TWO INTERSECTING LOGICAL OR 0x2A57: [536,29,706,106,683], // SLOPING LARGE OR 0x2A58: [536,29,706,23,600], // SLOPING LARGE AND 0x2A59: [585,77,620,31,589], // LOGICAL OR OVERLAPPING LOGICAL AND 0x2A5A: [536,29,620,31,589], // LOGICAL AND WITH MIDDLE STEM 0x2A5B: [536,29,620,31,589], // LOGICAL OR WITH MIDDLE STEM 0x2A5C: [536,29,620,31,589], // LOGICAL AND WITH HORIZONTAL DASH 0x2A5D: [536,29,620,31,589], // LOGICAL OR WITH HORIZONTAL DASH 0x2A5E: [796,29,620,31,589], // LOGICAL AND WITH DOUBLE OVERBAR 0x2A5F: [536,139,620,30,590], // LOGICAL AND WITH UNDERBAR 0x2A60: [536,289,620,30,590], // LOGICAL AND WITH DOUBLE UNDERBAR 0x2A61: [479,0,620,45,575], // SMALL VEE WITH UNDERBAR 0x2A62: [806,29,620,30,590], // LOGICAL OR WITH DOUBLE OVERBAR 0x2A63: [536,289,620,30,590], // LOGICAL OR WITH DOUBLE UNDERBAR 0x2A64: [791,284,1043,70,1008], // Z NOTATION DOMAIN ANTIRESTRICTION 0x2A65: [791,284,1043,70,1008], // Z NOTATION RANGE ANTIRESTRICTION 0x2A66: [386,105,685,48,637], // EQUALS SIGN WITH DOT BELOW 0x2A67: [703,-28,685,48,637], // IDENTICAL WITH DOT ABOVE 0x2A68: [695,189,685,48,637], // TRIPLE HORIZONTAL BAR WITH DOUBLE VERTICAL STROKE 0x2A69: [662,156,685,48,637], // TRIPLE HORIZONTAL BAR WITH TRIPLE VERTICAL STROKE 0x2A6A: [521,-148,685,48,637], // TILDE OPERATOR WITH DOT ABOVE 0x2A6B: [521,13,685,48,637], // TILDE OPERATOR WITH RISING DOTS 0x2A6C: [543,38,685,48,637], // SIMILAR MINUS SIMILAR 0x2A6D: [703,27,685,48,637], // CONGRUENT WITH DOT ABOVE 0x2A6E: [847,-120,685,48,637], // EQUALS WITH ASTERISK 0x2A6F: [707,-25,685,48,637], // ALMOST EQUAL TO WITH CIRCUMFLEX ACCENT 0x2A70: [650,146,685,48,637], // APPROXIMATELY EQUAL OR EQUAL TO 0x2A71: [648,141,685,48,637], // EQUALS SIGN ABOVE PLUS SIGN 0x2A72: [648,141,685,48,637], // PLUS SIGN ABOVE EQUALS SIGN 0x2A73: [532,27,685,48,637], // EQUALS SIGN ABOVE TILDE OPERATOR 0x2A74: [417,-89,1015,48,967], // DOUBLE COLON EQUAL 0x2A75: [386,-120,997,48,949], // TWO CONSECUTIVE EQUALS SIGNS 0x2A76: [386,-120,1436,48,1388], // THREE CONSECUTIVE EQUALS SIGNS 0x2A77: [611,106,685,48,637], // EQUALS SIGN WITH TWO DOTS ABOVE AND TWO DOTS BELOW 0x2A78: [703,-28,685,38,647], // EQUIVALENT WITH FOUR DOTS ABOVE 0x2A79: [532,26,685,44,609], // LESS-THAN WITH CIRCLE INSIDE 0x2A7A: [532,26,685,76,641], // GREATER-THAN WITH CIRCLE INSIDE 0x2A7B: [806,26,685,44,609], // LESS-THAN WITH QUESTION MARK ABOVE 0x2A7C: [806,26,685,76,641], // GREATER-THAN WITH QUESTION MARK ABOVE 0x2A7D: [625,137,685,56,621], // LESS-THAN OR SLANTED EQUAL TO 0x2A7E: [625,137,685,56,621], // GREATER-THAN OR SLANTED EQUAL TO 0x2A7F: [625,137,685,60,625], // LESS-THAN OR SLANTED EQUAL TO WITH DOT INSIDE 0x2A80: [625,137,685,60,625], // GREATER-THAN OR SLANTED EQUAL TO WITH DOT INSIDE 0x2A81: [625,137,685,60,625], // LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE 0x2A82: [625,137,685,60,625], // GREATER-THAN OR SLANTED EQUAL TO WITH DOT ABOVE 0x2A83: [777,137,685,60,625], // LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE RIGHT 0x2A84: [777,137,685,60,625], // GREATER-THAN OR SLANTED EQUAL TO WITH DOT ABOVE LEFT 0x2A85: [746,275,685,48,637], // LESS-THAN OR APPROXIMATE 0x2A86: [746,275,685,48,637], // GREATER-THAN OR APPROXIMATE 0x2A87: [628,216,685,60,625], // LESS-THAN AND SINGLE-LINE NOT EQUAL TO 0x2A88: [628,216,687,56,621], // GREATER-THAN AND SINGLE-LINE NOT EQUAL TO 0x2A89: [746,309,685,48,637], // LESS-THAN AND NOT APPROXIMATE 0x2A8A: [746,309,685,48,637], // GREATER-THAN AND NOT APPROXIMATE 0x2A8B: [930,424,685,56,621], // LESS-THAN ABOVE DOUBLE-LINE EQUAL ABOVE GREATER-THAN 0x2A8C: [930,424,685,56,621], // GREATER-THAN ABOVE DOUBLE-LINE EQUAL ABOVE LESS-THAN 0x2A8D: [746,176,685,48,637], // LESS-THAN ABOVE SIMILAR OR EQUAL 0x2A8E: [746,176,685,48,637], // GREATER-THAN ABOVE SIMILAR OR EQUAL 0x2A8F: [867,361,685,60,649], // LESS-THAN ABOVE SIMILAR ABOVE GREATER-THAN 0x2A90: [867,361,685,60,649], // GREATER-THAN ABOVE SIMILAR ABOVE LESS-THAN 0x2A91: [844,338,685,55,630], // LESS-THAN ABOVE GREATER-THAN ABOVE DOUBLE-LINE EQUAL 0x2A92: [844,338,685,55,630], // GREATER-THAN ABOVE LESS-THAN ABOVE DOUBLE-LINE EQUAL 0x2A93: [866,361,685,60,625], // LESS-THAN ABOVE SLANTED EQUAL ABOVE GREATER-THAN ABOVE SLANTED EQUAL 0x2A94: [866,361,685,60,625], // GREATER-THAN ABOVE SLANTED EQUAL ABOVE LESS-THAN ABOVE SLANTED EQUAL 0x2A95: [640,122,685,56,621], // SLANTED EQUAL TO OR LESS-THAN 0x2A96: [640,122,685,56,621], // SLANTED EQUAL TO OR GREATER-THAN 0x2A97: [640,122,685,56,621], // SLANTED EQUAL TO OR LESS-THAN WITH DOT INSIDE 0x2A98: [640,122,685,56,621], // SLANTED EQUAL TO OR GREATER-THAN WITH DOT INSIDE 0x2A99: [718,211,685,60,625], // DOUBLE-LINE EQUAL TO OR LESS-THAN 0x2A9A: [718,211,685,60,625], // DOUBLE-LINE EQUAL TO OR GREATER-THAN 0x2A9B: [726,220,685,60,625], // DOUBLE-LINE SLANTED EQUAL TO OR LESS-THAN 0x2A9C: [726,220,685,60,625], // DOUBLE-LINE SLANTED EQUAL TO OR GREATER-THAN 0x2A9D: [664,164,685,53,642], // stix-similar (conforming) or less-than 0x2A9E: [664,164,685,43,632], // SIMILAR OR GREATER-THAN 0x2A9F: [774,267,685,48,637], // SIMILAR ABOVE LESS-THAN ABOVE EQUALS SIGN 0x2AA0: [774,267,685,48,637], // SIMILAR ABOVE GREATER-THAN ABOVE EQUALS SIGN 0x2AA1: [532,26,685,44,609], // DOUBLE NESTED LESS-THAN 0x2AA2: [532,26,685,76,641], // DOUBLE NESTED GREATER-THAN 0x2AA3: [609,103,933,25,908], // DOUBLE NESTED LESS-THAN WITH UNDERBAR 0x2AA4: [532,26,782,60,722], // GREATER-THAN OVERLAPPING LESS-THAN 0x2AA5: [532,26,855,60,795], // GREATER-THAN BESIDE LESS-THAN 0x2AA6: [532,26,685,35,625], // LESS-THAN CLOSED BY CURVE 0x2AA7: [532,26,685,60,650], // GREATER-THAN CLOSED BY CURVE 0x2AA8: [625,137,685,50,640], // LESS-THAN CLOSED BY CURVE ABOVE SLANTED EQUAL 0x2AA9: [626,137,685,45,635], // GREATER-THAN CLOSED BY CURVE ABOVE SLANTED EQUAL 0x2AAA: [537,31,685,45,609], // SMALLER THAN 0x2AAB: [537,31,685,76,640], // LARGER THAN 0x2AAC: [613,103,685,60,625], // stix-smaller than or equal, slanted 0x2AAD: [613,103,685,60,625], // stix-larger than or equal, slanted 0x2AAE: [563,-28,685,48,637], // EQUALS SIGN WITH BUMPY ABOVE 0x2AB1: [628,216,685,60,625], // PRECEDES ABOVE SINGLE-LINE NOT EQUAL TO 0x2AB2: [628,216,685,60,625], // SUCCEEDS ABOVE SINGLE-LINE NOT EQUAL TO 0x2AB3: [717,211,685,60,625], // PRECEDES ABOVE EQUALS SIGN 0x2AB4: [717,211,685,60,625], // SUCCEEDS ABOVE EQUALS SIGN 0x2AB5: [747,260,685,65,622], // PRECEDES ABOVE NOT EQUAL TO 0x2AB6: [747,260,685,65,622], // SUCCEEDS ABOVE NOT EQUAL TO 0x2AB7: [747,275,685,48,637], // PRECEDES ABOVE ALMOST EQUAL TO 0x2AB8: [747,275,685,48,637], // SUCCEEDS ABOVE ALMOST EQUAL TO 0x2AB9: [747,309,685,48,637], // PRECEDES ABOVE NOT ALMOST EQUAL TO 0x2ABA: [747,309,685,48,637], // SUCCEEDS ABOVE NOT ALMOST EQUAL TO 0x2ABB: [532,26,933,25,908], // DOUBLE PRECEDES 0x2ABC: [532,26,933,25,908], // DOUBLE SUCCEEDS 0x2ABD: [532,26,685,60,625], // SUBSET WITH DOT 0x2ABE: [532,26,685,60,625], // SUPERSET WITH DOT 0x2ABF: [607,103,685,60,625], // SUBSET WITH PLUS SIGN BELOW 0x2AC0: [607,103,685,60,625], // SUPERSET WITH PLUS SIGN BELOW 0x2AC1: [607,103,685,60,625], // SUBSET WITH MULTIPLICATION SIGN BELOW 0x2AC2: [607,103,685,60,625], // SUPERSET WITH MULTIPLICATION SIGN BELOW 0x2AC3: [709,103,685,60,625], // SUBSET OF OR EQUAL TO WITH DOT ABOVE 0x2AC4: [709,103,685,60,625], // SUPERSET OF OR EQUAL TO WITH DOT ABOVE 0x2AC5: [717,211,685,64,622], // SUBSET OF ABOVE EQUALS SIGN 0x2AC6: [717,211,685,65,623], // SUPERSET OF ABOVE EQUALS SIGN 0x2AC7: [665,164,685,60,625], // SUBSET OF ABOVE TILDE OPERATOR 0x2AC8: [665,164,685,60,625], // SUPERSET OF ABOVE TILDE OPERATOR 0x2AC9: [746,274,685,60,625], // SUBSET OF ABOVE ALMOST EQUAL TO 0x2ACA: [746,274,685,60,625], // SUPERSET OF ABOVE ALMOST EQUAL TO 0x2ACB: [717,319,685,61,619], // stix-subset not double equals, variant 0x2ACC: [717,319,685,66,624], // SUPERSET OF ABOVE NOT EQUAL TO 0x2ACD: [558,53,1352,64,1288], // SQUARE LEFT OPEN BOX OPERATOR 0x2ACE: [558,53,1352,64,1288], // SQUARE RIGHT OPEN BOX OPERATOR 0x2ACF: [532,26,685,50,615], // CLOSED SUBSET 0x2AD0: [532,26,685,70,635], // CLOSED SUPERSET 0x2AD1: [609,103,685,60,626], // CLOSED SUBSET OR EQUAL TO 0x2AD2: [609,103,685,60,625], // CLOSED SUPERSET OR EQUAL TO 0x2AD3: [715,209,685,60,625], // SUBSET ABOVE SUPERSET 0x2AD4: [715,209,685,60,625], // SUPERSET ABOVE SUBSET 0x2AD5: [715,209,685,60,625], // SUBSET ABOVE SUBSET 0x2AD6: [715,209,685,60,625], // SUPERSET ABOVE SUPERSET 0x2AD7: [532,26,1250,60,1190], // SUPERSET BESIDE SUBSET 0x2AD8: [532,26,1250,60,1190], // SUPERSET BESIDE AND JOINED BY DASH WITH SUBSET 0x2AD9: [536,31,620,48,572], // ELEMENT OF OPENING DOWNWARDS 0x2ADA: [697,128,620,48,572], // PITCHFORK WITH TEE TOP 0x2ADB: [695,97,620,48,572], // TRANSVERSAL INTERSECTION 0x2ADC: [557,10,620,11,572], // FORKING 0x2ADD: [557,10,620,48,572], // NONFORKING 0x2ADE: [662,0,497,64,433], // SHORT LEFT TACK 0x2ADF: [371,0,685,48,637], // SHORT DOWN TACK 0x2AE0: [371,0,685,48,637], // SHORT UP TACK 0x2AE1: [662,0,685,48,637], // PERPENDICULAR WITH S 0x2AE2: [662,0,685,60,625], // VERTICAL BAR TRIPLE RIGHT TURNSTILE 0x2AE3: [662,0,860,46,803], // DOUBLE VERTICAL BAR LEFT TURNSTILE 0x2AE4: [662,0,685,60,625], // VERTICAL BAR DOUBLE LEFT TURNSTILE 0x2AE5: [662,0,860,46,803], // DOUBLE VERTICAL BAR DOUBLE LEFT TURNSTILE 0x2AE6: [662,0,685,57,626], // LONG DASH FROM LEFT MEMBER OF DOUBLE VERTICAL 0x2AE7: [571,0,685,48,637], // SHORT DOWN TACK WITH OVERBAR 0x2AE8: [571,0,685,48,637], // SHORT UP TACK WITH UNDERBAR 0x2AE9: [691,185,685,48,637], // SHORT UP TACK ABOVE SHORT DOWN TACK 0x2AEA: [662,0,685,48,637], // DOUBLE DOWN TACK 0x2AEB: [662,0,685,48,637], // DOUBLE UP TACK 0x2AEC: [489,-18,600,48,552], // DOUBLE STROKE NOT SIGN 0x2AED: [489,-18,600,48,552], // REVERSED DOUBLE STROKE NOT SIGN 0x2AEE: [690,189,404,23,381], // stix-short mid negated by backslash 0x2AEF: [660,154,502,101,401], // VERTICAL LINE WITH CIRCLE ABOVE 0x2AF0: [660,154,502,101,401], // VERTICAL LINE WITH CIRCLE BELOW 0x2AF1: [693,187,502,101,401], // DOWN TACK WITH CIRCLE BELOW 0x2AF2: [695,189,523,10,513], // PARALLEL WITH HORIZONTAL STROKE 0x2AF3: [695,189,685,48,637], // PARALLEL WITH TILDE OPERATOR 0x2AF4: [695,189,685,131,555], // TRIPLE VERTICAL BAR BINARY RELATION 0x2AF5: [695,189,685,12,674], // TRIPLE VERTICAL BAR WITH HORIZONTAL STROKE 0x2AF6: [608,102,685,279,406], // TRIPLE COLON OPERATOR 0x2AF7: [661,155,1170,58,1080], // TRIPLE NESTED LESS-THAN 0x2AF8: [661,155,1170,90,1112], // TRIPLE NESTED GREATER-THAN 0x2AF9: [726,220,685,60,625], // DOUBLE-LINE SLANTED LESS-THAN OR EQUAL TO 0x2AFA: [726,220,685,60,625], // DOUBLE-LINE SLANTED GREATER-THAN OR EQUAL TO 0x2AFB: [710,222,894,46,848], // TRIPLE SOLIDUS BINARY RELATION 0x2AFC: [763,259,654,94,560], // LARGE TRIPLE VERTICAL BAR OPERATOR 0x2AFD: [710,222,709,46,663], // DOUBLE SOLIDUS OPERATOR 0x2AFE: [690,189,410,100,310], // WHITE VERTICAL BAR 0x2AFF: [763,259,478,94,384] // N-ARY WHITE VERTICAL BAR } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Regular/SuppMathOperators.js");
sampleTag`left${0}\u{${1}right`
'use strict'; angular.module('angularPassportApp') .factory('User', function ($resource) { return $resource('/auth/users/:id/', {}, { 'update': { method:'PUT' } }); });
/** PURE_IMPORTS_START ._AsapAction,._AsapScheduler PURE_IMPORTS_END */ import { AsapAction } from './AsapAction'; import { AsapScheduler } from './AsapScheduler'; /** * * Asap Scheduler * * <span class="informal">Perform task as fast as it can be performed asynchronously</span> * * `asap` scheduler behaves the same as {@link async} scheduler when you use it to delay task * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing * code to end and then it will try to execute given task as fast as possible. * * `asap` scheduler will do its best to minimize time between end of currently executing code * and start of scheduled task. This makes it best candidate for performing so called "deferring". * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves * some (although minimal) unwanted delay. * * Note that using `asap` scheduler does not necessarily mean that your task will be first to process * after currently executing code. In particular, if some task was also scheduled with `asap` before, * that task will execute first. That being said, if you need to schedule task asynchronously, but * as soon as possible, `asap` scheduler is your best bet. * * @example <caption>Compare async and asap scheduler</caption> * * Rx.Scheduler.async.schedule(() => console.log('async')); // scheduling 'async' first... * Rx.Scheduler.asap.schedule(() => console.log('asap')); * * // Logs: * // "asap" * // "async" * // ... but 'asap' goes first! * * @static true * @name asap * @owner Scheduler */ export var asap = /*@__PURE__*/ new AsapScheduler(AsapAction); //# sourceMappingURL=asap.js.map
// Generated by CoffeeScript 1.8.0 var error; alert((function() { try { return nonexistent / void 0; } catch (_error) { error = _error; return "And the error is ... " + error; } })());
define("ace/mode/matlab_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var MatlabHighlightRules = function() { var keywords = ( "break|case|catch|classdef|continue|else|elseif|end|for|function|global|if|otherwise|parfor|persistent|return|spmd|switch|try|while" ); var builtinConstants = ( "true|false|inf|Inf|nan|NaN|eps|pi|ans|nargin|nargout|varargin|varargout" ); var builtinFunctions = ( "abs|accumarray|acos(?:d|h)?|acot(?:d|h)?|acsc(?:d|h)?|actxcontrol(?:list|select)?|actxGetRunningServer|actxserver|addlistener|addpath|addpref|addtodate|"+ "airy|align|alim|all|allchild|alpha|alphamap|amd|ancestor|and|angle|annotation|any|area|arrayfun|asec(?:d|h)?|asin(?:d|h)?|assert|assignin|atan(?:2|d|h)?|" + "audiodevinfo|audioplayer|audiorecorder|aufinfo|auread|autumn|auwrite|avifile|aviinfo|aviread|axes|axis|balance|bar(?:3|3h|h)?|base2dec|beep|BeginInvoke|bench|"+ "bessel(?:h|i|j|k|y)|beta|betainc|betaincinv|betaln|bicg|bicgstab|bicgstabl|bin2dec|bitand|bitcmp|bitget|bitmax|bitnot|bitor|bitset|bitshift|bitxor|blanks|blkdiag|"+ "bone|box|brighten|brush|bsxfun|builddocsearchdb|builtin|bvp4c|bvp5c|bvpget|bvpinit|bvpset|bvpxtend|calendar|calllib|callSoapService|camdolly|cameratoolbar|camlight|"+ "camlookat|camorbit|campan|campos|camproj|camroll|camtarget|camup|camva|camzoom|cart2pol|cart2sph|cast|cat|caxis|cd|cdf2rdf|cdfepoch|cdfinfo|cdflib(?:.(?:close|closeVar|"+ "computeEpoch|computeEpoch16|create|createAttr|createVar|delete|deleteAttr|deleteAttrEntry|deleteAttrgEntry|deleteVar|deleteVarRecords|epoch16Breakdown|epochBreakdown|getAttrEntry|"+ "getAttrgEntry|getAttrMaxEntry|getAttrMaxgEntry|getAttrName|getAttrNum|getAttrScope|getCacheSize|getChecksum|getCompression|getCompressionCacheSize|getConstantNames|"+ "getConstantValue|getCopyright|getFileBackward|getFormat|getLibraryCopyright|getLibraryVersion|getMajority|getName|getNumAttrEntries|getNumAttrgEntries|getNumAttributes|"+ "getNumgAttributes|getReadOnlyMode|getStageCacheSize|getValidate|getVarAllocRecords|getVarBlockingFactor|getVarCacheSize|getVarCompression|getVarData|getVarMaxAllocRecNum|"+ "getVarMaxWrittenRecNum|getVarName|getVarNum|getVarNumRecsWritten|getVarPadValue|getVarRecordData|getVarReservePercent|getVarsMaxWrittenRecNum|getVarSparseRecords|getVersion|"+ "hyperGetVarData|hyperPutVarData|inquire|inquireAttr|inquireAttrEntry|inquireAttrgEntry|inquireVar|open|putAttrEntry|putAttrgEntry|putVarData|putVarRecordData|renameAttr|"+ "renameVar|setCacheSize|setChecksum|setCompression|setCompressionCacheSize|setFileBackward|setFormat|setMajority|setReadOnlyMode|setStageCacheSize|setValidate|"+ "setVarAllocBlockRecords|setVarBlockingFactor|setVarCacheSize|setVarCompression|setVarInitialRecs|setVarPadValue|SetVarReservePercent|setVarsCacheSize|setVarSparseRecords))?|"+ "cdfread|cdfwrite|ceil|cell2mat|cell2struct|celldisp|cellfun|cellplot|cellstr|cgs|checkcode|checkin|checkout|chol|cholinc|cholupdate|circshift|cla|clabel|class|clc|clear|"+ "clearvars|clf|clipboard|clock|close|closereq|cmopts|cmpermute|cmunique|colamd|colon|colorbar|colordef|colormap|colormapeditor|colperm|Combine|comet|comet3|commandhistory|"+ "commandwindow|compan|compass|complex|computer|cond|condeig|condest|coneplot|conj|containers.Map|contour(?:3|c|f|slice)?|contrast|conv|conv2|convhull|convhulln|convn|cool|"+ "copper|copyfile|copyobj|corrcoef|cos(?:d|h)?|cot(?:d|h)?|cov|cplxpair|cputime|createClassFromWsdl|createSoapMessage|cross|csc(?:d|h)?|csvread|csvwrite|ctranspose|cumprod|"+ "cumsum|cumtrapz|curl|customverctrl|cylinder|daqread|daspect|datacursormode|datatipinfo|date|datenum|datestr|datetick|datevec|dbclear|dbcont|dbdown|dblquad|dbmex|dbquit|"+ "dbstack|dbstatus|dbstep|dbstop|dbtype|dbup|dde23|ddeget|ddesd|ddeset|deal|deblank|dec2base|dec2bin|dec2hex|decic|deconv|del2|delaunay|delaunay3|delaunayn|DelaunayTri|delete|"+ "demo|depdir|depfun|det|detrend|deval|diag|dialog|diary|diff|diffuse|dir|disp|display|dither|divergence|dlmread|dlmwrite|dmperm|doc|docsearch|dos|dot|dragrect|drawnow|dsearch|"+ "dsearchn|dynamicprops|echo|echodemo|edit|eig|eigs|ellipj|ellipke|ellipsoid|empty|enableNETfromNetworkDrive|enableservice|EndInvoke|enumeration|eomday|eq|erf|erfc|erfcinv|"+ "erfcx|erfinv|error|errorbar|errordlg|etime|etree|etreeplot|eval|evalc|evalin|event.(?:EventData|listener|PropertyEvent|proplistener)|exifread|exist|exit|exp|expint|expm|"+ "expm1|export2wsdlg|eye|ezcontour|ezcontourf|ezmesh|ezmeshc|ezplot|ezplot3|ezpolar|ezsurf|ezsurfc|factor|factorial|fclose|feather|feature|feof|ferror|feval|fft|fft2|fftn|"+ "fftshift|fftw|fgetl|fgets|fieldnames|figure|figurepalette|fileattrib|filebrowser|filemarker|fileparts|fileread|filesep|fill|fill3|filter|filter2|find|findall|findfigs|"+ "findobj|findstr|finish|fitsdisp|fitsinfo|fitsread|fitswrite|fix|flag|flipdim|fliplr|flipud|floor|flow|fminbnd|fminsearch|fopen|format|fplot|fprintf|frame2im|fread|freqspace|"+ "frewind|fscanf|fseek|ftell|FTP|full|fullfile|func2str|functions|funm|fwrite|fzero|gallery|gamma|gammainc|gammaincinv|gammaln|gca|gcbf|gcbo|gcd|gcf|gco|ge|genpath|genvarname|"+ "get|getappdata|getenv|getfield|getframe|getpixelposition|getpref|ginput|gmres|gplot|grabcode|gradient|gray|graymon|grid|griddata(?:3|n)?|griddedInterpolant|gsvd|gt|gtext|"+ "guidata|guide|guihandles|gunzip|gzip|h5create|h5disp|h5info|h5read|h5readatt|h5write|h5writeatt|hadamard|handle|hankel|hdf|hdf5|hdf5info|hdf5read|hdf5write|hdfinfo|"+ "hdfread|hdftool|help|helpbrowser|helpdesk|helpdlg|helpwin|hess|hex2dec|hex2num|hgexport|hggroup|hgload|hgsave|hgsetget|hgtransform|hidden|hilb|hist|histc|hold|home|horzcat|"+ "hostid|hot|hsv|hsv2rgb|hypot|ichol|idivide|ifft|ifft2|ifftn|ifftshift|ilu|im2frame|im2java|imag|image|imagesc|imapprox|imfinfo|imformats|import|importdata|imread|imwrite|"+ "ind2rgb|ind2sub|inferiorto|info|inline|inmem|inpolygon|input|inputdlg|inputname|inputParser|inspect|instrcallback|instrfind|instrfindall|int2str|integral(?:2|3)?|interp(?:1|"+ "1q|2|3|ft|n)|interpstreamspeed|intersect|intmax|intmin|inv|invhilb|ipermute|isa|isappdata|iscell|iscellstr|ischar|iscolumn|isdir|isempty|isequal|isequaln|isequalwithequalnans|"+ "isfield|isfinite|isfloat|isglobal|ishandle|ishghandle|ishold|isinf|isinteger|isjava|iskeyword|isletter|islogical|ismac|ismatrix|ismember|ismethod|isnan|isnumeric|isobject|"+ "isocaps|isocolors|isonormals|isosurface|ispc|ispref|isprime|isprop|isreal|isrow|isscalar|issorted|isspace|issparse|isstr|isstrprop|isstruct|isstudent|isunix|isvarname|"+ "isvector|javaaddpath|javaArray|javachk|javaclasspath|javacomponent|javaMethod|javaMethodEDT|javaObject|javaObjectEDT|javarmpath|jet|keyboard|kron|lasterr|lasterror|"+ "lastwarn|lcm|ldivide|ldl|le|legend|legendre|length|libfunctions|libfunctionsview|libisloaded|libpointer|libstruct|license|light|lightangle|lighting|lin2mu|line|lines|"+ "linkaxes|linkdata|linkprop|linsolve|linspace|listdlg|listfonts|load|loadlibrary|loadobj|log|log10|log1p|log2|loglog|logm|logspace|lookfor|lower|ls|lscov|lsqnonneg|lsqr|"+ "lt|lu|luinc|magic|makehgtform|mat2cell|mat2str|material|matfile|matlab.io.MatFile|matlab.mixin.(?:Copyable|Heterogeneous(?:.getDefaultScalarElement)?)|matlabrc|"+ "matlabroot|max|maxNumCompThreads|mean|median|membrane|memmapfile|memory|menu|mesh|meshc|meshgrid|meshz|meta.(?:class(?:.fromName)?|DynamicProperty|EnumeratedValue|event|"+ "MetaData|method|package(?:.(?:fromName|getAllPackages))?|property)|metaclass|methods|methodsview|mex(?:.getCompilerConfigurations)?|MException|mexext|mfilename|min|minres|"+ "minus|mislocked|mkdir|mkpp|mldivide|mlint|mlintrpt|mlock|mmfileinfo|mmreader|mod|mode|more|move|movefile|movegui|movie|movie2avi|mpower|mrdivide|msgbox|mtimes|mu2lin|"+ "multibandread|multibandwrite|munlock|namelengthmax|nargchk|narginchk|nargoutchk|native2unicode|nccreate|ncdisp|nchoosek|ncinfo|ncread|ncreadatt|ncwrite|ncwriteatt|"+ "ncwriteschema|ndgrid|ndims|ne|NET(?:.(?:addAssembly|Assembly|convertArray|createArray|createGeneric|disableAutoRelease|enableAutoRelease|GenericClass|invokeGenericMethod|"+ "NetException|setStaticProperty))?|netcdf.(?:abort|close|copyAtt|create|defDim|defGrp|defVar|defVarChunking|defVarDeflate|defVarFill|defVarFletcher32|delAtt|endDef|getAtt|"+ "getChunkCache|getConstant|getConstantNames|getVar|inq|inqAtt|inqAttID|inqAttName|inqDim|inqDimID|inqDimIDs|inqFormat|inqGrpName|inqGrpNameFull|inqGrpParent|inqGrps|"+ "inqLibVers|inqNcid|inqUnlimDims|inqVar|inqVarChunking|inqVarDeflate|inqVarFill|inqVarFletcher32|inqVarID|inqVarIDs|open|putAtt|putVar|reDef|renameAtt|renameDim|renameVar|"+ "setChunkCache|setDefaultFormat|setFill|sync)|newplot|nextpow2|nnz|noanimate|nonzeros|norm|normest|not|notebook|now|nthroot|null|num2cell|num2hex|num2str|numel|nzmax|"+ "ode(?:113|15i|15s|23|23s|23t|23tb|45)|odeget|odeset|odextend|onCleanup|ones|open|openfig|opengl|openvar|optimget|optimset|or|ordeig|orderfields|ordqz|ordschur|orient|"+ "orth|pack|padecoef|pagesetupdlg|pan|pareto|parseSoapResponse|pascal|patch|path|path2rc|pathsep|pathtool|pause|pbaspect|pcg|pchip|pcode|pcolor|pdepe|pdeval|peaks|perl|perms|"+ "permute|pie|pink|pinv|planerot|playshow|plot|plot3|plotbrowser|plotedit|plotmatrix|plottools|plotyy|plus|pol2cart|polar|poly|polyarea|polyder|polyeig|polyfit|polyint|polyval|"+ "polyvalm|pow2|power|ppval|prefdir|preferences|primes|print|printdlg|printopt|printpreview|prod|profile|profsave|propedit|propertyeditor|psi|publish|PutCharArray|PutFullMatrix|"+ "PutWorkspaceData|pwd|qhull|qmr|qr|qrdelete|qrinsert|qrupdate|quad|quad2d|quadgk|quadl|quadv|questdlg|quit|quiver|quiver3|qz|rand|randi|randn|randperm|RandStream(?:.(?:create|"+ "getDefaultStream|getGlobalStream|list|setDefaultStream|setGlobalStream))?|rank|rat|rats|rbbox|rcond|rdivide|readasync|real|reallog|realmax|realmin|realpow|realsqrt|record|"+ "rectangle|rectint|recycle|reducepatch|reducevolume|refresh|refreshdata|regexp|regexpi|regexprep|regexptranslate|rehash|rem|Remove|RemoveAll|repmat|reset|reshape|residue|"+ "restoredefaultpath|rethrow|rgb2hsv|rgb2ind|rgbplot|ribbon|rmappdata|rmdir|rmfield|rmpath|rmpref|rng|roots|rose|rosser|rot90|rotate|rotate3d|round|rref|rsf2csf|run|save|saveas|"+ "saveobj|savepath|scatter|scatter3|schur|sec|secd|sech|selectmoveresize|semilogx|semilogy|sendmail|serial|set|setappdata|setdiff|setenv|setfield|setpixelposition|setpref|setstr|"+ "setxor|shading|shg|shiftdim|showplottool|shrinkfaces|sign|sin(?:d|h)?|size|slice|smooth3|snapnow|sort|sortrows|sound|soundsc|spalloc|spaugment|spconvert|spdiags|specular|speye|"+ "spfun|sph2cart|sphere|spinmap|spline|spones|spparms|sprand|sprandn|sprandsym|sprank|spring|sprintf|spy|sqrt|sqrtm|squeeze|ss2tf|sscanf|stairs|startup|std|stem|stem3|stopasync|"+ "str2double|str2func|str2mat|str2num|strcat|strcmp|strcmpi|stream2|stream3|streamline|streamparticles|streamribbon|streamslice|streamtube|strfind|strjust|strmatch|strncmp|"+ "strncmpi|strread|strrep|strtok|strtrim|struct2cell|structfun|strvcat|sub2ind|subplot|subsasgn|subsindex|subspace|subsref|substruct|subvolume|sum|summer|superclasses|superiorto|"+ "support|surf|surf2patch|surface|surfc|surfl|surfnorm|svd|svds|swapbytes|symamd|symbfact|symmlq|symrcm|symvar|system|tan(?:d|h)?|tar|tempdir|tempname|tetramesh|texlabel|text|"+ "textread|textscan|textwrap|tfqmr|throw|tic|Tiff(?:.(?:getTagNames|getVersion))?|timer|timerfind|timerfindall|times|timeseries|title|toc|todatenum|toeplitz|toolboxdir|trace|"+ "transpose|trapz|treelayout|treeplot|tril|trimesh|triplequad|triplot|TriRep|TriScatteredInterp|trisurf|triu|tscollection|tsearch|tsearchn|tstool|type|typecast|uibuttongroup|"+ "uicontextmenu|uicontrol|uigetdir|uigetfile|uigetpref|uiimport|uimenu|uiopen|uipanel|uipushtool|uiputfile|uiresume|uisave|uisetcolor|uisetfont|uisetpref|uistack|uitable|"+ "uitoggletool|uitoolbar|uiwait|uminus|undocheckout|unicode2native|union|unique|unix|unloadlibrary|unmesh|unmkpp|untar|unwrap|unzip|uplus|upper|urlread|urlwrite|usejava|"+ "userpath|validateattributes|validatestring|vander|var|vectorize|ver|verctrl|verLessThan|version|vertcat|VideoReader(?:.isPlatformSupported)?|VideoWriter(?:.getProfiles)?|"+ "view|viewmtx|visdiff|volumebounds|voronoi|voronoin|wait|waitbar|waitfor|waitforbuttonpress|warndlg|warning|waterfall|wavfinfo|wavplay|wavread|wavrecord|wavwrite|web|weekday|"+ "what|whatsnew|which|whitebg|who|whos|wilkinson|winopen|winqueryreg|winter|wk1finfo|wk1read|wk1write|workspace|xlabel|xlim|xlsfinfo|xlsread|xlswrite|xmlread|xmlwrite|xor|xslt|"+ "ylabel|ylim|zeros|zip|zlabel|zlim|zoom|addedvarplot|andrewsplot|anova(?:1|2|n)|ansaribradley|aoctool|barttest|bbdesign|beta(?:cdf|fit|inv|like|pdf|rnd|stat)|bino(?:cdf|fit|inv|"+ "pdf|rnd|stat)|biplot|bootci|bootstrp|boxplot|candexch|candgen|canoncorr|capability|capaplot|caseread|casewrite|categorical|ccdesign|cdfplot|chi2(?:cdf|gof|inv|pdf|rnd|stat)|"+ "cholcov|Classification(?:BaggedEnsemble|Discriminant(?:.(?:fit|make|template))?|Ensemble|KNN(?:.(?:fit|template))?|PartitionedEnsemble|PartitionedModel|Tree(?:.(?:fit|"+ "template))?)|classify|classregtree|cluster|clusterdata|cmdscale|combnk|Compact(?:Classification(?:Discriminant|Ensemble|Tree)|Regression(?:Ensemble|Tree)|TreeBagger)|confusionmat|"+ "controlchart|controlrules|cophenet|copula(?:cdf|fit|param|pdf|rnd|stat)|cordexch|corr|corrcov|coxphfit|createns|crosstab|crossval|cvpartition|datasample|dataset|daugment|dcovary|"+ "dendrogram|dfittool|disttool|dummyvar|dwtest|ecdf|ecdfhist|ev(?:cdf|fit|inv|like|pdf|rnd|stat)|ExhaustiveSearcher|exp(?:cdf|fit|inv|like|pdf|rnd|stat)|factoran|fcdf|ff2n|finv|"+ "fitdist|fitensemble|fpdf|fracfact|fracfactgen|friedman|frnd|fstat|fsurfht|fullfact|gagerr|gam(?:cdf|fit|inv|like|pdf|rnd|stat)|GeneralizedLinearModel(?:.fit)?|geo(?:cdf|inv|mean|"+ "pdf|rnd|stat)|gev(?:cdf|fit|inv|like|pdf|rnd|stat)|gline|glmfit|glmval|glyphplot|gmdistribution(?:.fit)?|gname|gp(?:cdf|fit|inv|like|pdf|rnd|stat)|gplotmatrix|grp2idx|grpstats|"+ "gscatter|haltonset|harmmean|hist3|histfit|hmm(?:decode|estimate|generate|train|viterbi)|hougen|hyge(?:cdf|inv|pdf|rnd|stat)|icdf|inconsistent|interactionplot|invpred|iqr|iwishrnd|"+ "jackknife|jbtest|johnsrnd|KDTreeSearcher|kmeans|knnsearch|kruskalwallis|ksdensity|kstest|kstest2|kurtosis|lasso|lassoglm|lassoPlot|leverage|lhsdesign|lhsnorm|lillietest|"+ "LinearModel(?:.fit)?|linhyptest|linkage|logn(?:cdf|fit|inv|like|pdf|rnd|stat)|lsline|mad|mahal|maineffectsplot|manova1|manovacluster|mdscale|mhsample|mle|mlecov|mnpdf|"+ "mnrfit|mnrnd|mnrval|moment|multcompare|multivarichart|mvn(?:cdf|pdf|rnd)|mvregress|mvregresslike|mvt(?:cdf|pdf|rnd)|NaiveBayes(?:.fit)?|nan(?:cov|max|mean|median|min|std|"+ "sum|var)|nbin(?:cdf|fit|inv|pdf|rnd|stat)|ncf(?:cdf|inv|pdf|rnd|stat)|nct(?:cdf|inv|pdf|rnd|stat)|ncx2(?:cdf|inv|pdf|rnd|stat)|NeighborSearcher|nlinfit|nlintool|nlmefit|nlmefitsa|"+ "nlparci|nlpredci|nnmf|nominal|NonLinearModel(?:.fit)?|norm(?:cdf|fit|inv|like|pdf|rnd|stat)|normplot|normspec|ordinal|outlierMeasure|parallelcoords|paretotails|partialcorr|"+ "pcacov|pcares|pdf|pdist|pdist2|pearsrnd|perfcurve|perms|piecewisedistribution|plsregress|poiss(?:cdf|fit|inv|pdf|rnd|tat)|polyconf|polytool|prctile|princomp|ProbDist(?:Kernel|"+ "Parametric|UnivKernel|UnivParam)?|probplot|procrustes|qqplot|qrandset|qrandstream|quantile|randg|random|randsample|randtool|range|rangesearch|ranksum|rayl(?:cdf|fit|inv|pdf|"+ "rnd|stat)|rcoplot|refcurve|refline|regress|Regression(?:BaggedEnsemble|Ensemble|PartitionedEnsemble|PartitionedModel|Tree(?:.(?:fit|template))?)|regstats|relieff|ridge|"+ "robustdemo|robustfit|rotatefactors|rowexch|rsmdemo|rstool|runstest|sampsizepwr|scatterhist|sequentialfs|signrank|signtest|silhouette|skewness|slicesample|sobolset|squareform|"+ "statget|statset|stepwise|stepwisefit|surfht|tabulate|tblread|tblwrite|tcdf|tdfread|tiedrank|tinv|tpdf|TreeBagger|treedisp|treefit|treeprune|treetest|treeval|trimmean|trnd|tstat|"+ "ttest|ttest2|unid(?:cdf|inv|pdf|rnd|stat)|unif(?:cdf|inv|it|pdf|rnd|stat)|vartest(?:2|n)?|wbl(?:cdf|fit|inv|like|pdf|rnd|stat)|wblplot|wishrnd|x2fx|xptread|zscore|ztest"+ "adapthisteq|analyze75info|analyze75read|applycform|applylut|axes2pix|bestblk|blockproc|bwarea|bwareaopen|bwboundaries|bwconncomp|bwconvhull|bwdist|bwdistgeodesic|bweuler|"+ "bwhitmiss|bwlabel|bwlabeln|bwmorph|bwpack|bwperim|bwselect|bwtraceboundary|bwulterode|bwunpack|checkerboard|col2im|colfilt|conndef|convmtx2|corner|cornermetric|corr2|cp2tform|"+ "cpcorr|cpselect|cpstruct2pairs|dct2|dctmtx|deconvblind|deconvlucy|deconvreg|deconvwnr|decorrstretch|demosaic|dicom(?:anon|dict|info|lookup|read|uid|write)|edge|edgetaper|entropy|"+ "entropyfilt|fan2para|fanbeam|findbounds|fliptform|freqz2|fsamp2|fspecial|ftrans2|fwind1|fwind2|getheight|getimage|getimagemodel|getline|getneighbors|getnhood|getpts|"+ "getrangefromclass|getrect|getsequence|gray2ind|graycomatrix|graycoprops|graydist|grayslice|graythresh|hdrread|hdrwrite|histeq|hough|houghlines|houghpeaks|iccfind|iccread|"+ "iccroot|iccwrite|idct2|ifanbeam|im2bw|im2col|im2double|im2int16|im2java2d|im2single|im2uint16|im2uint8|imabsdiff|imadd|imadjust|ImageAdapter|imageinfo|imagemodel|imapplymatrix|"+ "imattributes|imbothat|imclearborder|imclose|imcolormaptool|imcomplement|imcontour|imcontrast|imcrop|imdilate|imdisplayrange|imdistline|imdivide|imellipse|imerode|imextendedmax|"+ "imextendedmin|imfill|imfilter|imfindcircles|imfreehand|imfuse|imgca|imgcf|imgetfile|imhandles|imhist|imhmax|imhmin|imimposemin|imlincomb|imline|immagbox|immovie|immultiply|imnoise|"+ "imopen|imoverview|imoverviewpanel|impixel|impixelinfo|impixelinfoval|impixelregion|impixelregionpanel|implay|impoint|impoly|impositionrect|improfile|imputfile|impyramid|"+ "imreconstruct|imrect|imregconfig|imregionalmax|imregionalmin|imregister|imresize|imroi|imrotate|imsave|imscrollpanel|imshow|imshowpair|imsubtract|imtool|imtophat|imtransform|"+ "imview|ind2gray|ind2rgb|interfileinfo|interfileread|intlut|ippl|iptaddcallback|iptcheckconn|iptcheckhandle|iptcheckinput|iptcheckmap|iptchecknargin|iptcheckstrs|iptdemos|iptgetapi|"+ "iptGetPointerBehavior|iptgetpref|ipticondir|iptnum2ordinal|iptPointerManager|iptprefs|iptremovecallback|iptSetPointerBehavior|iptsetpref|iptwindowalign|iradon|isbw|isflat|isgray|"+ "isicc|isind|isnitf|isrgb|isrset|lab2double|lab2uint16|lab2uint8|label2rgb|labelmatrix|makecform|makeConstrainToRectFcn|makehdr|makelut|makeresampler|maketform|mat2gray|mean2|"+ "medfilt2|montage|nitfinfo|nitfread|nlfilter|normxcorr2|ntsc2rgb|openrset|ordfilt2|otf2psf|padarray|para2fan|phantom|poly2mask|psf2otf|qtdecomp|qtgetblk|qtsetblk|radon|rangefilt|"+ "reflect|regionprops|registration.metric.(?:MattesMutualInformation|MeanSquares)|registration.optimizer.(?:OnePlusOneEvolutionary|RegularStepGradientDescent)|rgb2gray|"+ "rgb2ntsc|rgb2ycbcr|roicolor|roifill|roifilt2|roipoly|rsetwrite|std2|stdfilt|strel|stretchlim|subimage|tformarray|tformfwd|tforminv|tonemap|translate|truesize|uintlut|viscircles|"+ "warp|watershed|whitepoint|wiener2|xyz2double|xyz2uint16|ycbcr2rgb|bintprog|color|fgoalattain|fminbnd|fmincon|fminimax|fminsearch|fminunc|fseminf|fsolve|fzero|fzmult|gangstr|ktrlink|"+ "linprog|lsqcurvefit|lsqlin|lsqnonlin|lsqnonneg|optimget|optimset|optimtool|quadprog" ); var storageType = ( "cell|struct|char|double|single|logical|u?int(?:8|16|32|64)|sparse" ); var keywordMapper = this.createKeywordMapper({ "storage.type": storageType, "support.function": builtinFunctions, "keyword": keywords, "constant.language": builtinConstants }, "identifier", true); this.$rules = { start: [{ token : "string", regex : "'", stateName : "qstring", next : [{ token : "constant.language.escape", regex : "''" }, { token : "string", regex : "'|$", next : "start" }, { defaultToken: "string" }] }, { token : "text", regex : "\\s+" }, { regex: "", next: "noQstring" }], noQstring : [{ regex: "^\\s*%{\\s*$", token: "comment.start", push: "blockComment" }, { token : "comment", regex : "%[^\r\n]*" }, { token : "string", regex : '"', stateName : "qqstring", next : [{ token : "constant.language.escape", regex : /\\./ }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "start" }, { defaultToken: "string" }] }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\/|\\/\\/|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=", next: "start" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\.", next: "start" }, { token : "paren.lparen", regex : "[({\\[]", next: "start" }, { token : "paren.rparen", regex : "[\\]})]" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "$", next : "start" }], blockComment: [{ regex: "^\\s*%{\\s*$", token: "comment.start", push: "blockComment" }, { regex: "^\\s*%}\\s*$", token: "comment.end", next: "pop" }, { defaultToken: "comment" }] }; this.normalizeRules(); }; oop.inherits(MatlabHighlightRules, TextHighlightRules); exports.MatlabHighlightRules = MatlabHighlightRules; }); define("ace/mode/matlab",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/matlab_highlight_rules","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var MatlabHighlightRules = require("./matlab_highlight_rules").MatlabHighlightRules; var Range = require("../range").Range; var Mode = function() { this.HighlightRules = MatlabHighlightRules; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "%"; this.blockComment = {start: "%{", end: "%}"}; this.$id = "ace/mode/matlab"; }).call(Mode.prototype); exports.Mode = Mode; });
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ /** * @author Ed Spencer * @class Ext.data.validations * @extends Object * * <p>This singleton contains a set of validation functions that can be used to validate any type * of data. They are most often used in {@link Ext.data.Model Models}, where they are automatically * set up and executed.</p> */ Ext.define('Ext.data.validations', { singleton: true, /** * The default error message used when a presence validation fails * @property presenceMessage * @type String */ presenceMessage: 'must be present', /** * The default error message used when a length validation fails * @property lengthMessage * @type String */ lengthMessage: 'is the wrong length', /** * The default error message used when a format validation fails * @property formatMessage * @type Boolean */ formatMessage: 'is the wrong format', /** * The default error message used when an inclusion validation fails * @property inclusionMessage * @type String */ inclusionMessage: 'is not included in the list of acceptable values', /** * The default error message used when an exclusion validation fails * @property exclusionMessage * @type String */ exclusionMessage: 'is not an acceptable value', /** * Validates that the given value is present * @param {Object} config Optional config object * @param {Mixed} value The value to validate * @return {Boolean} True if validation passed */ presence: function(config, value) { if (value === undefined) { value = config; } return !!value; }, /** * Returns true if the given value is between the configured min and max values * @param {Object} config Optional config object * @param {String} value The value to validate * @return {Boolean} True if the value passes validation */ length: function(config, value) { if (value === undefined) { return false; } var length = value.length, min = config.min, max = config.max; if ((min && length < min) || (max && length > max)) { return false; } else { return true; } }, /** * Returns true if the given value passes validation against the configured {@link #matcher} regex * @param {Object} config Optional config object * @param {String} value The value to validate * @return {Boolean} True if the value passes the format validation */ format: function(config, value) { return !!(config.matcher && config.matcher.test(value)); }, /** * Validates that the given value is present in the configured {@link #list} * @param {String} value The value to validate * @return {Boolean} True if the value is present in the list */ inclusion: function(config, value) { return config.list && Ext.Array.indexOf(config.list,value) != -1; }, /** * Validates that the given value is present in the configured {@link #list} * @param {Object} config Optional config object * @param {String} value The value to validate * @return {Boolean} True if the value is not present in the list */ exclusion: function(config, value) { return config.list && Ext.Array.indexOf(config.list,value) == -1; } });
version https://git-lfs.github.com/spec/v1 oid sha256:ce3806c309ea128911ab2158c361b4ccf823043c3f6d361786d1313355454252 size 15921
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); // see this link for more info on what all of this means // https://github.com/halt-hammerzeit/webpack-isomorphic-tools module.exports = { webpack_assets_file_path: 'webpack-stats.json', assets: { images: { extensions: [ 'jpeg', 'jpg', 'png', 'gif', 'svg' ], parser: WebpackIsomorphicToolsPlugin.url_loader_parser }, style_modules: { extension: 'scss', filter: function(m, regex, options, log) { if (!options.development) { return regex.test(m.name); } //filter by modules with '.scss' inside name string, that also have name and moduleName that end with 'ss'(allows for css, less, sass, and scss extensions) //this ensures that the proper scss module is returned, so that namePrefix variable is no longer needed return (regex.test(m.name) && m.name.slice(-2) === 'ss' && m.reasons[0].moduleName.slice(-2) === 'ss'); }, naming: function(m, options, log) { //find index of '/src' inside the module name, slice it and resolve path var srcIndex = m.name.indexOf('/src'); var name = '.' + m.name.slice(srcIndex); if (name) { // Resolve the e.g.: "C:\" issue on windows const i = name.indexOf(':'); if (i >= 0) { name = name.slice(i + 1); } } return name; }, parser: function(m, options, log) { if (m.source) { var regex = options.development ? /exports\.locals = ((.|\n)+);/ : /module\.exports = ((.|\n)+);/; var match = m.source.match(regex); return match ? JSON.parse(match[1]) : {}; } } } } }